blade-code 0.10.21 → 0.10.22

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 (100) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-ns5015tn.js → chunk-04gq93dx.js} +1 -1
  3. package/dist/{chunk-bjf7ecgy.js → chunk-06pbdpcg.js} +1 -1
  4. package/dist/{chunk-4v8nxcxp.js → chunk-18f9g8ja.js} +1 -1
  5. package/dist/{chunk-2c3zavy2.js → chunk-18n15nn8.js} +1 -1
  6. package/dist/chunk-1ejj4jvg.js +1 -0
  7. package/dist/{chunk-4tkn9bky.js → chunk-244cdt25.js} +1 -1
  8. package/dist/{chunk-wc1ee4tc.js → chunk-2kpynwxa.js} +1 -1
  9. package/dist/{chunk-72ztan96.js → chunk-2rbct4ks.js} +3 -3
  10. package/dist/{chunk-e9xv0yyr.js → chunk-33wheqb0.js} +1 -1
  11. package/dist/chunk-34cqp0rx.js +1 -0
  12. package/dist/chunk-3bk8jveq.js +1 -0
  13. package/dist/{chunk-095x2ykj.js → chunk-4dnvydyv.js} +1 -1
  14. package/dist/{chunk-bdn1tkyz.js → chunk-5bgyskdm.js} +1 -1
  15. package/dist/{chunk-6sb7cg95.js → chunk-5sw8j9ae.js} +1 -1
  16. package/dist/{chunk-r1jxbx1h.js → chunk-5xph8r1k.js} +1 -1
  17. package/dist/{chunk-q4fjec99.js → chunk-5ztdsaex.js} +2 -2
  18. package/dist/{chunk-jahf977w.js → chunk-698qsvyb.js} +2 -2
  19. package/dist/chunk-7nygnmnm.js +1 -0
  20. package/dist/{chunk-w5m418w5.js → chunk-8472vz3s.js} +2 -2
  21. package/dist/{chunk-r561wfcz.js → chunk-9ka0bdry.js} +1 -1
  22. package/dist/{chunk-65kbckpt.js → chunk-9m80tr4t.js} +2 -2
  23. package/dist/chunk-9nc6sfj4.js +1 -0
  24. package/dist/chunk-9wdg2mqh.js +1 -0
  25. package/dist/{chunk-ryhk5qmv.js → chunk-a3yg9fd5.js} +275 -275
  26. package/dist/{chunk-jhzk287k.js → chunk-abtq0kjb.js} +1 -1
  27. package/dist/{chunk-jdsr22s2.js → chunk-afv2grka.js} +1 -1
  28. package/dist/chunk-avtsweaa.js +1 -0
  29. package/dist/{chunk-g7p165yz.js → chunk-bh42pn4d.js} +2 -2
  30. package/dist/{chunk-fasxw5bb.js → chunk-c7zk9zj2.js} +1 -1
  31. package/dist/{chunk-kmeccj99.js → chunk-czjbz0fp.js} +2 -2
  32. package/dist/{chunk-17jpjcvb.js → chunk-d3kqhv5k.js} +3 -3
  33. package/dist/{chunk-77z6x1zb.js → chunk-djh79rde.js} +2 -2
  34. package/dist/{chunk-whftbz4b.js → chunk-ef8rr9eh.js} +2 -2
  35. package/dist/{chunk-9wqr1sbq.js → chunk-f9tahtz6.js} +1 -1
  36. package/dist/{chunk-pmw9pn3v.js → chunk-g1zrs8tj.js} +1 -1
  37. package/dist/{chunk-ah8hky46.js → chunk-gcsygn5a.js} +1 -1
  38. package/dist/{chunk-wxqkpvqw.js → chunk-gwvds95j.js} +2 -2
  39. package/dist/{chunk-1y52h772.js → chunk-h0q03x9f.js} +1 -1
  40. package/dist/{chunk-vzgy95tp.js → chunk-haqfbgv4.js} +1 -1
  41. package/dist/chunk-hfveg7c1.js +1 -0
  42. package/dist/{chunk-k106g2p6.js → chunk-hjvdsrzb.js} +2 -2
  43. package/dist/chunk-kky5ydtw.js +2 -0
  44. package/dist/{chunk-kfqj54ax.js → chunk-kntre6sz.js} +2 -2
  45. package/dist/{chunk-afhdpen9.js → chunk-ksm02qjh.js} +2 -2
  46. package/dist/{chunk-dbb20rxh.js → chunk-kvd5nexw.js} +1 -1
  47. package/dist/{chunk-5chec8rs.js → chunk-m27w377p.js} +1 -1
  48. package/dist/{chunk-edphxwj1.js → chunk-m96f2aq9.js} +2 -2
  49. package/dist/chunk-mrx6qkax.js +1 -0
  50. package/dist/chunk-n63thdsq.js +100 -0
  51. package/dist/{chunk-2wp6h1p8.js → chunk-nwy1rpwf.js} +2 -2
  52. package/dist/chunk-p29w4zfc.js +1 -0
  53. package/dist/{chunk-a1ztrwjb.js → chunk-pefrn6n0.js} +1 -1
  54. package/dist/{chunk-mvc0tad6.js → chunk-qw900zg9.js} +2 -2
  55. package/dist/{chunk-4ypy5bk8.js → chunk-r40fthzd.js} +2 -2
  56. package/dist/{chunk-sj2w24fe.js → chunk-rxfmqnf7.js} +2 -2
  57. package/dist/chunk-s1310gqw.js +1 -0
  58. package/dist/{chunk-73jh6fz9.js → chunk-s7g6jt82.js} +2 -2
  59. package/dist/{chunk-033vmd74.js → chunk-se1ef1r7.js} +2 -2
  60. package/dist/{chunk-jyeas4p9.js → chunk-sr2stcda.js} +1 -1
  61. package/dist/chunk-tnt2hhcg.js +1 -0
  62. package/dist/chunk-txqccp76.js +1 -0
  63. package/dist/{chunk-y68sxcgk.js → chunk-vannpbp0.js} +1 -1
  64. package/dist/chunk-vc2c8wkx.js +2 -0
  65. package/dist/chunk-vxhf2q0r.js +1 -0
  66. package/dist/{chunk-vprpk6q1.js → chunk-vypake1a.js} +2 -2
  67. package/dist/{chunk-5hhfv1w1.js → chunk-wax3nm7t.js} +1 -1
  68. package/dist/{chunk-yz2bsntj.js → chunk-xjqcc0nt.js} +1 -1
  69. package/dist/chunk-y5xyh4br.js +10 -0
  70. package/dist/{chunk-7mpa4esh.js → chunk-yqk501wp.js} +1 -1
  71. package/dist/{chunk-2ygqbd1z.js → chunk-zj651nrm.js} +1 -1
  72. package/dist/web/assets/ChatView-CCxjYDmJ.js +7 -0
  73. package/dist/web/assets/{CodeBlockHighlighter-DYuOTwXS.js → CodeBlockHighlighter-D9MqsrZP.js} +1 -1
  74. package/dist/web/assets/{FilePreview-CWOBOnzz.js → FilePreview-Cn5HOlPw.js} +1 -1
  75. package/dist/web/assets/{MarkdownRenderer-YiYvkN2w.js → MarkdownRenderer-ALTOCdfi.js} +3 -3
  76. package/dist/web/assets/{SettingsModal-BT-oFKGN.js → SettingsModal-Dk69F1bS.js} +1 -1
  77. package/dist/web/assets/{TaskSwitcher-D5Gd6FN9.js → TaskSwitcher-DRZZocE1.js} +1 -1
  78. package/dist/web/assets/{TerminalPanel-C1hLHq_K.js → TerminalPanel-ByAqKZ47.js} +1 -1
  79. package/dist/web/assets/{index-DuYx6fkN.js → index-CRCirUK7.js} +5 -5
  80. package/dist/web/index.html +1 -1
  81. package/package.json +1 -1
  82. package/dist/chunk-0et4h9p3.js +0 -1
  83. package/dist/chunk-0qayfsc9.js +0 -2
  84. package/dist/chunk-1p5822w7.js +0 -100
  85. package/dist/chunk-303cba4k.js +0 -1
  86. package/dist/chunk-51vnya3v.js +0 -1
  87. package/dist/chunk-6f3rp67k.js +0 -1
  88. package/dist/chunk-6v4dwkw7.js +0 -1
  89. package/dist/chunk-7p4qvftj.js +0 -1
  90. package/dist/chunk-9snsxf18.js +0 -1
  91. package/dist/chunk-c23c1vn6.js +0 -1
  92. package/dist/chunk-cb0rb9ss.js +0 -1
  93. package/dist/chunk-cysaxtfp.js +0 -10
  94. package/dist/chunk-efkqwhff.js +0 -1
  95. package/dist/chunk-ktbe458z.js +0 -2
  96. package/dist/chunk-r73fanrm.js +0 -1
  97. package/dist/chunk-smh39yy2.js +0 -1
  98. package/dist/chunk-w9tnd1q2.js +0 -1
  99. package/dist/chunk-zz9rax72.js +0 -1
  100. package/dist/web/assets/ChatView-YFotW0KS.js +0 -7
