blade-code 0.11.1 → 0.11.3

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 (141) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-s1cch8tt.js → chunk-0759ckbc.js} +1 -1
  3. package/dist/{chunk-4cdk4mds.js → chunk-0eajnhrj.js} +1 -1
  4. package/dist/{chunk-2ftyzk83.js → chunk-0pcrccgp.js} +1 -1
  5. package/dist/{chunk-5034apfz.js → chunk-0wxnrjes.js} +2 -2
  6. package/dist/{chunk-vbjgcn49.js → chunk-1cy4ab77.js} +1 -1
  7. package/dist/{chunk-a74ynw4t.js → chunk-33w0b9r4.js} +1 -1
  8. package/dist/chunk-3d4wgfkr.js +1 -0
  9. package/dist/chunk-3rxs9vxm.js +6 -0
  10. package/dist/{chunk-30p7aff1.js → chunk-45xdp95z.js} +1 -1
  11. package/dist/{chunk-9ydrwcpy.js → chunk-4e4qtpca.js} +2 -2
  12. package/dist/{chunk-ts5xzefm.js → chunk-5qrw9g8c.js} +2 -2
  13. package/dist/{chunk-0wcnkxe8.js → chunk-5s2x98rx.js} +2 -2
  14. package/dist/{chunk-8sth12hd.js → chunk-6v23hdt8.js} +1 -1
  15. package/dist/{chunk-06hkf59s.js → chunk-7ajvrtb3.js} +1 -1
  16. package/dist/chunk-7p8r4q6f.js +1 -0
  17. package/dist/{chunk-gzbb747a.js → chunk-a95jmx2j.js} +1 -1
  18. package/dist/{chunk-n8qg68y2.js → chunk-amabfzc8.js} +1 -1
  19. package/dist/{chunk-m30qwpe9.js → chunk-b22ab7yw.js} +1 -1
  20. package/dist/chunk-b3kvf23h.js +357 -0
  21. package/dist/chunk-b7pn03pb.js +1 -0
  22. package/dist/chunk-b8hm4td5.js +1 -0
  23. package/dist/{chunk-xz7dddaj.js → chunk-cmpxdek8.js} +1 -1
  24. package/dist/{chunk-8n3jythp.js → chunk-crbt25b4.js} +2 -2
  25. package/dist/{chunk-0b83mt1c.js → chunk-crv3sghv.js} +2 -2
  26. package/dist/{chunk-7eset766.js → chunk-dv5ts9ae.js} +6 -6
  27. package/dist/{chunk-g0hhqxpg.js → chunk-dyf12wbv.js} +2 -2
  28. package/dist/chunk-fa5sebe2.js +1 -0
  29. package/dist/{chunk-hmw99nm1.js → chunk-faedrfhd.js} +27 -27
  30. package/dist/chunk-ffq1k7q5.js +10 -0
  31. package/dist/chunk-fnvh22vc.js +1 -0
  32. package/dist/{chunk-xcy45yxx.js → chunk-g0xtk1yy.js} +2 -2
  33. package/dist/{chunk-h8w3ahnk.js → chunk-g2295k8s.js} +2 -2
  34. package/dist/chunk-gfhb2h6z.js +1 -0
  35. package/dist/chunk-gqypt03h.js +1 -0
  36. package/dist/chunk-hn2p1296.js +1 -0
  37. package/dist/chunk-hnnhpv75.js +1 -0
  38. package/dist/{chunk-ms0wve9g.js → chunk-hzz27w5w.js} +2 -2
  39. package/dist/{chunk-ta99scbr.js → chunk-jbpasjg9.js} +1 -1
  40. package/dist/{chunk-2vrsfb8p.js → chunk-jm1chm6x.js} +55 -55
  41. package/dist/{chunk-pm5ssr7m.js → chunk-kb4hwa5a.js} +1 -1
  42. package/dist/{chunk-sa9fxss4.js → chunk-kdtj92em.js} +1 -1
  43. package/dist/{chunk-3kszepm6.js → chunk-kehgewqh.js} +1 -1
  44. package/dist/{chunk-wcps5gjm.js → chunk-kkzznz4w.js} +1 -1
  45. package/dist/chunk-m2x6pb4f.js +2 -0
  46. package/dist/chunk-mmpcq1yh.js +1 -0
  47. package/dist/{chunk-xzva8y4e.js → chunk-mqfayxf7.js} +3 -3
  48. package/dist/{chunk-tqt5c2f5.js → chunk-n30najxq.js} +2 -2
  49. package/dist/{chunk-9yn01a90.js → chunk-nts19h6v.js} +1 -1
  50. package/dist/{chunk-v1k6nvth.js → chunk-nvj4da2w.js} +1 -1
  51. package/dist/{chunk-80946c9a.js → chunk-p36k2e96.js} +1 -1
  52. package/dist/{chunk-a1tt14a2.js → chunk-pbckwd41.js} +2 -2
  53. package/dist/{chunk-zfxcef0z.js → chunk-pm163dfm.js} +1 -1
  54. package/dist/{chunk-1beqtjsw.js → chunk-prqtwzxd.js} +1 -1
  55. package/dist/{chunk-zjezws85.js → chunk-px45q235.js} +2 -2
  56. package/dist/{chunk-5bc4hwt9.js → chunk-q6sr4979.js} +2 -2
  57. package/dist/{chunk-m8te4s8f.js → chunk-qvew5nk3.js} +2 -2
  58. package/dist/{chunk-yrr9mdjn.js → chunk-qy6p8bpr.js} +2 -2
  59. package/dist/{chunk-xseh3f4m.js → chunk-r5svk833.js} +1 -1
  60. package/dist/{chunk-25s0c8km.js → chunk-r9nyzqzb.js} +5 -5
  61. package/dist/{chunk-27bjk35b.js → chunk-s3pnhdqk.js} +1 -1
  62. package/dist/{chunk-f552hzcx.js → chunk-sdapqhj0.js} +1 -1
  63. package/dist/{chunk-a731hdwa.js → chunk-skktstg8.js} +1 -1
  64. package/dist/chunk-sqsfztrv.js +1 -0
  65. package/dist/{chunk-xcj23spc.js → chunk-t0swttvj.js} +2 -2
  66. package/dist/{chunk-m70cnaeg.js → chunk-v0eanse2.js} +1 -1
  67. package/dist/{chunk-dxq7462e.js → chunk-wan9q99y.js} +2 -2
  68. package/dist/{chunk-f6hc7t65.js → chunk-wnzr9h84.js} +1 -1
  69. package/dist/{chunk-447ps2te.js → chunk-x2crj6jq.js} +2 -2
  70. package/dist/{chunk-5yyp6njq.js → chunk-x6k5ye1z.js} +1 -1
  71. package/dist/{chunk-fqxzzsgr.js → chunk-yeandcre.js} +1 -1
  72. package/dist/{chunk-3y2x6fb6.js → chunk-ys8gysg8.js} +1 -1
  73. package/dist/chunk-yw3achrm.js +1 -0
  74. package/dist/{chunk-rt3f4xjz.js → chunk-zc8erdkc.js} +14 -6
  75. package/dist/web/assets/ChatView-CvuKp3Yl.js +17 -0
  76. package/dist/web/assets/{CodeBlockHighlighter-B5kcdVCA.js → CodeBlockHighlighter-CYiAdOLs.js} +1 -1
  77. package/dist/web/assets/FilePreview-DGolvoH6.js +8 -0
  78. package/dist/web/assets/KanbanBoard-DdwrLpvb.js +1 -0
  79. package/dist/web/assets/{MarkdownRenderer-d7DdyYdx.js → MarkdownRenderer-fJny7W8J.js} +3 -3
  80. package/dist/web/assets/{ScrollArea-D1tPWHKZ.js → ScrollArea-CSCl8r35.js} +1 -1
  81. package/dist/web/assets/{SessionHistorySurface-Cv_jRoJr.js → SessionHistorySurface-dttyHhtN.js} +1 -1
  82. package/dist/web/assets/SettingsModal-Bn9m-F-v.js +5 -0
  83. package/dist/web/assets/Sidebar-JYvLuHTi.js +1 -0
  84. package/dist/web/assets/{TaskSwitcher-C9AKJrl-.js → TaskSwitcher-InE9ArQH.js} +1 -1
  85. package/dist/web/assets/{TerminalPanel-BxBGcuB9.js → TerminalPanel-BLRAlQoa.js} +1 -1
  86. package/dist/web/assets/{archive-DNa9b1YE.js → archive-D3alcPOa.js} +1 -1
  87. package/dist/web/assets/{arrow-left-BQh8jlfT.js → arrow-left-CNfcSdE2.js} +1 -1
  88. package/dist/web/assets/{calendar-clock-CC7FeYTg.js → calendar-clock-BoRTfsxW.js} +1 -1
  89. package/dist/web/assets/chevron-right-B8JH5N50.js +1 -0
  90. package/dist/web/assets/{clock-3-P2q6i6vm.js → clock-3-BGymk4sE.js} +1 -1
  91. package/dist/web/assets/{copy-C-KvzjCC.js → copy-CLG3LQ2v.js} +1 -1
  92. package/dist/web/assets/{dist-DiQNoDMg.js → dist-BtGkS2rG.js} +1 -1
  93. package/dist/web/assets/{download-CJHn20x1.js → download-DxK6pukC.js} +1 -1
  94. package/dist/web/assets/{folder-DmyFehXD.js → folder-B0xRimYH.js} +1 -1
  95. package/dist/web/assets/index-BJdxoBtv.css +1 -0
  96. package/dist/web/assets/{index-D-oma3Je.js → index-DkwePtIh.js} +4 -4
  97. package/dist/web/assets/{pause-D2FxNG-w.js → pause-CKNq9DgJ.js} +1 -1
  98. package/dist/web/assets/{pencil-D6HI7KC8.js → pencil-CMjIwtk5.js} +1 -1
  99. package/dist/web/assets/{play-4jKCDYR-.js → play-BOz9Sqzf.js} +1 -1
  100. package/dist/web/assets/plus-BJIEQjD7.js +1 -0
  101. package/dist/web/assets/preload-helper-HI3NtP3B.js +1 -0
  102. package/dist/web/assets/{session-events-CvFfHkFA.js → session-events-B-hnDC4L.js} +7 -7
  103. package/dist/web/assets/{settings-fWlqCZ-U.js → settings-CP6ArjQ7.js} +1 -1
  104. package/dist/web/assets/team-BHlihaeV.js +1 -0
  105. package/dist/web/assets/{teamService-DfIvlI2_.js → teamService-DDfifLYm.js} +1 -1
  106. package/dist/web/assets/{terminal-DZkEoiSb.js → terminal-BYHhWXe-.js} +1 -1
  107. package/dist/web/assets/tooltip-DJBQZhJD.js +1 -0
  108. package/dist/web/assets/triangle-alert-BCJaJaVj.js +1 -0
  109. package/dist/web/assets/{vendor-radix-CHeA_3Pt.js → vendor-radix-BCAvgfOW.js} +1 -1
  110. package/dist/web/assets/{vendor-react-hNfZDUf2.js → vendor-react-DQwAdeyS.js} +1 -1
  111. package/dist/web/index.html +5 -5
  112. package/package.json +1 -1
  113. package/dist/chunk-1kxpnt9q.js +0 -1
  114. package/dist/chunk-2g3v9qpz.js +0 -1
  115. package/dist/chunk-43gg1wdc.js +0 -1
  116. package/dist/chunk-72wn385d.js +0 -1
  117. package/dist/chunk-7vzz3rsx.js +0 -332
  118. package/dist/chunk-8emp6ysb.js +0 -1
  119. package/dist/chunk-8evyh5t0.js +0 -1
  120. package/dist/chunk-8hdtssvs.js +0 -1
  121. package/dist/chunk-b36egepz.js +0 -1
  122. package/dist/chunk-hrtf7dba.js +0 -2
  123. package/dist/chunk-j7dx054r.js +0 -1
  124. package/dist/chunk-j9ppeg6v.js +0 -1
  125. package/dist/chunk-jemb0vwa.js +0 -1
  126. package/dist/chunk-r9m3b170.js +0 -1
  127. package/dist/chunk-tf1qz4q6.js +0 -1
  128. package/dist/chunk-v17q4bsd.js +0 -6
  129. package/dist/chunk-y0wc0hef.js +0 -10
  130. package/dist/web/assets/ChatView-BA3kB_z1.js +0 -17
  131. package/dist/web/assets/FilePreview-BQid6G2-.js +0 -8
  132. package/dist/web/assets/KanbanBoard-CTR7bMLa.js +0 -1
  133. package/dist/web/assets/SettingsModal-CFa2uCzI.js +0 -5
  134. package/dist/web/assets/Sidebar-DrRNJOgU.js +0 -1
  135. package/dist/web/assets/chevron-right-6ZTOJE0p.js +0 -1
  136. package/dist/web/assets/index-BVEiHNFk.css +0 -1
  137. package/dist/web/assets/message-square-plus-CKu9bFq3.js +0 -1
  138. package/dist/web/assets/plus-C4p8E1Nk.js +0 -1
  139. package/dist/web/assets/preload-helper-BC9Zf9qO.js +0 -1
  140. package/dist/web/assets/team-qGS2kixH.js +0 -1
  141. package/dist/web/assets/triangle-alert-Detl9fRQ.js +0 -1