@@ -0,0 +1,2 @@
1
+ import{ne as o}from"./chunk-djh79rde.js";import{hf as J,if as $,jf as O,kf as K}from"./chunk-9ka0bdry.js";import{lf as v,mf as S,nf as l}from"./chunk-vc2c8wkx.js";import{Tf as n}from"./chunk-czjbz0fp.js";var G=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],a={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},f=new Map;function D(Q,Z,W){let B=new Set;for(let X of Q.split(",")){let[Y,k]=X.split("/"),V=k?Number.parseInt(k,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=W;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[U,i]=Y.split("-");j=Number.parseInt(U,10),H=Number.parseInt(i,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>W||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let U=j;U<=H;U+=V)B.add(U)}return B}function C(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[W,B,X,Y,k]=Z,V=D(k,G[4].min,G[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(W,G[0].min,G[0].max),hours:D(B,G[1].min,G[1].max),daysOfMonth:D(X,G[2].min,G[2].max),months:D(Y,G[3].min,G[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:k.trim()!=="*"}}function t(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let W=f.get(Z);if(!W)W=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),f.set(Z,W);let B=Object.fromEntries(W.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:a[B.weekday]??-1}}function r(Q,Z,W){let B=t(Z,W);if(!Q.minutes.has(B.minute))return!1;if(!Q.hours.has(B.hour))return!1;if(!Q.months.has(B.month))return!1;let X=Q.daysOfMonth.has(B.dayOfMonth),Y=Q.daysOfWeek.has(B.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function T(Q,Z,W){let B=C(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(r(B,X,W))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var E={s:1000,m:60000,h:3600000,d:86400000};function DJ(Q){let W=Q.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!W)return null;let B=Number.parseInt(W[1],10);if(!Number.isInteger(B)||B<=0)return null;let X=W[2]||"m";return B*E[X]}function y(Q){for(let Z of["d","h","m","s"]){let W=E[Z];if(Q%W===0)return`${Q/W}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,W){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return T(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((W??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let B=new Date(Q.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>Z.getTime()?B:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(C(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function FJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?y(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as bJ,readFile as wJ}from"node:fs/promises";import s from"node:path";import{nanoid as LJ}from"nanoid";import PJ from"write-file-atomic";var w=$(K(["default","autoEdit","yolo","plan"]));var N=$(K(["user","assistant","system","tool"])),p=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),h=J.Union([J.String(),J.Array(p)]),NJ=$(J.Object({id:J.String(),role:N,content:h,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),e=$(K(["queued","running","completed","failed","cancelled","interrupted"])),F=$(K(["local","worktree"])),JJ=$(K(["applied","discarded","conflicted"])),QJ=$(J.Object({status:JJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),ZJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),$J=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),qJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array($J,{maxItems:100}),truncated:J.Boolean()})),BJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),KJ=$(J.Object({name:J.String(),type:K(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(BJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(K(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),xJ=$(J.Object({serverName:J.String(),mode:K(["form","url"]),message:J.String(),fields:J.Optional(J.Array(KJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),WJ=$(J.Object({type:K(["permission","question","elicitation"]),requestId:J.String()})),XJ=$(J.Object({code:K(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean()})),L=$(K(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(K(["auto","standard","fast","flex"])),M=$(K(["auto","low","medium","high"])),b=$(J.Union([K(["auto","pragmatic","friendly","explanatory"]),J.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(K(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:O(e,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(XJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional(QJ),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(ZJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(WJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),fJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),CJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),EJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),RJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:K(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),completionVerification:J.Optional(J.Object({attempt:J.Integer({minimum:1}),status:K(["pending","pass","fail","partial"]),requestedAt:J.String(),completedAt:J.Optional(J.String()),verifierSessionId:J.Optional(J.String()),summary:J.Optional(J.String()),evidenceSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),createdAt:J.String(),updatedAt:J.String()})),u=$(J.Object({role:N,content:h,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),SJ=$(J.Object({session:z,messages:J.Array(u)})),d=$(K(["conversation","code","both"])),YJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),lJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:O(d,"conversation")})),hJ=$(J.Object({checkpoint:YJ,mode:d,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(u)})),HJ=K(["running","completed","failed","cancelled"]),R=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:HJ,rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),restartRecovery:J.Optional(J.Object({outcome:K(["completed","interrupted","failed"]),recoveredAt:J.Number()})),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(K(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),uJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),dJ=$(J.Object({source:R,session:R})),mJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),cJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),gJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),nJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),m=J.Object({type:K(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:S})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),c=J.Record(J.String(),J.Unknown()),oJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),sJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:K(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),iJ=$(J.Object({action:K(["apply","discard"])})),q=$(J.Object({kind:K(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),jJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default")})),x=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,dispatch:jJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(K(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),enabled:O(J.Boolean(),!0)})),tJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(q),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),rJ=$(J.Object({schedules:J.Array(x)})),TJ=$(J.Object({content:J.String({maxLength:l}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),UJ=K(["completed","failed","aborted","timed_out","spawn_error"]),kJ=$(J.Object({version:J.Literal(1),command:J.String(),status:UJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),yJ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),pJ=$(J.Object({executionId:J.String(),messageId:J.String(),record:kJ,auxiliary:J.Boolean(),delivery:J.Optional(K(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),eJ=$(J.Object({projectPath:J.String(),kind:K(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),JQ=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),QQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),ZQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(K(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:K(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),VJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:K(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),$Q=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(K(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(K(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(K(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(VJ,{maxItems:36})),input:J.Optional(J.Array(K(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),BQ=$(K(["vs-dark","vs-light","hc-black"])),GJ=$(K(["light","dark","system"])),OJ=$(J.Object({language:J.String(),theme:J.String(),uiTheme:GJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),KQ=$(J.Partial(OJ));var g=o("Service"),MJ=1;function IJ(){return s.join(n(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=IJ()){this.filePath=Q}async readFile(){try{let Q=await wJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let W=[],B=0;for(let X of Z.schedules){let Y=x.safeParse(X);if(Y.success)W.push(Y.data);else B+=1}if(B>0)g.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return W}catch(Q){let Z=Q;if(Z.code!=="ENOENT")g.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await bJ(s.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:MJ,schedules:Q};await PJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((W)=>W.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,W=_(Z);if(W)throw Error(W);let B=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let X=B.toISOString(),Y=A(Z,B),k={id:LJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(k),await this.writeFile(V),k})}async update(Q,Z){return this.serializeWrite(async()=>{let W=await this.readFile(),B=W.findIndex((H)=>H.id===Q);if(B===-1)return;let X=W[B];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,U=_(H);if(U)throw Error(U);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},k=!X.enabled,V=Y.enabled,j=Z.trigger!==void 0;if((j||k&&V)&&Z.nextRunAt===void 0){let H=new Date,U=A(Y.trigger,H);if(Y.nextRunAt=U?U.toISOString():null,j)Y.expiresAt=null}return W[B]=Y,await this.writeFile(W),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),W=Z.filter((B)=>B.id!==Q);if(W.length===Z.length)return!1;return await this.writeFile(W),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var LQ=I.getInstance();
2
+ export{DJ as la,A as ma,_ as na,FJ as oa,qJ as pa,z as qa,lJ as ra,uJ as sa,oJ as ta,sJ as ua,iJ as va,x as wa,aJ as xa,tJ as ya,rJ as za,TJ as Aa,yJ as Ba,eJ as Ca,I as Da,LQ as Ea};
@@ -1,5 +1,5 @@
1
- import{r as E}from"./chunk-a1ztrwjb.js";import{s as YJ}from"./chunk-4v8nxcxp.js";import{$ as o,F as m,I as d,J as l,L as i,Z as r,_ as a,aa as n,v as A}from"./chunk-ryhk5qmv.js";import{ka as WJ}from"./chunk-4tkn9bky.js";import"./chunk-ktbe458z.js";import{Va as c,Ya as p,hb as v}from"./chunk-72ztan96.js";import{sb as T}from"./chunk-095x2ykj.js";import{Hb as f,Qb as M,Rb as u,Tb as R,Wb as g,_b as N,bc as D}from"./chunk-1p5822w7.js";import"./chunk-vprpk6q1.js";import"./chunk-65kbckpt.js";import"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import{hd as ZJ}from"./chunk-yz2bsntj.js";import"./chunk-sj2w24fe.js";import"./chunk-afhdpen9.js";import{sd as $J}from"./chunk-5chec8rs.js";import"./chunk-4ypy5bk8.js";import"./chunk-g7p165yz.js";import"./chunk-r1jxbx1h.js";import{Xd as zJ}from"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import{je as b}from"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import{hf as I,if as S,jf as y}from"./chunk-0qayfsc9.js";import{nf as e}from"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import{tf as JJ,wf as QJ}from"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import{Readable as VJ,Writable as wJ}from"node:stream";import*as x from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as BJ}from"@agentclientprotocol/sdk";import s from"node:path";import{RequestError as GJ}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var j=b("Agent");function C(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function XJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:C(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:C("headers"in J?J.headers:void 0)};return null}function jJ(J){let Z={};for(let Q of J){let Y=XJ(Q);if(Y)Z[Q.name]=Y}return Z}function t(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 DJ(J){let Z=u(J.metadata);return Z?[{type:"text",text:M(Z)}]:t(J.content)}function LJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}class O{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;contextMessages;mode;constructor(J,Z,Q,Y,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode)}async refreshPersistedMessages(){let[J,Z]=await Promise.all([D.loadSession(this.id,this.cwd),D.loadSessionModelContext(this.id,this.cwd)]);if(J.length>0)this.messages=J;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(J){let Z=await D.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...J]}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 i.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(j.debug(`[AcpSession ${this.id}] Initializing...`),await D.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),A.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),j.debug(`[AcpSession ${this.id}] ACP service context initialized`),await v.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?jJ(this.options.mcpServers):void 0,Q=A.getInstance().getTerminalService(this.id);if(this.runtime=await m.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(z,$)=>{let F=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(G)=>$.onOutput?.("stdout",G)});return{exitCode:F.exitCode,stdout:F.stdout,stderr:F.stderr,...F.error?{error:F.error}:{},timedOut:F.error==="Command timed out",aborted:F.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await a(this.cwd),j.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=p.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of DJ(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);j.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{j.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],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 F=await this.runtime.rewindSession($);return this.messages=[...F.messages],this.contextMessages=await this.loadModelContextOr(F.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),F}},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($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=!1,X,L=(W)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.id,status:W.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:W.result?.message||W.result?.error||`Subagent ${W.status}`}}]})},B=this.runtime.resumeSubagent({agentId:$,prompt:F,onCompleted:(W)=>{if(G)L(W);else X=W}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.session.id,status:"in_progress",title:`Resuming ${B.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${B.source.id} at depth ${B.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),G=!0,X)L(X);return B}},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($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,F,G)},complete:async($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,F,G)},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($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,F)},getLogs:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,F)},setLoggingLevel:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,F)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:F,onEvent:(B)=>{if(B.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.toolCall.id,status:"in_progress",title:`Review: ${B.toolCall.function.name}`,content:[],kind:this.mapToolKind(B.toolKind)});else if(B.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.toolCall.id,status:B.result.success?"completed":"failed",content:[]})}}),X=await G.completion,L=(await E.list(this.cwd,this.id)).find((B)=>B.start.reviewId===G.reviewId);if(!L)throw Error(`Review not found: ${G.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:G.reviewId,status:X.status,findings:X.findings.length,content:f(L.start,X)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,F,G)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(G);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(F,null,2)}}],kind:L})},sendToolResult:($,F)=>{if(F.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:F.summary}})}}},Y=await o(J,Q),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let $=await D.loadSession(this.id,this.cwd);if($.length>0)this.messages=$}let z=Y.content||Y.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});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 j.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=n(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});j.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),j.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){j.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(A.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((G)=>G.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=g(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let G=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!G.accepted)throw Error(G.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(j.debug(`[AcpSession ${this.id}] Queued steering for active turn (${G.queued})`),G.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let F=new AbortController;this.pendingPrompt=F;try{if(j.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),r(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,F.signal)}let G={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.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)}}},X=await c(this.agent.chatStream(Y,G,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(W)=>{switch(W.kind){case"content_delta":if($)break;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 w=W.toolCall,_=w.function.name;if(_===R)break;let q=this.mapToolKind(W.toolKind),V=`Executing ${_}`;if(_==="Task"&&"function"in w)try{let P=JSON.parse(w.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")V=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:q});break}case"tool_progress":{let w=W.toolCall;if(w.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let w=W.toolCall;if(w.function.name===R)break;let _=W.result,q=[],V=_.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let K of V.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;q.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))q.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let K=w.function.name,HJ=l(d(K,_));q.push({type:"content",content:{type:"text",text:HJ}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let P=_.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:P,content:q});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(W.output)}});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}
1
+ import{r as E}from"./chunk-pefrn6n0.js";import{s as YJ}from"./chunk-18f9g8ja.js";import{$ as o,F as m,I as d,J as l,L as i,Z as r,_ as a,aa as n,v as A}from"./chunk-a3yg9fd5.js";import{ka as WJ}from"./chunk-244cdt25.js";import"./chunk-kky5ydtw.js";import{$a as p,Ma as c,ib as v}from"./chunk-2rbct4ks.js";import{tb as T}from"./chunk-4dnvydyv.js";import{Lb as f,Ub as M,Vb as u,Xb as R,_b as g,cc as N,fc as D}from"./chunk-n63thdsq.js";import"./chunk-vypake1a.js";import"./chunk-9m80tr4t.js";import"./chunk-ef8rr9eh.js";import"./chunk-wax3nm7t.js";import{ld as ZJ}from"./chunk-xjqcc0nt.js";import"./chunk-rxfmqnf7.js";import"./chunk-ksm02qjh.js";import{wd as $J}from"./chunk-m27w377p.js";import"./chunk-r40fthzd.js";import"./chunk-bh42pn4d.js";import"./chunk-5xph8r1k.js";import{$d as zJ}from"./chunk-5sw8j9ae.js";import"./chunk-18n15nn8.js";import"./chunk-d3kqhv5k.js";import"./chunk-sr2stcda.js";import{ne as b}from"./chunk-djh79rde.js";import"./chunk-qw900zg9.js";import"./chunk-gcsygn5a.js";import"./chunk-9ka0bdry.js";import{lf as I,mf as S,nf as y}from"./chunk-vc2c8wkx.js";import{rf as e}from"./chunk-kvd5nexw.js";import"./chunk-8472vz3s.js";import{Af as QJ,xf as JJ}from"./chunk-f9tahtz6.js";import"./chunk-gwvds95j.js";import"./chunk-698qsvyb.js";import"./chunk-h0q03x9f.js";import"./chunk-czjbz0fp.js";import"./chunk-c7zk9zj2.js";import{Readable as VJ,Writable as wJ}from"node:stream";import*as x from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as BJ}from"@agentclientprotocol/sdk";import s from"node:path";import{RequestError as GJ}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var j=b("Agent");function C(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function XJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:C(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:C("headers"in J?J.headers:void 0)};return null}function jJ(J){let Z={};for(let Q of J){let Y=XJ(Q);if(Y)Z[Q.name]=Y}return Z}function t(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 DJ(J){let Z=u(J.metadata);return Z?[{type:"text",text:M(Z)}]:t(J.content)}function LJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
+ `)}class O{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;contextMessages;mode;constructor(J,Z,Q,Y,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode)}async refreshPersistedMessages(){let[J,Z]=await Promise.all([D.loadSession(this.id,this.cwd),D.loadSessionModelContext(this.id,this.cwd)]);if(J.length>0)this.messages=J;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(J){let Z=await D.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...J]}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 i.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(j.debug(`[AcpSession ${this.id}] Initializing...`),await D.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),A.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),j.debug(`[AcpSession ${this.id}] ACP service context initialized`),await v.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?jJ(this.options.mcpServers):void 0,Q=A.getInstance().getTerminalService(this.id);if(this.runtime=await m.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(z,$)=>{let F=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(G)=>$.onOutput?.("stdout",G)});return{exitCode:F.exitCode,stdout:F.stdout,stderr:F.stderr,...F.error?{error:F.error}:{},timedOut:F.error==="Command timed out",aborted:F.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await a(this.cwd),j.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=c.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of DJ(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);j.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{j.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],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 F=await this.runtime.rewindSession($);return this.messages=[...F.messages],this.contextMessages=await this.loadModelContextOr(F.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),F}},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($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=!1,X,L=(W)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.id,status:W.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:W.result?.message||W.result?.error||`Subagent ${W.status}`}}]})},B=this.runtime.resumeSubagent({agentId:$,prompt:F,onCompleted:(W)=>{if(G)L(W);else X=W}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.session.id,status:"in_progress",title:`Resuming ${B.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${B.source.id} at depth ${B.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),G=!0,X)L(X);return B}},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($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,F,G)},complete:async($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,F,G)},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($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,F)},getLogs:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,F)},setLoggingLevel:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,F)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:F,onEvent:(B)=>{if(B.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.toolCall.id,status:"in_progress",title:`Review: ${B.toolCall.function.name}`,content:[],kind:this.mapToolKind(B.toolKind)});else if(B.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.toolCall.id,status:B.result.success?"completed":"failed",content:[]})}}),X=await G.completion,L=(await E.list(this.cwd,this.id)).find((B)=>B.start.reviewId===G.reviewId);if(!L)throw Error(`Review not found: ${G.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:G.reviewId,status:X.status,findings:X.findings.length,content:f(L.start,X)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,F,G)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(G);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(F,null,2)}}],kind:L})},sendToolResult:($,F)=>{if(F.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:F.summary}})}}},Y=await o(J,Q),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let $=await D.loadSession(this.id,this.cwd);if($.length>0)this.messages=$}let z=Y.content||Y.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});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 j.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=n(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});j.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),j.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){j.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(A.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((G)=>G.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=g(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let G=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!G.accepted)throw Error(G.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(j.debug(`[AcpSession ${this.id}] Queued steering for active turn (${G.queued})`),G.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let F=new AbortController;this.pendingPrompt=F;try{if(j.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),r(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,F.signal)}let G={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.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)}}},X=await p(this.agent.chatStream(Y,G,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(W)=>{switch(W.kind){case"content_delta":if($)break;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 w=W.toolCall,_=w.function.name;if(_===R)break;let q=this.mapToolKind(W.toolKind),V=`Executing ${_}`;if(_==="Task"&&"function"in w)try{let P=JSON.parse(w.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")V=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:q});break}case"tool_progress":{let w=W.toolCall;if(w.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let w=W.toolCall;if(w.function.name===R)break;let _=W.result,q=[],V=_.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let K of V.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;q.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))q.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let K=w.function.name,HJ=l(d(K,_));q.push({type:"content",content:{type:"text",text:HJ}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let P=_.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:P,content:q});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(W.output)}});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
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
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
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}
@@ -1,2 +1,2 @@
1
- import{td as B}from"./chunk-5chec8rs.js";import{sf as Y}from"./chunk-w5m418w5.js";import{vf as Z,yf as $}from"./chunk-9wqr1sbq.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
- export{K as pd,O as qd,E as rd};
1
+ import{xd as B}from"./chunk-m27w377p.js";import{wf as Y}from"./chunk-8472vz3s.js";import{Cf as $,zf as Z}from"./chunk-f9tahtz6.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
+ export{K as td,O as ud,E as vd};
@@ -1,2 +1,2 @@
1
1
  import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
2
- export{N as kf,D as lf,P as mf,V as nf};
2
+ export{N as of,D as pf,P as qf,V as rf};
@@ -1,2 +1,2 @@
1
1
  import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
2
- export{s as sd,g as td};
2
+ export{s as wd,g as xd};
@@ -1,4 +1,4 @@
1
- import{Sc as W}from"./chunk-whftbz4b.js";import{de as X}from"./chunk-17jpjcvb.js";import{he as Q,je as U}from"./chunk-77z6x1zb.js";import{nf as V}from"./chunk-dbb20rxh.js";function _(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=U("Service");function $(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class F{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!F.instance)F.instance=new F;return F.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{Wc as W}from"./chunk-ef8rr9eh.js";import{he as X}from"./chunk-d3kqhv5k.js";import{le as Q,ne as U}from"./chunk-djh79rde.js";import{rf as V}from"./chunk-kvd5nexw.js";function _(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=U("Service");function $(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class F{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!F.instance)F.instance=new F;return F.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await Q()}catch(z){}try{let z=X.getInstance(),J=W(),N=J.session?.sessionId||"unknown",O=J.session?.workspaceRoot||V();if(z.isEnabled(O,N)){let Z=J.config?.config?.permissionMode||"default";await z.executeSessionEndHooks($(b),{projectDir:O,sessionId:N,permissionMode:Z})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,Y=new Promise((z,J)=>{setTimeout(()=>{J(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,Y])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{_(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var K=()=>{return F.getInstance()},P=(b)=>{return K().registerCleanup(b)},L=()=>{K().initialize()},k=(b=0)=>{K().shutdown("normal",b)};
4
- export{K as Ac,P as Bc,L as Cc,k as Dc};
4
+ export{K as Ec,P as Fc,L as Gc,k as Hc};
@@ -0,0 +1 @@
1
+ import{$c as g,Vc as a,Wc as b,Xc as c,Yc as d,Zc as e,_c as f,ad as h,bd as i,cd as j,dd as k,ed as l,fd as m,gd as n,hd as o,id as p,jd as q}from"./chunk-ef8rr9eh.js";import"./chunk-wax3nm7t.js";import"./chunk-xjqcc0nt.js";import"./chunk-djh79rde.js";import"./chunk-qw900zg9.js";import"./chunk-gcsygn5a.js";import"./chunk-9ka0bdry.js";import"./chunk-vc2c8wkx.js";import"./chunk-kvd5nexw.js";import"./chunk-8472vz3s.js";import"./chunk-f9tahtz6.js";import"./chunk-gwvds95j.js";import"./chunk-698qsvyb.js";import"./chunk-h0q03x9f.js";import"./chunk-czjbz0fp.js";import"./chunk-c7zk9zj2.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -0,0 +1,100 @@
1
+ import{gc as v,hc as fq,ic as x$,jc as Qq,kc as u,lc as G$,mc as Kq,nc as J$,oc as N$,pc as L$,rc as A0,uc as Z$,vc as Vq}from"./chunk-vypake1a.js";import{wd as Q0}from"./chunk-m27w377p.js";import{$d as K0}from"./chunk-5sw8j9ae.js";import{je as j$}from"./chunk-sr2stcda.js";import{ne as X0}from"./chunk-djh79rde.js";import{lf as Lq,mf as Zq}from"./chunk-vc2c8wkx.js";import{rf as O$}from"./chunk-kvd5nexw.js";import{Af as f0,xf as Z0}from"./chunk-f9tahtz6.js";import{Ef as n}from"./chunk-gwvds95j.js";import{Lf as Nq,Mf as B0,Of as R,Pf as m,Rf as q$,Sf as c,Tf as N0}from"./chunk-czjbz0fp.js";import{readdir as t$,readFile as a,rm as D0,stat as Q1}from"node:fs/promises";import*as F from"node:path";import{nanoid as j}from"nanoid";import{createHash as Uq,randomUUID as zq}from"node:crypto";import*as I from"node:fs/promises";import*as T0 from"node:path";import{execFileSync as Yq}from"node:child_process";import{createHash as Hq}from"node:crypto";import{readFileSync as Xq}from"node:fs";var Oq=/^[a-f0-9]{64}$/;function T$($){if(!$||typeof $!=="object")return!1;let q=$;return(q.platform==="linux"||q.platform==="darwin"||q.platform==="win32")&&typeof q.fingerprint==="string"&&Oq.test(q.fingerprint)}var Wq={readFile:($)=>Xq($,"utf8"),execFile:($,q)=>Yq($,q,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})};function m0($,q){return{platform:$,fingerprint:Hq("sha256").update(`${$}\x00${q}`).digest("hex")}}function _q($,q){let x=q.readFile(`/proc/${$}/stat`).trim(),G=x.lastIndexOf(")");if(G<0)throw Error("Invalid /proc process stat");let J=x.slice(G+2).split(/\s+/)[19];if(!J||!/^\d+$/.test(J))throw Error("Missing process start ticks");return J}function I0($,q=process.platform,x=Wq){if(!Number.isInteger($)||$<=1)return;try{if(q==="linux")return m0(q,_q($,x));if(q==="darwin"){let G=x.execFile("ps",["-o","lstart=","-p",String($)]).trim();return G?m0(q,G):void 0}if(q==="win32"){let G=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,N=x.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",G]).trim();return N?m0(q,N):void 0}}catch{return}return}function Y$($,q){return I0($,q.platform)?.fingerprint===q.fingerprint}var W$=1;function Dq($,q){let x=Uq("sha256").update(q).digest("hex");return T0.join(B0($),".locks",`${x}.lock`)}function F0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function v0($){try{let q=JSON.parse(await I.readFile($,"utf8"));if(q.version!==W$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||q.processIdentity!==void 0&&!T$(q.processIdentity)||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function H$($){let q=await v0($);if(q)return q;return await new Promise((x)=>setTimeout(x,10)),v0($)}function Rq($){try{return process.kill($,0),!0}catch(q){return F0(q,"EPERM")}}async function X$($,q){let x;try{return x=await I.open($,"wx",384),await x.writeFile(`${JSON.stringify(q)}
2
+ `,"utf8"),!0}catch(G){if(F0(G,"EEXIST"))return!1;if(x)await I.unlink($).catch(()=>{return});throw G}finally{await x?.close().catch(()=>{return})}}class p extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). 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 i{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=O$()){let x=Dq(q,$),G={version:W$,sessionId:$,ownerId:zq(),pid:process.pid,processIdentity:I0(process.pid),acquiredAt:new Date().toISOString()};if(await I.mkdir(T0.dirname(x),{recursive:!0,mode:448}),await X$(x,G))return new i(x,G);let N=await H$(x);if(N&&Rq(N.pid)&&(!N.processIdentity||Y$(N.pid,N.processIdentity)))throw new p(N.pid);if(await I.unlink(x).catch((J)=>{if(!F0(J,"ENOENT"))throw J}),await X$(x,G))return new i(x,G);throw new p((await H$(x))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await v0(this.filePath))?.ownerId!==this.record.ownerId)return;await I.unlink(this.filePath).catch((q)=>{if(!F0(q,"ENOENT"))throw q})}}var P1=1;function u0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Aq($){if(!u0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&u0($.image_url)&&typeof $.image_url.url==="string"}function Mq($){if(!u0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(Aq)}function _$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let q=JSON.stringify($);if(Buffer.byteLength(q)>16777216)return;let x=JSON.parse(q);if(!Array.isArray(x)||!x.every(Mq))return;return x}function h1($){let q=_$($);if(!q)throw Error("Compaction replacement context is invalid or exceeds limits");return q}function U$($){return _$($)}function wq($,q){for(let x of $){if(x.type!=="part_created"||x.data.partType!=="tool_result")continue;let G=x.data.payload;if(!G||typeof G!=="object"||Array.isArray(G))continue;let N=G;if(N.toolCallId===q||x.data.partId===q||x.data.messageId===q)return N}return}function z$($){let q=v($),x=new Map;for(let G of q){if(G.type==="interaction_requested"){x.set(G.data.requestId,{request:G.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(G.type==="interaction_responded"){let N=x.get(G.data.requestId);if(N)N.response=G.data;continue}if(G.type==="interaction_recovered"){let N=x.get(G.data.requestId);if(N)N.recovery=G.data}}for(let G of x.values()){let N=wq(q,G.request.toolCallId);G.hasToolResult=N!==void 0;let J=N?.metadata&&typeof N.metadata==="object"?N.metadata:void 0;G.hasRecoveryToolResult=J?.interactionRecovery===!0&&J.requestId===G.request.requestId}return[...x.values()]}function D$($){return z$($).reverse().find((q)=>!q.response&&!q.recovery)}function l1($){let q=new Map;for(let x of z$($))q.set(x.request.toolCallId,x);return[...q.values()].filter((x)=>x.response&&!x.recovery&&(!x.hasToolResult||x.hasRecoveryToolResult))}function R$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function Y0($){let q=new Map,x=[];for(let G of $){if(G.type==="review_started"){if(!q.has(G.data.reviewId))x.push(G.data.reviewId),q.set(G.data.reviewId,{start:G.data});continue}if(G.type!=="review_completed")continue;let N=q.get(G.data.reviewId);if(N&&N.completion===void 0)N.completion=G.data}return x.map((G)=>q.get(G)).filter((G)=>G!==void 0)}function i1($){return Y0($).reverse().find((q)=>q.completion===void 0)}function P0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function A$($,q){let x=["## Code Review","",`Target: ${$.target.label}`,`Status: ${P0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)x.push("","No actionable findings.");else{x.push("","### Findings");for(let[G,N]of q.findings.entries()){let J=N.codeLocation.lineStart===N.codeLocation.lineEnd?`${N.codeLocation.lineStart}`:`${N.codeLocation.lineStart}-${N.codeLocation.lineEnd}`;x.push("",`${G+1}. ${N.title}`,` ${N.codeLocation.path}:L${J} · confidence ${N.confidenceScore.toFixed(2)}`,` ${N.body}`)}}if(q.error)x.push("",`Error: ${q.error}`);return x.join(`
3
+ `)}function M$($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((x)=>({title:x.title,body:x.body,priority:x.priority,confidenceScore:x.confidenceScore,codeLocation:{...x.codeLocation}})),...q.error?{error:q.error}:{}}}var h0={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($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function bq($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";return"runtime"}function gq($){return{code:$,...h0[$]}}function c0($){return gq(bq(Eq($)))}function n0($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in h0))return!1;let x=h0[q.code];return q.message===x.message&&q.retryable===x.retryable}import{promises as x0,realpathSync as yq}from"node:fs";import H0 from"node:path";import*as r from"fs/promises";import*as O from"path";var w$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class l0{static normalize($,q){let x=O.isAbsolute($)?$:O.resolve(q,$),G=O.normalize(x),N=O.normalize(q);if(!this.isWithinWorkspace(G,N))throw new d(`Path outside workspace: ${$} (resolved to ${G}, workspace: ${N})`,"PATH_OUTSIDE_WORKSPACE");return G}static checkRestricted($){let q=$.split(O.sep);for(let x of w$)if(q.includes(x))throw new d(`Access denied: "${x}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let x=this.normalize($,q);this.checkRestricted(x);try{await r.access(x)}catch(G){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return x}static async resolveSymlink($,q){try{let x=await r.realpath($),G=await r.realpath(q);if(!this.isWithinWorkspace(x,G))throw new d(`Symlink points outside workspace: ${$} -> ${x}`,"SYMLINK_OUTSIDE_WORKSPACE");return x}catch(x){if(x instanceof d)throw x;return $}}static getRelativePath($,q){return O.relative(q,$)}static isWithinWorkspace($,q){let x=O.resolve($),G=O.resolve(q),N=O.relative(G,x);return N===""||N!==".."&&!N.startsWith(`..${O.sep}`)&&!O.isAbsolute(N)}static async isWithinWorkspaceResolved($,q){let x=O.resolve(q),G=O.isAbsolute($)?O.resolve($):O.resolve(x,$);if(!this.isWithinWorkspace(G,x))return!1;let N;try{N=await r.realpath(x)}catch{return!1}let J=G;while(!0){try{let Z=await r.realpath(J);return this.isWithinWorkspace(Z,N)}catch(Z){let K=Z.code;if(K!=="ENOENT"&&K!=="ENOTDIR")return!1}let L=O.dirname(J);if(L===J)return!1;J=L}}static isRestricted($){let q=$.split(O.sep);return w$.some((x)=>q.includes(x))}}var G0=X0("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 x=await x0.stat($),G={filePath:H0.resolve($),accessTime:Date.now(),mtime:x.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(G),await this.recordAliases($,G.filePath),G0.debug(`记录文件读取: ${$}`)}catch(x){G0.warn(`记录文件读取失败: ${$}`,x)}}async recordFileEdit($,q,x="edit"){try{let G=await x0.stat($),N={filePath:H0.resolve($),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:q,lastOperation:x};this.setRecord(N),await this.recordAliases($,N.filePath),G0.debug(`记录文件${x==="edit"?"编辑":"写入"}: ${$}`)}catch(G){G0.warn(`记录文件${x==="edit"?"编辑":"写入"}失败: ${$}`,G)}}hasFileBeenRead($,q){let x=this.accessedFiles.get(this.resolveTrackedPath($));if(!x)return!1;return q?x.has(q):x.size>0}async checkFileModification($,q){let x=this.getFileRecord($,q);if(!x)return{modified:!1,message:"文件未被跟踪"};try{let G=await x0.stat($);if(Math.abs(G.mtimeMs-x.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(x.accessTime).toISOString()}, 当前修改时间: ${G.mtime.toISOString()})`};return{modified:!1}}catch(G){let N=G;if(N.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${N.message}`}}}async checkExternalModification($,q){let x=this.getFileRecord($,q);if(!x)return{isExternal:!1,message:"文件未被跟踪"};try{let G=await x0.stat($);if(G.mtimeMs-x.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(x.accessTime).toISOString()} (${x.lastOperation}) 之后被外部程序修改(当前修改时间: ${G.mtime.toISOString()})`};return{isExternal:!1}}catch(G){let N=G;if(N.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return G0.warn(`检查文件外部修改失败: ${$}`,G),{isExternal:!1,message:`无法检查文件状态: ${N.message}`}}}getFileRecord($,q){let x=this.accessedFiles.get(this.resolveTrackedPath($));if(!x)return;if(q)return x.get(q);return[...x.values()].sort((G,N)=>N.accessTime-G.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let x=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(x),this.removeAliases(x);return}let G=this.accessedFiles.get(x);if(G?.delete(q),G?.size===0)this.accessedFiles.delete(x),this.removeAliases(x)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[x,G]of this.accessedFiles.entries()){if(q&&!l0.isWithinWorkspace(x,q))continue;if(G.delete($),G.size===0)this.accessedFiles.delete(x),this.removeAliases(x)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){h.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(H0.resolve($),q);let x=await x0.realpath($).catch(()=>{return});if(x)this.pathAliases.set(x,q)}resolveTrackedPath($){let q=H0.resolve($);if(this.accessedFiles.has(q))return q;let x=this.pathAliases.get(q);if(x)return x;try{let G=yq.native(q);return this.pathAliases.get(G)??G}catch{return q}}removeAliases($){for(let[q,x]of this.pathAliases)if(x===$)this.pathAliases.delete(q)}}import*as J0 from"node:crypto";import{promises as T}from"node:fs";import*as H from"node:path";import p0 from"write-file-atomic";var E$="missing";class O0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(R($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!H.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?H.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=N0();this.snapshotDir=H.join(q,"file-history",this.sessionId),this.manifestPath=H.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await T.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=N0(),q=await T.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),x=J0.createHash("sha256").update(q).digest("hex").slice(0,24),G=H.join($,"file-history",this.sessionId),N=H.join($,"file-history","workspaces",x,this.sessionId),J=H.join(N,"manifest.json");try{await T.access(J)}catch{await this.migrateLegacySnapshotDir(G,N,q)}this.snapshotDir=N,this.manifestPath=J}async migrateLegacySnapshotDir($,q,x){let G;try{G=JSON.parse(await T.readFile(H.join($,"manifest.json"),"utf8"))}catch{return}if(G.schemaVersion!==1||!Array.isArray(G.snapshots)||!G.snapshots.every((N)=>this.isWithinWorkspace(N.filePath,x)))return;await T.mkdir(H.dirname(q),{recursive:!0,mode:493});try{await T.rename($,q)}catch(N){let J=N.code;if(J!=="ENOENT"&&J!=="EEXIST"&&J!=="ENOTEMPTY")throw N}}isWithinWorkspace($,q){if(!H.isAbsolute($))return!1;let x=H.relative(q,H.resolve($));return x===""||x!==".."&&!x.startsWith(`..${H.sep}`)&&!H.isAbsolute(x)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let x=await this.resolveFileIdentity($),G=!0;try{await T.access(x)}catch{G=!1}let N=this.trackedFileBackups.get(x),J=N?N.version+1:1,L=this.generateFileHash(x,J),Z=this.getSnapshotPath(L,J),K=new Date;if(G){let Q=await T.readFile(x);await T.writeFile(Z,Q)}let f={backupFileName:L,version:J,backupTime:K};return this.trackedFileBackups.set(x,f),this.snapshots.push({messageId:q,backupFileName:L,timestamp:K,filePath:x,version:J,existedBefore:G}),await this.cleanupOldSnapshots(x),await this.persistManifest(),f}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let x=await this.resolveFileIdentity($),G=this.snapshots.find((N)=>N.filePath===x&&N.backupFileName===q.backupFileName&&N.version===q.version);if(!G)throw Error(`未找到待完成的快照: ${x}`);G.postEditHash=await this.hashFile(x),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let x=await this.resolveFileIdentity($),G=this.snapshots.find((N)=>N.filePath===x&&N.backupFileName===q.backupFileName&&N.version===q.version);if(!G)return;this.removeSnapshot(G),await T.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),x=this.snapshots.slice().reverse().find((J)=>J.filePath===q&&J.postEditHash!==void 0);if(!x?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==x.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let N=this.getSnapshotPath(x.backupFileName,x.version);if(x.existedBefore){let J=await T.readFile(N);await T.mkdir(H.dirname(q),{recursive:!0}),await T.writeFile(q,J)}else await T.rm(q,{force:!0});return this.removeSnapshot(x),await T.rm(N,{force:!0}),await this.persistManifest(),x}async restoreSnapshot($,q){let x=await this.resolveFileIdentity($),G=this.snapshots.slice().reverse().find((J)=>J.messageId===q&&J.filePath===x);if(!G)throw Error(`未找到快照: messageId=${q}, filePath=${x}`);let N=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let J=await T.readFile(N);await T.mkdir(H.dirname(x),{recursive:!0}),await T.writeFile(x,J)}else await T.rm(x,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((x)=>x.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((x)=>x.filePath),snapshotCount:q.reduce((x,G)=>x+G.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let x=new Map;for(let N of q){let J,L=!0;try{J=await T.readFile(N.filePath)}catch(K){if(K.code!=="ENOENT")throw K;L=!1}if((J?J0.createHash("sha256").update(J).digest("hex"):E$)!==N.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${N.filePath}`);if(x.set(N.filePath,{existed:L,content:J}),N.target.existedBefore)await T.access(this.getSnapshotPath(N.target.backupFileName,N.target.version))}let G=[...this.snapshots];try{for(let J of q)if(J.target.existedBefore){let L=await T.readFile(this.getSnapshotPath(J.target.backupFileName,J.target.version));await T.mkdir(H.dirname(J.filePath),{recursive:!0}),await p0(J.filePath,L)}else await T.rm(J.filePath,{force:!0});let N=new Set(q.flatMap((J)=>J.selected));this.snapshots=this.snapshots.filter((J)=>!N.has(J)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...N].map((J)=>T.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return})))}catch(N){this.snapshots=G,this.rebuildTrackedFileBackups();let J=[];for(let[L,Z]of x)try{if(Z.existed&&Z.content)await p0(L,Z.content);else await T.rm(L,{force:!0})}catch(K){J.push(K)}if(J.length>0)throw AggregateError([N,...J],"快照回退失败且无法完整恢复回退前状态");throw N}return{files:q.map((N)=>N.filePath),snapshotCount:q.reduce((N,J)=>N+J.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),x=new Set(q.flatMap((N)=>N.selected));if(x.size===0)return{files:[],snapshotCount:0};let G=[...this.snapshots];this.snapshots=this.snapshots.filter((N)=>!x.has(N)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(N){throw this.snapshots=G,this.rebuildTrackedFileBackups(),N}return await Promise.all([...x].map((N)=>T.rm(this.getSnapshotPath(N.backupFileName,N.version),{force:!0}).catch(()=>{return}))),{files:q.map((N)=>N.filePath),snapshotCount:x.size}}buildRewindPlan($){let q=new Set($),x=this.snapshots.filter((J)=>J.postEditHash!==void 0),G=x.filter((J)=>q.has(J.messageId));return[...new Set(G.map((J)=>J.filePath))].sort().map((J)=>{let L=x.filter((Q)=>Q.filePath===J),Z=L.filter((Q)=>q.has(Q.messageId)),K=L.indexOf(Z[0]),f=L.slice(K);if(f.length!==Z.length||f.some((Q)=>!q.has(Q.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${J}`);return{filePath:J,selected:Z,target:Z[0],latest:Z.at(-1)}})}async loadManifest(){try{let $=await T.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(x)=>({...x,filePath:await this.resolveFileIdentity(x.filePath),timestamp:new Date(x.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await T.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await p0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let x=this.snapshots.filter((G)=>G.filePath===$).slice(0,-this.maxSnapshots);for(let G of x)await T.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}),this.removeSnapshot(G)}async cleanup($=0){let q=this.snapshots.slice().sort((G,N)=>N.timestamp.getTime()-G.timestamp.getTime()),x=new Set(q.slice(0,$));for(let G of this.snapshots)if(!x.has(G))await T.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return H.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=H.resolve($),x=[],G=q;while(!0){try{let J=await T.realpath(G);return H.join(J,...x.reverse())}catch(J){let L=J.code;if(L!=="ENOENT"&&L!=="ENOTDIR")throw J}let N=H.dirname(G);if(N===G)return q;x.push(H.basename(G)),G=N}}async hashFile($){try{let q=await T.readFile($);return J0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return E$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let x=J0.createHash("md5");return x.update(`${$}:${q}`),x.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 iq}from"node:crypto";import v$ from"node:path";import{StringDecoder as Iq}from"node:string_decoder";function Sq($,q){let x=q;while(x<$.length&&($[x]&192)===128)x+=1;return x}class i0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?Buffer.from($):Buffer.from($);if(q.length===0)return;this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),omittedBytes:this.omittedBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}trimToLimit(){while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let q=this.retainedBytes-this.maxBytes;if($.length<=q){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length;continue}let x=Sq($,q);this.chunks[0]=$.subarray(x),this.retainedBytes-=x,this.omittedBytes+=x}}}var W0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},o={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},b$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},jq={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},mq=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:W0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:W0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:o,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:b$},{pattern:/^git\s+(status|branch|remote)/i,config:o},{pattern:/^git\s+(log|diff|show)/i,config:b$},{pattern:/^(ls|dir|tree)\s+/i,config:o,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:o,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:o,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:W0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:W0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:o,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:o,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class d0{static getConfigForCommand($){for(let{pattern:q,config:x,summaryTemplate:G}of mq)if(q.test($))return{config:x,summaryTemplate:G};return{config:jq}}static truncate($,q){let{config:x,summaryTemplate:G}=this.getConfigForCommand(q);return this.truncateWithConfig($,x,G)}static truncateWithConfig($,q,x){let G=$.length,N=$.split(`
4
+ `),J=N.length;if(J<=q.maxLines&&G<=q.maxChars)return{content:$,truncated:!1,originalLines:J,originalChars:G};let L=N.slice(0,q.keepHead),Z=N.slice(-q.keepTail),K=J-q.keepHead-q.keepTail,f=L.join(`
5
+ `);if(f+=`
6
+
7
+ ... (${K} lines truncated, showing first ${q.keepHead} and last ${q.keepTail} of ${J} total) ...
8
+
9
+ `,f+=Z.join(`
10
+ `),f.length>q.maxChars){let V=Math.floor(q.maxChars/2)-50,C=f.slice(0,V),B=f.slice(-V);f=`${C}
11
+
12
+ ... (content truncated to ${q.maxChars} chars) ...
13
+
14
+ ${B}`}let Q=q.summarize&&x?x(J,G):void 0;if(Q)f+=`
15
+
16
+ [Summary: ${Q}]`;return{content:f,truncated:!0,originalLines:J,originalChars:G,summary:Q}}static truncateForLLM($,q,x){let G=this.truncate($,x),N=this.truncate(q,x),J;if(G.truncated||N.truncated){let L=[];if(G.truncated)L.push(`stdout: ${G.originalLines} lines -> ${G.content.split(`
17
+ `).length} lines`);if(N.truncated)L.push(`stderr: ${N.originalLines} lines -> ${N.content.split(`
18
+ `).length} lines`);J=`Output truncated: ${L.join(", ")}`}return{stdout:G.content,stderr:N.content,truncationInfo:J}}static shouldTruncate($,q){let{config:x}=this.getConfigForCommand(q);return $.split(`
19
+ `).length>x.maxLines||$.length>x.maxChars}static getStats($){return{lines:$.split(`
20
+ `).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var g$=32768,vq=1048576,uq=65536,Pq=3600000,k$=4096,hq=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;class r0{stream;executionId;onEvent;output=new i0(vq/2);decoder=new Iq("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor($,q,x){this.stream=$;this.executionId=q;this.onEvent=x}append($){let q=Buffer.isBuffer($)?$:Buffer.from($);if(q.length===0)return;if(this.totalBytes+=q.length,this.sniffBytes<k$){let G=q.subarray(0,Math.min(q.length,k$-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 x=y$(this.decoder.write(q));this.output.append(x),this.emit(x)}finish(){if(this.binary)return;let $=y$(this.decoder.end());this.output.append($),this.emit($)}snapshot(){let $=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:$.content,omittedBytes:$.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit($){if(!$||!this.onEvent||this.streamTruncated)return;let q=uq-this.streamedBytes;if(q<=0){this.streamTruncated=!0;return}let x=cq($,q);if(this.streamedBytes+=Buffer.byteLength(x),x.length<$.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:x,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function y$($){return $.replace(hq,"")}function cq($,q){let x=Buffer.from($);if(x.length<=q)return $;let G=q;while(G>0&&(x[G]&192)===128)G-=1;return x.subarray(0,G).toString("utf8")}function S$($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function nq($){let q=$.trim();if(!q)throw Error("User shell command cannot be empty");if(q.length>g$)throw Error(`User shell command exceeds ${g$} characters`);if(q.includes("\x00"))throw Error("User shell command contains a null byte");return q}function lq(){return{execute($,q){return new Promise((x)=>{let G=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",N=process.platform==="win32"?["/d","/s","/c",$]:["-l","-c",$],{child:J,processTree:L}=j$(G,N,{cwd:q.cwd,env:q.env,stdio:["ignore","pipe","pipe"]}),Z="",K="",f=!1,Q=!1,V=!1,C,B=()=>{return C??=L.terminate(),C},E=setTimeout(()=>{f=!0,B()},q.timeoutMs),M=()=>{Q=!0,B()};if(q.signal.addEventListener("abort",M,{once:!0}),q.signal.aborted)M();J.stdout?.on("data",(_)=>{q.onOutput?.("stdout",_)}),J.stderr?.on("data",(_)=>{q.onOutput?.("stderr",_)});let b=async(_)=>{if(V)return;if(V=!0,clearTimeout(E),q.signal.removeEventListener("abort",M),f||Q)await B();x({..._,stdout:"",stderr:"",timedOut:f,aborted:Q})};J.once("error",(_)=>{b({exitCode:null,error:_.message})}),J.once("close",(_)=>{b({exitCode:_})})})}}}async function V2($,q){let x=nq($),G=q.timeoutMs??Pq,N=new r0("stdout",q.executionId,q.onEvent),J=new r0("stderr",q.executionId,q.onEvent),L=Date.now();await q.onEvent?.({type:"started",executionId:q.executionId,command:x});let Z,K=!1,f=!1;try{Z=await(q.executor??lq()).execute(x,{cwd:q.cwd,env:q.env,timeoutMs:G,signal:q.signal,onOutput:(M,b)=>{if(M==="stdout")K=!0;else f=!0;(M==="stdout"?N:J).append(b)}})}catch(M){Z={exitCode:null,stdout:"",stderr:"",error:M instanceof Error?M.message:String(M)}}if(!K)N.append(Z.stdout);if(!f)J.append(Z.stderr);N.finish(),J.finish(),await Promise.all([N.flushEvents(),J.flushEvents()]);let Q=N.snapshot(),V=J.snapshot(),C=d0.truncateForLLM(Q.content.trim(),V.content.trim(),x),B=Z.aborted||q.signal.aborted?"aborted":Z.timedOut?"timed_out":Z.error?"spawn_error":Z.exitCode===0?"completed":"failed",E={version:1,command:x,status:B,exitCode:Z.exitCode,durationMs:Math.max(0,Date.now()-L),stdout:C.stdout,stderr:Z.error?[C.stderr,Z.error].filter(Boolean).join(`
21
+ `):C.stderr,stdoutOmittedBytes:Q.omittedBytes,stderrOmittedBytes:V.omittedBytes,binaryOutput:Q.binary||V.binary,truncated:Boolean(C.truncationInfo)||Q.omittedBytes>0||V.omittedBytes>0};return await q.onEvent?.({type:"completed",executionId:q.executionId,record:E}),E}function C2($){let q=[$.stdout?`stdout:
22
+ ${$.stdout}`:"",$.stderr?`stderr:
23
+ ${$.stderr}`:""].filter(Boolean).join(`
24
+ `);return["<user_shell_command>",`<command>${S$($.command)}</command>`,"<result>",`Status: ${$.status}`,`Exit code: ${$.exitCode??"null"}`,`Duration: ${($.durationMs/1000).toFixed(3)} seconds`,`Output:
25
+ ${S$(q||"(no output)")}`,"</result>","</user_shell_command>"].join(`
26
+ `)}function m$($){let q=[$.stdout,$.stderr?`stderr:
27
+ ${$.stderr}`:""].filter(Boolean).join(`
28
+ `);return[`! ${$.command}`,q||"(no output)"].join(`
29
+ `)}function pq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(q.version!==1||typeof q.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String(q.status))||q.exitCode!==null&&typeof q.exitCode!=="number"||typeof q.durationMs!=="number"||typeof q.stdout!=="string"||typeof q.stderr!=="string"||typeof q.stdoutOmittedBytes!=="number"||typeof q.stderrOmittedBytes!=="number"||typeof q.binaryOutput!=="boolean"||typeof q.truncated!=="boolean")return;return q}function _0($){if(!$||typeof $!=="object"||Array.isArray($))return;return pq($.userShellCommand)}var U0=16777216,I$=65536,X2=1048576,dq=8,z0=200,rq=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,oq=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,tq=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,aq=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),sq=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function k($,q){return $.count+=1,q}function eq($){return rq.test($.replace(/[A-Z]/g,(q)=>`_${q.toLowerCase()}`))}function $1($){return[...$].filter((q)=>{if(q===`
30
+ `||q==="\r"||q==="\t")return!0;let x=q.codePointAt(0)??0;if(x<32||x===127)return!1;if(x>=57344&&x<=63743)return!1;if(x>=983040&&x<=1048573)return!1;if(x>=1048576&&x<=1114109)return!1;if(x>=917504&&x<=917631)return!1;return!/[\p{Cf}\p{Cn}]/u.test(q)}).join("")}function g($,q){let x=$.normalize("NFKC"),G=x.replace(aq,"");if(G!==x)q.count+=1;x=G,x=x.replace(sq,()=>k(q,"[redacted-private-key]")),x=x.replace(/\bBearer\s+[^\s"'`]+/gi,()=>k(q,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>k(q,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>k(q,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(J,L,Z)=>`${L}${Z}${k(q,"[redacted]")}`);let N=$1(x);if(N!==x)q.count+=1;return N.replace(/\r\n?/g,`
31
+ `)}function u$($,q,x){if(/^data:[^;,]+;base64,/i.test($))return k(x,"[binary omitted]");let G=g($,x),N=v$.resolve(q);for(let J of[N,N.startsWith("/private/")?N.slice(8):`/private${N}`])G=G.replaceAll(J,".");return G=G.replace(oq,(J)=>J.startsWith("./")?J:k(x,"[host-path]")),G=G.replace(tq,()=>k(x,"[host-path]")),G=G.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(J)=>{try{let L=new URL(J);if(L.username||L.password||L.search||L.hash)x.count+=1;return L.username="",L.password="",L.search="",L.hash="",L.toString()}catch{return k(x,"[redacted-url]")}}),G}function a0($,q,x,G=0,N){if(N&&eq(N))return k(x,"[redacted]");if(G>=dq)return k(x,"[depth limit]");if(typeof $==="string")return u$($,q,x);if($===null||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return $;if(Array.isArray($)){let J=$.slice(0,z0).map((L)=>a0(L,q,x,G+1));if($.length>J.length)J.push(k(x,`[${$.length-J.length} items omitted]`));return J}if($&&typeof $==="object"){let J={},L=Object.entries($);for(let[Z,K]of L.slice(0,z0))J[g(Z,x)]=a0(K,q,x,G+1,Z);if(L.length>z0)J["[entries omitted]"]=L.length-z0;return J}return String($)}function q1($,q){let x=Buffer.from($,"utf8");if(x.length<=q)return $;let G=x.subarray(0,q).toString("utf8");while(Buffer.byteLength(G,"utf8")>q)G=G.slice(0,-1);return G}function x1($,q,x){let G=JSON.stringify(a0($,q,x),null,2);if(Buffer.byteLength(G,"utf8")<=I$)return G;x.count+=1;let N=`
32
+ ... [activity truncated]`;return q1(G,I$-Buffer.byteLength(N))+N}function s0($,q=""){let x=Math.max(2,...[...$.matchAll(/`+/g)].map((N)=>N[0].length)),G="`".repeat(x+1);return`${G}${q}
33
+ ${$}
34
+ ${G}`}function o0($){return $.replace(/\s+/g," ").trim()}function G1($){let q=new Map,x=new Map,G=new Map,N=0;for(let J of v($)){if(J.type==="message_created"){let Q=x.get(J.data.messageId);if(Q)Q.role=J.data.role,Q.metadata=J.data.metadata,q.set(J.data.messageId,Q),x.delete(J.data.messageId);else if(!q.has(J.data.messageId))q.set(J.data.messageId,{order:N++,role:J.data.role,parts:[],metadata:J.data.metadata});continue}if(J.type!=="part_created"&&J.type!=="part_updated")continue;let L=q.get(J.data.messageId)??x.get(J.data.messageId);if(!L)L={order:N++,role:"activity",parts:[]},x.set(J.data.messageId,L);let Z=`${J.data.messageId}\x00${J.data.partType}\x00${J.data.partId}`,K=G.get(Z);if(K){K.event=J;continue}let f={order:N++,event:J};G.set(Z,f),L.parts.push(f)}return[...q.values(),...x.values()].sort((J,L)=>J.order-L.order)}function t0($,q,x,G){return`## Activity: ${$}
35
+
36
+ ${s0(x1(q,x.projectPath,G),"json")}`}function P$($,q,x={}){let G={count:0},N=x.includeReasoning===!0,J=[],L=0,Z=0,K=0;for(let b of G1($)){let _=_0(b.metadata);if(_){let D=g(_.command,G),z=g([_.stdout,_.stderr?`stderr:
37
+ ${_.stderr}`:""].filter(Boolean).join(`
38
+ `)||"(no output)",G);J.push(`## User shell command
39
+
40
+ ${s0(`$ ${D}
41
+ ${z}`,"console")}`),L+=1;continue}let s=[],e=[],y=[],S=Number.POSITIVE_INFINITY;for(let D of b.parts.sort((z,A)=>z.order-A.order)){let{partType:z,payload:A}=D.event.data;if(z==="text"){let Y=A.text;if(typeof Y==="string"&&Y.trim())s.push(g(Y,G)),S=Math.min(S,D.order)}else if(z==="image"){let Y=A.mimeType;e.push(typeof Y==="string"?`[Image: ${g(Y,G)}]`:"[Image]"),S=Math.min(S,D.order)}else if(z==="reasoning"&&N){let Y=A.text;if(typeof Y==="string"&&Y.trim())y.push({order:D.order,markdown:`## Reasoning
42
+
43
+ ${g(Y,G).trim()}`}),K+=1}else if(z==="tool_call"){let Y=A,w=typeof Y.toolName==="string"?g(Y.toolName,G):"unknown";y.push({order:D.order,markdown:t0(`${w} call`,Y.input??{},q,G)}),Z+=1}else if(z==="tool_result"){let Y=A,w=typeof Y.toolName==="string"?g(Y.toolName,G):"unknown";y.push({order:D.order,markdown:t0(`${w} result`,typeof Y.error==="string"?{error:Y.error}:{output:Y.output??null},q,G)}),Z+=1}else if(z==="summary"){let Y=A.text;if(typeof Y==="string"&&Y.trim())y.push({order:D.order,markdown:`## Summary
44
+
45
+ ${g(Y,G).trim()}`})}else if(z==="subtask_ref")y.push({order:D.order,markdown:t0("Subagent",A,q,G)}),Z+=1;else if(z==="diff"||z==="patch"){let Y=typeof A==="string"?A:JSON.stringify(A,null,2);y.push({order:D.order,markdown:`## File changes
46
+
47
+ ${s0(u$(Y,q.projectPath,G),"diff")}`}),Z+=1}}if((b.role==="user"||b.role==="assistant")&&(s.length>0||e.length>0))y.push({order:S,markdown:`## ${b.role==="user"?"User":"Assistant"}
48
+
49
+ ${[...s,...e].join(`
50
+
51
+ `).trim()}`}),L+=1;J.push(...y.sort((D,z)=>D.order-z.order).map((D)=>D.markdown))}if(J.length===0)throw Error("No conversation content to export");let f=`${J.join(`
52
+
53
+ `)}
54
+ `,Q=Buffer.byteLength(f,"utf8");if(Q>U0)throw Error(`Session export exceeds ${U0} bytes`);let V=iq("sha256").update(f).digest("hex"),C=v$.basename(q.taskSourceProjectPath??q.projectPath),B=q.selectedModelId??q.taskModelId,M=["# Blade conversation","",`- Session: \`${q.sessionId}\``,...q.title?[`- Title: ${o0(g(q.title,G))}`]:[],`- Project: \`${o0(g(C,G))}\``,...B?[`- Model: \`${o0(g(B,G))}\``]:[],...q.permissionMode?[`- Permission mode: ${q.permissionMode}`]:[],`- Created: ${q.firstMessageTime}`,`- Updated: ${q.lastMessageTime}`,`- State: ${q.archivedAt?"archived":"active"}`,`- Reasoning: ${N?"included":"omitted"}`,...q.reasoningEffort?[`- Reasoning effort: ${q.reasoningEffort}`]:[],...q.serviceTier?[`- Service tier: ${q.serviceTier}`]:[],...q.responseVerbosity?[`- Response verbosity: ${q.responseVerbosity}`]:[],...q.communicationStyle?[`- Communication style: ${q.communicationStyle}`]:[],...q.communicationStyleDigest?[`- Communication style SHA-256: \`${q.communicationStyleDigest}\``]:[],...q.projectInstructionsDigest?[`- Project instructions SHA-256: \`${q.projectInstructionsDigest}\``]:[],`- Content SHA-256: \`${V}\``,`- Content bytes: ${Q}`,`- Redactions: ${G.count}`,"","---",""].join(`
55
+ `)+`
56
+ `+f;if(Buffer.byteLength(M,"utf8")>U0)throw Error(`Session export exceeds ${U0} bytes`);return{filename:`blade-session-${q.sessionId.slice(0,12)}.md`,markdown:M,contentSha256:V,contentBytes:Q,messageCount:L,activityCount:Z,reasoningIncluded:N,reasoningCount:K,redactionCount:G.count}}import{createHash as J1}from"node:crypto";import N1 from"ajv";var r$="StructuredOutput",h$=65536,c$=131072,U2=2,n$=20,l$=1000,p$=200;function t($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function i$($,q){if(!t($))throw Error(`${q} must be a JSON object`);let x;try{x=JSON.stringify($)}catch(N){throw Error(`${q} must be JSON-serializable`,{cause:N})}if(x===void 0)throw Error(`${q} must be JSON-serializable`);let G=JSON.parse(x);if(!t(G))throw Error(`${q} must be a JSON object`);return G}function L1($){let q=0,x=0,G=(N,J)=>{if(q++,q>l$)throw Error(`Output schema exceeds the ${l$} node complexity limit`);if(J>n$)throw Error(`Output schema exceeds the ${n$} level depth limit`);if(Array.isArray(N)){for(let L of N)G(L,J+1);return}if(!t(N))return;if("$ref"in N){let L=N.$ref;if(typeof L!=="string"||!(L==="#"||L.startsWith("#/$defs/")||L.startsWith("#/definitions/")))throw Error("Output schema only supports self-contained local $ref values")}if("properties"in N&&t(N.properties)){if(x+=Object.keys(N.properties).length,x>p$)throw Error(`Output schema exceeds the ${p$} property limit`)}for(let L of Object.values(N))G(L,J+1)};G($,0)}function Z1($){if(!$||$.length===0)return"Structured output does not match the requested schema";return $.slice(0,8).map((q)=>{return`${q.instancePath||"root"}: ${q.message??q.keyword}`}).join("; ")}function f1($){let q=new N1({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return q.compile($)}catch(x){throw Error(`Invalid output schema: ${x instanceof Error?x.message:String(x)}`)}}function o$($){let q=i$($,"Output schema"),x=JSON.stringify(q);if(Buffer.byteLength(x)>h$)throw Error(`Output schema exceeds ${h$} bytes`);if(q.type!=="object")throw Error('Output schema root type must be "object"');L1(q);let N=f1(q),J=J1("sha256").update(x).digest("hex");return{schema:q,schemaDigest:J,declaration:{name:r$,description:"Submit the final response as an object matching the requested JSON Schema. Call this exactly once after all requested work and verification are complete.",parameters:q,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(L){let Z;try{Z=i$(L,"Structured output")}catch(f){return{success:!1,message:f instanceof Error?f.message:String(f)}}let K=JSON.stringify(Z);if(Buffer.byteLength(K)>c$)return{success:!1,message:`Structured output exceeds ${c$} bytes`};if(!N(Z))return{success:!1,message:Z1(N.errors)};return{success:!0,output:Z}}}}function d$($,q){if(!t($))return;let x=t($.structuredOutput)?$.structuredOutput:$;if(x.schemaDigest!==q.schemaDigest||!("output"in x))return;let G=q.validate(x.output);return G.success?G.output:void 0}function z2($,q){for(let x=$.length-1;x>=0;x--){let G=$[x];if(!G)continue;if(G.role==="user")return;if(G.role==="assistant"){let L=d$(G.metadata,q);if(L)return{output:L,completed:!0};continue}if(G.role!=="tool"||G.name!==r$)continue;let N=t(G.metadata)?G.metadata:void 0,J=d$(N?.metadata,q);if(J)return{output:J,completed:!1}}return}var R0=X0("Service"),a$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),f$=new Set(["local","worktree"]),K1=new Set(["default","autoEdit","yolo","plan"]),V1=new Set(["applied","discarded","conflicted"]);class Q$ extends Error{}function s$($){try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}}function e$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["sessionId","name","branch","baseCommit","originalBranch","repositoryRoot","originalWorkspaceRoot","worktreeRoot","workspaceRoot"].some((G)=>typeof q[G]!=="string"||!q[G])||typeof q.sourceHadChanges!=="boolean"||q.sourceStateFingerprint!==void 0&&(typeof q.sourceStateFingerprint!=="string"||!/^[a-f0-9]{64}$/.test(q.sourceStateFingerprint)))return;return q}function $q($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(!V1.has(String(q.status))||typeof q.updatedAt!=="string"||!Number.isFinite(Date.parse(q.updatedAt))||q.sourceCommit!==void 0&&(typeof q.sourceCommit!=="string"||!/^[a-f0-9]{40,64}$/.test(q.sourceCommit))||q.changedFiles!==void 0&&(typeof q.changedFiles!=="number"||!Number.isInteger(q.changedFiles)||q.changedFiles<0)||q.message!==void 0&&(typeof q.message!=="string"||!q.message.trim()||q.message.length>500))return;return{status:q.status,updatedAt:q.updatedAt,...typeof q.sourceCommit==="string"?{sourceCommit:q.sourceCommit}:{},...typeof q.changedFiles==="number"?{changedFiles:q.changedFiles}:{},...typeof q.message==="string"?{message:q.message}:{}}}function qq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["changedFiles","additions","deletions","commits"].some((G)=>typeof q[G]!=="number"||!Number.isInteger(q[G])||q[G]<0))return;return q}function xq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$,x;if(q.outputSchema!==void 0)try{x=o$(q.outputSchema).schema}catch{return}if(q.version!==1||typeof q.prompt!=="string"||!q.prompt.trim()||q.prompt.length>32000||typeof q.sourceProjectPath!=="string"||!F.isAbsolute(q.sourceProjectPath)||!f$.has(q.isolation)||!M0(q.permissionMode)||q.title!==void 0&&(typeof q.title!=="string"||!q.title.trim()||q.title.length>200)||q.modelId!==void 0&&(typeof q.modelId!=="string"||!q.modelId.trim()||q.modelId.length>500)||q.reasoningEffort!==void 0&&!Q0(q.reasoningEffort)||q.serviceTier!==void 0&&!f0(q.serviceTier)||q.responseVerbosity!==void 0&&!Z0(q.responseVerbosity)||q.communicationStyle!==void 0&&!K0(q.communicationStyle)||q.communicationStyleDigest!==void 0&&(typeof q.communicationStyleDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.communicationStyleDigest))||q.projectInstructionsDigest!==void 0&&(typeof q.projectInstructionsDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.projectInstructionsDigest)))return;let G;if(q.attachments!==void 0){if(!Array.isArray(q.attachments)||q.attachments.length>Lq)return;let N=0;for(let J of q.attachments){if(!J||typeof J!=="object"||Array.isArray(J))return;let L=J;if(!["file","image","url"].includes(String(L.type)))return;for(let Z of["path","url","content","mimeType","name"])if(L[Z]!==void 0&&typeof L[Z]!=="string")return;N+=typeof L.content==="string"?Buffer.byteLength(L.content):0}if(N>Zq)return;G=q.attachments.map((J)=>{let L=J;return{type:L.type,...L.path!==void 0?{path:L.path}:{},...L.url!==void 0?{url:L.url}:{},...L.content!==void 0?{content:L.content}:{},...L.mimeType!==void 0?{mimeType:L.mimeType}:{},...L.name!==void 0?{name:L.name}:{}}})}return{version:1,prompt:q.prompt,...typeof q.title==="string"?{title:q.title}:{},sourceProjectPath:F.resolve(q.sourceProjectPath),isolation:q.isolation,permissionMode:q.permissionMode,...typeof q.modelId==="string"?{modelId:q.modelId}:{},...Q0(q.reasoningEffort)?{reasoningEffort:q.reasoningEffort}:{},...f0(q.serviceTier)?{serviceTier:q.serviceTier}:{},...Z0(q.responseVerbosity)?{responseVerbosity:q.responseVerbosity}:{},...K0(q.communicationStyle)?{communicationStyle:q.communicationStyle}:{},...typeof q.communicationStyleDigest==="string"?{communicationStyleDigest:q.communicationStyleDigest}:{},...typeof q.projectInstructionsDigest==="string"?{projectInstructionsDigest:q.projectInstructionsDigest}:{},...G?{attachments:G}:{},...x?{outputSchema:x}:{}}}function M0($){return typeof $==="string"&&K1.has($)}function Gq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(typeof q.sessionId!=="string"||!q.sessionId||typeof q.projectPath!=="string"||!F.isAbsolute(q.projectPath))return;return{sessionId:q.sessionId,projectPath:F.resolve(q.projectPath)}}var Cq={stat($){return Q1($,{bigint:!0})},readFile($){return a($,"utf-8")}},L0=Cq;function o2($){L0=$}function t2(){L0=Cq}class Fq extends Error{constructor($){super(`Session has no durable creation record: ${$}`);this.name="SessionMissingCreationError"}}class $0 extends Error{sessionId;archivedBySessionId;code="BLADE_SESSION_ARCHIVED";constructor($,q){super($===q?`Session is archived: ${$}`:`Session is archived by ancestor ${q}: ${$}`);this.sessionId=$;this.archivedBySessionId=q;this.name="SessionArchivedError"}}class P extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor($){super($);this.name="SessionArchiveConflictError"}}function e0($,q){return`${$}\x00${q}`}function C1($){if($.kind==="base")return`/review base ${$.baseSha??$.label}`;if($.kind==="commit")return`/review commit ${$.commitSha??$.label}`;return"/review uncommitted"}function Bq($){return typeof $==="string"&&$.length<=64&&Number.isFinite(Date.parse($))}function F1($){let q=new Map($.map((x)=>[e0(x.projectPath,x.sessionId),x]));return $.map((x)=>{let G=x,N=new Set;while(G){let K=e0(G.projectPath,G.sessionId);if(N.has(K))break;if(N.add(K),Bq(G.archivedAt))return{...x,archivedAt:G.archivedAt,archivedBySessionId:G.sessionId};G=G.parentId?q.get(e0(G.projectPath,G.parentId)):void 0}let{archivedAt:J,archivedBySessionId:L,...Z}=x;return Z})}function $$($,q){let x=F1($);if(q===null)return x;return x.filter((G)=>Boolean(G.archivedAt)===q)}class X{static toUISafeMessages($){let q=Date.now(),x=$.length,G=[];return $.forEach((N,J)=>{if(N.role!=="user"&&N.role!=="assistant")return;let L;if(typeof N.content==="string")L=N.content;else if(Array.isArray(N.content))L=N.content.map((V)=>V.type==="text"?V.text:"[Image]").join("");else L="";let Z=L.trim();if(!Z)return;let K=_0(N.metadata),f=K?m$(K):Z,Q=G[G.length-1];if(Q&&Q.role===N.role&&Q.content===f)return;G.push({id:`restored-${q}-${J}`,role:N.role,content:f,timestamp:q-(x-J)*1000,metadata:N.metadata&&typeof N.metadata==="object"?N.metadata:void 0})}),G}static async listSessionPage($={}){let q=J$($),x=await this.listSessionPageFromProjection(q);if(x)return x;let N=(await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,q.cursor?5000:0,q.archived)).sort(N$),J=L$(N,q);return{sessions:J.sessions.map((L)=>this.toPublicMetadata(L)),nextCursor:J.nextCursor}}static async listSessionPageFromProjection($){let q=Kq($);try{let x=await A0();if(!x)return null;await Z$(x,this.projectionDeriver(),$.cursor?5000:0);let G=[],N=[];if($.cwd)G.push("s.project_path = ?"),N.push($.cwd);if(!$.includeSubagents)G.push("s.is_subagent = 0");if(G.push($.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"),q){G.push(`(
57
+ s.last_message_time < ?
58
+ OR (
59
+ s.last_message_time = ?
60
+ AND (
61
+ s.project_sort_key > ?
62
+ OR (s.project_sort_key = ? AND s.session_sort_key > ?)
63
+ )
64
+ )
65
+ )`);let K=G$(q.projectPath);N.push(q.lastMessageTime,q.lastMessageTime,K,K,G$(q.sessionId))}let L=x.prepare(`WITH RECURSIVE archive_members(
66
+ project_path, session_id, archive_root_id, effective_archived_at, depth
67
+ ) AS (
68
+ SELECT project_path, session_id, session_id, archived_at, 0
69
+ FROM sessions
70
+ WHERE archived_at IS NOT NULL
71
+ UNION ALL
72
+ SELECT child.project_path, child.session_id, parent.archive_root_id,
73
+ parent.effective_archived_at, parent.depth + 1
74
+ FROM sessions child
75
+ JOIN archive_members parent
76
+ ON child.project_path = parent.project_path
77
+ AND child.parent_id = parent.session_id
78
+ WHERE parent.depth < 128
79
+ ),
80
+ ranked_archive AS (
81
+ SELECT project_path, session_id, archive_root_id,
82
+ effective_archived_at,
83
+ ROW_NUMBER() OVER (
84
+ PARTITION BY project_path, session_id
85
+ ORDER BY depth ASC, archive_root_id ASC
86
+ ) AS rank
87
+ FROM archive_members
88
+ )
89
+ SELECT s.metadata_json, a.archive_root_id, a.effective_archived_at
90
+ FROM sessions s
91
+ LEFT JOIN ranked_archive a
92
+ ON a.project_path = s.project_path
93
+ AND a.session_id = s.session_id
94
+ AND a.rank = 1
95
+ ${G.length>0?`WHERE ${G.join(" AND ")}`:""}
96
+ ORDER BY s.last_message_time DESC,
97
+ s.project_sort_key ASC,
98
+ s.session_sort_key ASC
99
+ LIMIT ?`).all(...N,$.limit+1).map((K)=>{let f=JSON.parse(K.metadata_json);if(K.archive_root_id&&K.effective_archived_at)return{...f,archivedAt:K.effective_archived_at,archivedBySessionId:K.archive_root_id};let{archivedAt:Q,archivedBySessionId:V,...C}=f;return C}),Z=L$(L,$);return{sessions:Z.sessions.map((K)=>this.toPublicMetadata(K)),nextCursor:Z.nextCursor}}catch{return null}}static async listSessions($={}){let q=J$($),x=await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,0,q.archived),G=new Set;return x.sort(N$).flatMap((N)=>{let J=`${N.projectPath}\x00${N.sessionId}`;if(G.has(J))return[];return G.add(J),[this.toPublicMetadata(N)]})}static async findSessionMetadata($,q){if(R($),q!==void 0){if(!F.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=F.resolve(q),N=this.getSessionFilePath(G,$);try{let J=await this.readStoredSessionMetadata(N,$,G);if(J.projectPath!==G)return;if(!J.parentId||J.archivedAt)return this.toPublicMetadata($$([J],null)[0]??J);let L=await this.scanStoredSessions(G,!0,0,null);return this.toPublicMetadata(L.find((Z)=>Z.sessionId===$)??J)}catch(J){if(J.code==="ENOENT")return;throw J}}let x=(await this.scanStoredSessions(void 0,!0,0,null)).filter((G)=>G.sessionId===$);if(x.length===0)return;if(x.length>1)throw Error(`Ambiguous session ID: ${$}`);return this.toPublicMetadata(x[0])}static async loadSession($,q){try{if(q){if(!F.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=F.resolve(q),N=this.getSessionFilePath(G,$);try{return await this.loadSessionFromFile(N,$,G)}catch(J){if(J.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw J}}let x=(await this.scanStoredSessions(void 0,!0,0,null)).find((G)=>G.sessionId===$);if(!x)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(x.filePath,$)}catch(x){throw R0.error(`[SessionService] 加载会话失败 (${$}):`,x),x}}static async loadSessionModelContext($,q){try{if(q){if(!F.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=F.resolve(q),N=this.getSessionFilePath(G,$);try{return await this.loadSessionModelContextFromFile(N,$,G)}catch(J){if(J.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw J}}let x=(await this.scanStoredSessions(void 0,!0,0,null)).find((G)=>G.sessionId===$);if(!x)throw Error(`未找到会话: ${$}`);return await this.loadSessionModelContextFromFile(x.filePath,$)}catch(x){throw R0.error(`[SessionService] 加载模型上下文失败 (${$}):`,x),x}}static async exportSessionMarkdown($,q,x={}){R($);let G=this.resolveCatalogWorkspace(q),N=m(G,$),J;try{J=await this.readStableSessionSnapshot(N,$)}catch(K){throw this.sanitizeStoredSessionError(K,$)}let L=this.projectMetadataFromEntries(J,$,G,N);if(L.projectPath!==G)throw Error(`Session export workspace mismatch: ${$}`);let Z=L.archivedAt;if(!Z&&L.parentId)Z=(await this.findArchivedAncestor(L.parentId,G))?.archivedAt;return P$(J,{...L,archivedAt:Z},x)}static async listRewindCheckpoints($,q){R($);let x=this.resolveCatalogWorkspace(q),G=m(x,$),N=await this.readStableSessionSnapshot(G,$);this.validateSessionWorkspace(N,$,x);let J=new O0({sessionId:$,workspaceRoot:x});await J.initialize();let L=fq(N),Z=[];for(let K of L){let f=x$(N,K.messageId),Q=await J.previewRewind(f.snapshotMessageIds);Z.push({...K,fileCount:Q.files.length})}return Z}static async rewindSession($,q,x){R($);let G=this.resolveCatalogWorkspace(q);await this.assertSessionWritable($,G);let N=m(G,$),J=new u(N),L;try{await J.appendValidatedAsync(async(Z)=>{this.validateSessionWorkspace(Z,$,G);let K=x$(Z,x.targetMessageId),f=new O0({sessionId:$,workspaceRoot:G});await f.initialize();let Q=await f.previewRewind(K.snapshotMessageIds),V=x.mode==="conversation"?await f.commitSnapshots(K.snapshotMessageIds):await f.rewindSnapshots(K.snapshotMessageIds),C=new Date().toISOString(),B={id:j(),sessionId:$,timestamp:C,type:"session_rewound",cwd:G,gitBranch:c(G),version:n(),data:{rewindId:j(),targetMessageId:x.targetMessageId,mode:x.mode,restoredFiles:x.mode==="conversation"?[]:V.files,createdAt:C}},E=v([...Z,B]);return L={checkpoint:{...K.checkpoint,fileCount:Q.files.length},mode:x.mode,removedTurns:K.removedTurns,restoredFiles:B.data.restoredFiles,messages:this.convertJSONLToMessages(E)},B})}catch(Z){throw this.sanitizeStoredSessionError(Z,$)}if(!L)throw Error(`Session rewind did not produce a result: ${$}`);for(let Z of L.restoredFiles)h.getInstance().clearFileRecord(Z);return L}static async forkSession($,q){R($);let x=q.newSessionId??`fork-${Date.now()}-${j(8)}`;R(x);let G=this.resolveForkWorkspace(q.sourceProjectPath),N=this.resolveForkWorkspace(q.targetProjectPath);if(G!==N)throw Error("Session forks must stay in the source workspace");let J=m(G,$),L=await this.readStableSessionSnapshot(J,$),Z=this.getSessionCreatedEntry(L,$);if(Z.data.sessionId!==$)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!F.isAbsolute(Z.cwd)||F.resolve(Z.cwd)!==G)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let K=this.projectMetadataFromEntries(L,$,G,J);if(K.archivedAt)throw new $0($,$);if(K.parentId){let W=await this.findArchivedAncestor(K.parentId,G);if(W)throw new $0($,W.sessionId)}let f=v(L),Q=new Date().toISOString(),V=Z.data.rootId||$,C=c(N),B=n(),{status:E,taskStatus:M,taskStatusReason:b,taskFailure:_,taskStartedAt:s,taskCompletedAt:e,taskOwnerPid:y,taskPromptSummary:S,taskDispatch:D,taskModelId:z,taskRetriedFrom:A,taskDelivery:Y,taskIsolation:w,taskSourceProjectPath:w0,taskWorktree:K$,taskDiffStat:V$,taskQueuePosition:C$,taskQueueDepth:F$,taskConcurrencyLimit:B$,pendingInteraction:E0,...b0}=Z.data,g0={id:j(),sessionId:x,timestamp:Q,type:"session_created",cwd:N,gitBranch:C,version:B,data:{...b0,sessionId:x,rootId:V,parentId:$,relationType:"fork",taskStatus:"completed",taskCompletedAt:Q,taskIsolation:"local",taskSourceProjectPath:N,createdAt:Q,updatedAt:Q}},k0=f.filter((W)=>W.type!=="session_created"&&W.type!=="inbox_acknowledged"&&W.type!=="interaction_requested"&&W.type!=="interaction_responded"&&W.type!=="interaction_recovered"&&W.type!=="review_started"&&W.type!=="review_completed").map((W)=>{let l={...W,id:j(),sessionId:x,cwd:N,gitBranch:C,version:B};if(W.type==="session_updated"){let{status:C0,taskStatus:U,taskStatusReason:j0,taskFailure:B1,taskStartedAt:T1,taskCompletedAt:Y1,taskOwnerPid:H1,taskPromptSummary:X1,taskDispatch:O1,taskModelId:W1,taskRetriedFrom:_1,taskDelivery:U1,taskIsolation:z1,taskSourceProjectPath:D1,taskWorktree:R1,taskDiffStat:A1,taskQueuePosition:M1,taskQueueDepth:w1,taskConcurrencyLimit:E1,pendingInteraction:b1,...Tq}=W.data;return{...l,type:"session_updated",data:{...Tq,sessionId:x,rootId:V,parentId:$,relationType:"fork"}}}if(W.type==="message_created"){let{inboxMessageId:C0,...U}=W.data;return{...l,type:"message_created",data:U}}return l}),y0={id:j(),sessionId:x,timestamp:Q,type:"session_updated",cwd:N,gitBranch:C,version:B,data:{sessionId:x,rootId:V,parentId:$,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:Q,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:N,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:Q}},q0=[g0,...k0,y0],V0=m(N,x);try{await new u(V0).createExclusive(q0)}catch(W){if(W.code==="EEXIST")throw Error(`Fork session already exists: ${x}`,{cause:W});throw W}let S0=this.projectMetadataFromEntries(q0,x,N,V0);return{sessionId:x,parentSessionId:$,projectPath:N,messages:this.convertJSONLToMessages(q0),metadata:this.toPublicMetadata(S0)}}static async deleteSession($,q){if(R($),q){if(!F.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let G=F.resolve(q),N=this.getSessionFilePath(G,$),J=new u(N),L;try{L=await J.deleteValidated((Z)=>{return this.projectMetadataFromEntries(Z,$,G,N).projectPath===G})}catch(Z){if(!this.isCorruptSessionJSONLError(Z))throw Z;L=await J.delete()}if(!L)return 0;return await D0(F.join(F.dirname(N),`${$}.inbox.json`),{force:!0}),await D0(q$(G,$),{force:!0}),await this.removeFromProjection($,G),1}let x=(await this.scanStoredSessions(void 0,!0)).filter((G)=>G.sessionId===$);if(x.length===0)return 0;return await Promise.all(x.map(async(G)=>{await new u(G.filePath).delete(),await D0(F.join(F.dirname(G.filePath),`${G.sessionId}.inbox.json`),{force:!0}),await D0(q$(G.projectPath,G.sessionId),{force:!0}),await this.removeFromProjection(G.sessionId,G.projectPath)})),x.length}static async removeFromProjection($,q){try{let x=await A0();if(x)Vq(x,$,q)}catch{}}static validateTaskMetadataUpdate($,q){if($.taskPromptSummary!==void 0&&$.taskPromptSummary!==null&&(!$.taskPromptSummary.trim()||$.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if($.taskFailure!==void 0&&$.taskFailure!==null&&!n0($.taskFailure))throw Error("Invalid session task failure");if($.taskDispatch!==void 0&&$.taskDispatch!==null&&!xq($.taskDispatch))throw Error("Invalid durable task dispatch");if($.taskModelId!==void 0&&$.taskModelId!==null&&(!$.taskModelId.trim()||$.taskModelId.length>500))throw Error("Invalid session task model ID");if($.selectedModelId!==void 0&&$.selectedModelId!==null&&(!$.selectedModelId.trim()||$.selectedModelId.length>500))throw Error("Invalid selected session model ID");if($.permissionMode!==void 0&&$.permissionMode!==null&&!M0($.permissionMode))throw Error("Invalid session permission mode");if($.reasoningEffort!==void 0&&$.reasoningEffort!==null&&!Q0($.reasoningEffort))throw Error("Invalid session reasoning effort");if($.serviceTier!==void 0&&$.serviceTier!==null&&!f0($.serviceTier))throw Error("Invalid session service tier");if($.responseVerbosity!==void 0&&$.responseVerbosity!==null&&!Z0($.responseVerbosity))throw Error("Invalid session response verbosity");if($.communicationStyle!==void 0&&$.communicationStyle!==null&&!K0($.communicationStyle))throw Error("Invalid session communication style");if($.communicationStyleDigest!==void 0&&$.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test($.communicationStyleDigest))throw Error("Invalid session communication style digest");if($.projectInstructionsDigest!==void 0&&$.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test($.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if($.taskRetriedFrom!==void 0&&$.taskRetriedFrom!==null&&!Gq($.taskRetriedFrom))throw Error("Invalid session task retry source");if($.taskDelivery!==void 0&&$.taskDelivery!==null&&!$q($.taskDelivery))throw Error("Invalid session task delivery");if($.taskIsolation!==void 0&&$.taskIsolation!==null&&!f$.has($.taskIsolation))throw Error(`Invalid session task isolation: ${String($.taskIsolation)}`);if($.taskSourceProjectPath!==void 0&&$.taskSourceProjectPath!==null&&!F.isAbsolute($.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if($.taskWorktree!==void 0&&$.taskWorktree!==null){let x=e$($.taskWorktree);if(!x||x.sessionId!==q||![x.repositoryRoot,x.originalWorkspaceRoot,x.worktreeRoot,x.workspaceRoot].every((G)=>F.isAbsolute(G)))throw Error("Invalid session task worktree metadata")}if($.taskDiffStat!==void 0&&$.taskDiffStat!==null&&!qq($.taskDiffStat))throw Error("Invalid session task diff stat");if($.taskQueuePosition!==void 0&&$.taskQueuePosition!==null&&(!Number.isInteger($.taskQueuePosition)||$.taskQueuePosition<1))throw Error("Invalid session task queue position");if($.taskQueueDepth!==void 0&&$.taskQueueDepth!==null&&(!Number.isInteger($.taskQueueDepth)||$.taskQueueDepth<0))throw Error("Invalid session task queue depth");if($.taskConcurrencyLimit!==void 0&&$.taskConcurrencyLimit!==null&&(!Number.isInteger($.taskConcurrencyLimit)||$.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof $.taskQueuePosition==="number"&&typeof $.taskQueueDepth==="number"&&$.taskQueuePosition>$.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata($,q,x={}){R($),X.validateTaskMetadataUpdate(x,$);let G=X.resolveCatalogWorkspace(q);if(x.taskWorktree&&F.resolve(x.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let N=new Date().toISOString(),J={id:j(),sessionId:$,timestamp:N,type:"session_created",cwd:G,gitBranch:c(G),version:n(),data:{sessionId:$,rootId:$,...x.title!==void 0?{title:x.title}:{},taskStatus:x.taskStatus??"queued",...x.taskPromptSummary!==void 0?{taskPromptSummary:x.taskPromptSummary}:{},...x.taskDispatch!==void 0?{taskDispatch:x.taskDispatch}:{},...x.taskModelId!==void 0?{taskModelId:x.taskModelId}:{},...x.taskRetriedFrom!==void 0?{taskRetriedFrom:x.taskRetriedFrom}:{},...x.taskIsolation!==void 0?{taskIsolation:x.taskIsolation}:{},...x.taskSourceProjectPath!==void 0?{taskSourceProjectPath:x.taskSourceProjectPath}:{},...x.taskWorktree!==void 0?{taskWorktree:x.taskWorktree}:{},...x.selectedModelId!==void 0?{selectedModelId:x.selectedModelId}:{},...x.permissionMode!==void 0?{permissionMode:x.permissionMode}:{},...x.reasoningEffort!==void 0?{reasoningEffort:x.reasoningEffort}:{},...x.serviceTier!==void 0?{serviceTier:x.serviceTier}:{},...x.responseVerbosity!==void 0?{responseVerbosity:x.responseVerbosity}:{},...x.communicationStyle!==void 0?{communicationStyle:x.communicationStyle}:{},...x.communicationStyleDigest!==void 0?{communicationStyleDigest:x.communicationStyleDigest}:{},...x.projectInstructionsDigest!==void 0?{projectInstructionsDigest:x.projectInstructionsDigest}:{},createdAt:N,updatedAt:N}},L=X.getSessionFilePath(G,$);return await new u(L).createExclusive([J]),X.toPublicMetadata(X.projectMetadataFromEntries([J],$,G,L))}static async assertSessionWritable($,q){let x=await this.findSessionMetadata($,q);if(!x)throw Error(`Session not found: ${$}`);if(x.archivedAt)throw new $0($,x.archivedBySessionId??$);return x}static async findArchivedAncestor($,q){let x=new Set,G=$;while(G){if(x.has(G))throw Error("Session lineage contains a cycle");x.add(G),R(G);let N=m(q,G),J;try{J=await a(N,"utf8")}catch(Z){if(Z.code==="ENOENT")return;throw Z}let L=this.projectMetadataFromEntries(this.parseStoredSession(J,G),G,q,N);if(L.projectPath!==q)throw Error("Session lineage escapes the requested workspace");if(L.archivedAt)return{sessionId:L.sessionId,archivedAt:L.archivedAt};G=L.parentId}return}static async listSessionArchiveMembers($,q){R($);let x=this.resolveCatalogWorkspace(q),G=await this.scanStoredSessions(x,!0,0,null);if(!G.some((L)=>L.sessionId===$))throw Error(`Session not found: ${$}`);let N=new Set([$]),J=!0;while(J){J=!1;for(let L of G)if(L.parentId&&N.has(L.parentId)&&!N.has(L.sessionId))N.add(L.sessionId),J=!0}return G.filter((L)=>N.has(L.sessionId)).sort((L,Z)=>L.sessionId.localeCompare(Z.sessionId)).map((L)=>this.toPublicMetadata(L))}static async archiveSession($,q){R($);let x=this.resolveCatalogWorkspace(q),G=await this.findSessionMetadata($,x);if(!G)throw Error(`Session not found: ${$}`);if(G.archivedAt)return G;let N=await this.listSessionArchiveMembers($,x),J=N.find((Z)=>Z.taskStatus==="queued"||Z.taskStatus==="running");if(J)throw new P(`Stop session ${J.sessionId} before archiving this session tree`);let L=[];try{for(let Q of N)L.push(await i.acquire(Q.sessionId,x));let Z=m(x,$),K=new u(Z),f=[];return await K.appendValidated((Q)=>{let V=this.projectMetadataFromEntries(Q,$,x,Z);if(V.archivedAt)throw new P(`Session archive state changed concurrently: ${$}`);if(V.taskStatus==="queued"||V.taskStatus==="running")throw new P(`Stop session ${$} before archiving it`);let C=new Date().toISOString(),B={id:j(),sessionId:$,timestamp:C,type:"session_updated",cwd:x,gitBranch:c(x),version:n(),data:{sessionId:$,archivedAt:C,updatedAt:C}};return f=[...Q,B],B}),this.toPublicMetadata({...this.projectMetadataFromEntries(f,$,x,Z),archivedBySessionId:$})}catch(Z){if(Z instanceof P)throw Z;if(Z instanceof p)throw new P(Z.message);throw this.sanitizeStoredSessionError(Z,$)}finally{for(let Z of L.reverse())await Z.release()}}static async unarchiveSession($,q){R($);let x=this.resolveCatalogWorkspace(q),G=await this.findSessionMetadata($,x);if(!G)throw Error(`Session not found: ${$}`);if(!G.archivedAt)return G;if(G.archivedBySessionId&&G.archivedBySessionId!==$)throw new P(`Unarchive ancestor ${G.archivedBySessionId} to restore session ${$}`);let N;try{N=await i.acquire($,x);let J=m(x,$),L=new u(J),Z=[];return await L.appendValidated((K)=>{if(!this.projectMetadataFromEntries(K,$,x,J).archivedAt)throw new P(`Session archive state changed concurrently: ${$}`);let Q=new Date().toISOString(),V={id:j(),sessionId:$,timestamp:Q,type:"session_updated",cwd:x,gitBranch:c(x),version:n(),data:{sessionId:$,archivedAt:null,updatedAt:Q}};return Z=[...K,V],V}),this.toPublicMetadata(this.projectMetadataFromEntries(Z,$,x,J))}catch(J){if(J instanceof P)throw J;if(J instanceof p)throw new P(J.message);throw this.sanitizeStoredSessionError(J,$)}finally{await N?.release()}}static async updateSessionMetadata($,q,x){if(R($),X.validateTaskMetadataUpdate(x,$),x.taskStatus!==void 0&&!a$.has(x.taskStatus))throw Error(`Invalid session task status: ${String(x.taskStatus)}`);if(x.taskOwnerPid!==void 0&&x.taskOwnerPid!==null&&(!Number.isInteger(x.taskOwnerPid)||x.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let G=X.resolveCatalogWorkspace(q);if(x.taskWorktree&&F.resolve(x.taskWorktree.workspaceRoot)!==G)throw Error("Session task worktree must match the catalog workspace");let N=X.getSessionFilePath(G,$),J=new u(N),L=[];try{await J.appendValidatedAsync(async(Z)=>{let K=X.getSessionCreatedEntry(Z,$);if(K.data.sessionId!==$)throw Error(`Session metadata creation record sessionId mismatch: ${$}`);if(!F.isAbsolute(K.cwd)||F.resolve(K.cwd)!==G)throw Error(`Session metadata creation record cwd mismatch: ${$}`);let f=X.projectMetadataFromEntries(Z,$,G,N);if(f.archivedAt)throw new $0($,$);if(f.parentId){let C=await X.findArchivedAncestor(f.parentId,G);if(C)throw new $0($,C.sessionId)}let Q=new Date().toISOString(),V={id:j(),sessionId:$,timestamp:Q,type:"session_updated",cwd:G,gitBranch:c(G),version:n(),data:{sessionId:$,...x.title!==void 0?{title:x.title}:{},...x.taskStatus!==void 0?{taskStatus:x.taskStatus}:{},...x.taskStatusReason!==void 0?{taskStatusReason:x.taskStatusReason}:{},...x.taskFailure!==void 0?{taskFailure:x.taskFailure}:{},...x.taskStartedAt!==void 0?{taskStartedAt:x.taskStartedAt}:{},...x.taskCompletedAt!==void 0?{taskCompletedAt:x.taskCompletedAt}:{},...x.taskOwnerPid!==void 0?{taskOwnerPid:x.taskOwnerPid}:{},...x.taskPromptSummary!==void 0?{taskPromptSummary:x.taskPromptSummary}:{},...x.taskDispatch!==void 0?{taskDispatch:x.taskDispatch}:{},...x.taskModelId!==void 0?{taskModelId:x.taskModelId}:{},...x.taskRetriedFrom!==void 0?{taskRetriedFrom:x.taskRetriedFrom}:{},...x.taskDelivery!==void 0?{taskDelivery:x.taskDelivery}:{},...x.taskIsolation!==void 0?{taskIsolation:x.taskIsolation}:{},...x.taskSourceProjectPath!==void 0?{taskSourceProjectPath:x.taskSourceProjectPath}:{},...x.taskWorktree!==void 0?{taskWorktree:x.taskWorktree}:{},...x.taskDiffStat!==void 0?{taskDiffStat:x.taskDiffStat}:{},...x.taskQueuePosition!==void 0?{taskQueuePosition:x.taskQueuePosition}:{},...x.taskQueueDepth!==void 0?{taskQueueDepth:x.taskQueueDepth}:{},...x.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:x.taskConcurrencyLimit}:{},...x.selectedModelId!==void 0?{selectedModelId:x.selectedModelId}:{},...x.permissionMode!==void 0?{permissionMode:x.permissionMode}:{},...x.reasoningEffort!==void 0?{reasoningEffort:x.reasoningEffort}:{},...x.serviceTier!==void 0?{serviceTier:x.serviceTier}:{},...x.responseVerbosity!==void 0?{responseVerbosity:x.responseVerbosity}:{},...x.communicationStyle!==void 0?{communicationStyle:x.communicationStyle}:{},...x.communicationStyleDigest!==void 0?{communicationStyleDigest:x.communicationStyleDigest}:{},...x.projectInstructionsDigest!==void 0?{projectInstructionsDigest:x.projectInstructionsDigest}:{},updatedAt:Q}};return L=[...Z,V],V})}catch(Z){throw X.sanitizeStoredSessionError(Z,$)}return X.toPublicMetadata(X.projectMetadataFromEntries(L,$,G,N))}static async setSessionPermissionMode($,q,x){if(R($),!M0(x))throw Error("Invalid session permission mode");let G=X.resolveCatalogWorkspace(q),N=await X.findSessionMetadata($,G);if(N?.permissionMode===x)return N;if(N)return X.updateSessionMetadata($,G,{permissionMode:x});try{return await X.createSessionMetadata($,G,{taskStatus:"completed",permissionMode:x})}catch(J){if(J.code!=="EEXIST")throw J;return X.updateSessionMetadata($,G,{permissionMode:x})}}static async findSessionTaskWorktree($,q){R($);let x=X.resolveCatalogWorkspace(q),G=X.getSessionFilePath(x,$);try{return(await X.readStoredSessionMetadata(G,$,x)).taskWorktree}catch(N){if(N.code==="ENOENT")return;throw X.sanitizeStoredSessionError(N,$)}}static async findSessionTaskDispatch($,q){R($);let x=X.resolveCatalogWorkspace(q),G=X.getSessionFilePath(x,$);try{return(await X.readStoredSessionMetadata(G,$,x)).taskDispatch}catch(N){if(N.code==="ENOENT")return;throw X.sanitizeStoredSessionError(N,$)}}static async loadSessionFromFile($,q,x){let G=await a($,"utf-8"),N=this.parseStoredSession(G,q);if(x!==void 0){if(this.projectMetadataFromEntries(N,q,x,$).projectPath!==x)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToMessages(N)}static async loadSessionModelContextFromFile($,q,x){let G=await a($,"utf-8"),N=this.parseStoredSession(G,q);if(x!==void 0){if(this.projectMetadataFromEntries(N,q,x,$).projectPath!==x)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToModelContext(N)}static convertJSONLToModelContext($){let q=v($),x=-1,G;for(let J=0;J<q.length;J++){let L=q[J];if(L?.type!=="part_created"||L.data.partType!=="summary")continue;let Z=L.data.payload;if(x=J,G=U$(Z.replacementMessages),!G)G=[{role:"user",content:Z.text??"",metadata:L.data.payload}]}if(x<0||!G)return this.convertJSONLToMessages(q);let N=this.convertJSONLToMessages(q.slice(x+1));return[...G,...N]}static convertJSONLToMessages($){let q=[],x=new Map,G=new Map,N=new Map,J=new Map,L=new Map,Z=v($),K=new Set;for(let f of Z){if(f.type==="message_created"){let Q=f.data.metadata&&typeof f.data.metadata==="object"&&!Array.isArray(f.data.metadata)?f.data.metadata:void 0,V=Q?.codeReview&&typeof Q.codeReview==="object"&&!Array.isArray(Q.codeReview)?Q.codeReview:void 0;if(V?.phase==="completed"&&typeof V.reviewId==="string")K.add(V.reviewId);let C=f.data.role==="assistant"&&f.data.parentMessageId?N.get(f.data.parentMessageId):void 0,B=C??{role:f.data.role,content:"",...f.data.metadata||f.data.inboxMessageId?{metadata:{...f.data.metadata&&typeof f.data.metadata==="object"&&!Array.isArray(f.data.metadata)?f.data.metadata:{},...f.data.inboxMessageId?{inboxMessageId:f.data.inboxMessageId}:{}}}:{}};if(x.set(f.data.messageId,B),G.set(f.data.messageId,[]),!C)q.push(B)}if(f.type==="part_created"){if(f.data.partType==="reasoning"){let Q=x.get(f.data.messageId);if(Q){let V=f.data.payload;Q.reasoningContent=(Q.reasoningContent??"")+(V.text??"")}}if(f.data.partType==="text"){let Q=x.get(f.data.messageId);if(Q){let V=f.data.payload,C=G.get(f.data.messageId);if(C)C.push({type:"text",text:V.text??""}),Q.content=Jq(C);else Q.content=V.text??""}}if(f.data.partType==="image"){let Q=x.get(f.data.messageId);if(Q){let V=f.data.payload,C=G.get(f.data.messageId);if(C&&V.dataUrl)C.push({type:"image_url",image_url:{url:V.dataUrl}}),Q.content=Jq(C)}}if(f.data.partType==="tool_call"){let Q=x.get(f.data.messageId);if(Q?.role!=="assistant"){if(Q=N.get(f.data.messageId),!Q)Q={role:"assistant",content:"",tool_calls:[]},N.set(f.data.messageId,Q),q.push(Q)}if(Q.role==="assistant"){let V=f.data.payload,C=V.toolCallId??f.data.partId;J.set(f.data.partId,C),L.set(C,Q),Q.tool_calls??=[],Q.tool_calls.push({id:C,type:"function",function:{name:V.toolName??"unknown",arguments:JSON.stringify(V.input??{})}})}}if(f.data.partType==="tool_result"){let Q=f.data.payload,V=typeof Q.error==="string"?`Error: ${Q.error}`:typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??""),C=Q;q.push({role:"tool",content:V,tool_call_id:J.get(f.data.messageId)??Q.toolCallId,name:Q.toolName,metadata:C})}if(f.data.partType==="summary"){let Q=f.data.payload,V=f.data.payload;q.push({role:"system",content:Q.text??"",metadata:V})}if(f.data.partType==="subtask_ref"){let Q=x.get(f.data.messageId)??L.get(f.data.messageId);if(Q){let V=f.data.payload,C=Q.metadata??{};Q.metadata={...C,subtaskRef:V}}}}}for(let f of Y0(Z)){if(f.completion===void 0||K.has(f.start.reviewId))continue;q.push({role:"assistant",content:A$(f.start,f.completion),metadata:{codeReview:{...M$(f.start,f.completion),synthetic:!0}}})}return q}static projectionDeriver(){return($,q,x)=>{try{let G=m(x,q);return this.projectMetadataFromEntries($,q,x,G)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection($,q,x=0,G=!1){try{let N=await A0();if(!N)return null;await Z$(N,this.projectionDeriver(),x);let J=$?N.prepare("SELECT metadata_json, is_subagent FROM sessions WHERE project_path=?").all($):N.prepare("SELECT metadata_json, is_subagent FROM sessions").all(),L=[];for(let Z of J){if(!q&&Z.is_subagent===1)continue;try{let K=JSON.parse(Z.metadata_json);if($!==void 0&&K.projectPath!==$)continue;L.push(K)}catch{}}return $$(L,G)}catch{return null}}static async scanStoredSessions($,q=!1,x=0,G=!1){let N=$?F.resolve($):void 0,J=await this.scanStoredSessionsFromProjection(N,q,x,G);if(J)return J;let L=N?[{storagePath:B0(N),projectPath:N}]:await this.listAllProjectStorageDirectories(),Z=[];for(let K of L){let f;try{f=await t$(K.storagePath)}catch(Q){if(Q.code==="ENOENT")continue;throw Q}for(let Q of f){if(!Q.endsWith(".jsonl"))continue;let V=Q.slice(0,-6),C=F.join(K.storagePath,Q);try{let B=await this.readStoredSessionMetadata(C,V,K.projectPath);if(N!==void 0&&B.projectPath!==N){R0.warn(`[SessionService] Skipping out-of-scope session transcript: ${V}`);continue}if(!q&&B.relationType==="subagent")continue;Z.push(B)}catch(B){let E=B.code;if(E==="ENOENT")continue;if(E)throw B;R0.warn(`[SessionService] Skipping invalid session transcript: ${V}`)}}}return $$(Z,G)}static async listAllProjectStorageDirectories(){let $=F.join(N0(),"projects"),q;try{q=await t$($,{withFileTypes:!0,encoding:"utf8"})}catch(x){if(x.code==="ENOENT")return[];throw x}return q.filter((x)=>x.isDirectory()).map((x)=>({storagePath:F.join($,x.name),projectPath:Nq(x.name)}))}static async readStoredSessionMetadata($,q,x){let G=await a($,"utf-8"),N=this.parseStoredSession(G,q);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(N,q,x,$))}static async reconcileInterruptedTask($){let q=$.taskOwnerPid;if($.taskStatus!=="running"||q===void 0||s$(q))return $;let x;try{x=await i.acquire($.sessionId,$.projectPath)}catch(J){if(!(J instanceof p))throw J;let L=await a($.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(L,$.sessionId),$.sessionId,$.projectPath,$.filePath)}let G=new u($.filePath),N;try{try{await G.appendValidated((J)=>{let L=this.projectMetadataFromEntries(J,$.sessionId,$.projectPath,$.filePath);if(L.taskStatus!=="running"||L.taskOwnerPid!==q||s$(q))throw new Q$;let Z=new Date().toISOString(),K={id:j(),sessionId:$.sessionId,timestamp:Z,type:"session_updated",cwd:$.projectPath,gitBranch:c($.projectPath),version:n(),data:{sessionId:$.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:Z,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:Z}};return N=[...J,K],K})}catch(J){if(!(J instanceof Q$))throw J}if(!N){let J=await a($.filePath,"utf-8");N=this.parseStoredSession(J,$.sessionId)}return this.projectMetadataFromEntries(N,$.sessionId,$.projectPath,$.filePath)}finally{await x.release()}}static projectMetadataFromEntries($,q,x,G){if($.length===0)throw Error(`Empty session transcript: ${q}`);let N=this.getSessionCreatedEntry($,q),J=$.reduce((U,j0)=>j0.type==="session_updated"?{...U,...j0.data}:U,{...N.data}),L=v($),Z=R$(D$(L)),f=Y0(L).at(-1),Q=L.findLastIndex((U)=>U.type==="review_started"&&U.data.reviewId===f?.start.reviewId||U.type==="review_completed"&&U.data.reviewId===f?.start.reviewId),V=L.findLastIndex((U)=>(U.type==="session_created"||U.type==="session_updated")&&Object.hasOwn(U.data,"taskStatus")),C=f!==void 0&&Q>V,B=C?f.completion===void 0?"running":f.completion.status==="completed"||f.completion.status==="stale"?"completed":f.completion.status==="aborted"?"cancelled":f.completion.status==="interrupted"?"interrupted":"failed":void 0,E=L.filter((U)=>U.type==="message_created"&&["user","assistant"].includes(U.data.role)).length,M=L.some((U)=>U.type==="part_created"&&U.data.partType==="tool_result"&&typeof U.data.payload.error==="string"),b=a$.has(J.taskStatus)?J.taskStatus:void 0,_=B??b??(M?"failed":"completed"),s=typeof J.taskOwnerPid==="number"&&Number.isInteger(J.taskOwnerPid)&&J.taskOwnerPid>0?J.taskOwnerPid:void 0,e=f$.has(J.taskIsolation)?J.taskIsolation:void 0,y=typeof J.taskSourceProjectPath==="string"&&F.isAbsolute(J.taskSourceProjectPath)?F.resolve(J.taskSourceProjectPath):void 0,S=N.cwd;if(S!==void 0&&!F.isAbsolute(S))throw Error(`Session catalog cwd must be absolute: ${q}`);let D=S===void 0?x:F.resolve(S),z=e$(J.taskWorktree),A=z?.sessionId===q&&F.resolve(z.workspaceRoot)===D?z:void 0,Y=qq(J.taskDiffStat),w=xq(J.taskDispatch),w0=typeof J.taskModelId==="string"&&J.taskModelId.trim()?J.taskModelId:w?.modelId,K$=typeof J.selectedModelId==="string"&&J.selectedModelId.trim()?J.selectedModelId:w0,V$=M0(J.permissionMode)?J.permissionMode:w?.permissionMode,C$=Q0(J.reasoningEffort)?J.reasoningEffort:w?.reasoningEffort,F$=f0(J.serviceTier)?J.serviceTier:w?.serviceTier,B$=Z0(J.responseVerbosity)?J.responseVerbosity:w?.responseVerbosity,E0=K0(J.communicationStyle)?J.communicationStyle:w?.communicationStyle,b0=Object.hasOwn(J,"communicationStyleDigest")?typeof J.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(J.communicationStyleDigest)?J.communicationStyleDigest:void 0:E0===w?.communicationStyle?w?.communicationStyleDigest:void 0,g0=Object.hasOwn(J,"projectInstructionsDigest")?typeof J.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(J.projectInstructionsDigest)?J.projectInstructionsDigest:void 0:w?.projectInstructionsDigest,k0=Bq(J.archivedAt)?J.archivedAt:void 0,y0=Gq(J.taskRetriedFrom),q0=$q(J.taskDelivery),V0=typeof J.taskQueuePosition==="number"&&Number.isInteger(J.taskQueuePosition)&&J.taskQueuePosition>0?J.taskQueuePosition:void 0,S0=typeof J.taskQueueDepth==="number"&&Number.isInteger(J.taskQueueDepth)&&J.taskQueueDepth>=0?J.taskQueueDepth:void 0,W=typeof J.taskConcurrencyLimit==="number"&&Number.isInteger(J.taskConcurrencyLimit)&&J.taskConcurrencyLimit>0?J.taskConcurrencyLimit:void 0,l=C?f?.completion?f.completion.status==="completed"?void 0:`Code review ${P0(f.completion.status)}`:`Reviewing ${f?.start.target.label??"changes"}`:void 0,C0=C?_==="failed"&&l?c0(l):void 0:n0(J.taskFailure)?J.taskFailure:_==="failed"&&typeof J.taskStatusReason==="string"?c0(J.taskStatusReason):void 0;return{sessionId:q,projectPath:D,gitBranch:N.gitBranch,rootId:J.rootId||q,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:K$,permissionMode:V$,reasoningEffort:C$,serviceTier:F$,responseVerbosity:B$,communicationStyle:E0,communicationStyleDigest:b0,projectInstructionsDigest:g0,pendingInteraction:Z,taskStatus:_,taskStatusReason:C0?.message??l??(typeof J.taskStatusReason==="string"?J.taskStatusReason:void 0),taskFailure:C0,taskStartedAt:C?f?.start.startedAt:typeof J.taskStartedAt==="string"?J.taskStartedAt:void 0,taskCompletedAt:C?f?.completion?.completedAt:typeof J.taskCompletedAt==="string"?J.taskCompletedAt:void 0,taskPromptSummary:C?f?C1(f.start.target):"/review uncommitted":typeof J.taskPromptSummary==="string"?J.taskPromptSummary:void 0,taskModelId:w0,taskRetryAvailable:w!==void 0,taskRetriedFrom:y0,taskDelivery:q0,taskIsolation:e,taskSourceProjectPath:y,taskWorktreePath:A?.worktreeRoot,taskWorktreeBranch:A?.branch,taskBaseCommit:A?.baseCommit,taskDiffStat:Y,taskQueuePosition:V0,taskQueueDepth:S0,taskConcurrencyLimit:W,archivedAt:k0,taskOwnerPid:C?void 0:s,taskWorktree:A,taskDispatch:w,messageCount:E,firstMessageTime:$[0].timestamp,lastMessageTime:$.at(-1).timestamp,hasErrors:M||_==="failed",filePath:G}}static toPublicMetadata($){let{filePath:q,taskOwnerPid:x,taskWorktree:G,taskDispatch:N,...J}=$;return J}static getSessionFilePath($,q){return m($,q)}static getSessionCreatedEntry($,q){let x=$.find((G)=>G.type==="session_created");if(!x)throw new Fq(q);return x}static resolveCatalogWorkspace($){if(!F.isAbsolute($))throw Error("Session catalog cwd must be absolute");return F.resolve($)}static validateSessionWorkspace($,q,x){let G=this.getSessionCreatedEntry($,q);if(G.data.sessionId!==q)throw Error(`Session creation record sessionId mismatch: ${q}`);if(!F.isAbsolute(G.cwd)||F.resolve(G.cwd)!==x)throw Error(`Session creation record cwd mismatch: ${q}`)}static resolveForkWorkspace($){if(!F.isAbsolute($))throw Error("Fork workspace paths must be absolute");return F.resolve($)}static parseStoredSession($,q){return Qq($,`session ${q}`)}static isCorruptSessionJSONLError($){return $ instanceof Error&&$.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError($,q){if(!this.isCorruptSessionJSONLError($)||!($ instanceof Error))return $;let x=$.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${q}${x?` at line ${x}`:""}`,{cause:$.cause})}static async readStableSessionSnapshot($,q,x=3){for(let G=0;G<x;G+=1){let N=await L0.stat($),J=await L0.readFile($),L=this.parseStoredSession(J,q),Z=await L0.stat($);if(N.size===Z.size&&N.mtimeNs===Z.mtimeNs&&N.dev===Z.dev&&N.ino===Z.ino)return L}throw Error("Session changed while creating fork; retry the operation")}}function Jq($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}
100
+ export{l0 as yb,T$ as zb,I0 as Ab,Y$ as Bb,p as Cb,i as Db,P1 as Eb,h1 as Fb,D$ as Gb,l1 as Hb,Y0 as Ib,i1 as Jb,P0 as Kb,A$ as Lb,M$ as Mb,c0 as Nb,h as Ob,O0 as Pb,i0 as Qb,d0 as Rb,V2 as Sb,C2 as Tb,m$ as Ub,_0 as Vb,X2 as Wb,r$ as Xb,h$ as Yb,U2 as Zb,o$ as _b,z2 as $b,o2 as ac,t2 as bc,Fq as cc,$0 as dc,P as ec,X as fc};
@@ -1,6 +1,6 @@
1
- import{zc as I}from"./chunk-k106g2p6.js";import{Sc as A}from"./chunk-whftbz4b.js";import{je as h}from"./chunk-77z6x1zb.js";import{Ne as f,Re as T,Se as w,Te as M,Ue as P,Xe as k,Ye as E}from"./chunk-mvc0tad6.js";import{Ze as c,_e as y}from"./chunk-ah8hky46.js";import{bf as S,df as n,gf as p}from"./chunk-r561wfcz.js";import{lf as O}from"./chunk-dbb20rxh.js";import{promises as R}from"node:fs";import C from"node:path";var U=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],x=new Set([...Object.keys(f),...U]),m=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:p(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),timeout:n.Optional(m),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(m),theme:n.Optional(n.String()),uiTheme:n.Optional(p(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(m),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1,maximum:y})),maxConcurrentTasks:n.Optional(n.Integer({minimum:T,maximum:w})),maxQueuedTasks:n.Optional(n.Integer({minimum:M,maximum:P})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(p(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(p(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(r),ask:n.Optional(r),deny:n.Optional(r)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),_=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!x.has(s))throw Error(`Unknown --settings field: ${s}`);let l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.data}async function N(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=C.resolve(O(),i),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of _){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}var u=h("General"),Z=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},g=async(o)=>{let i=await N(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let l=await k.getInstance().initialize(i),s=E(l,o);if(A().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
1
+ import{Dc as I}from"./chunk-hjvdsrzb.js";import{Wc as A}from"./chunk-ef8rr9eh.js";import{ne as h}from"./chunk-djh79rde.js";import{$e as k,Re as f,Ve as T,We as w,Xe as M,Ye as P,af as E}from"./chunk-qw900zg9.js";import{bf as c,cf as y}from"./chunk-gcsygn5a.js";import{ff as S,hf as n,kf as p}from"./chunk-9ka0bdry.js";import{pf as O}from"./chunk-kvd5nexw.js";import{promises as R}from"node:fs";import C from"node:path";var U=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],x=new Set([...Object.keys(f),...U]),m=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:p(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),timeout:n.Optional(m),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(m),theme:n.Optional(n.String()),uiTheme:n.Optional(p(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(m),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1,maximum:y})),maxConcurrentTasks:n.Optional(n.Integer({minimum:T,maximum:w})),maxQueuedTasks:n.Optional(n.Integer({minimum:M,maximum:P})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(p(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(p(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(r),ask:n.Optional(r),deny:n.Optional(r)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),_=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!x.has(s))throw Error(`Unknown --settings field: ${s}`);let l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.data}async function N(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=C.resolve(O(),i),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of _){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}var u=h("General"),Z=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},g=async(o)=>{let i=await N(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let l=await k.getInstance().initialize(i),s=E(l,o);if(A().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
5
  `),process.exit(1)}};function F(o){if(o.continue&&o.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(o.forkSession&&!o.continue&&!o.resume)throw Error("--fork-session requires --resume or --continue");if(o.sessionId&&(o.continue||o.resume)&&!o.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var v=(o)=>{if(o.jsonSchema&&o.outputSchema)throw Error("--json-schema cannot be combined with --output-schema");if((o.jsonSchema||o.outputSchema)&&!o.print&&!o.headless)throw Error("--json-schema and --output-schema can only be used with --print or --headless");if(o.outputFormat&&o.outputFormat!=="text"&&!o.print&&!o.headless)throw Error("--output-format can only be used with --print or --headless");if(o.headless&&o.outputFormat&&!["text","jsonl"].includes(o.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${o.outputFormat}". Use --print for json|stream-json support.`);if(o.print&&o.outputFormat&&!["text","json","stream-json"].includes(o.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${o.outputFormat}". Use --headless for jsonl support.`);if(o.inputFormat==="stream-json"&&o.print)u.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
- export{Z as wc,g as xc,v as yc};
6
+ export{Z as Ac,g as Bc,v as Cc};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-zj651nrm.js";import"./chunk-c7zk9zj2.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};