@@ -1,2 +1,2 @@
1
- import{Q as GP}from"./chunk-25s0c8km.js";import{me as N}from"./chunk-hmw99nm1.js";import{Te as r,Ue as e,Xe as L,Ze as PP,af as d,cf as l,ef as JP,gf as QP,hf as ZP,if as $P,jf as w}from"./chunk-dxq7462e.js";import{lf as t,mf as a,of as R,qf as y,rf as A,tf as p}from"./chunk-tqt5c2f5.js";import{Pj as q}from"./chunk-0wcnkxe8.js";import{ek as o,yk as s,zk as n}from"./chunk-gzbb747a.js";async function qP(){return q().listProviders()}async function EP(P){return q().listModels(P)}import{randomBytes as XP}from"node:crypto";var NP=600000,OP=2048,jP=64,MP=32,HP=67108864,WP=4,D={catalog:"session-surface-catalog:",history:"session-surface-history:",snapshot:"session-surface-snapshot:"},c={session_surface_cursor_invalid:{message:"session surface cursor is invalid",retryable:!1},session_surface_snapshot_changed:{message:"session surface snapshot changed",retryable:!1},session_surface_capacity:{message:"session surface cursor capacity exceeded",retryable:!0},session_surface_unavailable:{message:"session surface cursor registry is unavailable",retryable:!0}};class U extends Error{code;retryable;constructor(P){super(c[P].message);this.code=P;this.name="SessionSurfaceCursorRegistryError",this.retryable=c[P].retryable}}class g{now;tokenSource;tokenCollisionRetries;limitsValue;entries=new Map;chains=new Map;closed=!1;closePromise;totalIssues=0;activeLoads=0;frozenSnapshotBytes=0;retainedPayloadBytes=0;constructor(P={}){if(this.now=P.now??(()=>Date.now()),this.tokenSource=P.tokenSource??(()=>XP(32).toString("base64url")),this.tokenCollisionRetries=P.tokenCollisionRetries??WP,this.limitsValue=_P(P.limits??{}),!Number.isSafeInteger(this.tokenCollisionRetries)||this.tokenCollisionRetries<0)throw Error("tokenCollisionRetries must be a non-negative safe integer")}issueCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=m(P.boundary);if(J.value===void 0)throw new U("session_surface_cursor_invalid");let Q=T(P.request);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Z=this.createToken("catalog"),$=this.now(),G=this.ensureChain(P.chainId,$),Y={token:Z,chainId:P.chainId,kind:"catalog",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,scopeKey:P.scopeKey,epoch:P.epoch,revision:P.revision,boundary:J.value,boundaryBytes:J.bytes,requestHash:Q,cachedResultBytes:0};return this.storeEntry(G,Y),this.retainedPayloadBytes+=J.bytes,G.retainedPayloadBytes+=J.bytes,Z}issueHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=T(P.request),Q=this.assertSnapshotIssuableForHistory(P);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:0,chainId:P.chainId});let Z=this.createToken("history"),$=this.now(),G=this.ensureChain(P.chainId,$);this.touch(Q);let Y={token:Z,chainId:P.chainId,kind:"history",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,nextSequence:P.nextSequence,snapshotToken:P.snapshotToken,requestHash:J,cachedResultBytes:0};return this.storeEntry(G,Y),Z}issueSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=P.frozenSnapshot===void 0?{value:void 0,bytes:0}:m(P.frozenSnapshot);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Q=this.createToken("snapshot"),Z=this.now(),$=this.ensureChain(P.chainId,Z),G={token:Q,chainId:P.chainId,kind:"snapshot",expiresAt:Z+this.limitsValue.idleTtlMs,lastAccessAt:Z,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,frozenBytes:J.bytes,frozenSnapshot:J.value};return this.storeEntry($,G),this.frozenSnapshotBytes+=J.bytes,this.retainedPayloadBytes+=J.bytes,$.frozenSnapshotBytes+=J.bytes,$.retainedPayloadBytes+=J.bytes,Q}async redeemCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"catalog");if(J.scopeKey!==P.scopeKey)throw new U("session_surface_cursor_invalid");if(J.epoch!==P.epoch||J.revision!==P.revision)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");if(this.touch(J),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startCatalogLoad(J,P.loader)}async redeemHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"history");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_snapshot_changed");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");let Q=this.resolveHistorySnapshot(J);if(this.touch(J),this.touch(Q),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startHistoryLoad(J,Q,P.loader)}async assertSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"snapshot");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_cursor_invalid");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return this.touch(J),{chainId:J.chainId,locatorDigest:J.locatorDigest,transcriptFingerprint:J.transcriptFingerprint,frozenBytes:J.frozenBytes,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)}}completeChain(P){this.cleanup();let J=this.chains.get(P);if(!J)return;J.completed=!0,J.lastAccessAt=this.now()}stats(){this.cleanup();let P=0;for(let J of this.chains.values())if(J.completed)P+=1;return{closed:this.closed,chainCount:this.chains.size,activeChains:this.chains.size-P,completedChains:P,entryCount:this.entries.size,activeLoads:this.activeLoads,frozenSnapshotBytes:this.frozenSnapshotBytes,retainedPayloadBytes:this.retainedPayloadBytes,totalIssues:this.totalIssues,limits:{...this.limitsValue}}}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;let J=[];for(let Q of this.entries.values())if((Q.kind==="catalog"||Q.kind==="history")&&Q.activeLoad)J.push(Q.activeLoad.promise),Q.activeLoad.controller.abort(_());return this.closePromise=Promise.allSettled(J).then(()=>{this.entries.clear(),this.chains.clear(),this.activeLoads=0,this.frozenSnapshotBytes=0,this.retainedPayloadBytes=0}),this.closePromise}startCatalogLoad(P,J){let Q=this.requireChain(P.chainId),Z=new AbortController;this.activeLoads+=1,Q.activeLoads+=1;let $=Promise.resolve().then(()=>J({boundary:W(P.boundary)},Z.signal)).then((G)=>{return this.assertLoadAvailable(Z.signal),this.admitCachedResult(P,G)}).catch((G)=>{if(this.closed||Z.signal.aborted)throw _();throw G}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Q.activeLoads-=1});return P.activeLoad={controller:Z,promise:$},this.cloneActiveLoadResult(P.activeLoad)}startHistoryLoad(P,J,Q){let Z=this.requireChain(P.chainId),$=new AbortController;this.activeLoads+=1,Z.activeLoads+=1;let G=Promise.resolve().then(()=>Q({nextSequence:P.nextSequence,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)},$.signal)).then((Y)=>{return this.assertLoadAvailable($.signal),this.admitCachedResult(P,Y)}).catch((Y)=>{if(this.closed||$.signal.aborted)throw _();throw Y}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Z.activeLoads-=1});return P.activeLoad={controller:$,promise:G},this.cloneActiveLoadResult(P.activeLoad)}resolveHistorySnapshot(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}assertSnapshotIssuableForHistory(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.chainId!==P.chainId||Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}requireChain(P){let J=this.chains.get(P);if(!J)throw new U("session_surface_cursor_invalid");return J}assertLoadAvailable(P){if(this.closed||P.aborted)throw _()}getEntry(P,J){if(E(P)!==J)throw new U("session_surface_cursor_invalid");let Z=this.entries.get(P);if(!Z)throw new U("session_surface_cursor_invalid");if(Z.kind!==J)throw new U("session_surface_cursor_invalid");if(Z.expiresAt<=this.now()&&!f(Z))throw this.removeEntry(Z),new U("session_surface_cursor_invalid");return Z}touch(P){let J=this.now();P.lastAccessAt=J,P.expiresAt=J+this.limitsValue.idleTtlMs;let Q=this.chains.get(P.chainId);if(Q)Q.lastAccessAt=J}storeEntry(P,J){if(P.tokens.size>=this.limitsValue.maxEntriesPerChain)throw new U("session_surface_capacity");this.entries.set(J.token,J),P.tokens.add(J.token),P.completed=!1,P.lastAccessAt=J.lastAccessAt,P.issueCount+=1,this.totalIssues+=1}ensureChain(P,J){let Q=this.chains.get(P);if(Q)return Q.lastAccessAt=J,Q;let Z={chainId:P,tokens:new Set,completed:!1,lastAccessAt:J,issueCount:0,activeLoads:0,frozenSnapshotBytes:0,retainedPayloadBytes:0};return this.chains.set(P,Z),Z}cloneActiveLoadResult(P){return P.promise.then((J)=>W(J))}admitCachedResult(P,J){let Q=m(J),Z=this.requireChain(P.chainId),$=Q.bytes-P.cachedResultBytes;if(this.ensureCapacity({requestedEntries:0,requestedRetainedBytes:Math.max(0,$),chainId:P.chainId}),this.releaseCachedResult(P,Z),Q.value===void 0)throw new U("session_surface_cursor_invalid");return P.cachedResult=Q.value,P.cachedResultBytes=Q.bytes,this.retainedPayloadBytes+=Q.bytes,Z.retainedPayloadBytes+=Q.bytes,P.cachedResult}createToken(P){let J=D[P];for(let Q=0;Q<=this.tokenCollisionRetries;Q+=1){this.assertAvailable();let Z=`${J}${this.tokenSource()}`;if(!this.entries.has(Z))return Z}throw new U("session_surface_capacity")}ensureCapacity(P){this.reclaimCompletedChains(P);let J=this.entries.size+P.requestedEntries,Q=this.chains.size+(this.chains.has(P.chainId)?0:1),Z=this.retainedPayloadBytes+P.requestedRetainedBytes,$=(this.chains.get(P.chainId)?.tokens.size??0)+P.requestedEntries;if(J>this.limitsValue.maxEntries||Q>this.limitsValue.maxChains||$>this.limitsValue.maxEntriesPerChain||Z>this.limitsValue.maxFrozenSnapshotBytes)throw new U("session_surface_capacity")}reclaimCompletedChains(P){let J=[...this.chains.values()].filter((Q)=>Q.completed&&Q.activeLoads===0).sort((Q,Z)=>Q.lastAccessAt-Z.lastAccessAt);for(let Q of J){if(!(this.entries.size+P.requestedEntries>this.limitsValue.maxEntries||this.chains.size+(P.chainId!==""&&this.chains.has(P.chainId)?0:1)>this.limitsValue.maxChains||this.retainedPayloadBytes+P.requestedRetainedBytes>this.limitsValue.maxFrozenSnapshotBytes))break;this.removeChain(Q.chainId)}}cleanup(){let P=this.now();for(let J of[...this.entries.values()]){if(J.expiresAt>P||f(J))continue;this.removeEntry(J)}for(let J of[...this.chains.values()])if(J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}removeEntry(P){this.entries.delete(P.token);let J=this.chains.get(P.chainId);if(J){if(J.tokens.delete(P.token),this.releaseEntryRetainedPayload(P,J),J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}else this.releaseEntryRetainedPayload(P)}removeChain(P){let J=this.chains.get(P);if(!J)return;for(let Q of J.tokens){let Z=this.entries.get(Q);if(!Z||f(Z))continue;this.entries.delete(Q),this.releaseEntryRetainedPayload(Z,J)}this.chains.delete(P)}releaseEntryRetainedPayload(P,J){if(P.kind==="snapshot"){if(this.frozenSnapshotBytes-=P.frozenBytes,this.retainedPayloadBytes-=P.frozenBytes,J)J.frozenSnapshotBytes-=P.frozenBytes,J.retainedPayloadBytes-=P.frozenBytes;return}if(P.kind==="catalog"){if(this.retainedPayloadBytes-=P.boundaryBytes,J)J.retainedPayloadBytes-=P.boundaryBytes}this.releaseCachedResult(P,J)}releaseCachedResult(P,J){if(P.cachedResultBytes===0){P.cachedResult=void 0;return}if(this.retainedPayloadBytes-=P.cachedResultBytes,J)J.retainedPayloadBytes-=P.cachedResultBytes;P.cachedResult=void 0,P.cachedResultBytes=0}assertAvailable(){if(this.closed)throw _()}}function E(P){if(P.startsWith(D.catalog))return"catalog";if(P.startsWith(D.history))return"history";if(P.startsWith(D.snapshot))return"snapshot";return}function f(P){return P.kind!=="snapshot"&&P.activeLoad!==void 0}function _P(P){let J={idleTtlMs:P.idleTtlMs??NP,maxEntries:P.maxEntries??OP,maxChains:P.maxChains??jP,maxEntriesPerChain:P.maxEntriesPerChain??MP,maxFrozenSnapshotBytes:P.maxFrozenSnapshotBytes??HP};for(let Q of Object.values(J))if(!Number.isSafeInteger(Q)||Q<=0)throw Error("session surface cursor registry limits must be positive safe integers");return J}function _(){return new U("session_surface_unavailable")}function T(P){return B(W(P))}function W(P){try{return S(P,new Set)}catch{throw new U("session_surface_cursor_invalid")}}function S(P,J){if(P===null)return null;if(typeof P==="string"||typeof P==="boolean")return P;if(typeof P==="number"){if(!Number.isFinite(P))throw Error("invalid number");return P}if(typeof P>"u"||typeof P==="function"||typeof P==="symbol"||typeof P==="bigint")throw Error("invalid JSON type");if(!P||typeof P!=="object")throw Error("invalid JSON value");if(J.has(P))throw Error("cycle");J.add(P);try{if(Array.isArray(P)){let $=[];for(let G=0;G<P.length;G+=1){if(!(G in P))throw Error("sparse array");$.push(S(P[G],J))}return $}if(Object.getOwnPropertySymbols(P).length>0)throw Error("symbol keys");let Q=Object.getPrototypeOf(P);if(Q!==Object.prototype&&Q!==null)throw Error("non-plain object");let Z={};for(let $ of Object.keys(P)){let G=Reflect.get(P,$);if(G===void 0)throw Error("undefined object value");Z[$]=S(G,J)}return Z}finally{J.delete(P)}}function B(P){if(P===null)return"null";if(typeof P==="string"||typeof P==="number")return JSON.stringify(P);if(typeof P==="boolean")return P?"true":"false";if(Array.isArray(P))return`[${P.map((Q)=>B(Q)).join(",")}]`;return`{${Object.keys(P).sort().map((Q)=>`${JSON.stringify(Q)}:${B(P[Q])}`).join(",")}}`}function m(P,J={}){if(P===void 0){if(J.allowUndefined)return{value:void 0,bytes:0};throw new U("session_surface_cursor_invalid")}let Q=W(P);return{value:Q,bytes:Buffer.byteLength(B(Q),"utf8")}}import{createHash as C,randomBytes as F}from"node:crypto";import FP from"node:path";var YP=50,zP=100,AP=16,TP=1e4,DP=16777216;class z extends Error{code;retryable;constructor(P){let J=CP(P);super(J.message);this.code=P;this.name="SessionSurfaceServiceError",this.retryable=J.retryable}}class BP{database;registry;epoch;maxConcurrentOperations;activeControllers=new Set;activeOperations=new Set;closed=!1;closePromise;concurrentOperations=0;constructor(P={}){if(this.database=P.database,this.registry=P.cursorRegistry??new g(P.cursorRegistryOptions),this.epoch=P.epochSource?.()??`session-surface-epoch:${F(32).toString("base64url")}`,this.maxConcurrentOperations=P.maxConcurrentOperations??AP,!Number.isSafeInteger(this.maxConcurrentOperations)||this.maxConcurrentOperations<1||this.maxConcurrentOperations>256)throw Error("maxConcurrentOperations must be an integer from 1 to 256")}async listPage(P={}){return this.runOperation(async(J)=>{let Q=K(P.limit),Z=P.archived??!1,$={archived:Z,limit:Q,workspaceKind:P.workspaceKind??null},G=JSON.stringify([Z,P.workspaceKind??null]),Y=await this.requireDatabase();if(J.throwIfAborted(),!Y)return this.listFallbackPage($,G,J,P.cursor);if(await this.syncAllSurfaces(Y,J),P.cursor){let V=String(ZP(Y));return this.registry.redeemCatalogCursor({token:P.cursor,scopeKey:G,epoch:this.epoch,revision:V,request:$,loader:async({boundary:X})=>{let O=KP(X);return this.loadCatalogPage(Y,$,G,V,O,O.chainId,J)}})}return this.loadCatalogPage(Y,$,G,void 0,void 0,void 0,J)})}async open(P,J={}){return this.runOperation((Q)=>this.openInternal(P,J,Q))}async historyPage(P,J){return this.runOperation(async(Q)=>{let Z=I(P),$=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.readFallbackHistoryPage(Z,J,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:1}),X=x(Z);await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint});let O={expectedSnapshot:J.expectedSnapshot,limit:$},j=await this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint,request:O,loader:async({nextSequence:M})=>{let H=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,beforeSequence:M,limit:$});return this.publicHistoryPage({history:H,snapshot:J.expectedSnapshot,chainId:(await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint})).chainId,locatorDigest:X,limit:$})}});return A.parse(j)})}async fork(P){return this.runOperation(async(J)=>{let Q=I(P),Z=await this.requireDatabase(),$=Z?await this.resolveFromProjectionAfterSync(Z,Q,J):await this.resolveFallback(Q,J);if($.candidate.summary.archivedAt)throw new z("session_surface_read_only");J.throwIfAborted();let G=await N.forkSession(Q.sessionId,{sourceProjectPath:$.candidate.projectPath,targetProjectPath:$.candidate.projectPath,...$.remoteCandidate?{remote:{expectedDescriptor:$.remoteCandidate.descriptor}}:{}}),Y=$.remoteCandidate?{version:2,sessionId:G.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.candidate.publicWorkspaceRef}}:{version:2,sessionId:G.sessionId,workspace:{kind:"local",projectPath:$.candidate.projectPath}};return Z?this.openInternal(Y,{},J):this.openFallback(Y,YP,J)})}async resolveFromProjectionAfterSync(P,J,Q){return await this.syncForLocator(P,J,Q),this.resolveFromProjection(P,J,Q)}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;for(let J of this.activeControllers)J.abort(new z("session_surface_unavailable"));return this.closePromise=Promise.allSettled([...this.activeOperations,this.registry.close()]).then(()=>{return}),this.closePromise}async openInternal(P,J={},Q){let Z=I(P),$=K(J.limit);if(J.cursor!==void 0||J.expectedSnapshot!==void 0)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.openFallback(Z,$,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:$}),X=`history-chain:${F(16).toString("base64url")}`,O=x(Z),j=this.registry.issueSnapshotToken({chainId:X,locatorDigest:O,transcriptFingerprint:V.transcriptFingerprint}),M={session:this.toSummary(Y),history:this.publicHistoryPage({history:V,snapshot:j,chainId:X,locatorDigest:O,limit:$})};return p.parse(M)}runOperation(P){if(this.assertAvailable(),this.concurrentOperations>=this.maxConcurrentOperations)throw new z("session_surface_capacity");let J=new AbortController;this.activeControllers.add(J),this.concurrentOperations+=1;let Q;return Q=Promise.resolve().then(()=>P(J.signal)).then((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");return Z}).catch((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");throw kP(Z)}).finally(()=>{this.activeControllers.delete(J),this.activeOperations.delete(Q),this.concurrentOperations-=1}),this.activeOperations.add(Q),Q}async loadCatalogPage(P,J,Q,Z,$,G,Y){let V=$P(P,{archived:J.archived,limit:J.limit,...J.workspaceKind?{workspaceKind:J.workspaceKind}:{},...$?{boundary:$}:{}}),X=String(V.revision);if(Z!==void 0&&Z!==X)throw new z("session_surface_snapshot_changed");let O=G??`catalog-chain:${F(16).toString("base64url")}`,j={sessions:await Promise.all(V.sessions.map(async(M)=>this.toSummary(await this.resolveCandidate(M,Y)))),...V.nextBoundary?{nextCursor:this.registry.issueCatalogCursor({chainId:O,scopeKey:Q,epoch:this.epoch,revision:X,boundary:{...V.nextBoundary,chainId:O},request:J})}:{}};if(!V.nextBoundary)this.registry.completeChain(O);return y.parse(j)}publicHistoryPage(P){let J=h(P.history.messages,L()),Q={messages:J.messages,snapshot:P.snapshot,truncated:P.history.hasOlder||J.truncated||J.messages.some((Z)=>Z.truncated===!0),...P.history.hasOlder&&P.history.nextSequence!==void 0?{olderCursor:this.registry.issueHistoryCursor({chainId:P.chainId,locatorDigest:P.locatorDigest,transcriptFingerprint:P.history.transcriptFingerprint,nextSequence:P.history.nextSequence,snapshotToken:P.snapshot,request:{expectedSnapshot:P.snapshot,limit:P.limit}})}:{}};if(!P.history.hasOlder)this.registry.completeChain(P.chainId);return A.parse(Q)}async syncForLocator(P,J,Q){if(Q?.throwIfAborted(),J.workspace.kind==="local"){await N.findSessionMetadata(J.sessionId,J.workspace.projectPath),Q?.throwIfAborted(),await d(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await N.listValidatedRemoteSurfaceCandidates(Q),await l(P,N.projectionDeriverForSearch(),Q)}async syncAllSurfaces(P,J){let Q=N.projectionDeriverForSearch(),Z=await N.listValidatedLocalSurfaceCandidates(J),$=new Set(Z.map((Y)=>`${Y.projectPath}\x00${Y.sessionId}`)),G=P.prepare("SELECT project_path, session_id FROM sessions WHERE source_kind='local'").all();for(let Y of G)if(!$.has(`${Y.project_path}\x00${Y.session_id}`))JP(P,Y.session_id,Y.project_path,"local");for(let Y of Z)J?.throwIfAborted(),await d(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await N.listValidatedRemoteSurfaceCandidates(J),await l(P,Q,J)}async listFallbackPage(P,J,Q,Z){if(Z)return this.registry.redeemCatalogCursor({token:Z,scopeKey:J,epoch:this.epoch,revision:"fallback",request:P,loader:async({boundary:G})=>{let Y=LP(G);return this.pageFallbackCatalog(Y.entries,P,J,Y.chainId)}});let $=await this.loadFallbackCatalog(P,Q);return this.pageFallbackCatalog($,P,J,`catalog-fallback:${F(16).toString("base64url")}`)}async loadFallbackCatalog(P,J){let Q=[];if(P.workspaceKind!=="acp-remote")for(let $ of await N.listValidatedLocalSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedLocalSurfaceSnapshot($.sessionId,$.projectPath,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},summary:Y})}if(P.workspaceKind!=="local")for(let $ of await N.listValidatedRemoteSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedRemoteSurfaceSnapshot($,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.workspaceRef}},summary:Y})}Q.sort(IP);let Z=Buffer.byteLength(JSON.stringify(Q));if(Q.length>TP||Z>DP)throw new z("session_surface_capacity");return Q}async pageFallbackCatalog(P,J,Q,Z){let $=P.slice(0,J.limit),G=P.slice($.length),V={sessions:$.map((X)=>R.parse({locator:X.locator,...X.summary,capabilities:X.locator.workspace.kind==="local"?UP(Boolean(X.summary.archivedAt)):RP(Boolean(X.summary.archivedAt))})),...G.length>0?{nextCursor:this.registry.issueCatalogCursor({chainId:Z,scopeKey:Q,epoch:this.epoch,revision:"fallback",boundary:{chainId:Z,entries:G},request:J})}:{}};if(G.length===0)this.registry.completeChain(Z);return y.parse(V)}async openFallback(P,J,Q){let Z=await this.resolveFallback(P,Q),$=Z.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(Z.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(Z.candidate.sessionId,Z.candidate.projectPath,Q),G=e($.entries,{...Z.remoteCandidate?r(Z.remoteCandidate.hostStateRoot,Z.remoteCandidate.descriptor):{privateRoots:[]},bladeStorageRoots:[o()]}),Y=h(G.slice(-J),L()),V=`history-fallback:${F(16).toString("base64url")}`,X=x(P),O=C("sha256").update(JSON.stringify($.entries)).digest("hex"),j=this.registry.issueSnapshotToken({chainId:V,locatorDigest:X,transcriptFingerprint:O,frozenSnapshot:G}),M={session:this.toSummary(Z),history:A.parse({messages:Y.messages,snapshot:j,truncated:Y.messages.length<G.length||Y.truncated||Y.messages.some((H)=>H.truncated===!0),...G.length>Y.messages.length&&Y.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:V,locatorDigest:X,transcriptFingerprint:O,nextSequence:v(Y.messages[0].id),snapshotToken:j,request:{expectedSnapshot:j,limit:J}})}:{}})};if(G.length<=Y.messages.length)this.registry.completeChain(V);return p.parse(M)}async readFallbackHistoryPage(P,J,Q){let Z=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let $=x(P),G=await this.resolveFallback(P,Q),Y=G.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(G.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(G.candidate.sessionId,G.candidate.projectPath,Q),V=C("sha256").update(JSON.stringify(Y.entries)).digest("hex");await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V});let X={expectedSnapshot:J.expectedSnapshot,limit:Z};return this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:$,transcriptFingerprint:V,request:X,loader:async({nextSequence:O,frozenSnapshot:j})=>{let M=xP(j).filter((b)=>v(b.id)<O),H=h(M.slice(-Z),L()),u=await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V}),k=H.messages.length<M.length,VP={messages:H.messages,snapshot:J.expectedSnapshot,truncated:k||H.truncated||H.messages.some((b)=>b.truncated===!0),...k&&H.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:u.chainId,locatorDigest:$,transcriptFingerprint:V,nextSequence:v(H.messages[0].id),snapshotToken:J.expectedSnapshot,request:X})}:{}};if(!k)this.registry.completeChain(u.chainId);return A.parse(VP)}})}async resolveFallback(P,J){let Q=[];for(let G of[!1,!0]){let Y={archived:G,limit:zP,workspaceKind:P.workspace.kind};Q.push(...(await this.loadFallbackCatalog(Y,J)).filter((V)=>JSON.stringify(V.locator)===JSON.stringify(P)))}if(Q.length!==1)throw new z("session_surface_not_found");let Z=Q[0],$;if(P.workspace.kind==="acp-remote"){let G=P.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(J)).find((Y)=>Y.sessionId===P.sessionId&&Y.workspaceRef===G),!$)throw new z("workspace_binding_mismatch")}return{candidate:{sourceKind:P.workspace.kind,projectPath:P.workspace.kind==="local"?P.workspace.projectPath:$.hostStateRoot,sessionId:P.sessionId,...P.workspace.kind==="acp-remote"?{publicWorkspaceRef:P.workspace.workspaceRef}:{},publicWorkspaceSortKey:"",surfaceDigest:i(Z),transcriptFingerprint:i(Z),lastMessageTime:Z.summary.lastMessageTime,sessionSortKey:"",summary:Z.summary},...$?{remoteCandidate:$}:{}}}async resolveFromProjection(P,J,Q){let Z=QP(P,J.sessionId).filter((G)=>J.workspace.kind==="local"?G.sourceKind==="local"&&G.projectPath===FP.resolve(J.workspace.projectPath):G.sourceKind==="acp-remote"&&G.publicWorkspaceRef===J.workspace.workspaceRef);if(Z.length!==1)throw new z(Z.length===0?"session_surface_not_found":"workspace_binding_mismatch");let $;if(J.workspace.kind==="acp-remote"){let G=J.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(Q)).filter((Y)=>Y.sessionId===J.sessionId&&Y.workspaceRef===G),$.length===0)throw new z("workspace_binding_mismatch");if($.length>1)throw new z("session_surface_state_invalid")}return $?{candidate:Z[0],remoteCandidate:$[0]}:{candidate:Z[0]}}async resolveCandidate(P,J){if(P.sourceKind==="local")return{candidate:P};let Q=(await N.listValidatedRemoteSurfaceCandidates(J)).filter((Z)=>Z.sessionId===P.sessionId&&Z.workspaceRef===P.publicWorkspaceRef);if(Q.length!==1)throw new z(Q.length===0?"workspace_binding_mismatch":"session_surface_state_invalid");return{candidate:P,remoteCandidate:Q[0]}}toSummary(P){let J=P.candidate,Q=J.sourceKind==="local"?{version:2,sessionId:J.sessionId,workspace:{kind:"local",projectPath:J.projectPath}}:{version:2,sessionId:J.sessionId,workspace:{kind:"acp-remote",workspaceRef:J.publicWorkspaceRef}};return R.parse({locator:Q,...J.summary,capabilities:this.capabilitiesFor(P)})}capabilitiesFor(P){let J=P.candidate.summary.archivedAt!==void 0;if(!P.remoteCandidate)return{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}};return{connection:GP.getRemoteSurfaceOwnerSnapshot(P.candidate.sessionId,P.remoteCandidate.descriptor).connection,history:{read:!0,fork:!J},turn:{start:!1,reason:J?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:J?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:J?"archived":"history-only"}}}async requireDatabase(){if(this.database===null)return null;return this.database??await PP()}assertAvailable(){if(this.closed)throw new z("session_surface_unavailable")}}function K(P){let J=P??YP;if(!Number.isSafeInteger(J)||J<1||J>zP)throw new z("invalid_session_surface_request");return J}function I(P){try{let J=t.parse(P);if(!n(J.sessionId))throw Error("invalid");if(J.workspace.kind==="local"){if(s(J.workspace.projectPath)!==J.workspace.projectPath)throw Error("invalid")}return J}catch{throw new z("invalid_session_locator")}}function x(P){return C("sha256").update("session-surface-locator-v2\x00").update(JSON.stringify(P)).digest("hex")}function KP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.lastMessageTime!=="string"||J.sourceKind!=="local"&&J.sourceKind!=="acp-remote"||typeof J.publicWorkspaceSortKey!=="string"||typeof J.sessionSortKey!=="string"||typeof J.chainId!=="string"||!J.chainId)throw new z("session_surface_cursor_invalid");return{lastMessageTime:J.lastMessageTime,sourceKind:J.sourceKind,publicWorkspaceSortKey:J.publicWorkspaceSortKey,sessionSortKey:J.sessionSortKey,chainId:J.chainId}}function h(P,J){let Q=[];for(let Z=P.length-1;Z>=0;Z-=1){let $=P[Z];if(!$)continue;let G=[$,...Q];if(Q.length>0&&Buffer.byteLength(JSON.stringify(G))>J)break;Q.unshift($)}return{messages:Q,truncated:Q.length<P.length}}function v(P){let J=/^surface-message:([0-9]+):/.exec(P),Q=J?Number(J[1]):Number.NaN;if(!Number.isSafeInteger(Q)||Q<=0)throw new z("session_surface_state_invalid");return Q}function xP(P){if(!Array.isArray(P))throw new z("session_surface_snapshot_changed");return P.map((J)=>{try{return a.parse(J)}catch{throw new z("session_surface_snapshot_changed")}})}function LP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.chainId!=="string"||J.chainId.length===0||!Array.isArray(J.entries))throw new z("session_surface_cursor_invalid");let Q=J.entries.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new z("session_surface_cursor_invalid");let $=Z;return{locator:I($.locator),summary:wP($.summary)}});return{chainId:J.chainId,entries:Q}}function wP(P){let J={version:2,sessionId:"placeholder",workspace:{kind:"local",projectPath:"/"}},Q=R.parse({...P&&typeof P==="object"&&!Array.isArray(P)?P:{},locator:J,capabilities:UP(!1)}),{locator:Z,capabilities:$,...G}=Q;return G}function IP(P,J){if(P.summary.lastMessageTime>J.summary.lastMessageTime)return-1;if(P.summary.lastMessageTime<J.summary.lastMessageTime)return 1;if(P.locator.workspace.kind!==J.locator.workspace.kind)return P.locator.workspace.kind==="local"?-1:1;let Q=P.locator.workspace.kind==="local"?P.locator.workspace.projectPath:P.locator.workspace.workspaceRef,Z=J.locator.workspace.kind==="local"?J.locator.workspace.projectPath:J.locator.workspace.workspaceRef;if(Q<Z)return-1;if(Q>Z)return 1;return P.locator.sessionId<J.locator.sessionId?-1:P.locator.sessionId>J.locator.sessionId?1:0}function i(P){return C("sha256").update("session-surface-fallback-entry\x00").update(JSON.stringify(P)).digest("hex")}function UP(P){return{connection:"local",history:{read:!0,fork:!P},turn:P?{start:!1,reason:"archived"}:{start:!0},files:P?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:P?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}}function RP(P){return{connection:"offline",history:{read:!0,fork:!P},turn:{start:!1,reason:P?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:P?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:P?"archived":"history-only"}}}function CP(P){if(P==="session_surface_cursor_invalid")return{message:"Session surface cursor is invalid",retryable:!1};if(P==="session_surface_snapshot_changed")return{message:"Session surface snapshot changed",retryable:!1};if(P==="session_surface_state_invalid")return{message:"Session surface state is invalid",retryable:!1};if(P==="session_surface_capability_unavailable")return{message:"Session surface capability is unavailable",retryable:!1};if(P==="session_surface_unavailable")return{message:"Session surface is unavailable",retryable:!0};if(P==="session_surface_not_found")return{message:"Session surface was not found",retryable:!1};if(P==="workspace_binding_mismatch")return{message:"Session workspace binding changed",retryable:!1};if(P==="session_surface_read_only")return{message:"Session surface is read only",retryable:!1};if(P==="session_surface_capacity")return{message:"Session surface capacity is exhausted",retryable:!0};if(P==="invalid_session_locator")return{message:"Session locator is invalid",retryable:!1};return{message:"Session surface request is invalid",retryable:!1}}function kP(P){if(P instanceof z)return P;if(P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"){let J=P.code;if(J==="session_surface_cursor_invalid"||J==="session_surface_snapshot_changed"||J==="session_surface_capacity"||J==="session_surface_unavailable"||J==="session_surface_state_invalid")return new z(J);if(J==="acp_remote_workspace_state_invalid")return new z("session_surface_state_invalid")}return P instanceof Error?P:new z("session_surface_state_invalid")}
1
+ import{Q as GP}from"./chunk-r9nyzqzb.js";import{ne as N}from"./chunk-faedrfhd.js";import{Ue as r,Ve as e,Ye as L,_e as PP,bf as d,df as l,ff as JP,hf as QP,if as ZP,jf as $P,kf as w}from"./chunk-wan9q99y.js";import{mf as t,nf as a,pf as R,rf as y,sf as A,uf as p}from"./chunk-n30najxq.js";import{Qj as q}from"./chunk-5s2x98rx.js";import{Ak as n,fk as o,zk as s}from"./chunk-a95jmx2j.js";async function qP(){return q().listProviders()}async function EP(P){return q().listModels(P)}import{randomBytes as XP}from"node:crypto";var NP=600000,OP=2048,jP=64,MP=32,HP=67108864,WP=4,D={catalog:"session-surface-catalog:",history:"session-surface-history:",snapshot:"session-surface-snapshot:"},c={session_surface_cursor_invalid:{message:"session surface cursor is invalid",retryable:!1},session_surface_snapshot_changed:{message:"session surface snapshot changed",retryable:!1},session_surface_capacity:{message:"session surface cursor capacity exceeded",retryable:!0},session_surface_unavailable:{message:"session surface cursor registry is unavailable",retryable:!0}};class U extends Error{code;retryable;constructor(P){super(c[P].message);this.code=P;this.name="SessionSurfaceCursorRegistryError",this.retryable=c[P].retryable}}class g{now;tokenSource;tokenCollisionRetries;limitsValue;entries=new Map;chains=new Map;closed=!1;closePromise;totalIssues=0;activeLoads=0;frozenSnapshotBytes=0;retainedPayloadBytes=0;constructor(P={}){if(this.now=P.now??(()=>Date.now()),this.tokenSource=P.tokenSource??(()=>XP(32).toString("base64url")),this.tokenCollisionRetries=P.tokenCollisionRetries??WP,this.limitsValue=_P(P.limits??{}),!Number.isSafeInteger(this.tokenCollisionRetries)||this.tokenCollisionRetries<0)throw Error("tokenCollisionRetries must be a non-negative safe integer")}issueCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=m(P.boundary);if(J.value===void 0)throw new U("session_surface_cursor_invalid");let Q=T(P.request);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Z=this.createToken("catalog"),$=this.now(),G=this.ensureChain(P.chainId,$),Y={token:Z,chainId:P.chainId,kind:"catalog",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,scopeKey:P.scopeKey,epoch:P.epoch,revision:P.revision,boundary:J.value,boundaryBytes:J.bytes,requestHash:Q,cachedResultBytes:0};return this.storeEntry(G,Y),this.retainedPayloadBytes+=J.bytes,G.retainedPayloadBytes+=J.bytes,Z}issueHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=T(P.request),Q=this.assertSnapshotIssuableForHistory(P);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:0,chainId:P.chainId});let Z=this.createToken("history"),$=this.now(),G=this.ensureChain(P.chainId,$);this.touch(Q);let Y={token:Z,chainId:P.chainId,kind:"history",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,nextSequence:P.nextSequence,snapshotToken:P.snapshotToken,requestHash:J,cachedResultBytes:0};return this.storeEntry(G,Y),Z}issueSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=P.frozenSnapshot===void 0?{value:void 0,bytes:0}:m(P.frozenSnapshot);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Q=this.createToken("snapshot"),Z=this.now(),$=this.ensureChain(P.chainId,Z),G={token:Q,chainId:P.chainId,kind:"snapshot",expiresAt:Z+this.limitsValue.idleTtlMs,lastAccessAt:Z,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,frozenBytes:J.bytes,frozenSnapshot:J.value};return this.storeEntry($,G),this.frozenSnapshotBytes+=J.bytes,this.retainedPayloadBytes+=J.bytes,$.frozenSnapshotBytes+=J.bytes,$.retainedPayloadBytes+=J.bytes,Q}async redeemCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"catalog");if(J.scopeKey!==P.scopeKey)throw new U("session_surface_cursor_invalid");if(J.epoch!==P.epoch||J.revision!==P.revision)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");if(this.touch(J),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startCatalogLoad(J,P.loader)}async redeemHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"history");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_snapshot_changed");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");let Q=this.resolveHistorySnapshot(J);if(this.touch(J),this.touch(Q),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startHistoryLoad(J,Q,P.loader)}async assertSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"snapshot");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_cursor_invalid");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return this.touch(J),{chainId:J.chainId,locatorDigest:J.locatorDigest,transcriptFingerprint:J.transcriptFingerprint,frozenBytes:J.frozenBytes,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)}}completeChain(P){this.cleanup();let J=this.chains.get(P);if(!J)return;J.completed=!0,J.lastAccessAt=this.now()}stats(){this.cleanup();let P=0;for(let J of this.chains.values())if(J.completed)P+=1;return{closed:this.closed,chainCount:this.chains.size,activeChains:this.chains.size-P,completedChains:P,entryCount:this.entries.size,activeLoads:this.activeLoads,frozenSnapshotBytes:this.frozenSnapshotBytes,retainedPayloadBytes:this.retainedPayloadBytes,totalIssues:this.totalIssues,limits:{...this.limitsValue}}}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;let J=[];for(let Q of this.entries.values())if((Q.kind==="catalog"||Q.kind==="history")&&Q.activeLoad)J.push(Q.activeLoad.promise),Q.activeLoad.controller.abort(_());return this.closePromise=Promise.allSettled(J).then(()=>{this.entries.clear(),this.chains.clear(),this.activeLoads=0,this.frozenSnapshotBytes=0,this.retainedPayloadBytes=0}),this.closePromise}startCatalogLoad(P,J){let Q=this.requireChain(P.chainId),Z=new AbortController;this.activeLoads+=1,Q.activeLoads+=1;let $=Promise.resolve().then(()=>J({boundary:W(P.boundary)},Z.signal)).then((G)=>{return this.assertLoadAvailable(Z.signal),this.admitCachedResult(P,G)}).catch((G)=>{if(this.closed||Z.signal.aborted)throw _();throw G}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Q.activeLoads-=1});return P.activeLoad={controller:Z,promise:$},this.cloneActiveLoadResult(P.activeLoad)}startHistoryLoad(P,J,Q){let Z=this.requireChain(P.chainId),$=new AbortController;this.activeLoads+=1,Z.activeLoads+=1;let G=Promise.resolve().then(()=>Q({nextSequence:P.nextSequence,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)},$.signal)).then((Y)=>{return this.assertLoadAvailable($.signal),this.admitCachedResult(P,Y)}).catch((Y)=>{if(this.closed||$.signal.aborted)throw _();throw Y}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Z.activeLoads-=1});return P.activeLoad={controller:$,promise:G},this.cloneActiveLoadResult(P.activeLoad)}resolveHistorySnapshot(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}assertSnapshotIssuableForHistory(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.chainId!==P.chainId||Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}requireChain(P){let J=this.chains.get(P);if(!J)throw new U("session_surface_cursor_invalid");return J}assertLoadAvailable(P){if(this.closed||P.aborted)throw _()}getEntry(P,J){if(E(P)!==J)throw new U("session_surface_cursor_invalid");let Z=this.entries.get(P);if(!Z)throw new U("session_surface_cursor_invalid");if(Z.kind!==J)throw new U("session_surface_cursor_invalid");if(Z.expiresAt<=this.now()&&!f(Z))throw this.removeEntry(Z),new U("session_surface_cursor_invalid");return Z}touch(P){let J=this.now();P.lastAccessAt=J,P.expiresAt=J+this.limitsValue.idleTtlMs;let Q=this.chains.get(P.chainId);if(Q)Q.lastAccessAt=J}storeEntry(P,J){if(P.tokens.size>=this.limitsValue.maxEntriesPerChain)throw new U("session_surface_capacity");this.entries.set(J.token,J),P.tokens.add(J.token),P.completed=!1,P.lastAccessAt=J.lastAccessAt,P.issueCount+=1,this.totalIssues+=1}ensureChain(P,J){let Q=this.chains.get(P);if(Q)return Q.lastAccessAt=J,Q;let Z={chainId:P,tokens:new Set,completed:!1,lastAccessAt:J,issueCount:0,activeLoads:0,frozenSnapshotBytes:0,retainedPayloadBytes:0};return this.chains.set(P,Z),Z}cloneActiveLoadResult(P){return P.promise.then((J)=>W(J))}admitCachedResult(P,J){let Q=m(J),Z=this.requireChain(P.chainId),$=Q.bytes-P.cachedResultBytes;if(this.ensureCapacity({requestedEntries:0,requestedRetainedBytes:Math.max(0,$),chainId:P.chainId}),this.releaseCachedResult(P,Z),Q.value===void 0)throw new U("session_surface_cursor_invalid");return P.cachedResult=Q.value,P.cachedResultBytes=Q.bytes,this.retainedPayloadBytes+=Q.bytes,Z.retainedPayloadBytes+=Q.bytes,P.cachedResult}createToken(P){let J=D[P];for(let Q=0;Q<=this.tokenCollisionRetries;Q+=1){this.assertAvailable();let Z=`${J}${this.tokenSource()}`;if(!this.entries.has(Z))return Z}throw new U("session_surface_capacity")}ensureCapacity(P){this.reclaimCompletedChains(P);let J=this.entries.size+P.requestedEntries,Q=this.chains.size+(this.chains.has(P.chainId)?0:1),Z=this.retainedPayloadBytes+P.requestedRetainedBytes,$=(this.chains.get(P.chainId)?.tokens.size??0)+P.requestedEntries;if(J>this.limitsValue.maxEntries||Q>this.limitsValue.maxChains||$>this.limitsValue.maxEntriesPerChain||Z>this.limitsValue.maxFrozenSnapshotBytes)throw new U("session_surface_capacity")}reclaimCompletedChains(P){let J=[...this.chains.values()].filter((Q)=>Q.completed&&Q.activeLoads===0).sort((Q,Z)=>Q.lastAccessAt-Z.lastAccessAt);for(let Q of J){if(!(this.entries.size+P.requestedEntries>this.limitsValue.maxEntries||this.chains.size+(P.chainId!==""&&this.chains.has(P.chainId)?0:1)>this.limitsValue.maxChains||this.retainedPayloadBytes+P.requestedRetainedBytes>this.limitsValue.maxFrozenSnapshotBytes))break;this.removeChain(Q.chainId)}}cleanup(){let P=this.now();for(let J of[...this.entries.values()]){if(J.expiresAt>P||f(J))continue;this.removeEntry(J)}for(let J of[...this.chains.values()])if(J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}removeEntry(P){this.entries.delete(P.token);let J=this.chains.get(P.chainId);if(J){if(J.tokens.delete(P.token),this.releaseEntryRetainedPayload(P,J),J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}else this.releaseEntryRetainedPayload(P)}removeChain(P){let J=this.chains.get(P);if(!J)return;for(let Q of J.tokens){let Z=this.entries.get(Q);if(!Z||f(Z))continue;this.entries.delete(Q),this.releaseEntryRetainedPayload(Z,J)}this.chains.delete(P)}releaseEntryRetainedPayload(P,J){if(P.kind==="snapshot"){if(this.frozenSnapshotBytes-=P.frozenBytes,this.retainedPayloadBytes-=P.frozenBytes,J)J.frozenSnapshotBytes-=P.frozenBytes,J.retainedPayloadBytes-=P.frozenBytes;return}if(P.kind==="catalog"){if(this.retainedPayloadBytes-=P.boundaryBytes,J)J.retainedPayloadBytes-=P.boundaryBytes}this.releaseCachedResult(P,J)}releaseCachedResult(P,J){if(P.cachedResultBytes===0){P.cachedResult=void 0;return}if(this.retainedPayloadBytes-=P.cachedResultBytes,J)J.retainedPayloadBytes-=P.cachedResultBytes;P.cachedResult=void 0,P.cachedResultBytes=0}assertAvailable(){if(this.closed)throw _()}}function E(P){if(P.startsWith(D.catalog))return"catalog";if(P.startsWith(D.history))return"history";if(P.startsWith(D.snapshot))return"snapshot";return}function f(P){return P.kind!=="snapshot"&&P.activeLoad!==void 0}function _P(P){let J={idleTtlMs:P.idleTtlMs??NP,maxEntries:P.maxEntries??OP,maxChains:P.maxChains??jP,maxEntriesPerChain:P.maxEntriesPerChain??MP,maxFrozenSnapshotBytes:P.maxFrozenSnapshotBytes??HP};for(let Q of Object.values(J))if(!Number.isSafeInteger(Q)||Q<=0)throw Error("session surface cursor registry limits must be positive safe integers");return J}function _(){return new U("session_surface_unavailable")}function T(P){return B(W(P))}function W(P){try{return S(P,new Set)}catch{throw new U("session_surface_cursor_invalid")}}function S(P,J){if(P===null)return null;if(typeof P==="string"||typeof P==="boolean")return P;if(typeof P==="number"){if(!Number.isFinite(P))throw Error("invalid number");return P}if(typeof P>"u"||typeof P==="function"||typeof P==="symbol"||typeof P==="bigint")throw Error("invalid JSON type");if(!P||typeof P!=="object")throw Error("invalid JSON value");if(J.has(P))throw Error("cycle");J.add(P);try{if(Array.isArray(P)){let $=[];for(let G=0;G<P.length;G+=1){if(!(G in P))throw Error("sparse array");$.push(S(P[G],J))}return $}if(Object.getOwnPropertySymbols(P).length>0)throw Error("symbol keys");let Q=Object.getPrototypeOf(P);if(Q!==Object.prototype&&Q!==null)throw Error("non-plain object");let Z={};for(let $ of Object.keys(P)){let G=Reflect.get(P,$);if(G===void 0)throw Error("undefined object value");Z[$]=S(G,J)}return Z}finally{J.delete(P)}}function B(P){if(P===null)return"null";if(typeof P==="string"||typeof P==="number")return JSON.stringify(P);if(typeof P==="boolean")return P?"true":"false";if(Array.isArray(P))return`[${P.map((Q)=>B(Q)).join(",")}]`;return`{${Object.keys(P).sort().map((Q)=>`${JSON.stringify(Q)}:${B(P[Q])}`).join(",")}}`}function m(P,J={}){if(P===void 0){if(J.allowUndefined)return{value:void 0,bytes:0};throw new U("session_surface_cursor_invalid")}let Q=W(P);return{value:Q,bytes:Buffer.byteLength(B(Q),"utf8")}}import{createHash as C,randomBytes as F}from"node:crypto";import FP from"node:path";var YP=50,zP=100,AP=16,TP=1e4,DP=16777216;class z extends Error{code;retryable;constructor(P){let J=CP(P);super(J.message);this.code=P;this.name="SessionSurfaceServiceError",this.retryable=J.retryable}}class BP{database;registry;epoch;maxConcurrentOperations;activeControllers=new Set;activeOperations=new Set;closed=!1;closePromise;concurrentOperations=0;constructor(P={}){if(this.database=P.database,this.registry=P.cursorRegistry??new g(P.cursorRegistryOptions),this.epoch=P.epochSource?.()??`session-surface-epoch:${F(32).toString("base64url")}`,this.maxConcurrentOperations=P.maxConcurrentOperations??AP,!Number.isSafeInteger(this.maxConcurrentOperations)||this.maxConcurrentOperations<1||this.maxConcurrentOperations>256)throw Error("maxConcurrentOperations must be an integer from 1 to 256")}async listPage(P={}){return this.runOperation(async(J)=>{let Q=K(P.limit),Z=P.archived??!1,$={archived:Z,limit:Q,workspaceKind:P.workspaceKind??null},G=JSON.stringify([Z,P.workspaceKind??null]),Y=await this.requireDatabase();if(J.throwIfAborted(),!Y)return this.listFallbackPage($,G,J,P.cursor);if(await this.syncAllSurfaces(Y,J),P.cursor){let V=String(ZP(Y));return this.registry.redeemCatalogCursor({token:P.cursor,scopeKey:G,epoch:this.epoch,revision:V,request:$,loader:async({boundary:X})=>{let O=KP(X);return this.loadCatalogPage(Y,$,G,V,O,O.chainId,J)}})}return this.loadCatalogPage(Y,$,G,void 0,void 0,void 0,J)})}async open(P,J={}){return this.runOperation((Q)=>this.openInternal(P,J,Q))}async historyPage(P,J){return this.runOperation(async(Q)=>{let Z=I(P),$=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.readFallbackHistoryPage(Z,J,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:1}),X=x(Z);await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint});let O={expectedSnapshot:J.expectedSnapshot,limit:$},j=await this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint,request:O,loader:async({nextSequence:M})=>{let H=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,beforeSequence:M,limit:$});return this.publicHistoryPage({history:H,snapshot:J.expectedSnapshot,chainId:(await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint})).chainId,locatorDigest:X,limit:$})}});return A.parse(j)})}async fork(P){return this.runOperation(async(J)=>{let Q=I(P),Z=await this.requireDatabase(),$=Z?await this.resolveFromProjectionAfterSync(Z,Q,J):await this.resolveFallback(Q,J);if($.candidate.summary.archivedAt)throw new z("session_surface_read_only");J.throwIfAborted();let G=await N.forkSession(Q.sessionId,{sourceProjectPath:$.candidate.projectPath,targetProjectPath:$.candidate.projectPath,...$.remoteCandidate?{remote:{expectedDescriptor:$.remoteCandidate.descriptor}}:{}}),Y=$.remoteCandidate?{version:2,sessionId:G.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.candidate.publicWorkspaceRef}}:{version:2,sessionId:G.sessionId,workspace:{kind:"local",projectPath:$.candidate.projectPath}};return Z?this.openInternal(Y,{},J):this.openFallback(Y,YP,J)})}async resolveFromProjectionAfterSync(P,J,Q){return await this.syncForLocator(P,J,Q),this.resolveFromProjection(P,J,Q)}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;for(let J of this.activeControllers)J.abort(new z("session_surface_unavailable"));return this.closePromise=Promise.allSettled([...this.activeOperations,this.registry.close()]).then(()=>{return}),this.closePromise}async openInternal(P,J={},Q){let Z=I(P),$=K(J.limit);if(J.cursor!==void 0||J.expectedSnapshot!==void 0)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.openFallback(Z,$,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:$}),X=`history-chain:${F(16).toString("base64url")}`,O=x(Z),j=this.registry.issueSnapshotToken({chainId:X,locatorDigest:O,transcriptFingerprint:V.transcriptFingerprint}),M={session:this.toSummary(Y),history:this.publicHistoryPage({history:V,snapshot:j,chainId:X,locatorDigest:O,limit:$})};return p.parse(M)}runOperation(P){if(this.assertAvailable(),this.concurrentOperations>=this.maxConcurrentOperations)throw new z("session_surface_capacity");let J=new AbortController;this.activeControllers.add(J),this.concurrentOperations+=1;let Q;return Q=Promise.resolve().then(()=>P(J.signal)).then((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");return Z}).catch((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");throw kP(Z)}).finally(()=>{this.activeControllers.delete(J),this.activeOperations.delete(Q),this.concurrentOperations-=1}),this.activeOperations.add(Q),Q}async loadCatalogPage(P,J,Q,Z,$,G,Y){let V=$P(P,{archived:J.archived,limit:J.limit,...J.workspaceKind?{workspaceKind:J.workspaceKind}:{},...$?{boundary:$}:{}}),X=String(V.revision);if(Z!==void 0&&Z!==X)throw new z("session_surface_snapshot_changed");let O=G??`catalog-chain:${F(16).toString("base64url")}`,j={sessions:await Promise.all(V.sessions.map(async(M)=>this.toSummary(await this.resolveCandidate(M,Y)))),...V.nextBoundary?{nextCursor:this.registry.issueCatalogCursor({chainId:O,scopeKey:Q,epoch:this.epoch,revision:X,boundary:{...V.nextBoundary,chainId:O},request:J})}:{}};if(!V.nextBoundary)this.registry.completeChain(O);return y.parse(j)}publicHistoryPage(P){let J=h(P.history.messages,L()),Q={messages:J.messages,snapshot:P.snapshot,truncated:P.history.hasOlder||J.truncated||J.messages.some((Z)=>Z.truncated===!0),...P.history.hasOlder&&P.history.nextSequence!==void 0?{olderCursor:this.registry.issueHistoryCursor({chainId:P.chainId,locatorDigest:P.locatorDigest,transcriptFingerprint:P.history.transcriptFingerprint,nextSequence:P.history.nextSequence,snapshotToken:P.snapshot,request:{expectedSnapshot:P.snapshot,limit:P.limit}})}:{}};if(!P.history.hasOlder)this.registry.completeChain(P.chainId);return A.parse(Q)}async syncForLocator(P,J,Q){if(Q?.throwIfAborted(),J.workspace.kind==="local"){await N.findSessionMetadata(J.sessionId,J.workspace.projectPath),Q?.throwIfAborted(),await d(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await N.listValidatedRemoteSurfaceCandidates(Q),await l(P,N.projectionDeriverForSearch(),Q)}async syncAllSurfaces(P,J){let Q=N.projectionDeriverForSearch(),Z=await N.listValidatedLocalSurfaceCandidates(J),$=new Set(Z.map((Y)=>`${Y.projectPath}\x00${Y.sessionId}`)),G=P.prepare("SELECT project_path, session_id FROM sessions WHERE source_kind='local'").all();for(let Y of G)if(!$.has(`${Y.project_path}\x00${Y.session_id}`))JP(P,Y.session_id,Y.project_path,"local");for(let Y of Z)J?.throwIfAborted(),await d(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await N.listValidatedRemoteSurfaceCandidates(J),await l(P,Q,J)}async listFallbackPage(P,J,Q,Z){if(Z)return this.registry.redeemCatalogCursor({token:Z,scopeKey:J,epoch:this.epoch,revision:"fallback",request:P,loader:async({boundary:G})=>{let Y=LP(G);return this.pageFallbackCatalog(Y.entries,P,J,Y.chainId)}});let $=await this.loadFallbackCatalog(P,Q);return this.pageFallbackCatalog($,P,J,`catalog-fallback:${F(16).toString("base64url")}`)}async loadFallbackCatalog(P,J){let Q=[];if(P.workspaceKind!=="acp-remote")for(let $ of await N.listValidatedLocalSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedLocalSurfaceSnapshot($.sessionId,$.projectPath,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},summary:Y})}if(P.workspaceKind!=="local")for(let $ of await N.listValidatedRemoteSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedRemoteSurfaceSnapshot($,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.workspaceRef}},summary:Y})}Q.sort(IP);let Z=Buffer.byteLength(JSON.stringify(Q));if(Q.length>TP||Z>DP)throw new z("session_surface_capacity");return Q}async pageFallbackCatalog(P,J,Q,Z){let $=P.slice(0,J.limit),G=P.slice($.length),V={sessions:$.map((X)=>R.parse({locator:X.locator,...X.summary,capabilities:X.locator.workspace.kind==="local"?UP(Boolean(X.summary.archivedAt)):RP(Boolean(X.summary.archivedAt))})),...G.length>0?{nextCursor:this.registry.issueCatalogCursor({chainId:Z,scopeKey:Q,epoch:this.epoch,revision:"fallback",boundary:{chainId:Z,entries:G},request:J})}:{}};if(G.length===0)this.registry.completeChain(Z);return y.parse(V)}async openFallback(P,J,Q){let Z=await this.resolveFallback(P,Q),$=Z.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(Z.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(Z.candidate.sessionId,Z.candidate.projectPath,Q),G=e($.entries,{...Z.remoteCandidate?r(Z.remoteCandidate.hostStateRoot,Z.remoteCandidate.descriptor):{privateRoots:[]},bladeStorageRoots:[o()]}),Y=h(G.slice(-J),L()),V=`history-fallback:${F(16).toString("base64url")}`,X=x(P),O=C("sha256").update(JSON.stringify($.entries)).digest("hex"),j=this.registry.issueSnapshotToken({chainId:V,locatorDigest:X,transcriptFingerprint:O,frozenSnapshot:G}),M={session:this.toSummary(Z),history:A.parse({messages:Y.messages,snapshot:j,truncated:Y.messages.length<G.length||Y.truncated||Y.messages.some((H)=>H.truncated===!0),...G.length>Y.messages.length&&Y.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:V,locatorDigest:X,transcriptFingerprint:O,nextSequence:v(Y.messages[0].id),snapshotToken:j,request:{expectedSnapshot:j,limit:J}})}:{}})};if(G.length<=Y.messages.length)this.registry.completeChain(V);return p.parse(M)}async readFallbackHistoryPage(P,J,Q){let Z=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let $=x(P),G=await this.resolveFallback(P,Q),Y=G.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(G.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(G.candidate.sessionId,G.candidate.projectPath,Q),V=C("sha256").update(JSON.stringify(Y.entries)).digest("hex");await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V});let X={expectedSnapshot:J.expectedSnapshot,limit:Z};return this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:$,transcriptFingerprint:V,request:X,loader:async({nextSequence:O,frozenSnapshot:j})=>{let M=xP(j).filter((b)=>v(b.id)<O),H=h(M.slice(-Z),L()),u=await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V}),k=H.messages.length<M.length,VP={messages:H.messages,snapshot:J.expectedSnapshot,truncated:k||H.truncated||H.messages.some((b)=>b.truncated===!0),...k&&H.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:u.chainId,locatorDigest:$,transcriptFingerprint:V,nextSequence:v(H.messages[0].id),snapshotToken:J.expectedSnapshot,request:X})}:{}};if(!k)this.registry.completeChain(u.chainId);return A.parse(VP)}})}async resolveFallback(P,J){let Q=[];for(let G of[!1,!0]){let Y={archived:G,limit:zP,workspaceKind:P.workspace.kind};Q.push(...(await this.loadFallbackCatalog(Y,J)).filter((V)=>JSON.stringify(V.locator)===JSON.stringify(P)))}if(Q.length!==1)throw new z("session_surface_not_found");let Z=Q[0],$;if(P.workspace.kind==="acp-remote"){let G=P.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(J)).find((Y)=>Y.sessionId===P.sessionId&&Y.workspaceRef===G),!$)throw new z("workspace_binding_mismatch")}return{candidate:{sourceKind:P.workspace.kind,projectPath:P.workspace.kind==="local"?P.workspace.projectPath:$.hostStateRoot,sessionId:P.sessionId,...P.workspace.kind==="acp-remote"?{publicWorkspaceRef:P.workspace.workspaceRef}:{},publicWorkspaceSortKey:"",surfaceDigest:i(Z),transcriptFingerprint:i(Z),lastMessageTime:Z.summary.lastMessageTime,sessionSortKey:"",summary:Z.summary},...$?{remoteCandidate:$}:{}}}async resolveFromProjection(P,J,Q){let Z=QP(P,J.sessionId).filter((G)=>J.workspace.kind==="local"?G.sourceKind==="local"&&G.projectPath===FP.resolve(J.workspace.projectPath):G.sourceKind==="acp-remote"&&G.publicWorkspaceRef===J.workspace.workspaceRef);if(Z.length!==1)throw new z(Z.length===0?"session_surface_not_found":"workspace_binding_mismatch");let $;if(J.workspace.kind==="acp-remote"){let G=J.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(Q)).filter((Y)=>Y.sessionId===J.sessionId&&Y.workspaceRef===G),$.length===0)throw new z("workspace_binding_mismatch");if($.length>1)throw new z("session_surface_state_invalid")}return $?{candidate:Z[0],remoteCandidate:$[0]}:{candidate:Z[0]}}async resolveCandidate(P,J){if(P.sourceKind==="local")return{candidate:P};let Q=(await N.listValidatedRemoteSurfaceCandidates(J)).filter((Z)=>Z.sessionId===P.sessionId&&Z.workspaceRef===P.publicWorkspaceRef);if(Q.length!==1)throw new z(Q.length===0?"workspace_binding_mismatch":"session_surface_state_invalid");return{candidate:P,remoteCandidate:Q[0]}}toSummary(P){let J=P.candidate,Q=J.sourceKind==="local"?{version:2,sessionId:J.sessionId,workspace:{kind:"local",projectPath:J.projectPath}}:{version:2,sessionId:J.sessionId,workspace:{kind:"acp-remote",workspaceRef:J.publicWorkspaceRef}};return R.parse({locator:Q,...J.summary,capabilities:this.capabilitiesFor(P)})}capabilitiesFor(P){let J=P.candidate.summary.archivedAt!==void 0;if(!P.remoteCandidate)return{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}};return{connection:GP.getRemoteSurfaceOwnerSnapshot(P.candidate.sessionId,P.remoteCandidate.descriptor).connection,history:{read:!0,fork:!J},turn:{start:!1,reason:J?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:J?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:J?"archived":"history-only"}}}async requireDatabase(){if(this.database===null)return null;return this.database??await PP()}assertAvailable(){if(this.closed)throw new z("session_surface_unavailable")}}function K(P){let J=P??YP;if(!Number.isSafeInteger(J)||J<1||J>zP)throw new z("invalid_session_surface_request");return J}function I(P){try{let J=t.parse(P);if(!n(J.sessionId))throw Error("invalid");if(J.workspace.kind==="local"){if(s(J.workspace.projectPath)!==J.workspace.projectPath)throw Error("invalid")}return J}catch{throw new z("invalid_session_locator")}}function x(P){return C("sha256").update("session-surface-locator-v2\x00").update(JSON.stringify(P)).digest("hex")}function KP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.lastMessageTime!=="string"||J.sourceKind!=="local"&&J.sourceKind!=="acp-remote"||typeof J.publicWorkspaceSortKey!=="string"||typeof J.sessionSortKey!=="string"||typeof J.chainId!=="string"||!J.chainId)throw new z("session_surface_cursor_invalid");return{lastMessageTime:J.lastMessageTime,sourceKind:J.sourceKind,publicWorkspaceSortKey:J.publicWorkspaceSortKey,sessionSortKey:J.sessionSortKey,chainId:J.chainId}}function h(P,J){let Q=[];for(let Z=P.length-1;Z>=0;Z-=1){let $=P[Z];if(!$)continue;let G=[$,...Q];if(Q.length>0&&Buffer.byteLength(JSON.stringify(G))>J)break;Q.unshift($)}return{messages:Q,truncated:Q.length<P.length}}function v(P){let J=/^surface-message:([0-9]+):/.exec(P),Q=J?Number(J[1]):Number.NaN;if(!Number.isSafeInteger(Q)||Q<=0)throw new z("session_surface_state_invalid");return Q}function xP(P){if(!Array.isArray(P))throw new z("session_surface_snapshot_changed");return P.map((J)=>{try{return a.parse(J)}catch{throw new z("session_surface_snapshot_changed")}})}function LP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.chainId!=="string"||J.chainId.length===0||!Array.isArray(J.entries))throw new z("session_surface_cursor_invalid");let Q=J.entries.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new z("session_surface_cursor_invalid");let $=Z;return{locator:I($.locator),summary:wP($.summary)}});return{chainId:J.chainId,entries:Q}}function wP(P){let J={version:2,sessionId:"placeholder",workspace:{kind:"local",projectPath:"/"}},Q=R.parse({...P&&typeof P==="object"&&!Array.isArray(P)?P:{},locator:J,capabilities:UP(!1)}),{locator:Z,capabilities:$,...G}=Q;return G}function IP(P,J){if(P.summary.lastMessageTime>J.summary.lastMessageTime)return-1;if(P.summary.lastMessageTime<J.summary.lastMessageTime)return 1;if(P.locator.workspace.kind!==J.locator.workspace.kind)return P.locator.workspace.kind==="local"?-1:1;let Q=P.locator.workspace.kind==="local"?P.locator.workspace.projectPath:P.locator.workspace.workspaceRef,Z=J.locator.workspace.kind==="local"?J.locator.workspace.projectPath:J.locator.workspace.workspaceRef;if(Q<Z)return-1;if(Q>Z)return 1;return P.locator.sessionId<J.locator.sessionId?-1:P.locator.sessionId>J.locator.sessionId?1:0}function i(P){return C("sha256").update("session-surface-fallback-entry\x00").update(JSON.stringify(P)).digest("hex")}function UP(P){return{connection:"local",history:{read:!0,fork:!P},turn:P?{start:!1,reason:"archived"}:{start:!0},files:P?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:P?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}}function RP(P){return{connection:"offline",history:{read:!0,fork:!P},turn:{start:!1,reason:P?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:P?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:P?"archived":"history-only"}}}function CP(P){if(P==="session_surface_cursor_invalid")return{message:"Session surface cursor is invalid",retryable:!1};if(P==="session_surface_snapshot_changed")return{message:"Session surface snapshot changed",retryable:!1};if(P==="session_surface_state_invalid")return{message:"Session surface state is invalid",retryable:!1};if(P==="session_surface_capability_unavailable")return{message:"Session surface capability is unavailable",retryable:!1};if(P==="session_surface_unavailable")return{message:"Session surface is unavailable",retryable:!0};if(P==="session_surface_not_found")return{message:"Session surface was not found",retryable:!1};if(P==="workspace_binding_mismatch")return{message:"Session workspace binding changed",retryable:!1};if(P==="session_surface_read_only")return{message:"Session surface is read only",retryable:!1};if(P==="session_surface_capacity")return{message:"Session surface capacity is exhausted",retryable:!0};if(P==="invalid_session_locator")return{message:"Session locator is invalid",retryable:!1};return{message:"Session surface request is invalid",retryable:!1}}function kP(P){if(P instanceof z)return P;if(P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"){let J=P.code;if(J==="session_surface_cursor_invalid"||J==="session_surface_snapshot_changed"||J==="session_surface_capacity"||J==="session_surface_unavailable"||J==="session_surface_state_invalid")return new z(J);if(J==="acp_remote_workspace_state_invalid")return new z("session_surface_state_invalid")}return P instanceof Error?P:new z("session_surface_state_invalid")}
2
2
  export{qP as e,EP as f,g,z as h,BP as i};
@@ -1,3 +1,3 @@
1
- import{ek as E}from"./chunk-gzbb747a.js";import{createHash as y}from"node:crypto";import{constants as I,promises as b}from"node:fs";import S from"node:os";import Y from"node:path";import{Mutex as P}from"async-mutex";import{LRUCache as v}from"lru-cache";import f from"write-file-atomic";import{promises as G}from"node:fs";import K from"node:path";import{LRUCache as k}from"lru-cache";var g=512,W=new k({max:g});async function m(q){let Q=q;while(!0){try{return await G.lstat(K.join(Q,".git")),Q}catch($){if($.code!=="ENOENT")return}let Z=K.dirname(Q);if(Z===Q)return;Q=Z}}async function j(q){let Q=K.join(q,".git"),Z=await G.lstat(Q);if(Z.isDirectory())return q;if(!Z.isFile())return;let $=await G.readFile(Q,"utf8"),H=/^gitdir:\s*(.+)\s*$/im.exec($);if(!H)return;let J=await G.realpath(K.isAbsolute(H[1])?H[1]:K.resolve(q,H[1])),F=J;try{let L=(await G.readFile(K.join(J,"commondir"),"utf8")).trim();if(L)F=await G.realpath(K.resolve(J,L))}catch(L){if(L.code!=="ENOENT")throw L}return K.basename(F)===".git"?G.realpath(K.dirname(F)):void 0}async function A(q){if(!K.isAbsolute(q))throw Error("Workspace path must be absolute");let Q=await G.realpath(q),Z=W.get(Q);if(Z)return Z;let $=Q;try{let J=await m(Q);if(J){let F=await j(J),L=K.relative(J,Q);if(F&&(L===""||!L.startsWith(`..${K.sep}`)&&L!==".."&&!K.isAbsolute(L))){let z=K.resolve(F,L);$=await G.realpath(z).catch(()=>z)}}}catch{}let H={projectPath:Q,trustRoot:$};return W.set(Q,H),H}async function _(q){if(!K.isAbsolute(q))throw Error("Workspace path must be absolute");let Q=await G.realpath(q);W.delete(Q)}var N=1,l=65536,R=1048576,V=100,D=64;function Bq(q){return q.state==="trusted"||q.state==="not_required"}function U(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function M(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function T(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return M(`${Q.origin}${Q.pathname}`)}catch{return M(q)}}function w(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function h(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",J=typeof $.command==="string"?$.command:void 0,F=w($.args),L=H==="stdio"?M([J,...F].filter(Boolean).join(" ")):T($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function d(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.command==="string"?M($.command):void 0,J=U($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${J})`,...H?{target:H}:{}}})}function u(q){if(!Array.isArray(q))return[];return q.slice(0,V).flatMap((Q)=>{if(!U(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",J=U(Q.overrides)?Q.overrides:{},F=T(J.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...F?{target:F}:{}}]})}function p(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",J=T($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...J?{target:J}:{}}})}function n(q){if(!U(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of w(q[Z]).slice(0,V))Q.push({kind:"permission",name:`${Z}: ${M($,512)}`});return Q}function c(q){let Q=[...h(q.mcpServers),...d(q.lspServers),...u(q.models),...p(q.modelProviders),...n(q.permissions)];if(U(q.env))for(let Z of Object.keys(q.env).slice(0,V))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function s(q){return q!=="hooks"&&q!=="disableAllHooks"}function o(q){return y("sha256").update(q).digest("hex")}function i(q,Q){let Z=Y.relative(q,Q);return Z===""||!Z.startsWith(`..${Y.sep}`)&&Z!==".."&&!Y.isAbsolute(Z)}class O{storeDir;static instance=null;mutex=new P;statusCache=new v({max:D});constructor(q=Y.join(E(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!O.instance)O.instance=new O;return O.instance}static resetInstance(){O.instance=null}async getStatus(q){let Q=await A(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(B){let X={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:B instanceof Error?B.message:"Workspace trust review failed"};return this.cacheStatus(q,X),X}if(Z.length===0){let B={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,B),B}let $;try{$=await this.readDecisions()}catch(B){let X={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:B instanceof Error?B.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,X),X}let H=$.filter((B)=>i(B.path,Q.trustRoot)),J=Math.max(-1,...H.map((B)=>B.path.split(Y.sep).length)),F=H.filter((B)=>B.path.split(Y.sep).length===J),L=F.length>0&&F.every((B)=>B.trusted),z=F[0],x=z?.path===Q.trustRoot,C={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:z?x?z.trusted?"trusted":"untrusted":"inherited":"undecided",...z?.decidedAt?{decidedAt:z.decidedAt}:{},...!x&&z?.path?{inheritedFrom:z.path}:{}};return this.cacheStatus(q,C),C}cacheStatus(q,Q){this.statusCache.set(Y.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(Y.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:D,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await _(q);let Z=await A(q);await this.assertSafeTrustRoot(Z);let $={version:N,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=Y.parse(q.trustRoot).root,Z=await b.realpath(S.homedir()).catch(()=>Y.resolve(S.homedir()));if(!Y.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let J=await this.reviewConfigFile(q,$,H);if(J)Q.push(J)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,J]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let F=await this.reviewResourceDirectory(q,$,H,J);if(F)Q.push(F)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=Y.join(q,"package.json"),Z;try{Z=await b.stat(Q)}catch(F){if(F.code==="ENOENT")return;throw F}if(!Z.isFile())return;if(Z.size>R)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await b.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!U($)||!U($.scripts))return;let H=$.scripts,J=Object.keys(H).filter((F)=>typeof H[F]==="string").sort().slice(0,V);if(J.length===0)return;return{path:"package.json",kind:"package",keys:J,effects:J.map((F)=>({kind:"command",name:`package script: ${F}`}))}}async reviewInstructionFile(q,Q){try{if(!(await b.stat(Y.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=Y.join(q,Q),H;try{H=await b.stat($)}catch(x){if(x.code==="ENOENT")return;throw x}if(!H.isFile())return;if(H.size>R)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let J;try{J=JSON.parse(await b.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!U(J))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let F=Object.keys(J).filter(s).sort();if(F.length===0)return;let L=c(J),z=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let x of F)if(!z.has(x))L.push({kind:"configuration",name:x});return{path:Q,kind:Z,keys:F,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=Y.join(q,Q),J;try{J=await b.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let F=J.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,V);if(F.length===0)return;return{path:Q,kind:Z,keys:F.map((L)=>L.name),effects:F.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await b.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await b.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(Y.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await b.open(q,I.O_RDONLY|I.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>l)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!U($)||$.version!==N||typeof $.path!=="string"||!Y.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:N,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=Y.join(this.storeDir,`${o(q.path)}.json`);try{let Z=await b.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await f(Q,`${JSON.stringify(q,null,2)}
1
+ import{fk as E}from"./chunk-a95jmx2j.js";import{createHash as y}from"node:crypto";import{constants as I,promises as b}from"node:fs";import S from"node:os";import Y from"node:path";import{Mutex as P}from"async-mutex";import{LRUCache as v}from"lru-cache";import f from"write-file-atomic";import{promises as G}from"node:fs";import K from"node:path";import{LRUCache as k}from"lru-cache";var g=512,W=new k({max:g});async function m(q){let Q=q;while(!0){try{return await G.lstat(K.join(Q,".git")),Q}catch($){if($.code!=="ENOENT")return}let Z=K.dirname(Q);if(Z===Q)return;Q=Z}}async function j(q){let Q=K.join(q,".git"),Z=await G.lstat(Q);if(Z.isDirectory())return q;if(!Z.isFile())return;let $=await G.readFile(Q,"utf8"),H=/^gitdir:\s*(.+)\s*$/im.exec($);if(!H)return;let J=await G.realpath(K.isAbsolute(H[1])?H[1]:K.resolve(q,H[1])),F=J;try{let L=(await G.readFile(K.join(J,"commondir"),"utf8")).trim();if(L)F=await G.realpath(K.resolve(J,L))}catch(L){if(L.code!=="ENOENT")throw L}return K.basename(F)===".git"?G.realpath(K.dirname(F)):void 0}async function A(q){if(!K.isAbsolute(q))throw Error("Workspace path must be absolute");let Q=await G.realpath(q),Z=W.get(Q);if(Z)return Z;let $=Q;try{let J=await m(Q);if(J){let F=await j(J),L=K.relative(J,Q);if(F&&(L===""||!L.startsWith(`..${K.sep}`)&&L!==".."&&!K.isAbsolute(L))){let z=K.resolve(F,L);$=await G.realpath(z).catch(()=>z)}}}catch{}let H={projectPath:Q,trustRoot:$};return W.set(Q,H),H}async function _(q){if(!K.isAbsolute(q))throw Error("Workspace path must be absolute");let Q=await G.realpath(q);W.delete(Q)}var N=1,l=65536,R=1048576,V=100,D=64;function Bq(q){return q.state==="trusted"||q.state==="not_required"}function U(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function M(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function T(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return M(`${Q.origin}${Q.pathname}`)}catch{return M(q)}}function w(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function h(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",J=typeof $.command==="string"?$.command:void 0,F=w($.args),L=H==="stdio"?M([J,...F].filter(Boolean).join(" ")):T($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function d(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.command==="string"?M($.command):void 0,J=U($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${J})`,...H?{target:H}:{}}})}function u(q){if(!Array.isArray(q))return[];return q.slice(0,V).flatMap((Q)=>{if(!U(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",J=U(Q.overrides)?Q.overrides:{},F=T(J.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...F?{target:F}:{}}]})}function p(q){if(!U(q))return[];return Object.entries(q).slice(0,V).map(([Q,Z])=>{let $=U(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",J=T($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...J?{target:J}:{}}})}function n(q){if(!U(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of w(q[Z]).slice(0,V))Q.push({kind:"permission",name:`${Z}: ${M($,512)}`});return Q}function c(q){let Q=[...h(q.mcpServers),...d(q.lspServers),...u(q.models),...p(q.modelProviders),...n(q.permissions)];if(U(q.env))for(let Z of Object.keys(q.env).slice(0,V))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function s(q){return q!=="hooks"&&q!=="disableAllHooks"}function o(q){return y("sha256").update(q).digest("hex")}function i(q,Q){let Z=Y.relative(q,Q);return Z===""||!Z.startsWith(`..${Y.sep}`)&&Z!==".."&&!Y.isAbsolute(Z)}class O{storeDir;static instance=null;mutex=new P;statusCache=new v({max:D});constructor(q=Y.join(E(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!O.instance)O.instance=new O;return O.instance}static resetInstance(){O.instance=null}async getStatus(q){let Q=await A(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(B){let X={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:B instanceof Error?B.message:"Workspace trust review failed"};return this.cacheStatus(q,X),X}if(Z.length===0){let B={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,B),B}let $;try{$=await this.readDecisions()}catch(B){let X={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:B instanceof Error?B.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,X),X}let H=$.filter((B)=>i(B.path,Q.trustRoot)),J=Math.max(-1,...H.map((B)=>B.path.split(Y.sep).length)),F=H.filter((B)=>B.path.split(Y.sep).length===J),L=F.length>0&&F.every((B)=>B.trusted),z=F[0],x=z?.path===Q.trustRoot,C={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:z?x?z.trusted?"trusted":"untrusted":"inherited":"undecided",...z?.decidedAt?{decidedAt:z.decidedAt}:{},...!x&&z?.path?{inheritedFrom:z.path}:{}};return this.cacheStatus(q,C),C}cacheStatus(q,Q){this.statusCache.set(Y.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(Y.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:D,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await _(q);let Z=await A(q);await this.assertSafeTrustRoot(Z);let $={version:N,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=Y.parse(q.trustRoot).root,Z=await b.realpath(S.homedir()).catch(()=>Y.resolve(S.homedir()));if(!Y.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let J=await this.reviewConfigFile(q,$,H);if(J)Q.push(J)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,J]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let F=await this.reviewResourceDirectory(q,$,H,J);if(F)Q.push(F)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=Y.join(q,"package.json"),Z;try{Z=await b.stat(Q)}catch(F){if(F.code==="ENOENT")return;throw F}if(!Z.isFile())return;if(Z.size>R)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await b.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!U($)||!U($.scripts))return;let H=$.scripts,J=Object.keys(H).filter((F)=>typeof H[F]==="string").sort().slice(0,V);if(J.length===0)return;return{path:"package.json",kind:"package",keys:J,effects:J.map((F)=>({kind:"command",name:`package script: ${F}`}))}}async reviewInstructionFile(q,Q){try{if(!(await b.stat(Y.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=Y.join(q,Q),H;try{H=await b.stat($)}catch(x){if(x.code==="ENOENT")return;throw x}if(!H.isFile())return;if(H.size>R)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let J;try{J=JSON.parse(await b.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!U(J))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let F=Object.keys(J).filter(s).sort();if(F.length===0)return;let L=c(J),z=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let x of F)if(!z.has(x))L.push({kind:"configuration",name:x});return{path:Q,kind:Z,keys:F,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=Y.join(q,Q),J;try{J=await b.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let F=J.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,V);if(F.length===0)return;return{path:Q,kind:Z,keys:F.map((L)=>L.name),effects:F.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await b.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await b.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(Y.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await b.open(q,I.O_RDONLY|I.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>l)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!U($)||$.version!==N||typeof $.path!=="string"||!Y.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:N,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=Y.join(this.storeDir,`${o(q.path)}.json`);try{let Z=await b.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await f(Q,`${JSON.stringify(q,null,2)}
2
2
  `,{mode:384}),await b.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await b.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await b.mkdir(this.storeDir,{recursive:!0,mode:448}),await b.chmod(this.storeDir,448)}}}
3
- export{A as ak,D as bk,Bq as ck,O as dk};
3
+ export{A as bk,D as ck,Bq as dk,O as ek};
@@ -1,2 +1,2 @@
1
- import{Hj as b,Ij as K,Kj as j}from"./chunk-9ydrwcpy.js";var L=256,Z=128,p=1e6,$=86400000,G=8640000000000000,g=b.Integer({minimum:0,maximum:p}),f=b.Integer({minimum:0,maximum:$}),q=b.Integer({minimum:0,maximum:G}),x=b.String({minLength:1,maxLength:L,pattern:"^(?!.*://)[^\x00-\x1F]+$"}),H=j(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),U=j(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),F=b.Object({provider:x,model:x},{additionalProperties:!1}),J=j(["rate_limit","server_error","timeout","transport","stream_closed"]),s=b.Union([b.Object({source:b.Literal("retry"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("circuit"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("admission"),reason:j(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),b.Object({source:b.Literal("stall"),reason:b.Literal("timeout")},{additionalProperties:!1})]),T=b.Object({from:F,to:F,candidate:b.Integer({minimum:1,maximum:p}),candidateCount:b.Integer({minimum:1,maximum:p}),trigger:s},{additionalProperties:!1}),X=b.Object({attempt:g,maxRetries:g,statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),delayMs:b.Optional(f),recoveryBudgetMs:b.Optional(f),recoveryElapsedMs:b.Optional(f),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),Y=b.Object({requestClass:j(["foreground","background","internal"]),scope:j(["global","domain","owner","class"]),resource:j(["stream","pending_count","pending_bytes"]),queuePosition:g,queueDepth:g,inFlight:g,limit:g,waitMs:f,maxWaitMs:f,recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),z=b.Object({phase:j(["opened","reopened","waiting","probe","rejected"]),statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),retryAfterMs:b.Optional(f),nextProbeAt:b.Optional(q),openDurationMs:f,sampleCount:b.Optional(g),failureCount:b.Optional(g),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),C=b.Object({stallCount:g,durationMs:f,warningAfterMs:f,timeoutMs:f,outputStarted:b.Boolean()},{additionalProperties:!1}),I=b.Object({activity:U,reason:H,updatedAt:q,nextActionAt:b.Optional(q),retry:b.Optional(X),admission:b.Optional(Y),circuit:b.Optional(z),stall:b.Optional(C),fallback:b.Optional(T)},{additionalProperties:!1}),N=K(b.Object({version:b.Literal(1),generation:b.String({minLength:1,maxLength:Z,pattern:"^[^\x00-\x1F]+$"}),revision:g,snapshot:b.Union([I,b.Null()])},{additionalProperties:!1}));function V(Q){let k=[...Q].filter((W)=>{let w=W.codePointAt(0)??0;return w>31&&w!==127}).join("").trim().slice(0,L);if(!k)throw Error("Provider recovery identity is empty");if(k.includes("://"))throw Error("Provider recovery identity cannot be a URL");return k}
2
- export{N as rg,V as sg};
1
+ import{Ij as b,Jj as K,Lj as j}from"./chunk-4e4qtpca.js";var L=256,Z=128,p=1e6,$=86400000,G=8640000000000000,g=b.Integer({minimum:0,maximum:p}),f=b.Integer({minimum:0,maximum:$}),q=b.Integer({minimum:0,maximum:G}),x=b.String({minLength:1,maxLength:L,pattern:"^(?!.*://)[^\x00-\x1F]+$"}),H=j(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),U=j(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),F=b.Object({provider:x,model:x},{additionalProperties:!1}),J=j(["rate_limit","server_error","timeout","transport","stream_closed"]),s=b.Union([b.Object({source:b.Literal("retry"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("circuit"),reason:J,statusCode:b.Optional(b.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),b.Object({source:b.Literal("admission"),reason:j(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),b.Object({source:b.Literal("stall"),reason:b.Literal("timeout")},{additionalProperties:!1})]),T=b.Object({from:F,to:F,candidate:b.Integer({minimum:1,maximum:p}),candidateCount:b.Integer({minimum:1,maximum:p}),trigger:s},{additionalProperties:!1}),X=b.Object({attempt:g,maxRetries:g,statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),delayMs:b.Optional(f),recoveryBudgetMs:b.Optional(f),recoveryElapsedMs:b.Optional(f),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),Y=b.Object({requestClass:j(["foreground","background","internal"]),scope:j(["global","domain","owner","class"]),resource:j(["stream","pending_count","pending_bytes"]),queuePosition:g,queueDepth:g,inFlight:g,limit:g,waitMs:f,maxWaitMs:f,recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),z=b.Object({phase:j(["opened","reopened","waiting","probe","rejected"]),statusCode:b.Optional(b.Integer({minimum:100,maximum:999})),retryAfterMs:b.Optional(f),nextProbeAt:b.Optional(q),openDurationMs:f,sampleCount:b.Optional(g),failureCount:b.Optional(g),recoveryRemainingMs:b.Optional(f)},{additionalProperties:!1}),C=b.Object({stallCount:g,durationMs:f,warningAfterMs:f,timeoutMs:f,outputStarted:b.Boolean()},{additionalProperties:!1}),I=b.Object({activity:U,reason:H,updatedAt:q,nextActionAt:b.Optional(q),retry:b.Optional(X),admission:b.Optional(Y),circuit:b.Optional(z),stall:b.Optional(C),fallback:b.Optional(T)},{additionalProperties:!1}),N=K(b.Object({version:b.Literal(1),generation:b.String({minLength:1,maxLength:Z,pattern:"^[^\x00-\x1F]+$"}),revision:g,snapshot:b.Union([I,b.Null()])},{additionalProperties:!1}));function V(Q){let k=[...Q].filter((W)=>{let w=W.codePointAt(0)??0;return w>31&&w!==127}).join("").trim().slice(0,L);if(!k)throw Error("Provider recovery identity is empty");if(k.includes("://"))throw Error("Provider recovery identity cannot be a URL");return k}
2
+ export{N as sg,V as tg};
@@ -1,6 +1,6 @@
1
- import{Bf as v}from"./chunk-5034apfz.js";import{Uf as e}from"./chunk-7eset766.js";import{Ai as C,Eh as Y,Ei as S,Fi as m,Gi as c,Hi as p,Ji as u,Ki as d,Oi as l,Ti as i,Ui as t,gi as y,ii as D,ji as h,li as A,si as P,ti as T,vi as E,xi as _,yi as f}from"./chunk-yrr9mdjn.js";import{Wi as X}from"./chunk-m30qwpe9.js";import{$i as L,_i as U,fj as M,gj as O,ij as $,jj as I,kj as G,mj as N,nj as j,pj as F,qj as R}from"./chunk-n8qg68y2.js";import{Dj as s,Fj as x,Hj as k,Kj as Z}from"./chunk-9ydrwcpy.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{Cf as v}from"./chunk-0wxnrjes.js";import{Vf as e}from"./chunk-dv5ts9ae.js";import{Bi as C,Fh as Y,Fi as S,Gi as m,Hi as c,Ii as p,Ki as u,Li as d,Pi as l,Ui as i,Vi as t,hi as y,ji as D,ki as h,mi as A,ti as P,ui as T,wi as E,yi as _,zi as f}from"./chunk-qy6p8bpr.js";import{Xi as X}from"./chunk-b22ab7yw.js";import{$i as U,aj as L,gj as M,hj as O,jj as $,kj as I,lj as G,nj as N,oj as j,qj as F,rj as R}from"./chunk-amabfzc8.js";import{Ej as s,Gj as x,Ij as k,Lj as Z}from"./chunk-4e4qtpca.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
5
  `),process.exit(1)}};function zk(q){if(q.continue&&q.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(q.forkSession&&!q.continue&&!q.resume)throw Error("--fork-session requires --resume or --continue");if(q.sessionId&&(q.continue||q.resume)&&!q.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var Mk=(q)=>{if(q.jsonSchema&&q.outputSchema)throw Error("--json-schema cannot be combined with --output-schema");if((q.jsonSchema||q.outputSchema)&&!q.print&&!q.headless)throw Error("--json-schema and --output-schema can only be used with --print or --headless");if(q.outputFormat&&q.outputFormat!=="text"&&!q.print&&!q.headless)throw Error("--output-format can only be used with --print or --headless");if(q.headless&&q.outputFormat&&!["text","jsonl"].includes(q.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${q.outputFormat}". Use --print for json|stream-json support.`);if(q.print&&q.outputFormat&&!["text","json","stream-json"].includes(q.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${q.outputFormat}". Use --headless for jsonl support.`);if(q.inputFormat==="stream-json"&&q.print)Q.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
- export{Uk as yf,Lk as zf,Mk as Af};
6
+ export{Uk as zf,Lk as Af,Mk as Bf};
@@ -1,4 +1,4 @@
1
- import{Yi as i}from"./chunk-m30qwpe9.js";import{$i as Hn,Zi as rn,_i as Kn,dj as Yn,ej as _n,fj as Fn,gj as Vn,hj as qn,ij as ct,jj as Jn,kj as Qn,lj as Mn,mj as jn,nj as Wn,oj as Sn,pj as Zn,qj as kn,rj as ln,sj as yn,tj as vn,uj as te}from"./chunk-n8qg68y2.js";import{vj as Pn,wj as xn}from"./chunk-hrtf7dba.js";import{Dj as Ut,Fj as Lt,Gj as St,Hj as m}from"./chunk-9ydrwcpy.js";import{Mj as Gn,Pj as tt}from"./chunk-0wcnkxe8.js";import{Xj as xt,Yj as Bt}from"./chunk-a1tt14a2.js";import{dk as b}from"./chunk-zjezws85.js";import{ek as It}from"./chunk-gzbb747a.js";var nt;((r)=>{r.DEFAULT="default";r.AUTO_EDIT="autoEdit";r.YOLO="yolo";r.PLAN="plan"})(nt||={});var ne=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function ee(t){return t==="127.0.0.1"||t==="[::1]"||t.toLowerCase()==="localhost"}function $(t,n="MCP OAuth URL"){let e=new URL(t);if(e.username||e.password)throw Error(`${n} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ee(e.hostname)))throw Error(`${n} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var K=async(t,n)=>{$(t,"MCP OAuth request URL");let e=await fetch(t,{...n,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function et(t){let n=t.oauth;if(!n)return;let e=n;for(let s of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[s]!==void 0)throw Error(`MCP OAuth "${s}" is not supported; use standards-based discovery`);if(n.enabled!==!0)return{enabled:!1};if(t.type!=="http"&&t.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!t.url)throw Error("MCP OAuth requires an MCP server URL");if($(t.url,"MCP OAuth server URL"),Object.keys(t.headers??{}).find((s)=>s.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=n.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=n.scopes?.map((s)=>s.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((s)=>!s||s.length>128||!ne.test(s)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let M=n.callbackPort;if(M!==void 0&&(!Number.isInteger(M)||M<1024||M>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},...M!==void 0?{callbackPort:M}:{}}}import{randomUUID as Et}from"node:crypto";import ge from"node:http";import{auth as wt}from"@modelcontextprotocol/sdk/client/auth.js";import ce from"open";import{createHash as _e,randomUUID as Me}from"node:crypto";import{constants as rt,promises as I}from"node:fs";import _t from"node:path";import Se from"write-file-atomic";import{Mutex as re}from"async-mutex";class U{entries=new Map;async runExclusive(t,n){let e=this.entries.get(t);if(!e)e={mutex:new re,operations:0},this.entries.set(t,e);e.operations++;try{return await e.mutex.runExclusive(n)}finally{if(e.operations--,e.operations===0&&this.entries.get(t)===e)this.entries.delete(t)}}getStats(){let t=0;for(let n of this.entries.values())t+=n.operations;return{keys:this.entries.size,operations:t}}}var bt=1,se=1048576,Ee=5000,ue=50,oe=/^[a-f0-9]{64}$/,me=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Te=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ae=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),dt=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(me),tokens:m.Optional(Te),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(ae),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),it=m.Object({version:m.Literal(bt),credentials:m.Record(m.String(),dt)},{additionalProperties:!1});function H(t,n){return t instanceof Error&&"code"in t&&t.code===n}function Ae(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(n){return H(n,"EPERM")}}function Mt(t){return structuredClone(t)}function ht(t){if(Object.keys(t.credentials).some((n)=>!oe.test(n)))throw Error("MCP OAuth credential store contains an invalid identity")}function Y(t){let n=new URL(t);return n.hash="",n.toString()}function st(t,n,e=[]){return _e("sha256").update(JSON.stringify({serverUrl:Y(t),clientId:n?.trim()||null,scopes:[...e].sort()})).digest("hex")}class N{static locks=new U;stateRoot;tokenFilePath;constructor(t=It()){this.stateRoot=_t.join(t,"mcp"),this.tokenFilePath=_t.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[t];return e?Mt(e):null})}async updateCredential(t,n){return this.runMutation(async(e)=>{let _=e.credentials[t],r=await n(_?Mt(_):null);if(r)e.credentials[t]=St(dt,r);else delete e.credentials[t];return r?Mt(e.credentials[t]):null})}async deleteCredential(t){await this.updateCredential(t,()=>null)}async listCredentialIds(){return N.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let n=await this.acquireStoreLock();try{let e=await this.readStore(),_=await t(e);return await this.writeStore(e),_}finally{await n()}})}async ensureStateRoot(){await I.mkdir(this.stateRoot,{recursive:!0,mode:448});let t=await I.lstat(this.stateRoot);if(!t.isDirectory()||t.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((t.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let t=await I.lstat(this.tokenFilePath);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((t.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(t.size>se)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let n=JSON.parse(await I.readFile(this.tokenFilePath,"utf8")),e=Lt(it,n);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return ht(e.data),e.data}catch(t){if(H(t,"ENOENT"))return{version:bt,credentials:{}};throw t}}async writeStore(t){await this.ensureStateRoot();let n=St(it,t);ht(n),await Se(this.tokenFilePath,`${JSON.stringify(n,null,2)}
1
+ import{Zi as i}from"./chunk-b22ab7yw.js";import{$i as Kn,_i as rn,aj as Hn,ej as Yn,fj as _n,gj as Fn,hj as Vn,ij as qn,jj as ct,kj as Jn,lj as Qn,mj as Mn,nj as jn,oj as Wn,pj as Sn,qj as Zn,rj as kn,sj as ln,tj as yn,uj as vn,vj as te}from"./chunk-amabfzc8.js";import{wj as Pn,xj as xn}from"./chunk-m2x6pb4f.js";import{Ej as Ut,Gj as Lt,Hj as St,Ij as m}from"./chunk-4e4qtpca.js";import{Nj as Gn,Qj as tt}from"./chunk-5s2x98rx.js";import{Yj as xt,Zj as Bt}from"./chunk-pbckwd41.js";import{ek as b}from"./chunk-px45q235.js";import{fk as It}from"./chunk-a95jmx2j.js";var nt;((r)=>{r.DEFAULT="default";r.AUTO_EDIT="autoEdit";r.YOLO="yolo";r.PLAN="plan"})(nt||={});var ne=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function ee(t){return t==="127.0.0.1"||t==="[::1]"||t.toLowerCase()==="localhost"}function $(t,n="MCP OAuth URL"){let e=new URL(t);if(e.username||e.password)throw Error(`${n} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ee(e.hostname)))throw Error(`${n} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var K=async(t,n)=>{$(t,"MCP OAuth request URL");let e=await fetch(t,{...n,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function et(t){let n=t.oauth;if(!n)return;let e=n;for(let s of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[s]!==void 0)throw Error(`MCP OAuth "${s}" is not supported; use standards-based discovery`);if(n.enabled!==!0)return{enabled:!1};if(t.type!=="http"&&t.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!t.url)throw Error("MCP OAuth requires an MCP server URL");if($(t.url,"MCP OAuth server URL"),Object.keys(t.headers??{}).find((s)=>s.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=n.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=n.scopes?.map((s)=>s.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((s)=>!s||s.length>128||!ne.test(s)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let M=n.callbackPort;if(M!==void 0&&(!Number.isInteger(M)||M<1024||M>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},...M!==void 0?{callbackPort:M}:{}}}import{randomUUID as Et}from"node:crypto";import ge from"node:http";import{auth as wt}from"@modelcontextprotocol/sdk/client/auth.js";import ce from"open";import{createHash as _e,randomUUID as Me}from"node:crypto";import{constants as rt,promises as I}from"node:fs";import _t from"node:path";import Se from"write-file-atomic";import{Mutex as re}from"async-mutex";class U{entries=new Map;async runExclusive(t,n){let e=this.entries.get(t);if(!e)e={mutex:new re,operations:0},this.entries.set(t,e);e.operations++;try{return await e.mutex.runExclusive(n)}finally{if(e.operations--,e.operations===0&&this.entries.get(t)===e)this.entries.delete(t)}}getStats(){let t=0;for(let n of this.entries.values())t+=n.operations;return{keys:this.entries.size,operations:t}}}var bt=1,se=1048576,Ee=5000,ue=50,oe=/^[a-f0-9]{64}$/,me=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Te=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ae=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),dt=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(me),tokens:m.Optional(Te),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(ae),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),it=m.Object({version:m.Literal(bt),credentials:m.Record(m.String(),dt)},{additionalProperties:!1});function H(t,n){return t instanceof Error&&"code"in t&&t.code===n}function Ae(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(n){return H(n,"EPERM")}}function Mt(t){return structuredClone(t)}function ht(t){if(Object.keys(t.credentials).some((n)=>!oe.test(n)))throw Error("MCP OAuth credential store contains an invalid identity")}function Y(t){let n=new URL(t);return n.hash="",n.toString()}function st(t,n,e=[]){return _e("sha256").update(JSON.stringify({serverUrl:Y(t),clientId:n?.trim()||null,scopes:[...e].sort()})).digest("hex")}class N{static locks=new U;stateRoot;tokenFilePath;constructor(t=It()){this.stateRoot=_t.join(t,"mcp"),this.tokenFilePath=_t.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[t];return e?Mt(e):null})}async updateCredential(t,n){return this.runMutation(async(e)=>{let _=e.credentials[t],r=await n(_?Mt(_):null);if(r)e.credentials[t]=St(dt,r);else delete e.credentials[t];return r?Mt(e.credentials[t]):null})}async deleteCredential(t){await this.updateCredential(t,()=>null)}async listCredentialIds(){return N.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(t){return N.locks.runExclusive(this.tokenFilePath,async()=>{let n=await this.acquireStoreLock();try{let e=await this.readStore(),_=await t(e);return await this.writeStore(e),_}finally{await n()}})}async ensureStateRoot(){await I.mkdir(this.stateRoot,{recursive:!0,mode:448});let t=await I.lstat(this.stateRoot);if(!t.isDirectory()||t.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((t.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let t=await I.lstat(this.tokenFilePath);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&t.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((t.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(t.size>se)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let n=JSON.parse(await I.readFile(this.tokenFilePath,"utf8")),e=Lt(it,n);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return ht(e.data),e.data}catch(t){if(H(t,"ENOENT"))return{version:bt,credentials:{}};throw t}}async writeStore(t){await this.ensureStateRoot();let n=St(it,t);ht(n),await Se(this.tokenFilePath,`${JSON.stringify(n,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await I.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let t=_t.join(this.stateRoot,".oauth-credentials.lock"),n=Me(),e=Date.now()+Ee;while(Date.now()<e)try{let _=await I.open(t,rt.O_CREAT|rt.O_EXCL|rt.O_WRONLY,384);return await _.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:n,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await _.close(),async()=>{try{if(JSON.parse(await I.readFile(t,"utf8")).token===n)await I.unlink(t)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(_){if(!H(_,"EEXIST"))throw _;await this.removeDeadLock(t),await new Promise((r)=>setTimeout(r,ue))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(t){let n=await I.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&n.uid!==process.getuid()||(n.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await I.readFile(t,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!Ae(e.pid))await I.unlink(t)}}var Nt="127.0.0.1",ft=7777,Pt="/oauth/callback",ie=300000;class ut extends Error{constructor(t){super(`MCP server "${t}" requires OAuth authorization; run "blade mcp login ${t}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Ct extends Error{constructor(t){super(`MCP OAuth credentials are unavailable in this runtime for server "${t}"`);this.name="McpOAuthUnavailableError"}}function he(t){let n=t?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -41,4 +41,4 @@ ${e.map((_)=>` - ${_}`).join(`
41
41
  ]
42
42
  }
43
43
  `)}}function rM(t,n={}){let e={...t};if(n.debug!==void 0)e.debug=n.debug===""?!0:n.debug;if(n.model){if(!t.models.some((r)=>r.id===n.model))throw Error(`模型配置未找到: ${n.model}`);e.currentModelId=n.model}if(n.yolo===!0)e.permissionMode="yolo";else if(n.permissionMode!==void 0)e.permissionMode=n.permissionMode;if(n.maxTurns!==void 0)e.maxTurns=n.maxTurns;if(n.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=n.maxConcurrentTasks;if(n.maxQueuedTasks!==void 0)e.maxQueuedTasks=n.maxQueuedTasks;if(n.maxQueuedTaskBytes!==void 0)e.maxQueuedTaskBytes=n.maxQueuedTaskBytes;if(n.maxResidentSessionRuntimes!==void 0)e.maxResidentSessionRuntimes=n.maxResidentSessionRuntimes;if(n.sessionRuntimeIdleMs!==void 0)e.sessionRuntimeIdleMs=n.sessionRuntimeIdleMs;if(n.maxResidentSessionProjections!==void 0)e.maxResidentSessionProjections=n.maxResidentSessionProjections;if(n.sessionProjectionIdleMs!==void 0)e.sessionProjectionIdleMs=n.sessionProjectionIdleMs;return e.systemPrompt=n.systemPrompt,e.appendSystemPrompt=n.appendSystemPrompt,e.model=n.model,e.resumeSessionId=n.sessionId,e.forkSession=n.forkSession,e.allowedTools=n.allowedTools,e.disallowedTools=n.disallowedTools,e.mcpConfigPaths=n.mcpConfig,e.strictMcpConfig=n.strictMcpConfig,e.addDirs=n.addDir,e.outputFormat=n.outputFormat,e.inputFormat=n.inputFormat,e.print=n.print,e.includePartialMessages=n.includePartialMessages,e.replayUserMessages=n.replayUserMessages,e.agentsConfig=n.agents,e.settingSources=n.settingSources,e}
44
- export{nt as Eh,K as Fh,et as Gh,U as Hh,N as Ih,ut as Jh,Ct as Kh,B as Lh,mn as Mh,vr as Nh,Z as Oh,e_ as Ph,r_ as Qh,__ as Rh,cn as Sh,Re as Th,M_ as Uh,Xe as Vh,S_ as Wh,Bn as Xh,u_ as Yh,o_ as Zh,T_ as _h,a_ as $h,A_ as ai,pn as bi,g_ as ci,c_ as di,i_ as ei,h_ as fi,F as gi,pt as hi,V as ii,q as ji,Rt as ki,J as li,hr as mi,Ir as ni,Q as oi,j as pi,C as qi,$r as ri,Dt as si,Gt as ti,zr as ui,Kt as vi,Ht as wi,Yt as xi,Ft as yi,Vt as zi,qt as Ai,Gr as Bi,Jt as Ci,Qt as Di,jt as Ei,Wt as Fi,Zt as Gi,kt as Hi,lt as Ii,yt as Ji,vt as Ki,tn as Li,nn as Mi,en as Ni,T as Oi,d as Pi,de as Qi,D as Ri,v as Si,R as Ti,rM as Ui};
44
+ export{nt as Fh,K as Gh,et as Hh,U as Ih,N as Jh,ut as Kh,Ct as Lh,B as Mh,mn as Nh,vr as Oh,Z as Ph,e_ as Qh,r_ as Rh,__ as Sh,cn as Th,Re as Uh,M_ as Vh,Xe as Wh,S_ as Xh,Bn as Yh,u_ as Zh,o_ as _h,T_ as $h,a_ as ai,A_ as bi,pn as ci,g_ as di,c_ as ei,i_ as fi,h_ as gi,F as hi,pt as ii,V as ji,q as ki,Rt as li,J as mi,hr as ni,Ir as oi,Q as pi,j as qi,C as ri,$r as si,Dt as ti,Gt as ui,zr as vi,Kt as wi,Ht as xi,Yt as yi,Ft as zi,Vt as Ai,qt as Bi,Gr as Ci,Jt as Di,Qt as Ei,jt as Fi,Wt as Gi,Zt as Hi,kt as Ii,lt as Ji,yt as Ki,vt as Li,tn as Mi,nn as Ni,en as Oi,T as Pi,d as Qi,de as Ri,D as Si,v as Ti,R as Ui,rM as Vi};
@@ -1,2 +1,2 @@
1
- import{hh as F,oh as a}from"./chunk-wcps5gjm.js";import{vj as A,wj as o,yj as s}from"./chunk-hrtf7dba.js";import{Dj as J1,Hj as $,Ij as Z,Jj as W,Kj as K}from"./chunk-9ydrwcpy.js";import{ek as $1}from"./chunk-gzbb747a.js";var w=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],K1={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},u=new Map;function I(J,B,j){let Y=new Set;for(let H of J.split(",")){let[k,G]=H.split("/"),V=G?Number.parseInt(G,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${J}"`);let X=B,Q=j;if(k!=="*"&&k!=="")if(k.includes("-")){let[b,B1]=k.split("-");X=Number.parseInt(b,10),Q=Number.parseInt(B1,10)}else X=Number.parseInt(k,10),Q=X;if(!Number.isInteger(X)||!Number.isInteger(Q)||X<B||Q>j||X>Q)throw Error(`Invalid cron range "${k}" in field "${J}"`);for(let b=X;b<=Q;b+=V)Y.add(b)}return Y}function d(J){let B=J.trim().split(/\s+/);if(B.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${B.length}`);let[j,Y,H,k,G]=B,V=I(G,w[4].min,w[4].max),X=new Set([...V].map((Q)=>Q===7?0:Q));return{minutes:I(j,w[0].min,w[0].max),hours:I(Y,w[1].min,w[1].max),daysOfMonth:I(H,w[2].min,w[2].max),months:I(k,w[3].min,w[3].max),daysOfWeek:X,domRestricted:H.trim()!=="*",dowRestricted:G.trim()!=="*"}}function Y1(J,B){if(!B)return{minute:J.getMinutes(),hour:J.getHours(),dayOfMonth:J.getDate(),month:J.getMonth()+1,dayOfWeek:J.getDay()};let j=u.get(B);if(!j)j=new Intl.DateTimeFormat("en-US",{timeZone:B,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),u.set(B,j);let Y=Object.fromEntries(j.formatToParts(J).filter((H)=>H.type!=="literal").map((H)=>[H.type,H.value]));return{minute:Number(Y.minute),hour:Number(Y.hour),dayOfMonth:Number(Y.day),month:Number(Y.month),dayOfWeek:K1[Y.weekday]??-1}}function j1(J,B,j){let Y=Y1(B,j);if(!J.minutes.has(Y.minute))return!1;if(!J.hours.has(Y.hour))return!1;if(!J.months.has(Y.month))return!1;let H=J.daysOfMonth.has(Y.dayOfMonth),k=J.daysOfWeek.has(Y.dayOfWeek);if(J.domRestricted&&J.dowRestricted)return H||k;if(J.domRestricted)return H;if(J.dowRestricted)return k;return!0}function H1(J,B,j){let Y=d(J),H=new Date(B.getTime());H.setSeconds(0,0),H.setMinutes(H.getMinutes()+1);let k=new Date(B.getTime());k.setFullYear(k.getFullYear()+4);while(H.getTime()<=k.getTime()){if(j1(Y,H,j))return new Date(H.getTime());H.setMinutes(H.getMinutes()+1)}return null}var m={s:1000,m:60000,h:3600000,d:86400000};function e1(J){let j=J.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!j)return null;let Y=Number.parseInt(j[1],10);if(!Number.isInteger(Y)||Y<=0)return null;let H=j[2]||"m";return Y*m[H]}function k1(J){for(let B of["d","h","m","s"]){let j=m[B];if(J%j===0)return`${J/j}${B}`}return`${Math.round(J/1000)}s`}function C(J,B,j){switch(J.kind){case"cron":{if(!J.cron)return null;try{return H1(J.cron,B,J.timezone)}catch{return null}}case"interval":{if(!J.intervalMs||J.intervalMs<=0)return null;let H=new Date((j??B).getTime()+J.intervalMs);return H.getTime()<=B.getTime()?new Date(B.getTime()+1000):H}case"once":{if(!J.runAt)return null;let Y=new Date(J.runAt);if(Number.isNaN(Y.getTime()))return null;return Y.getTime()>B.getTime()?Y:null}default:return null}}function L(J){switch(J.kind){case"cron":if(!J.cron)return"cron trigger requires a cron expression";try{if(d(J.cron),J.timezone)new Intl.DateTimeFormat("en-US",{timeZone:J.timezone}).format();return null}catch(B){return B instanceof Error?B.message:"invalid cron expression"}case"interval":if(!J.intervalMs||J.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!J.runAt)return"once trigger requires runAt timestamp";let B=new Date(J.runAt);if(Number.isNaN(B.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function $0(J){switch(J.kind){case"cron":return`cron: ${J.cron??"?"}`;case"interval":return`every ${J.intervalMs?k1(J.intervalMs):"?"}`;case"once":return`once at ${J.runAt??"?"}`;default:return"unknown"}}import{mkdir as a1,readFile as t1}from"node:fs/promises";import Z1 from"node:path";import{nanoid as r1}from"nanoid";import y1 from"write-file-atomic";var q=160,Q1=240,h=$.String({pattern:"^[a-f0-9]{64}$"}),X1=Z($.Object({id:$.String({minLength:1,maxLength:128}),position:$.Integer({minimum:0,maximum:q-1}),queuedAt:$.String({minLength:20,maxLength:32}),kind:K(["user","internal"]),state:K(["pending","locked"]),delivery:K(["current_turn","next_turn","recovery"]),mutable:$.Boolean(),preview:$.Optional($.String({maxLength:Q1})),previewTruncated:$.Boolean(),attachmentCount:$.Integer({minimum:0,maximum:20})},{additionalProperties:!1})),g=Z($.Object({version:h,pending:$.Integer({minimum:0,maximum:q}),mutable:$.Integer({minimum:0,maximum:q}),locked:$.Integer({minimum:0,maximum:q}),internal:$.Integer({minimum:0,maximum:q}),items:$.Array(X1,{maxItems:q})},{additionalProperties:!1})),W1=$.Union([$.Object({type:$.Literal("remove"),messageId:$.String({minLength:1,maxLength:128})},{additionalProperties:!1}),$.Object({type:$.Literal("move"),messageId:$.String({minLength:1,maxLength:128}),toPosition:$.Integer({minimum:0,maximum:q-1})},{additionalProperties:!1})]),B0=Z($.Object({expectedVersion:h,operation:W1},{additionalProperties:!1})),K0=Z($.Object({snapshot:g},{additionalProperties:!1})),b1=K(["revision_conflict","already_claimed","immutable_origin","immutable_boundary","not_found","runtime_unavailable","invalid_mutation","storage_unavailable"]),Y0=Z($.Object({error:$.Object({code:b1,message:$.String({minLength:1,maxLength:256})},{additionalProperties:!1}),snapshot:g},{additionalProperties:!1}));var G1=K(["preferences","conventions","lessons","debugging"]),V1=$.Object({outcome:K(["nothing_to_store","disabled","failed"]),entries:$.Literal(0),topics:$.Tuple([])},{additionalProperties:!1}),w1=$.Object({outcome:$.Literal("written"),entries:$.Integer({minimum:1,maximum:20}),topics:$.Array(G1,{minItems:1,maxItems:4,uniqueItems:!0})},{additionalProperties:!1}),k0=Z($.Union([w1,V1]));var c=128,D1=128,z1=8,q1=1e6,v1=8640000000000000,D=$.Integer({minimum:0,maximum:q1}),M=$.Integer({minimum:0,maximum:v1}),x1=$.String({minLength:1,maxLength:c,pattern:"^[^\x00-\x1F]+$"}),P1=K(["starting","thinking","responding","executing_tools","compacting","continuing"]),f1=$.Refine($.Object({name:x1,kind:$.Optional(K(["readonly","write","execute"])),startedAt:M,progress:$.Optional(D),total:$.Optional(D)},{additionalProperties:!1}),(J)=>J.progress===void 0&&J.total===void 0||J.progress!==void 0&&J.total!==void 0&&J.progress<=J.total,()=>"progress and total must be present together with progress <= total"),O1=$.Refine($.Object({phase:P1,startedAt:M,updatedAt:M,turn:D,maxTurns:$.Union([D,$.Null()]),outputStarted:$.Boolean(),toolCallsStarted:D,toolCallsCompleted:D,activeTools:$.Array(f1,{maxItems:z1}),activeToolOverflow:D},{additionalProperties:!1}),(J)=>J.startedAt<=J.updatedAt&&J.toolCallsCompleted<=J.toolCallsStarted&&J.activeTools.length+J.activeToolOverflow<=J.toolCallsStarted-J.toolCallsCompleted,()=>"turn activity snapshot counters and timestamps are inconsistent"),W0=Z($.Object({version:$.Literal(1),generation:$.String({minLength:1,maxLength:D1,pattern:"^[^\x00-\x1F]+$"}),revision:D,snapshot:$.Union([O1,$.Null()])},{additionalProperties:!1}));function b0(J){let B=[...J].filter((j)=>{let Y=j.codePointAt(0)??0;return Y>31&&Y!==127}).join("").trim().slice(0,c);if(!B)throw Error("Turn activity tool name is empty");return B}var n=16384;function V0(J){let B=/^\s*\/btw(?:\s+([\s\S]*))?\s*$/iu.exec(J);if(!B)return;return{question:(B[1]??"").trim()}}var v=Z(K(["default","autoEdit","yolo","plan"]));var R=Z(K(["user","assistant","system","tool"])),I1=Z($.Union([$.Object({type:$.Literal("text"),text:$.String()}),$.Object({type:$.Literal("image_url"),image_url:$.Object({url:$.String()})})])),t=$.Union([$.String(),$.Array(I1)]),P0=Z($.Object({id:$.String(),role:R,content:t,timestamp:$.Number(),metadata:$.Optional($.Record($.String(),$.Unknown())),thinkingContent:$.Optional($.String()),tool_call_id:$.Optional($.String()),name:$.Optional($.String()),tool_calls:$.Optional($.Unknown())})),N1=Z(K(["queued","running","completed","failed","cancelled","interrupted"])),N=Z(K(["local","worktree"])),E=Z(K(["high","medium","low"])),_=Z(K(["feature","bug","maintenance","research"])),U1=Z(K(["applied","discarded","conflicted"])),F1=Z($.Object({status:U1,updatedAt:$.String(),sourceCommit:$.Optional($.String()),changedFiles:$.Optional($.Integer({minimum:0})),message:$.Optional($.String())})),C1=Z($.Object({changedFiles:$.Integer({minimum:0}),additions:$.Integer({minimum:0}),deletions:$.Integer({minimum:0}),commits:$.Integer({minimum:0})})),L1=Z($.Object({path:$.String({minLength:1}),patch:$.String({maxLength:2097152}),additions:$.Integer({minimum:0}),deletions:$.Integer({minimum:0}),binary:$.Boolean(),truncated:$.Boolean()})),f0=Z($.Object({sessionId:$.String(),projectPath:$.String(),baseCommit:$.String(),files:$.Array(L1,{maxItems:100}),truncated:$.Boolean()})),M1=$.Union([$.String(),$.Number(),$.Boolean(),$.Array($.String())]),A1=Z($.Object({name:$.String(),type:K(["string","number","integer","boolean","select","multi-select"]),title:$.String(),description:$.Optional($.String()),required:$.Boolean(),defaultValue:$.Optional(M1),options:$.Optional($.Array($.Object({value:$.String(),label:$.String()}))),format:$.Optional(K(["date","uri","email","date-time"])),minimum:$.Optional($.Number()),maximum:$.Optional($.Number()),minLength:$.Optional($.Number()),maxLength:$.Optional($.Number()),minItems:$.Optional($.Number()),maxItems:$.Optional($.Number())})),O0=Z($.Object({serverName:$.String(),mode:K(["form","url"]),message:$.String(),fields:$.Optional($.Array(A1)),requestedSchema:$.Optional($.Record($.String(),$.Unknown())),url:$.Optional($.String()),domain:$.Optional($.String()),elicitationId:$.Optional($.String())})),R1=Z($.Object({type:K(["permission","question","elicitation"]),requestId:$.String()})),E1=Z($.Object({code:K(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","workspace_unavailable","capacity","runtime"]),message:$.String({minLength:1,maxLength:500}),retryable:$.Boolean(),resource:$.Optional(K(["pending_count","pending_bytes","resident_runtimes"]))})),x=Z(K(["auto","off","minimal","low","medium","high","xhigh","max"])),P=Z(K(["auto","standard","fast","flex"])),f=Z(K(["auto","low","medium","high"])),z=Z($.Union([K(["auto","pragmatic","friendly","explanatory"]),$.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})$"})])),U=Z($.Object({sessionId:$.String(),projectPath:$.String(),title:$.Optional($.String()),gitBranch:$.Optional($.String()),rootId:$.String(),parentId:$.Optional($.String()),relationType:$.Optional(K(["subagent","fork"])),resumedFrom:$.Optional($.String()),rootAgentId:$.Optional($.String()),resumeDepth:$.Optional($.Integer({minimum:0})),taskStatus:W(N1,"completed"),taskStatusReason:$.Optional($.String()),taskFailure:$.Optional(E1),taskStartedAt:$.Optional($.String()),taskCompletedAt:$.Optional($.String()),taskPromptSummary:$.Optional($.String()),taskPriority:$.Optional(E),taskKind:$.Optional(_),taskDueAt:$.Optional($.String()),taskModelId:$.Optional($.String()),selectedModelId:$.Optional($.String()),permissionMode:$.Optional(v),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),communicationStyleDigest:$.Optional($.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:$.Optional($.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:$.Optional($.Boolean()),taskRetriedFrom:$.Optional($.Object({sessionId:$.String(),projectPath:$.String()})),taskDelivery:$.Optional(F1),taskIsolation:$.Optional(N),taskSourceProjectPath:$.Optional($.String()),taskWorktreePath:$.Optional($.String()),taskWorktreeBranch:$.Optional($.String()),taskBaseCommit:$.Optional($.String()),taskDiffStat:$.Optional(C1),taskQueuePosition:$.Optional($.Integer({minimum:1})),taskQueueDepth:$.Optional($.Integer({minimum:0})),taskConcurrencyLimit:$.Optional($.Integer({minimum:1})),archivedAt:$.Optional($.String()),archivedBySessionId:$.Optional($.String()),pendingInteraction:$.Optional(R1),messageCount:$.Number(),firstMessageTime:$.String(),lastMessageTime:$.String(),hasErrors:$.Boolean()})),I0=Z($.Object({sessions:$.Array(U),nextCursor:$.Optional($.String())})),N0=Z($.Object({session:U,archivedSessionIds:$.Array($.String())})),U0=Z($.Object({session:U,restoredSessionIds:$.Array($.String())})),_1=$.Object({rootTurnId:$.Optional($.String({minLength:1,maxLength:F})),currentTurnId:$.String({minLength:1,maxLength:F}),parentTurnId:$.Optional($.String({minLength:1,maxLength:F}))},{additionalProperties:!1}),F0=Z($.Object({version:$.Union([$.Literal(1),$.Literal(2)]),sessionId:$.String(),goalId:$.String(),objective:$.String(),status:K(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:$.Optional($.Number()),tokensUsed:$.Number(),timeUsedSeconds:$.Number(),continuationCount:$.Number(),statusReason:$.Optional($.String()),completionVerification:$.Optional($.Object({attempt:$.Integer({minimum:1}),status:K(["pending","pass","fail","partial"]),requestedAt:$.String(),completedAt:$.Optional($.String()),verifierSessionId:$.Optional($.String()),summary:$.Optional($.String()),evidenceSha256:$.Optional($.String({pattern:"^[a-f0-9]{64}$"}))})),prematureStop:$.Optional($.Object({pattern:$.Unsafe({type:"string"}),consecutiveCount:$.Integer({minimum:1}),detectedAt:$.String()})),executionHostFailure:$.Optional($.Object({category:K(a),consecutiveCount:$.Integer({minimum:1,maximum:3}),detectedAt:$.String()},{additionalProperties:!1})),turnLineage:$.Optional(_1),verificationStall:$.Optional($.Unsafe({type:"object"})),executionFrontier:$.Optional($.Object({taskListId:$.String({minLength:1,maxLength:256}),total:$.Integer({minimum:0}),completed:$.Integer({minimum:0}),inProgress:$.Integer({minimum:0}),pending:$.Integer({minimum:0}),blocked:$.Integer({minimum:0}),nextTask:$.Optional($.Object({id:$.String({minLength:1}),subject:$.String({minLength:1,maxLength:512}),priority:K(["high","medium","low"])})),digestSha256:$.String({pattern:"^[a-f0-9]{64}$"}),observedAt:$.String()})),frontierStall:$.Optional($.Object({category:K(["waiting_dependency","same_task_no_effect","repeated_deferral"]),consecutiveCount:$.Integer({minimum:1,maximum:3}),digestSha256:$.String({pattern:"^[a-f0-9]{64}$"}),detectedAt:$.String()})),createdAt:$.String(),updatedAt:$.String()})),r=Z($.Object({id:$.Optional($.String({minLength:1})),role:R,content:t,metadata:$.Optional($.Unknown()),reasoningContent:$.Optional($.String()),thinkingContent:$.Optional($.String()),tool_call_id:$.Optional($.String()),name:$.Optional($.String()),tool_calls:$.Optional($.Unknown())})),C0=Z($.Object({session:U,messages:$.Array(r)})),y=Z(K(["conversation","code","both"])),S1=Z($.Object({messageId:$.String(),preview:$.String(),createdAt:$.String(),fileCount:$.Integer({minimum:0})})),L0=Z($.Object({targetMessageId:$.String({minLength:1}),mode:W(y,"conversation")})),M0=Z($.Object({checkpoint:S1,mode:y,removedTurns:$.Integer({minimum:1}),restoredFiles:$.Array($.String()),messages:$.Array(r)})),l1=K(["running","completed","failed","cancelled"]),i=Z($.Object({id:$.String(),subagentType:$.String(),description:$.String(),status:l1,background:$.Boolean(),rootAgentId:$.String(),resumedFrom:$.Optional($.String()),resumeDepth:$.Integer({minimum:0}),createdAt:$.Number(),lastActiveAt:$.Number(),completedAt:$.Optional($.Number()),restartRecovery:$.Optional($.Object({outcome:K(["completed","interrupted","failed"]),recoveredAt:$.Number()})),result:$.Optional($.Object({success:$.Boolean(),message:$.String(),error:$.Optional($.String()),verificationCommands:$.Optional($.Array($.String())),verificationVerdict:$.Optional(K(["pass","fail","partial"])),modifiedFiles:$.Optional($.Array($.String()))})),stats:$.Optional($.Object({tokens:$.Optional($.Number()),toolCalls:$.Optional($.Number()),duration:$.Optional($.Number())}))})),A0=Z($.Object({prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"})})),R0=Z($.Object({source:i,session:i})),E0=Z($.Object({sessionId:$.String(),projectPath:$.String()})),_0=Z($.Object({path:$.String(),name:$.String(),gitBranch:$.Optional($.String()),available:$.Boolean(),isCurrent:$.Boolean(),boundAt:$.String()})),S0=Z($.Union([$.Object({cancelled:$.Literal(!0)}),$.Object({cancelled:$.Literal(!1),path:$.String({minLength:1})})])),l0=Z($.Object({type:$.String(),seq:$.Optional($.Number()),properties:$.Record($.String(),$.Unknown())})),T=$.Object({type:K(["file","image","url"]),path:$.Optional($.String()),url:$.Optional($.String()),content:$.Optional($.String({maxLength:o})),mimeType:$.Optional($.String()),name:$.Optional($.String())}),u1=20,d1=12288,m1=4096,h1=$.Object({id:$.String({minLength:1,maxLength:200}),text:$.String({minLength:1,maxLength:d1}),sourceMessageId:$.String({minLength:1,maxLength:500}),sourceRole:K(["user","assistant"]),comment:$.Optional($.String({maxLength:m1}))}),p=$.Record($.String(),$.Unknown()),u0=Z($.Object({prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:$.Optional($.String({minLength:1,maxLength:200})),taskPriority:W(E,"medium"),taskKind:W(_,"feature"),taskDueAt:$.Optional($.String({minLength:1,maxLength:64})),projectPath:$.Optional($.String()),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),isolation:W(N,"worktree"),permissionMode:W(v,"default"),attachments:$.Optional($.Array(T,{maxItems:A})),outputSchema:$.Optional(p)})),d0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),taskPriority:$.Optional(E),taskKind:$.Optional(_),taskDueAt:$.Optional($.Union([$.String({minLength:1,maxLength:64}),$.Null()]))})),m0=Z($.Object({session:U,runId:$.String(),messageId:$.String(),status:K(["queued","running"]),queuePosition:$.Optional($.Integer({minimum:1})),queueDepth:$.Optional($.Integer({minimum:0})),maxConcurrentTasks:$.Optional($.Integer({minimum:1}))})),h0=Z($.Object({action:K(["apply","discard"])})),S=Z($.Object({kind:K(["cron","interval","once"]),cron:$.Optional($.String({minLength:1,maxLength:120})),intervalMs:$.Optional($.Integer({minimum:60000})),runAt:$.Optional($.String({minLength:1,maxLength:40})),timezone:$.Optional($.String({minLength:1,maxLength:80}))})),g1=Z($.Object({modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),isolation:W(N,"worktree"),permissionMode:W(v,"default")})),l=Z($.Object({id:$.String(),title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:$.String({minLength:1}),trigger:S,dispatch:g1,enabled:$.Boolean(),createdAt:$.String(),updatedAt:$.String(),nextRunAt:$.Union([$.String(),$.Null()]),expiresAt:$.Union([$.String(),$.Null()]),lastRunAt:$.Optional($.String()),lastRunSessionId:$.Optional($.String()),lastStatus:$.Optional(K(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:$.Optional($.String()),runCount:$.Integer({minimum:0})})),g0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:$.String({minLength:1}),trigger:S,modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),isolation:W(N,"worktree"),permissionMode:W(v,"default"),enabled:W($.Boolean(),!0)})),c0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.Optional($.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:$.Optional(S),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),isolation:$.Optional(N),permissionMode:$.Optional(v),enabled:$.Optional($.Boolean())})),n0=Z($.Object({schedules:$.Array(l)})),i0=Z($.Object({content:$.String({maxLength:s}),projectPath:$.Optional($.String()),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),permissionMode:$.Optional(v),attachments:$.Optional($.Array(T,{maxItems:A})),annotations:$.Optional($.Array(h1,{maxItems:u1})),outputSchema:$.Optional(p)})),c1=K(["completed","failed","aborted","timed_out","spawn_error"]),n1=Z($.Object({version:$.Literal(1),command:$.String(),status:c1,exitCode:$.Union([$.Integer(),$.Null()]),durationMs:$.Number({minimum:0}),stdout:$.String(),stderr:$.String(),stdoutOmittedBytes:$.Integer({minimum:0}),stderrOmittedBytes:$.Integer({minimum:0}),binaryOutput:$.Boolean(),truncated:$.Boolean()})),o0=Z($.Object({command:$.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:$.Optional($.String())})),s0=Z($.Object({executionId:$.String(),messageId:$.String(),record:n1,auxiliary:$.Boolean(),delivery:$.Optional(K(["current_turn","next_turn"])),queued:$.Optional($.Integer({minimum:0}))})),a0=Z($.Object({question:$.String({minLength:1,maxLength:n,pattern:"^(?![\\s\\S]*\\x00)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:$.Optional($.String())})),t0=Z($.Object({response:$.String({minLength:1}),durationMs:$.Number({minimum:0}),modelId:$.Optional($.String()),usage:$.Optional($.Object({promptTokens:$.Number({minimum:0}),completionTokens:$.Number({minimum:0}),totalTokens:$.Number({minimum:0}),reasoningTokens:$.Optional($.Number({minimum:0})),cacheCreationInputTokens:$.Optional($.Number({minimum:0})),cacheReadInputTokens:$.Optional($.Number({minimum:0})),costUsd:$.Optional($.Number({minimum:0}))}))})),r0=Z($.Object({projectPath:$.String(),kind:K(["uncommitted","base","commit"]),ref:$.Optional($.String({maxLength:200})),instructions:$.Optional($.String({maxLength:4000})),modelId:$.Optional($.String({minLength:1,maxLength:200}))})),y0=Z($.Object({reviewId:$.String(),status:$.Literal("running")})),T0=Z($.Object({messageId:$.String(),role:R,content:$.String(),timestamp:$.String()})),p0=Z($.Object({approved:$.Boolean(),remember:$.Optional($.Boolean()),scope:$.Optional(K(["once","session","project"])),targetMode:$.Optional(v),feedback:$.Optional($.String()),answers:$.Optional($.Record($.String(),$.Union([$.String(),$.Array($.String())]))),elicitation:$.Optional($.Object({action:K(["accept","decline","cancel"]),content:$.Optional($.Record($.String(),$.Union([$.String({maxLength:4000}),$.Number(),$.Boolean(),$.Array($.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),i1=Z($.Object({id:z,name:$.String({minLength:1,maxLength:80}),description:$.String({minLength:1,maxLength:256}),source:K(["built-in","user","project","plugin"]),contentSha256:$.Optional($.String({pattern:"^[a-f0-9]{64}$"}))})),e0=Z($.Object({id:$.String(),displayName:$.Optional($.String()),provider:$.String(),model:$.String(),contextWindow:$.Optional($.Number()),maxTokens:$.Optional($.Number()),reasoning:$.Optional($.Boolean()),supportedReasoningEfforts:$.Optional($.Array(K(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:$.Optional($.Array(K(["standard","fast","flex"]))),supportedResponseVerbosities:$.Optional($.Array(K(["low","medium","high"]))),communicationStyles:$.Optional($.Array(i1,{maxItems:36})),input:$.Optional($.Array(K(["text","image"]))),overrides:$.Optional($.Object({baseUrl:$.Optional($.String()),temperature:$.Optional($.Number()),maxOutputTokens:$.Optional($.Number()),timeout:$.Optional($.Number()),streamIdleTimeout:$.Optional($.Number({minimum:1000}))}))})),$2=Z(K(["vs-dark","vs-light","hc-black"])),o1=Z(K(["light","dark","system"])),s1=Z($.Object({language:$.String(),codeTheme:$.String(),uiTheme:o1,autoSaveSessions:$.Boolean(),notifyBuild:$.Boolean(),notifyErrors:$.Boolean(),notifySounds:$.Boolean(),privacyTelemetry:$.Boolean(),privacyCrash:$.Boolean(),agentTeamsEnabled:$.Boolean(),communicationStyle:$.Optional(z)})),J2=Z($.Partial(s1));var e=J1("Service"),T1=1;function p1(){return Z1.join($1(),"schedules.json")}class O{filePath;static instance;static getInstance(){if(!O.instance)O.instance=new O;return O.instance}writeChain=Promise.resolve();constructor(J=p1()){this.filePath=J}async readFile(){try{let J=await t1(this.filePath,"utf-8"),B=JSON.parse(J);if(!B||!Array.isArray(B.schedules))return[];let j=[],Y=0;for(let H of B.schedules){let k=l.safeParse(H);if(k.success)j.push(k.data);else Y+=1}if(Y>0)e.warn(`[ScheduleStore] Ignored ${Y} invalid persisted schedule(s)`);return j}catch(J){let B=J;if(B.code!=="ENOENT")e.warn("[ScheduleStore] Failed to read schedules; treating as empty:",B);return[]}}async writeFile(J){await a1(Z1.dirname(this.filePath),{recursive:!0,mode:493});let B={version:T1,schedules:J};await y1(this.filePath,JSON.stringify(B,null,2),{mode:384})}serializeWrite(J){let B=this.writeChain.then(J,J);return this.writeChain=B.then(()=>{return},()=>{return}),B}async list(){return this.readFile()}async get(J){return(await this.readFile()).find((j)=>j.id===J)}async create(J){return this.serializeWrite(async()=>{let B=J.trigger.kind==="cron"&&!J.trigger.timezone?{...J.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:J.trigger,j=L(B);if(j)throw Error(j);let Y=new Date;if(B.kind==="once"&&new Date(B.runAt).getTime()<=Y.getTime())throw Error("once trigger runAt must be in the future");let H=Y.toISOString(),k=C(B,Y),G={id:r1(10),title:J.title,prompt:J.prompt,projectPath:J.projectPath,trigger:B,dispatch:{modelId:J.modelId,reasoningEffort:J.reasoningEffort,serviceTier:J.serviceTier,responseVerbosity:J.responseVerbosity,communicationStyle:J.communicationStyle,isolation:J.isolation??"worktree",permissionMode:J.permissionMode??"default"},enabled:J.enabled??!0,createdAt:H,updatedAt:H,nextRunAt:k?k.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(G),await this.writeFile(V),G})}async update(J,B){return this.serializeWrite(async()=>{let j=await this.readFile(),Y=j.findIndex((Q)=>Q.id===J);if(Y===-1)return;let H=j[Y];if(B.trigger){let Q=B.trigger.kind==="cron"&&!B.trigger.timezone?{...B.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:B.trigger,b=L(Q);if(b)throw Error(b);if(Q.kind==="once"&&new Date(Q.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");B={...B,trigger:Q}}let k={...H,...B,dispatch:B.dispatch?{...H.dispatch,...B.dispatch}:H.dispatch,updatedAt:new Date().toISOString()},G=!H.enabled,V=k.enabled,X=B.trigger!==void 0;if((X||G&&V)&&B.nextRunAt===void 0){let Q=new Date,b=C(k.trigger,Q);if(k.nextRunAt=b?b.toISOString():null,X)k.expiresAt=null}return j[Y]=k,await this.writeFile(j),k})}async remove(J){return this.serializeWrite(async()=>{let B=await this.readFile(),j=B.filter((Y)=>Y.id!==J);if(j.length===B.length)return!1;return await this.writeFile(j),!0})}async setEnabled(J,B){return this.update(J,{enabled:B})}}var v2=O.getInstance();
1
+ import{ih as F,ph as a}from"./chunk-kkzznz4w.js";import{wj as A,xj as o,zj as s}from"./chunk-m2x6pb4f.js";import{Ej as J1,Ij as $,Jj as Z,Kj as W,Lj as K}from"./chunk-4e4qtpca.js";import{fk as $1}from"./chunk-a95jmx2j.js";var w=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],K1={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},u=new Map;function I(J,B,j){let Y=new Set;for(let H of J.split(",")){let[k,G]=H.split("/"),V=G?Number.parseInt(G,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${J}"`);let X=B,Q=j;if(k!=="*"&&k!=="")if(k.includes("-")){let[b,B1]=k.split("-");X=Number.parseInt(b,10),Q=Number.parseInt(B1,10)}else X=Number.parseInt(k,10),Q=X;if(!Number.isInteger(X)||!Number.isInteger(Q)||X<B||Q>j||X>Q)throw Error(`Invalid cron range "${k}" in field "${J}"`);for(let b=X;b<=Q;b+=V)Y.add(b)}return Y}function d(J){let B=J.trim().split(/\s+/);if(B.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${B.length}`);let[j,Y,H,k,G]=B,V=I(G,w[4].min,w[4].max),X=new Set([...V].map((Q)=>Q===7?0:Q));return{minutes:I(j,w[0].min,w[0].max),hours:I(Y,w[1].min,w[1].max),daysOfMonth:I(H,w[2].min,w[2].max),months:I(k,w[3].min,w[3].max),daysOfWeek:X,domRestricted:H.trim()!=="*",dowRestricted:G.trim()!=="*"}}function Y1(J,B){if(!B)return{minute:J.getMinutes(),hour:J.getHours(),dayOfMonth:J.getDate(),month:J.getMonth()+1,dayOfWeek:J.getDay()};let j=u.get(B);if(!j)j=new Intl.DateTimeFormat("en-US",{timeZone:B,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),u.set(B,j);let Y=Object.fromEntries(j.formatToParts(J).filter((H)=>H.type!=="literal").map((H)=>[H.type,H.value]));return{minute:Number(Y.minute),hour:Number(Y.hour),dayOfMonth:Number(Y.day),month:Number(Y.month),dayOfWeek:K1[Y.weekday]??-1}}function j1(J,B,j){let Y=Y1(B,j);if(!J.minutes.has(Y.minute))return!1;if(!J.hours.has(Y.hour))return!1;if(!J.months.has(Y.month))return!1;let H=J.daysOfMonth.has(Y.dayOfMonth),k=J.daysOfWeek.has(Y.dayOfWeek);if(J.domRestricted&&J.dowRestricted)return H||k;if(J.domRestricted)return H;if(J.dowRestricted)return k;return!0}function H1(J,B,j){let Y=d(J),H=new Date(B.getTime());H.setSeconds(0,0),H.setMinutes(H.getMinutes()+1);let k=new Date(B.getTime());k.setFullYear(k.getFullYear()+4);while(H.getTime()<=k.getTime()){if(j1(Y,H,j))return new Date(H.getTime());H.setMinutes(H.getMinutes()+1)}return null}var m={s:1000,m:60000,h:3600000,d:86400000};function e1(J){let j=J.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!j)return null;let Y=Number.parseInt(j[1],10);if(!Number.isInteger(Y)||Y<=0)return null;let H=j[2]||"m";return Y*m[H]}function k1(J){for(let B of["d","h","m","s"]){let j=m[B];if(J%j===0)return`${J/j}${B}`}return`${Math.round(J/1000)}s`}function C(J,B,j){switch(J.kind){case"cron":{if(!J.cron)return null;try{return H1(J.cron,B,J.timezone)}catch{return null}}case"interval":{if(!J.intervalMs||J.intervalMs<=0)return null;let H=new Date((j??B).getTime()+J.intervalMs);return H.getTime()<=B.getTime()?new Date(B.getTime()+1000):H}case"once":{if(!J.runAt)return null;let Y=new Date(J.runAt);if(Number.isNaN(Y.getTime()))return null;return Y.getTime()>B.getTime()?Y:null}default:return null}}function L(J){switch(J.kind){case"cron":if(!J.cron)return"cron trigger requires a cron expression";try{if(d(J.cron),J.timezone)new Intl.DateTimeFormat("en-US",{timeZone:J.timezone}).format();return null}catch(B){return B instanceof Error?B.message:"invalid cron expression"}case"interval":if(!J.intervalMs||J.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!J.runAt)return"once trigger requires runAt timestamp";let B=new Date(J.runAt);if(Number.isNaN(B.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function $0(J){switch(J.kind){case"cron":return`cron: ${J.cron??"?"}`;case"interval":return`every ${J.intervalMs?k1(J.intervalMs):"?"}`;case"once":return`once at ${J.runAt??"?"}`;default:return"unknown"}}import{mkdir as a1,readFile as t1}from"node:fs/promises";import Z1 from"node:path";import{nanoid as r1}from"nanoid";import y1 from"write-file-atomic";var q=160,Q1=240,h=$.String({pattern:"^[a-f0-9]{64}$"}),X1=Z($.Object({id:$.String({minLength:1,maxLength:128}),position:$.Integer({minimum:0,maximum:q-1}),queuedAt:$.String({minLength:20,maxLength:32}),kind:K(["user","internal"]),state:K(["pending","locked"]),delivery:K(["current_turn","next_turn","recovery"]),mutable:$.Boolean(),preview:$.Optional($.String({maxLength:Q1})),previewTruncated:$.Boolean(),attachmentCount:$.Integer({minimum:0,maximum:20})},{additionalProperties:!1})),g=Z($.Object({version:h,pending:$.Integer({minimum:0,maximum:q}),mutable:$.Integer({minimum:0,maximum:q}),locked:$.Integer({minimum:0,maximum:q}),internal:$.Integer({minimum:0,maximum:q}),items:$.Array(X1,{maxItems:q})},{additionalProperties:!1})),W1=$.Union([$.Object({type:$.Literal("remove"),messageId:$.String({minLength:1,maxLength:128})},{additionalProperties:!1}),$.Object({type:$.Literal("move"),messageId:$.String({minLength:1,maxLength:128}),toPosition:$.Integer({minimum:0,maximum:q-1})},{additionalProperties:!1})]),B0=Z($.Object({expectedVersion:h,operation:W1},{additionalProperties:!1})),K0=Z($.Object({snapshot:g},{additionalProperties:!1})),b1=K(["revision_conflict","already_claimed","immutable_origin","immutable_boundary","not_found","runtime_unavailable","invalid_mutation","storage_unavailable"]),Y0=Z($.Object({error:$.Object({code:b1,message:$.String({minLength:1,maxLength:256})},{additionalProperties:!1}),snapshot:g},{additionalProperties:!1}));var G1=K(["preferences","conventions","lessons","debugging"]),V1=$.Object({outcome:K(["nothing_to_store","disabled","failed"]),entries:$.Literal(0),topics:$.Tuple([])},{additionalProperties:!1}),w1=$.Object({outcome:$.Literal("written"),entries:$.Integer({minimum:1,maximum:20}),topics:$.Array(G1,{minItems:1,maxItems:4,uniqueItems:!0})},{additionalProperties:!1}),k0=Z($.Union([w1,V1]));var c=128,D1=128,z1=8,q1=1e6,v1=8640000000000000,D=$.Integer({minimum:0,maximum:q1}),M=$.Integer({minimum:0,maximum:v1}),x1=$.String({minLength:1,maxLength:c,pattern:"^[^\x00-\x1F]+$"}),P1=K(["starting","thinking","responding","executing_tools","compacting","continuing"]),f1=$.Refine($.Object({name:x1,kind:$.Optional(K(["readonly","write","execute"])),startedAt:M,progress:$.Optional(D),total:$.Optional(D)},{additionalProperties:!1}),(J)=>J.progress===void 0&&J.total===void 0||J.progress!==void 0&&J.total!==void 0&&J.progress<=J.total,()=>"progress and total must be present together with progress <= total"),O1=$.Refine($.Object({phase:P1,startedAt:M,updatedAt:M,turn:D,maxTurns:$.Union([D,$.Null()]),outputStarted:$.Boolean(),toolCallsStarted:D,toolCallsCompleted:D,activeTools:$.Array(f1,{maxItems:z1}),activeToolOverflow:D},{additionalProperties:!1}),(J)=>J.startedAt<=J.updatedAt&&J.toolCallsCompleted<=J.toolCallsStarted&&J.activeTools.length+J.activeToolOverflow<=J.toolCallsStarted-J.toolCallsCompleted,()=>"turn activity snapshot counters and timestamps are inconsistent"),W0=Z($.Object({version:$.Literal(1),generation:$.String({minLength:1,maxLength:D1,pattern:"^[^\x00-\x1F]+$"}),revision:D,snapshot:$.Union([O1,$.Null()])},{additionalProperties:!1}));function b0(J){let B=[...J].filter((j)=>{let Y=j.codePointAt(0)??0;return Y>31&&Y!==127}).join("").trim().slice(0,c);if(!B)throw Error("Turn activity tool name is empty");return B}var n=16384;function V0(J){let B=/^\s*\/btw(?:\s+([\s\S]*))?\s*$/iu.exec(J);if(!B)return;return{question:(B[1]??"").trim()}}var v=Z(K(["default","autoEdit","yolo","plan"]));var R=Z(K(["user","assistant","system","tool"])),I1=Z($.Union([$.Object({type:$.Literal("text"),text:$.String()}),$.Object({type:$.Literal("image_url"),image_url:$.Object({url:$.String()})})])),t=$.Union([$.String(),$.Array(I1)]),P0=Z($.Object({id:$.String(),role:R,content:t,timestamp:$.Number(),metadata:$.Optional($.Record($.String(),$.Unknown())),thinkingContent:$.Optional($.String()),tool_call_id:$.Optional($.String()),name:$.Optional($.String()),tool_calls:$.Optional($.Unknown())})),N1=Z(K(["queued","running","completed","failed","cancelled","interrupted"])),N=Z(K(["local","worktree"])),E=Z(K(["high","medium","low"])),_=Z(K(["feature","bug","maintenance","research"])),U1=Z(K(["applied","discarded","conflicted"])),F1=Z($.Object({status:U1,updatedAt:$.String(),sourceCommit:$.Optional($.String()),changedFiles:$.Optional($.Integer({minimum:0})),message:$.Optional($.String())})),C1=Z($.Object({changedFiles:$.Integer({minimum:0}),additions:$.Integer({minimum:0}),deletions:$.Integer({minimum:0}),commits:$.Integer({minimum:0})})),L1=Z($.Object({path:$.String({minLength:1}),patch:$.String({maxLength:2097152}),additions:$.Integer({minimum:0}),deletions:$.Integer({minimum:0}),binary:$.Boolean(),truncated:$.Boolean()})),f0=Z($.Object({sessionId:$.String(),projectPath:$.String(),baseCommit:$.String(),files:$.Array(L1,{maxItems:100}),truncated:$.Boolean()})),M1=$.Union([$.String(),$.Number(),$.Boolean(),$.Array($.String())]),A1=Z($.Object({name:$.String(),type:K(["string","number","integer","boolean","select","multi-select"]),title:$.String(),description:$.Optional($.String()),required:$.Boolean(),defaultValue:$.Optional(M1),options:$.Optional($.Array($.Object({value:$.String(),label:$.String()}))),format:$.Optional(K(["date","uri","email","date-time"])),minimum:$.Optional($.Number()),maximum:$.Optional($.Number()),minLength:$.Optional($.Number()),maxLength:$.Optional($.Number()),minItems:$.Optional($.Number()),maxItems:$.Optional($.Number())})),O0=Z($.Object({serverName:$.String(),mode:K(["form","url"]),message:$.String(),fields:$.Optional($.Array(A1)),requestedSchema:$.Optional($.Record($.String(),$.Unknown())),url:$.Optional($.String()),domain:$.Optional($.String()),elicitationId:$.Optional($.String())})),R1=Z($.Object({type:K(["permission","question","elicitation"]),requestId:$.String()})),E1=Z($.Object({code:K(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","workspace_unavailable","capacity","runtime"]),message:$.String({minLength:1,maxLength:500}),retryable:$.Boolean(),resource:$.Optional(K(["pending_count","pending_bytes","resident_runtimes"]))})),x=Z(K(["auto","off","minimal","low","medium","high","xhigh","max"])),P=Z(K(["auto","standard","fast","flex"])),f=Z(K(["auto","low","medium","high"])),z=Z($.Union([K(["auto","pragmatic","friendly","explanatory"]),$.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})$"})])),U=Z($.Object({sessionId:$.String(),projectPath:$.String(),title:$.Optional($.String()),gitBranch:$.Optional($.String()),rootId:$.String(),parentId:$.Optional($.String()),relationType:$.Optional(K(["subagent","fork"])),resumedFrom:$.Optional($.String()),rootAgentId:$.Optional($.String()),resumeDepth:$.Optional($.Integer({minimum:0})),taskStatus:W(N1,"completed"),taskStatusReason:$.Optional($.String()),taskFailure:$.Optional(E1),taskStartedAt:$.Optional($.String()),taskCompletedAt:$.Optional($.String()),taskPromptSummary:$.Optional($.String()),taskPriority:$.Optional(E),taskKind:$.Optional(_),taskDueAt:$.Optional($.String()),taskModelId:$.Optional($.String()),selectedModelId:$.Optional($.String()),permissionMode:$.Optional(v),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),communicationStyleDigest:$.Optional($.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:$.Optional($.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:$.Optional($.Boolean()),taskRetriedFrom:$.Optional($.Object({sessionId:$.String(),projectPath:$.String()})),taskDelivery:$.Optional(F1),taskIsolation:$.Optional(N),taskSourceProjectPath:$.Optional($.String()),taskWorktreePath:$.Optional($.String()),taskWorktreeBranch:$.Optional($.String()),taskBaseCommit:$.Optional($.String()),taskDiffStat:$.Optional(C1),taskQueuePosition:$.Optional($.Integer({minimum:1})),taskQueueDepth:$.Optional($.Integer({minimum:0})),taskConcurrencyLimit:$.Optional($.Integer({minimum:1})),archivedAt:$.Optional($.String()),archivedBySessionId:$.Optional($.String()),pendingInteraction:$.Optional(R1),messageCount:$.Number(),firstMessageTime:$.String(),lastMessageTime:$.String(),hasErrors:$.Boolean()})),I0=Z($.Object({sessions:$.Array(U),nextCursor:$.Optional($.String())})),N0=Z($.Object({session:U,archivedSessionIds:$.Array($.String())})),U0=Z($.Object({session:U,restoredSessionIds:$.Array($.String())})),_1=$.Object({rootTurnId:$.Optional($.String({minLength:1,maxLength:F})),currentTurnId:$.String({minLength:1,maxLength:F}),parentTurnId:$.Optional($.String({minLength:1,maxLength:F}))},{additionalProperties:!1}),F0=Z($.Object({version:$.Union([$.Literal(1),$.Literal(2)]),sessionId:$.String(),goalId:$.String(),objective:$.String(),status:K(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:$.Optional($.Number()),tokensUsed:$.Number(),timeUsedSeconds:$.Number(),continuationCount:$.Number(),statusReason:$.Optional($.String()),completionVerification:$.Optional($.Object({attempt:$.Integer({minimum:1}),status:K(["pending","pass","fail","partial"]),requestedAt:$.String(),completedAt:$.Optional($.String()),verifierSessionId:$.Optional($.String()),summary:$.Optional($.String()),evidenceSha256:$.Optional($.String({pattern:"^[a-f0-9]{64}$"}))})),prematureStop:$.Optional($.Object({pattern:$.Unsafe({type:"string"}),consecutiveCount:$.Integer({minimum:1}),detectedAt:$.String()})),executionHostFailure:$.Optional($.Object({category:K(a),consecutiveCount:$.Integer({minimum:1,maximum:3}),detectedAt:$.String()},{additionalProperties:!1})),turnLineage:$.Optional(_1),verificationStall:$.Optional($.Unsafe({type:"object"})),executionFrontier:$.Optional($.Object({taskListId:$.String({minLength:1,maxLength:256}),total:$.Integer({minimum:0}),completed:$.Integer({minimum:0}),inProgress:$.Integer({minimum:0}),pending:$.Integer({minimum:0}),blocked:$.Integer({minimum:0}),nextTask:$.Optional($.Object({id:$.String({minLength:1}),subject:$.String({minLength:1,maxLength:512}),priority:K(["high","medium","low"])})),digestSha256:$.String({pattern:"^[a-f0-9]{64}$"}),observedAt:$.String()})),frontierStall:$.Optional($.Object({category:K(["waiting_dependency","same_task_no_effect","repeated_deferral"]),consecutiveCount:$.Integer({minimum:1,maximum:3}),digestSha256:$.String({pattern:"^[a-f0-9]{64}$"}),detectedAt:$.String()})),createdAt:$.String(),updatedAt:$.String()})),r=Z($.Object({id:$.Optional($.String({minLength:1})),timestamp:$.Optional($.Number({minimum:0})),role:R,content:t,metadata:$.Optional($.Unknown()),reasoningContent:$.Optional($.String()),thinkingContent:$.Optional($.String()),tool_call_id:$.Optional($.String()),name:$.Optional($.String()),tool_calls:$.Optional($.Unknown())})),C0=Z($.Object({session:U,messages:$.Array(r)})),y=Z(K(["conversation","code","both"])),S1=Z($.Object({messageId:$.String(),preview:$.String(),createdAt:$.String(),fileCount:$.Integer({minimum:0})})),L0=Z($.Object({targetMessageId:$.String({minLength:1}),mode:W(y,"conversation")})),M0=Z($.Object({checkpoint:S1,mode:y,removedTurns:$.Integer({minimum:1}),restoredFiles:$.Array($.String()),messages:$.Array(r)})),l1=K(["running","completed","failed","cancelled"]),i=Z($.Object({id:$.String(),subagentType:$.String(),description:$.String(),status:l1,background:$.Boolean(),rootAgentId:$.String(),resumedFrom:$.Optional($.String()),resumeDepth:$.Integer({minimum:0}),createdAt:$.Number(),lastActiveAt:$.Number(),completedAt:$.Optional($.Number()),restartRecovery:$.Optional($.Object({outcome:K(["completed","interrupted","failed"]),recoveredAt:$.Number()})),result:$.Optional($.Object({success:$.Boolean(),message:$.String(),error:$.Optional($.String()),verificationCommands:$.Optional($.Array($.String())),verificationVerdict:$.Optional(K(["pass","fail","partial"])),modifiedFiles:$.Optional($.Array($.String()))})),stats:$.Optional($.Object({tokens:$.Optional($.Number()),toolCalls:$.Optional($.Number()),duration:$.Optional($.Number())}))})),A0=Z($.Object({prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"})})),R0=Z($.Object({source:i,session:i})),E0=Z($.Object({sessionId:$.String(),projectPath:$.String()})),_0=Z($.Object({path:$.String(),name:$.String(),gitBranch:$.Optional($.String()),available:$.Boolean(),isCurrent:$.Boolean(),boundAt:$.String()})),S0=Z($.Union([$.Object({cancelled:$.Literal(!0)}),$.Object({cancelled:$.Literal(!1),path:$.String({minLength:1})})])),l0=Z($.Object({type:$.String(),seq:$.Optional($.Number()),properties:$.Record($.String(),$.Unknown())})),T=$.Object({type:K(["file","image","url"]),path:$.Optional($.String()),url:$.Optional($.String()),content:$.Optional($.String({maxLength:o})),mimeType:$.Optional($.String()),name:$.Optional($.String())}),u1=20,d1=12288,m1=4096,h1=$.Object({id:$.String({minLength:1,maxLength:200}),text:$.String({minLength:1,maxLength:d1}),sourceMessageId:$.String({minLength:1,maxLength:500}),sourceRole:K(["user","assistant"]),comment:$.Optional($.String({maxLength:m1}))}),p=$.Record($.String(),$.Unknown()),u0=Z($.Object({prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:$.Optional($.String({minLength:1,maxLength:200})),taskPriority:W(E,"medium"),taskKind:W(_,"feature"),taskDueAt:$.Optional($.String({minLength:1,maxLength:64})),projectPath:$.Optional($.String()),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),isolation:W(N,"worktree"),permissionMode:W(v,"default"),attachments:$.Optional($.Array(T,{maxItems:A})),outputSchema:$.Optional(p)})),d0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),taskPriority:$.Optional(E),taskKind:$.Optional(_),taskDueAt:$.Optional($.Union([$.String({minLength:1,maxLength:64}),$.Null()]))})),m0=Z($.Object({session:U,runId:$.String(),messageId:$.String(),status:K(["queued","running"]),queuePosition:$.Optional($.Integer({minimum:1})),queueDepth:$.Optional($.Integer({minimum:0})),maxConcurrentTasks:$.Optional($.Integer({minimum:1}))})),h0=Z($.Object({action:K(["apply","discard"])})),S=Z($.Object({kind:K(["cron","interval","once"]),cron:$.Optional($.String({minLength:1,maxLength:120})),intervalMs:$.Optional($.Integer({minimum:60000})),runAt:$.Optional($.String({minLength:1,maxLength:40})),timezone:$.Optional($.String({minLength:1,maxLength:80}))})),g1=Z($.Object({modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),isolation:W(N,"worktree"),permissionMode:W(v,"default")})),l=Z($.Object({id:$.String(),title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:$.String({minLength:1}),trigger:S,dispatch:g1,enabled:$.Boolean(),createdAt:$.String(),updatedAt:$.String(),nextRunAt:$.Union([$.String(),$.Null()]),expiresAt:$.Union([$.String(),$.Null()]),lastRunAt:$.Optional($.String()),lastRunSessionId:$.Optional($.String()),lastStatus:$.Optional(K(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:$.Optional($.String()),runCount:$.Integer({minimum:0})})),g0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:$.String({minLength:1}),trigger:S,modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),isolation:W(N,"worktree"),permissionMode:W(v,"default"),enabled:W($.Boolean(),!0)})),c0=Z($.Object({title:$.Optional($.String({minLength:1,maxLength:200})),prompt:$.Optional($.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:$.Optional(S),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),isolation:$.Optional(N),permissionMode:$.Optional(v),enabled:$.Optional($.Boolean())})),n0=Z($.Object({schedules:$.Array(l)})),i0=Z($.Object({content:$.String({maxLength:s}),projectPath:$.Optional($.String()),modelId:$.Optional($.String({minLength:1,maxLength:500})),reasoningEffort:$.Optional(x),serviceTier:$.Optional(P),responseVerbosity:$.Optional(f),communicationStyle:$.Optional(z),permissionMode:$.Optional(v),attachments:$.Optional($.Array(T,{maxItems:A})),annotations:$.Optional($.Array(h1,{maxItems:u1})),outputSchema:$.Optional(p)})),c1=K(["completed","failed","aborted","timed_out","spawn_error"]),n1=Z($.Object({version:$.Literal(1),command:$.String(),status:c1,exitCode:$.Union([$.Integer(),$.Null()]),durationMs:$.Number({minimum:0}),stdout:$.String(),stderr:$.String(),stdoutOmittedBytes:$.Integer({minimum:0}),stderrOmittedBytes:$.Integer({minimum:0}),binaryOutput:$.Boolean(),truncated:$.Boolean()})),o0=Z($.Object({command:$.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:$.Optional($.String())})),s0=Z($.Object({executionId:$.String(),messageId:$.String(),record:n1,auxiliary:$.Boolean(),delivery:$.Optional(K(["current_turn","next_turn"])),queued:$.Optional($.Integer({minimum:0}))})),a0=Z($.Object({question:$.String({minLength:1,maxLength:n,pattern:"^(?![\\s\\S]*\\x00)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:$.Optional($.String())})),t0=Z($.Object({response:$.String({minLength:1}),durationMs:$.Number({minimum:0}),modelId:$.Optional($.String()),usage:$.Optional($.Object({promptTokens:$.Number({minimum:0}),completionTokens:$.Number({minimum:0}),totalTokens:$.Number({minimum:0}),reasoningTokens:$.Optional($.Number({minimum:0})),cacheCreationInputTokens:$.Optional($.Number({minimum:0})),cacheReadInputTokens:$.Optional($.Number({minimum:0})),costUsd:$.Optional($.Number({minimum:0}))}))})),r0=Z($.Object({projectPath:$.String(),kind:K(["uncommitted","base","commit"]),ref:$.Optional($.String({maxLength:200})),instructions:$.Optional($.String({maxLength:4000})),modelId:$.Optional($.String({minLength:1,maxLength:200}))})),y0=Z($.Object({reviewId:$.String(),status:$.Literal("running")})),T0=Z($.Object({messageId:$.String(),role:R,content:$.String(),timestamp:$.String()})),p0=Z($.Object({approved:$.Boolean(),remember:$.Optional($.Boolean()),scope:$.Optional(K(["once","session","project"])),targetMode:$.Optional(v),feedback:$.Optional($.String()),answers:$.Optional($.Record($.String(),$.Union([$.String(),$.Array($.String())]))),elicitation:$.Optional($.Object({action:K(["accept","decline","cancel"]),content:$.Optional($.Record($.String(),$.Union([$.String({maxLength:4000}),$.Number(),$.Boolean(),$.Array($.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),i1=Z($.Object({id:z,name:$.String({minLength:1,maxLength:80}),description:$.String({minLength:1,maxLength:256}),source:K(["built-in","user","project","plugin"]),contentSha256:$.Optional($.String({pattern:"^[a-f0-9]{64}$"}))})),e0=Z($.Object({id:$.String(),displayName:$.Optional($.String()),provider:$.String(),model:$.String(),contextWindow:$.Optional($.Number()),maxTokens:$.Optional($.Number()),reasoning:$.Optional($.Boolean()),supportedReasoningEfforts:$.Optional($.Array(K(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:$.Optional($.Array(K(["standard","fast","flex"]))),supportedResponseVerbosities:$.Optional($.Array(K(["low","medium","high"]))),communicationStyles:$.Optional($.Array(i1,{maxItems:36})),input:$.Optional($.Array(K(["text","image"]))),overrides:$.Optional($.Object({baseUrl:$.Optional($.String()),temperature:$.Optional($.Number()),maxOutputTokens:$.Optional($.Number()),timeout:$.Optional($.Number()),streamIdleTimeout:$.Optional($.Number({minimum:1000}))}))})),$2=Z(K(["vs-dark","vs-light","hc-black"])),o1=Z(K(["light","dark","system"])),s1=Z($.Object({language:$.String(),codeTheme:$.String(),uiTheme:o1,autoSaveSessions:$.Boolean(),notifyBuild:$.Boolean(),notifyErrors:$.Boolean(),notifySounds:$.Boolean(),privacyTelemetry:$.Boolean(),privacyCrash:$.Boolean(),agentTeamsEnabled:$.Boolean(),communicationStyle:$.Optional(z)})),J2=Z($.Partial(s1));var e=J1("Service"),T1=1;function p1(){return Z1.join($1(),"schedules.json")}class O{filePath;static instance;static getInstance(){if(!O.instance)O.instance=new O;return O.instance}writeChain=Promise.resolve();constructor(J=p1()){this.filePath=J}async readFile(){try{let J=await t1(this.filePath,"utf-8"),B=JSON.parse(J);if(!B||!Array.isArray(B.schedules))return[];let j=[],Y=0;for(let H of B.schedules){let k=l.safeParse(H);if(k.success)j.push(k.data);else Y+=1}if(Y>0)e.warn(`[ScheduleStore] Ignored ${Y} invalid persisted schedule(s)`);return j}catch(J){let B=J;if(B.code!=="ENOENT")e.warn("[ScheduleStore] Failed to read schedules; treating as empty:",B);return[]}}async writeFile(J){await a1(Z1.dirname(this.filePath),{recursive:!0,mode:493});let B={version:T1,schedules:J};await y1(this.filePath,JSON.stringify(B,null,2),{mode:384})}serializeWrite(J){let B=this.writeChain.then(J,J);return this.writeChain=B.then(()=>{return},()=>{return}),B}async list(){return this.readFile()}async get(J){return(await this.readFile()).find((j)=>j.id===J)}async create(J){return this.serializeWrite(async()=>{let B=J.trigger.kind==="cron"&&!J.trigger.timezone?{...J.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:J.trigger,j=L(B);if(j)throw Error(j);let Y=new Date;if(B.kind==="once"&&new Date(B.runAt).getTime()<=Y.getTime())throw Error("once trigger runAt must be in the future");let H=Y.toISOString(),k=C(B,Y),G={id:r1(10),title:J.title,prompt:J.prompt,projectPath:J.projectPath,trigger:B,dispatch:{modelId:J.modelId,reasoningEffort:J.reasoningEffort,serviceTier:J.serviceTier,responseVerbosity:J.responseVerbosity,communicationStyle:J.communicationStyle,isolation:J.isolation??"worktree",permissionMode:J.permissionMode??"default"},enabled:J.enabled??!0,createdAt:H,updatedAt:H,nextRunAt:k?k.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(G),await this.writeFile(V),G})}async update(J,B){return this.serializeWrite(async()=>{let j=await this.readFile(),Y=j.findIndex((Q)=>Q.id===J);if(Y===-1)return;let H=j[Y];if(B.trigger){let Q=B.trigger.kind==="cron"&&!B.trigger.timezone?{...B.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:B.trigger,b=L(Q);if(b)throw Error(b);if(Q.kind==="once"&&new Date(Q.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");B={...B,trigger:Q}}let k={...H,...B,dispatch:B.dispatch?{...H.dispatch,...B.dispatch}:H.dispatch,updatedAt:new Date().toISOString()},G=!H.enabled,V=k.enabled,X=B.trigger!==void 0;if((X||G&&V)&&B.nextRunAt===void 0){let Q=new Date,b=C(k.trigger,Q);if(k.nextRunAt=b?b.toISOString():null,X)k.expiresAt=null}return j[Y]=k,await this.writeFile(j),k})}async remove(J){return this.serializeWrite(async()=>{let B=await this.readFile(),j=B.filter((Y)=>Y.id!==J);if(j.length===B.length)return!1;return await this.writeFile(j),!0})}async setEnabled(J,B){return this.update(J,{enabled:B})}}var v2=O.getInstance();
2
2
  export{n as Wa,V0 as Xa,q as Ya,Q1 as Za,h as _a,g as $a,W1 as ab,z1 as bb,W0 as cb,b0 as db,k0 as eb,e1 as fb,C as gb,L as hb,$0 as ib,f0 as jb,U as kb,L0 as lb,A0 as mb,u0 as nb,d0 as ob,m0 as pb,h0 as qb,l as rb,g0 as sb,c0 as tb,n0 as ub,i0 as vb,o0 as wb,a0 as xb,r0 as yb,O as zb,v2 as Ab};