blade-code 0.11.7 → 0.11.8
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.
- package/dist/blade.js +2 -2
- package/dist/{chunk-j6tm12ft.js → chunk-0e9nrf53.js} +1 -1
- package/dist/{chunk-atjraymv.js → chunk-14jd0cj6.js} +1 -1
- package/dist/{chunk-vrk1p3p2.js → chunk-1crgzzz7.js} +53 -53
- package/dist/{chunk-0w3h2qnk.js → chunk-1gr9vqy1.js} +1 -1
- package/dist/{chunk-03ax0738.js → chunk-22py5y1p.js} +1 -1
- package/dist/{chunk-exp8ksxn.js → chunk-29t2wbwt.js} +1 -1
- package/dist/{chunk-dtv22yvk.js → chunk-2fj047zf.js} +1 -1
- package/dist/{chunk-ska66dmc.js → chunk-34y4z9ns.js} +1 -1
- package/dist/{chunk-d9gdv6hv.js → chunk-3m8949fr.js} +1 -1
- package/dist/{chunk-6s4btp37.js → chunk-3t655nhk.js} +1 -1
- package/dist/{chunk-4rqen6w9.js → chunk-53twn9t2.js} +1 -1
- package/dist/{chunk-wqk2nkm4.js → chunk-547g7bq5.js} +2 -2
- package/dist/{chunk-yeee0ac9.js → chunk-5q2gp1bb.js} +1 -1
- package/dist/{chunk-70n8qq1r.js → chunk-74vmjngm.js} +1 -1
- package/dist/{chunk-253fwyzb.js → chunk-7876fd4b.js} +1 -1
- package/dist/{chunk-j4v5f56k.js → chunk-8r8fp09p.js} +1 -1
- package/dist/{chunk-ghg7sbxt.js → chunk-926rkw87.js} +1 -1
- package/dist/{chunk-d561qcwy.js → chunk-ayqqhefz.js} +1 -1
- package/dist/{chunk-hdbxph08.js → chunk-b0smnpzh.js} +1 -1
- package/dist/{chunk-k17d0ysy.js → chunk-c1331rdc.js} +1 -1
- package/dist/{chunk-03hbrytg.js → chunk-de3wa8nq.js} +1 -1
- package/dist/{chunk-chhf109c.js → chunk-dgypy6yt.js} +1 -1
- package/dist/{chunk-4mamvx8a.js → chunk-e613h191.js} +3 -3
- package/dist/{chunk-zhnctpb5.js → chunk-erget6wk.js} +1 -1
- package/dist/{chunk-6f5gf32h.js → chunk-hdy7b6zw.js} +1 -1
- package/dist/{chunk-33sgdacd.js → chunk-j5e589we.js} +1 -1
- package/dist/chunk-jbp9wt3f.js +1 -0
- package/dist/chunk-kz842bqy.js +1 -0
- package/dist/{chunk-4v28fy5p.js → chunk-m8sttgjc.js} +1 -1
- package/dist/{chunk-9f99qxqc.js → chunk-mmwqe49e.js} +1 -1
- package/dist/{chunk-1khsmsem.js → chunk-np5t59fa.js} +1 -1
- package/dist/{chunk-ep0g03gq.js → chunk-nr5s7qtp.js} +1 -1
- package/dist/{chunk-f7nx3ewr.js → chunk-rcfef8qj.js} +1 -1
- package/dist/{chunk-9q7egv5e.js → chunk-re6hbrmb.js} +1 -1
- package/dist/{chunk-n90wq61v.js → chunk-rh1q6srx.js} +1 -1
- package/dist/{chunk-37exmxas.js → chunk-rwtsvy5y.js} +1 -1
- package/dist/{chunk-29ek6raw.js → chunk-s7jd42xp.js} +1 -1
- package/dist/{chunk-gt2wpeyx.js → chunk-vjvw3v6b.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-byrk9d45.js +0 -1
- package/dist/chunk-drqv15xs.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Q as GP}from"./chunk-4mamvx8a.js";import{ne as N}from"./chunk-d561qcwy.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-s14zayxp.js";import{mf as t,nf as a,pf as R,rf as y,sf as A,uf as p}from"./chunk-b5cz00mt.js";import{Qj as q}from"./chunk-xhwdac1j.js";import{dk as o,xk as s,yk as n}from"./chunk-ed2hdrwe.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-e613h191.js";import{ne as N}from"./chunk-ayqqhefz.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-s14zayxp.js";import{mf as t,nf as a,pf as R,rf as y,sf as A,uf as p}from"./chunk-b5cz00mt.js";import{Qj as q}from"./chunk-xhwdac1j.js";import{dk as o,xk as s,yk as n}from"./chunk-ed2hdrwe.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{k as a,l as b,m as c,n as d,o as e}from"./chunk-b0smnpzh.js";import"./chunk-c1331rdc.js";import"./chunk-gmpsfkgg.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{xf as a,yf as b}from"./chunk-re6hbrmb.js";import"./chunk-c1331rdc.js";import"./chunk-gmpsfkgg.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Af as b,Bf as c,zf as a}from"./chunk-
|
|
1
|
+
import{Af as b,Bf as c,zf as a}from"./chunk-1gr9vqy1.js";import"./chunk-yjdyzb5z.js";import"./chunk-dgypy6yt.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-7ajvrtb3.js";import"./chunk-nr5s7qtp.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-c1331rdc.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{M as N,ka as _,la as z}from"./chunk-4mamvx8a.js";import{$d as R,Xc as I,Zd as g,cd as x,dd as X,ed as B,fd as V,gd as b,wd as A}from"./chunk-d561qcwy.js";import{Di as M,Ei as O}from"./chunk-ep0g03gq.js";import{Mutex as j}from"async-mutex";class C extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(q){super("Session runtime capacity is full");this.limit=q;this.name="SessionRuntimeCapacityError"}}class W extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class Y extends Error{constructor(q){super(`Session runtime residency already owns key: ${q}`);this.name="SessionRuntimeResidencyConflictError"}}class k{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new j;nextGeneration=1;closed=!1;constructor(q){if(!M(q.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!O(q.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=q.maxResident,this.idleMs=q.idleMs,this.now=q.now??Date.now}acquire(q){let $=this.residents.get(q);if(!$||$.poisoned)return;return $.pins++,$.lastUsedAt=this.now(),this.createLease($)}owns(q,$){let Q=this.residents.get(q);return Boolean(Q&&($===void 0||Q.value===$))}async reserve(q,$){if(!q.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new W;if(this.residents.has(q)||this.reservations.has(q))throw new Y(q);while(this.retainedCount()>=this.maxResident){if(!$.allowEviction)throw new C(this.maxResident);let P=this.oldestEvictableWebResident();if(!P)throw new C(this.maxResident);await this.disposeResident(P,!0)}let Q={generation:this.allocateGeneration(),surface:$.surface};return this.reservations.set(q,Q),this.createReservation(q,Q)})}async remove(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$)return!1;if(Q.pins>0)return!1;return await this.disposeResident(Q,!0),!0})}async forget(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$||Q.pins>0)return!1;return this.residents.delete(q),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let q=0;while(!0){let $=this.oldestIdleWebResident();if(!$)return q;await this.disposeResident($,!0),q++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let q;for(let $ of[...this.residents.values()])try{await this.disposeResident($,!1)}catch(Q){q??=Q}if(this.residents.clear(),q!==void 0)throw q})}getStats(){let q=0;for(let $ of this.residents.values())if($.pins>0)q++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:q,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let q=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,q}createReservation(q,$){let Q=!1;return{commit:(P)=>{if(Q)throw new Y(q);if(P.key!==q||P.surface!==$.surface||this.reservations.get(q)!==$||this.closed)throw this.reservations.delete(q),Q=!0,this.closed?new W:new Y(q);this.reservations.delete(q);let L={...P,generation:$.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(q,L),Q=!0,this.createLease(L)},cancel:()=>{if(Q)return;if(this.reservations.get(q)===$)this.reservations.delete(q);Q=!0}}}createLease(q){let $=!1;return{value:q.value,release:()=>{if($)return;$=!0;let Q=this.residents.get(q.key);if(Q!==q||Q.generation!==q.generation)return;Q.pins=Math.max(0,Q.pins-1),Q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((q)=>this.canEvict(q))}oldestIdleWebResident(){let q=this.now();return this.sortedWebResidents().find(($)=>q-$.lastUsedAt>=this.idleMs&&this.canEvict($))}sortedWebResidents(){return[...this.residents.values()].filter((q)=>q.surface==="web").sort((q,$)=>q.lastUsedAt-$.lastUsedAt||q.generation-$.generation)}canEvict(q){if(q.pins>0||q.poisoned)return!1;try{return q.canEvict()}catch{return!1}}async disposeResident(q,$){if(this.residents.get(q.key)!==q)return;this.residents.delete(q.key);try{await q.dispose()}catch(Q){if($&&!this.closed&&!this.residents.has(q.key))q.lastUsedAt=this.now(),q.poisoned=!0,this.residents.set(q.key,q);throw Q}}}function f(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q,{code:Q,kind:P,limit:L,reason:D,scope:J}=$;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||D!=="queue_full"&&D!=="wait_timeout"&&D!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(L)||L<=0||P!==void 0&&P!=="readonly"&&P!=="write"&&P!=="execute")return;return{code:Q,reason:D,scope:J,retryable:$.retryable,...P===void 0?{}:{kind:P},limit:L}}function T(q,$){if(!$||typeof $!=="object")return $;let Q={...$},P=f(Q.tool_admission);if(P)Q.tool_admission=P;else delete Q.tool_admission;if(N(q)){let J=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},h={},G=(Z,F,K)=>{let H=J[Z];if(typeof H==="string"&&Buffer.byteLength(H)<=F&&(!K||K.test(H)))h[Z]=H};if(G("action",64),G("status",16,/^(?:ok|warning|error)$/),G("pageId",V,/^browser_page_[a-f0-9-]+$/),G("snapshotId",V,/^browser_snapshot_[a-f0-9-]+$/),G("origin",X),G("candidateOrigin",X),G("url",x),G("title",B),G("errorCode",64,/^browser_[a-z_]+$/),typeof J.truncated==="boolean")h.truncated=J.truncated;if(typeof J.actionApplied==="boolean"||J.actionApplied==="unknown")h.actionApplied=J.actionApplied;if(typeof J.sideEffectsUncertain==="boolean")h.sideEffectsUncertain=J.sideEffectsUncertain;if(typeof J.diagnosticCount==="number"&&Number.isSafeInteger(J.diagnosticCount)&&J.diagnosticCount>=0&&J.diagnosticCount<=I)h.diagnosticCount=J.diagnosticCount;if(J.interaction&&typeof J.interaction==="object"&&!Array.isArray(J.interaction)){let Z=J.interaction,F=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof Z.action==="string"&&F.has(Z.action)){let K={action:Z.action};if(typeof Z.ref==="string"&&Buffer.byteLength(Z.ref)<=b&&/^[a-z][a-z0-9]*$/.test(Z.ref))K.ref=Z.ref;let H=(U,E,S)=>typeof U==="number"&&Number.isFinite(U)&&U>=E&&U<=S;if(Z.viewport&&typeof Z.viewport==="object"&&!Array.isArray(Z.viewport)){let U=Z.viewport;if(H(U.width,1,16384)&&H(U.height,1,16384))K.viewport={width:U.width,height:U.height}}if(Z.targetBox&&typeof Z.targetBox==="object"&&!Array.isArray(Z.targetBox)){let U=Z.targetBox;if(H(U.x,-16384,32768)&&H(U.y,-16384,32768)&&H(U.width,0,16384)&&H(U.height,0,16384))K.targetBox={x:U.x,y:U.y,width:U.width,height:U.height}}h.interaction=K}}if(J.artifact&&typeof J.artifact==="object"&&!Array.isArray(J.artifact)){let Z=J.artifact;if(typeof Z.id==="string"&&/^[a-f0-9]{64}$/.test(Z.id)&&Z.sha256===Z.id&&Z.kind==="image"&&Z.mimeType==="image/png"&&typeof Z.size==="number"&&Number.isSafeInteger(Z.size)&&Z.size>=0&&Z.size<=A&&Z.persisted===!0)h.artifact={id:Z.id,sha256:Z.sha256,kind:Z.kind,mimeType:Z.mimeType,size:Z.size,persisted:!0,...typeof Z.path==="string"&&Buffer.byteLength(Z.path)<=8192?{path:Z.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:h,...P?{tool_admission:P}:{}}}if(q==="Bash"){let J={},h=["message","signal","status","summary"],G=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],Z=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let K of h){let H=Q[K];if(typeof H==="string")J[K]=H.slice(0,8192)}for(let K of G){let H=Q[K];if(typeof H==="boolean")J[K]=H}for(let K of Z){let H=Q[K];if(typeof H==="number"&&Number.isSafeInteger(H)&&H>=0)J[K]=H}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))J.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")J.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")J.background_reason=Q.background_reason;for(let K of["bash_id","shell_id"]){let H=Q[K];if(typeof H==="string"&&H.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(H))J[K]=H}if(P)J.tool_admission=P;let F=Q.background_shell_admission;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F;if(K.code==="background_shell_busy"&&(K.scope==="session"||K.scope==="global")&&K.retryable===!0&&Number.isSafeInteger(K.limit)&&K.limit>0)J.background_shell_admission={code:K.code,scope:K.scope,retryable:K.retryable,limit:K.limit}}return J}let L=200000,D=(J,h)=>typeof J==="number"&&Number.isSafeInteger(J)&&J>=0&&J<=h?J:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>L)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>L)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let J=Q.mcpResult,h=Array.isArray(J.artifacts)?J.artifacts.slice(0,64).flatMap((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return[];let Z=G,F=new Set(["text","image","audio","resource"]);if(typeof Z.id!=="string"||!/^[a-f0-9]{64}$/.test(Z.id)||typeof Z.sha256!=="string"||Z.sha256!==Z.id||typeof Z.kind!=="string"||!F.has(Z.kind)||D(Z.size,67108864)!==Z.size||typeof Z.persisted!=="boolean")return[];return[{id:Z.id.slice(0,128),sha256:Z.sha256.slice(0,128),kind:Z.kind,size:Z.size,persisted:Z.persisted,...typeof Z.mimeType==="string"?{mimeType:Z.mimeType.slice(0,256)}:{},...typeof Z.sourceUri==="string"?{sourceUri:Z.sourceUri.slice(0,8192)}:{},...typeof Z.path==="string"?{path:Z.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:J.isError===!0,contentCount:D(J.contentCount,64),textBytes:D(J.textBytes,4194304),structuredBytes:D(J.structuredBytes,4194304),artifactCount:D(J.artifactCount,64),truncated:J.truncated===!0,binaryOmitted:J.binaryOmitted===!0,artifacts:h}}else delete Q.mcpResult;return Q}var y=(q,$)=>Object.fromEntries($.map((Q)=>[String(Q),q[Q]])),w=(q,$,Q,P=!1)=>({type:$,messageScoped:P,properties:y(q,Q)});function m(q){switch(q.kind){case"tool_start":if(!("function"in q.toolCall))return;return{type:"tool.start",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,arguments:q.toolCall.function.arguments,toolKind:q.toolKind}};case"tool_progress":if(!("function"in q.toolCall))return;return{type:"tool.progress",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,...q.update}};case"tool_result":{if(!("function"in q.toolCall))return;let $=q.toolCall.function.name;return{type:"tool.result",messageScoped:!0,toolName:$,properties:{toolName:$,toolCallId:q.toolCall.id,success:q.result.success,summary:q.result.metadata?.summary,output:z(R(_($,q.result),g)),metadata:T($,q.result.metadata)}}}case"provider_admission":return w(q,"provider.admission",["phase","requestClass","resource","scope","reason","queuePosition","queueDepth","inFlight","limit","waitMs","maxWaitMs","recoveryRemainingMs"]);case"provider_circuit":return w(q,"provider.circuit",["phase","reason","statusCode","retryAfterMs","nextProbeAt","openDurationMs","sampleCount","failureCount","recoveryRemainingMs"]);case"provider_retry":return w(q,"provider.retry",["phase","attempt","maxRetries","reason","statusCode","delayMs","nextRetryAt","mode","recoveryBudgetMs","recoveryElapsedMs","recoveryRemainingMs","exhaustedBy"]);case"provider_stall":return w(q,"provider.stall",["phase","stallCount","durationMs","warningAfterMs","timeoutMs","outputStarted"]);case"action_stationarity":return w(q,"action.stationarity",["phase","toolName","runLength","nudgeThreshold","haltThreshold","progressAware"]);case"mcp_catalog_changed":return w(q,"mcp.catalog.changed",["revision","serverName","added","removed","updated"],!0);case"mcp_content_changed":return w(q,"mcp.content.changed",["revision","serverName","contentKind","added","removed","updated"],!0);case"mcp_resource_updated":return w(q,"mcp.resource.updated",["revision","serverName","uri"],!0);case"mcp_connection_changed":return w(q,"mcp.connection.changed",["revision","serverName","phase","reason","attempt","maxAttempts","nextRetryAt","error"],!0);case"mcp_log":return w(q,"mcp.log",["revision","serverName","level","logger","message","projectedBytes","dataSha256","truncated","detailsOmitted","timestamp","synthetic"],!0);case"mcp_instructions_changed":return w(q,"mcp.instructions.changed",["revision","serverName","action","reason","text","sourceBytes","projectedBytes","sha256","truncated","detailsOmitted"],!0);case"mcp_task_changed":return w(q,"mcp.task.changed",["revision","taskId","serverName","toolName","status","statusMessage","createdAt","updatedAt","completedAt","hasResult","error"],!0);case"project_rules_loaded":return w(q,"project.rules.loaded",["files","triggerPaths","blockedWrite"],!0);default:return}}function a(q,$={}){let Q=m(q);if(!Q||!$.omitUndefined)return Q;return{...Q,properties:Object.fromEntries(Object.entries(Q.properties).filter(([,P])=>P!==void 0))}}
|
|
1
|
+
import{M as N,ka as _,la as z}from"./chunk-e613h191.js";import{$d as R,Xc as I,Zd as g,cd as x,dd as X,ed as B,fd as V,gd as b,wd as A}from"./chunk-ayqqhefz.js";import{Di as M,Ei as O}from"./chunk-nr5s7qtp.js";import{Mutex as j}from"async-mutex";class C extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(q){super("Session runtime capacity is full");this.limit=q;this.name="SessionRuntimeCapacityError"}}class W extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class Y extends Error{constructor(q){super(`Session runtime residency already owns key: ${q}`);this.name="SessionRuntimeResidencyConflictError"}}class k{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new j;nextGeneration=1;closed=!1;constructor(q){if(!M(q.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!O(q.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=q.maxResident,this.idleMs=q.idleMs,this.now=q.now??Date.now}acquire(q){let $=this.residents.get(q);if(!$||$.poisoned)return;return $.pins++,$.lastUsedAt=this.now(),this.createLease($)}owns(q,$){let Q=this.residents.get(q);return Boolean(Q&&($===void 0||Q.value===$))}async reserve(q,$){if(!q.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new W;if(this.residents.has(q)||this.reservations.has(q))throw new Y(q);while(this.retainedCount()>=this.maxResident){if(!$.allowEviction)throw new C(this.maxResident);let P=this.oldestEvictableWebResident();if(!P)throw new C(this.maxResident);await this.disposeResident(P,!0)}let Q={generation:this.allocateGeneration(),surface:$.surface};return this.reservations.set(q,Q),this.createReservation(q,Q)})}async remove(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$)return!1;if(Q.pins>0)return!1;return await this.disposeResident(Q,!0),!0})}async forget(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$||Q.pins>0)return!1;return this.residents.delete(q),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let q=0;while(!0){let $=this.oldestIdleWebResident();if(!$)return q;await this.disposeResident($,!0),q++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let q;for(let $ of[...this.residents.values()])try{await this.disposeResident($,!1)}catch(Q){q??=Q}if(this.residents.clear(),q!==void 0)throw q})}getStats(){let q=0;for(let $ of this.residents.values())if($.pins>0)q++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:q,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let q=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,q}createReservation(q,$){let Q=!1;return{commit:(P)=>{if(Q)throw new Y(q);if(P.key!==q||P.surface!==$.surface||this.reservations.get(q)!==$||this.closed)throw this.reservations.delete(q),Q=!0,this.closed?new W:new Y(q);this.reservations.delete(q);let L={...P,generation:$.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(q,L),Q=!0,this.createLease(L)},cancel:()=>{if(Q)return;if(this.reservations.get(q)===$)this.reservations.delete(q);Q=!0}}}createLease(q){let $=!1;return{value:q.value,release:()=>{if($)return;$=!0;let Q=this.residents.get(q.key);if(Q!==q||Q.generation!==q.generation)return;Q.pins=Math.max(0,Q.pins-1),Q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((q)=>this.canEvict(q))}oldestIdleWebResident(){let q=this.now();return this.sortedWebResidents().find(($)=>q-$.lastUsedAt>=this.idleMs&&this.canEvict($))}sortedWebResidents(){return[...this.residents.values()].filter((q)=>q.surface==="web").sort((q,$)=>q.lastUsedAt-$.lastUsedAt||q.generation-$.generation)}canEvict(q){if(q.pins>0||q.poisoned)return!1;try{return q.canEvict()}catch{return!1}}async disposeResident(q,$){if(this.residents.get(q.key)!==q)return;this.residents.delete(q.key);try{await q.dispose()}catch(Q){if($&&!this.closed&&!this.residents.has(q.key))q.lastUsedAt=this.now(),q.poisoned=!0,this.residents.set(q.key,q);throw Q}}}function f(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q,{code:Q,kind:P,limit:L,reason:D,scope:J}=$;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||D!=="queue_full"&&D!=="wait_timeout"&&D!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(L)||L<=0||P!==void 0&&P!=="readonly"&&P!=="write"&&P!=="execute")return;return{code:Q,reason:D,scope:J,retryable:$.retryable,...P===void 0?{}:{kind:P},limit:L}}function T(q,$){if(!$||typeof $!=="object")return $;let Q={...$},P=f(Q.tool_admission);if(P)Q.tool_admission=P;else delete Q.tool_admission;if(N(q)){let J=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},h={},G=(Z,F,K)=>{let H=J[Z];if(typeof H==="string"&&Buffer.byteLength(H)<=F&&(!K||K.test(H)))h[Z]=H};if(G("action",64),G("status",16,/^(?:ok|warning|error)$/),G("pageId",V,/^browser_page_[a-f0-9-]+$/),G("snapshotId",V,/^browser_snapshot_[a-f0-9-]+$/),G("origin",X),G("candidateOrigin",X),G("url",x),G("title",B),G("errorCode",64,/^browser_[a-z_]+$/),typeof J.truncated==="boolean")h.truncated=J.truncated;if(typeof J.actionApplied==="boolean"||J.actionApplied==="unknown")h.actionApplied=J.actionApplied;if(typeof J.sideEffectsUncertain==="boolean")h.sideEffectsUncertain=J.sideEffectsUncertain;if(typeof J.diagnosticCount==="number"&&Number.isSafeInteger(J.diagnosticCount)&&J.diagnosticCount>=0&&J.diagnosticCount<=I)h.diagnosticCount=J.diagnosticCount;if(J.interaction&&typeof J.interaction==="object"&&!Array.isArray(J.interaction)){let Z=J.interaction,F=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof Z.action==="string"&&F.has(Z.action)){let K={action:Z.action};if(typeof Z.ref==="string"&&Buffer.byteLength(Z.ref)<=b&&/^[a-z][a-z0-9]*$/.test(Z.ref))K.ref=Z.ref;let H=(U,E,S)=>typeof U==="number"&&Number.isFinite(U)&&U>=E&&U<=S;if(Z.viewport&&typeof Z.viewport==="object"&&!Array.isArray(Z.viewport)){let U=Z.viewport;if(H(U.width,1,16384)&&H(U.height,1,16384))K.viewport={width:U.width,height:U.height}}if(Z.targetBox&&typeof Z.targetBox==="object"&&!Array.isArray(Z.targetBox)){let U=Z.targetBox;if(H(U.x,-16384,32768)&&H(U.y,-16384,32768)&&H(U.width,0,16384)&&H(U.height,0,16384))K.targetBox={x:U.x,y:U.y,width:U.width,height:U.height}}h.interaction=K}}if(J.artifact&&typeof J.artifact==="object"&&!Array.isArray(J.artifact)){let Z=J.artifact;if(typeof Z.id==="string"&&/^[a-f0-9]{64}$/.test(Z.id)&&Z.sha256===Z.id&&Z.kind==="image"&&Z.mimeType==="image/png"&&typeof Z.size==="number"&&Number.isSafeInteger(Z.size)&&Z.size>=0&&Z.size<=A&&Z.persisted===!0)h.artifact={id:Z.id,sha256:Z.sha256,kind:Z.kind,mimeType:Z.mimeType,size:Z.size,persisted:!0,...typeof Z.path==="string"&&Buffer.byteLength(Z.path)<=8192?{path:Z.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:h,...P?{tool_admission:P}:{}}}if(q==="Bash"){let J={},h=["message","signal","status","summary"],G=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],Z=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let K of h){let H=Q[K];if(typeof H==="string")J[K]=H.slice(0,8192)}for(let K of G){let H=Q[K];if(typeof H==="boolean")J[K]=H}for(let K of Z){let H=Q[K];if(typeof H==="number"&&Number.isSafeInteger(H)&&H>=0)J[K]=H}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))J.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")J.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")J.background_reason=Q.background_reason;for(let K of["bash_id","shell_id"]){let H=Q[K];if(typeof H==="string"&&H.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(H))J[K]=H}if(P)J.tool_admission=P;let F=Q.background_shell_admission;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F;if(K.code==="background_shell_busy"&&(K.scope==="session"||K.scope==="global")&&K.retryable===!0&&Number.isSafeInteger(K.limit)&&K.limit>0)J.background_shell_admission={code:K.code,scope:K.scope,retryable:K.retryable,limit:K.limit}}return J}let L=200000,D=(J,h)=>typeof J==="number"&&Number.isSafeInteger(J)&&J>=0&&J<=h?J:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>L)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>L)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let J=Q.mcpResult,h=Array.isArray(J.artifacts)?J.artifacts.slice(0,64).flatMap((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return[];let Z=G,F=new Set(["text","image","audio","resource"]);if(typeof Z.id!=="string"||!/^[a-f0-9]{64}$/.test(Z.id)||typeof Z.sha256!=="string"||Z.sha256!==Z.id||typeof Z.kind!=="string"||!F.has(Z.kind)||D(Z.size,67108864)!==Z.size||typeof Z.persisted!=="boolean")return[];return[{id:Z.id.slice(0,128),sha256:Z.sha256.slice(0,128),kind:Z.kind,size:Z.size,persisted:Z.persisted,...typeof Z.mimeType==="string"?{mimeType:Z.mimeType.slice(0,256)}:{},...typeof Z.sourceUri==="string"?{sourceUri:Z.sourceUri.slice(0,8192)}:{},...typeof Z.path==="string"?{path:Z.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:J.isError===!0,contentCount:D(J.contentCount,64),textBytes:D(J.textBytes,4194304),structuredBytes:D(J.structuredBytes,4194304),artifactCount:D(J.artifactCount,64),truncated:J.truncated===!0,binaryOmitted:J.binaryOmitted===!0,artifacts:h}}else delete Q.mcpResult;return Q}var y=(q,$)=>Object.fromEntries($.map((Q)=>[String(Q),q[Q]])),w=(q,$,Q,P=!1)=>({type:$,messageScoped:P,properties:y(q,Q)});function m(q){switch(q.kind){case"tool_start":if(!("function"in q.toolCall))return;return{type:"tool.start",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,arguments:q.toolCall.function.arguments,toolKind:q.toolKind}};case"tool_progress":if(!("function"in q.toolCall))return;return{type:"tool.progress",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,...q.update}};case"tool_result":{if(!("function"in q.toolCall))return;let $=q.toolCall.function.name;return{type:"tool.result",messageScoped:!0,toolName:$,properties:{toolName:$,toolCallId:q.toolCall.id,success:q.result.success,summary:q.result.metadata?.summary,output:z(R(_($,q.result),g)),metadata:T($,q.result.metadata)}}}case"provider_admission":return w(q,"provider.admission",["phase","requestClass","resource","scope","reason","queuePosition","queueDepth","inFlight","limit","waitMs","maxWaitMs","recoveryRemainingMs"]);case"provider_circuit":return w(q,"provider.circuit",["phase","reason","statusCode","retryAfterMs","nextProbeAt","openDurationMs","sampleCount","failureCount","recoveryRemainingMs"]);case"provider_retry":return w(q,"provider.retry",["phase","attempt","maxRetries","reason","statusCode","delayMs","nextRetryAt","mode","recoveryBudgetMs","recoveryElapsedMs","recoveryRemainingMs","exhaustedBy"]);case"provider_stall":return w(q,"provider.stall",["phase","stallCount","durationMs","warningAfterMs","timeoutMs","outputStarted"]);case"action_stationarity":return w(q,"action.stationarity",["phase","toolName","runLength","nudgeThreshold","haltThreshold","progressAware"]);case"mcp_catalog_changed":return w(q,"mcp.catalog.changed",["revision","serverName","added","removed","updated"],!0);case"mcp_content_changed":return w(q,"mcp.content.changed",["revision","serverName","contentKind","added","removed","updated"],!0);case"mcp_resource_updated":return w(q,"mcp.resource.updated",["revision","serverName","uri"],!0);case"mcp_connection_changed":return w(q,"mcp.connection.changed",["revision","serverName","phase","reason","attempt","maxAttempts","nextRetryAt","error"],!0);case"mcp_log":return w(q,"mcp.log",["revision","serverName","level","logger","message","projectedBytes","dataSha256","truncated","detailsOmitted","timestamp","synthetic"],!0);case"mcp_instructions_changed":return w(q,"mcp.instructions.changed",["revision","serverName","action","reason","text","sourceBytes","projectedBytes","sha256","truncated","detailsOmitted"],!0);case"mcp_task_changed":return w(q,"mcp.task.changed",["revision","taskId","serverName","toolName","status","statusMessage","createdAt","updatedAt","completedAt","hasResult","error"],!0);case"project_rules_loaded":return w(q,"project.rules.loaded",["files","triggerPaths","blockedWrite"],!0);default:return}}function a(q,$={}){let Q=m(q);if(!Q||!$.omitUndefined)return Q;return{...Q,properties:Object.fromEntries(Object.entries(Q.properties).filter(([,P])=>P!==void 0))}}
|
|
2
2
|
export{C as w,k as x,T as y,a as z};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Ui as I}from"./chunk-
|
|
1
|
+
import{Ui as I}from"./chunk-nr5s7qtp.js";import{Pj as G,Qj as H}from"./chunk-xhwdac1j.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
|
|
2
2
|
export{D as zg,Q as Ag,T as Bg,U as Cg};
|
|
@@ -1,4 +1,4 @@
|
|
|
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-saz6mwpq.js";import{Nj as Gn,Qj as tt}from"./chunk-xhwdac1j.js";import{Xj as xt,Yj as Bt}from"./chunk-
|
|
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-saz6mwpq.js";import{Nj as Gn,Qj as tt}from"./chunk-xhwdac1j.js";import{Xj as xt,Yj as Bt}from"./chunk-c1331rdc.js";import{ck as b}from"./chunk-asgmmaec.js";import{dk as It}from"./chunk-ed2hdrwe.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">
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ag as b,Bg as c,Cg as d,zg as a}from"./chunk-
|
|
1
|
+
import{Ag as b,Bg as c,Cg as d,zg as a}from"./chunk-np5t59fa.js";import"./chunk-nr5s7qtp.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-c1331rdc.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Xj as d,Zj as h}from"./chunk-
|
|
1
|
+
import{Xj as d,Zj as h}from"./chunk-c1331rdc.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as xf,w as yf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{k as o}from"./chunk-
|
|
1
|
+
import{k as o}from"./chunk-b0smnpzh.js";import"./chunk-c1331rdc.js";import"./chunk-gmpsfkgg.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$b as d,Ub as a,Vb as b,Xb as c,ac as e,bc as f,cc as g,dc as h,ec as i,fc as j,gc as k,pc as l,qc as m,rc as n,sc as o,uc as p,vc as q,wc as r}from"./chunk-
|
|
1
|
+
import{$b as d,Ub as a,Vb as b,Xb as c,ac as e,bc as f,cc as g,dc as h,ec as i,fc as j,gc as k,pc as l,qc as m,rc as n,sc as o,uc as p,vc as q,wc as r}from"./chunk-3t655nhk.js";import"./chunk-9qxch6sy.js";import"./chunk-ayqqhefz.js";import"./chunk-skktstg8.js";import"./chunk-s14zayxp.js";import"./chunk-b5cz00mt.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-1g7c3f82.js";import"./chunk-3v9epq9s.js";import"./chunk-pm163dfm.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-3m8949fr.js";import"./chunk-ys8gysg8.js";import"./chunk-nr5s7qtp.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-c1331rdc.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$f as h,Uf as a,Vf as b,Wf as c,Xf as d,Yf as e,Zf as f,_f as g,ag as i,bg as j,cg as k,dg as l,eg as m}from"./chunk-
|
|
1
|
+
import{$f as h,Uf as a,Vf as b,Wf as c,Xf as d,Yf as e,Zf as f,_f as g,ag as i,bg as j,cg as k,dg as l,eg as m}from"./chunk-dgypy6yt.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-nr5s7qtp.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-c1331rdc.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,h as getAllModels,g as ensureStoreInitialized,m as configActions,d as appActions};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ia as p}from"./chunk-
|
|
1
|
+
import{ia as p}from"./chunk-e613h191.js";import{Tb as _}from"./chunk-3t655nhk.js";import{Ed as N,Fd as U,Gd as I,Hd as A,Id as z,Td as q,ne as O}from"./chunk-ayqqhefz.js";import{ze as o}from"./chunk-s14zayxp.js";import{fg as P}from"./chunk-x6k5ye1z.js";import{Gg as e}from"./chunk-34y4z9ns.js";import{Ak as j}from"./chunk-ed2hdrwe.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
|
|
2
2
|
`)||f.includes("\r"))throw Error(`${c} must contain 1-${u} characters`);return f}function Q(a){return a.split("\x00").filter(Boolean)}async function X(a,c){return(await C(a,["rev-parse","--verify",`${c}^{commit}`])).trim()}async function Ff(a,c,f,w,h){let g=h,$=await i(a);for(let k of c){let l=n.resolve($,k),x=n.relative($,l);if(!x||x.startsWith("..")||n.isAbsolute(x))throw Error(`Untracked review path escapes the workspace: ${k}`);let b=await bf(l);if(!b.isFile()||b.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${k}`);if(g+=b.size,g>T)throw Error(`Review target exceeds ${T} bytes`);f.update("\x00untracked\x00"),f.update(x.replaceAll(n.sep,"/")),f.update("\x00");let F=await mf(l);f.update(F);let m=Math.max(1,F.toString("utf8").split(`
|
|
3
3
|
`).length);w.set(x.replaceAll(n.sep,"/"),[{start:1,end:m}])}}function Y(a,c){let f=new Map,w,h,g,$,k=!1,l=(x,b)=>{let F=f.get(x)??[],m=F.at(-1);if(m&&b<=m.end+1)m.end=Math.max(m.end,b);else F.push({start:b,end:b});f.set(x,F)};for(let x of a.split(`
|
|
4
4
|
`)){if(x.startsWith("--- ")){let b=x.slice(4).split("\t")[0]?.trim();w=b&&b!=="/dev/null"?b.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(x.startsWith("+++ ")){let b=x.slice(4).split("\t")[0]?.trim();k=b==="/dev/null",h=k?w:b?b.replace(/^b\//,"").replaceAll("\\","/"):void 0,g=void 0,$=void 0;continue}if(x.startsWith("@@ ")){let b=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(x);g=b?Math.max(1,Number(b[1])):void 0,$=b?Math.max(1,Number(b[2])):void 0;continue}if(!h||g===void 0||$===void 0)continue;if(x.startsWith("+")&&!x.startsWith("+++"))l(h,$),$++;else if(x.startsWith("-")&&!x.startsWith("---"))l(h,k?g:$),g++;else if(!x.startsWith("\\"))g++,$++}for(let x of c)if(!f.has(x))f.set(x,[{start:1,end:1}]);return f}function D(a){if(a.length>s)throw Error(`Review target exceeds the ${s} file limit`)}class K{static async resolve(a,c){let f=await i(a);await C(f,["rev-parse","--is-inside-work-tree"]);let w=await X(f,"HEAD"),h=xf("sha256");h.update(`kind\x00${c.kind}\x00head\x00${w}\x00`);let g="",$=[],k,l,x,b,F=new Map;switch(c.kind){case"uncommitted":{g=await C(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=Q(await C(f,["diff","--name-only","-z","--relative","HEAD","--","."])),L=Q(await C(f,["ls-files","--others","--exclude-standard","-z","--","."]));if($=[...new Set([...m,...L])].sort(),D($),$.length===0)throw Error("No uncommitted changes to review");h.update(g),F=Y(g,m),await Ff(f,L,h,F,Buffer.byteLength(g)),x="uncommitted changes",b=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=d(c.ref,"Base ref");k=await X(f,m);let L=(await C(f,["merge-base",k,w])).trim();if(g=await C(f,["diff","--binary","--no-ext-diff","--relative",`${L}..${w}`,"--","."]),$=Q(await C(f,["diff","--name-only","-z","--relative",`${L}..${w}`,"--","."])),D($),$.length===0)throw Error(`No changes between ${m} and HEAD`);h.update(g),h.update(`\x00merge-base\x00${L}`),F=Y(g,$),x=`changes against ${m}`,b=`Review changes introduced by ${L}..${w}.`;break}case"commit":{let m=d(c.ref,"Commit ref");if(l=await X(f,m),g=await C(f,["show","--format=","--binary","--no-ext-diff","--relative",l,"--","."]),$=Q(await C(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",l,"--","."])),D($),$.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);h.update(g),h.update(`\x00commit\x00${l}`),F=Y(g,$),x=`commit ${m}`,b=`Review only the changes introduced by commit ${l}.`;break}}if(Buffer.byteLength(g)>T)throw Error(`Review diff exceeds ${T} bytes`);return{info:{kind:c.kind,label:x,headSha:w,...k?{baseSha:k}:{},...l?{commitSha:l}:{},digest:h.digest("hex"),fileCount:$.length},instruction:b,changedLines:F}}}var Wf=131072,t=50,Z=new Set;function v(a,c){return`${R.resolve(a)}\x00${c}`}function S(a){return`/review ${a.kind}${a.kind==="uncommitted"?"":` ${a.ref?.trim()??""}`}`}function V(a,c,f,w=!1){if(typeof a!=="string")throw Error(`${c} must be a string`);let h=a.trim();if(!w&&!h||h.length>f)throw Error(`${c} exceeds its allowed length`);return h}function Hf(a,c,f){if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Review finding must be an object");let w=a,h=typeof w.line==="number"&&Number.isInteger(w.line)?w.line:void 0,g=w.code_location??(typeof w.file==="string"&&h!==void 0?{path:w.file,line_start:h,line_end:h}:void 0);if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Review finding has no code_location");let $=g,k=V($.path,"Finding path",1000),l=R.posix.normalize(k.replaceAll("\\","/"));if(R.posix.isAbsolute(l)||l===".."||l.startsWith("../"))throw Error("Review finding path must be workspace-relative");let x=R.resolve(c,l),b=R.relative(R.resolve(c),x);if(b.startsWith("..")||R.isAbsolute(b))throw Error("Review finding path escapes the workspace");let F=typeof w.severity==="string"?w.severity.toLowerCase():"",m=F==="critical"?0:F==="high"?1:F==="medium"?2:F==="low"?3:void 0,L=w.priority??m;if(L!==0&&L!==1&&L!==2&&L!==3)throw Error("Review finding priority must be 0-3");let W=w.confidence_score??w.confidence??0.8;if(typeof W!=="number"||!Number.isFinite(W)||W<0||W>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:H,line_end:r}=$;if(!Number.isInteger(H)||!Number.isInteger(r)||H<1||r<H||r-H>=10)throw Error("Review finding line range is invalid");let G=f.changedLines.get(l);if(!G)throw Error("Review finding path is outside the review target");if(!G.some((y)=>H<=y.end&&r>=y.start))throw Error("Review finding line range does not overlap the changed lines");let B=V(w.title??`[P${L}] ${String(w.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(y)=>y.toUpperCase())}`,"Finding title",120);if(!B.startsWith(`[P${L}] `))throw Error("Review finding title priority does not match priority");return{title:B,body:V(w.body??w.description,"Finding body",4000),priority:L,confidenceScore:W,codeLocation:{path:l,lineStart:H,lineEnd:r}}}function Rf(a,c,f){if(Buffer.byteLength(a)>Wf)throw Error("Review output exceeds the 128 KiB limit");let w=a.indexOf("{"),h=a.lastIndexOf("}");if(w<0||h<=w)throw Error("Reviewer did not return a JSON object");let g;try{g=JSON.parse(a.slice(w,h+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Reviewer output must be an object");let $=g;if(!Array.isArray($.findings))throw Error("Reviewer output must contain findings");if($.findings.length>t)throw Error(`Reviewer returned more than ${t} findings`);return{overallExplanation:V($.overall_explanation??$.summary,"Review explanation",1e4,!0),findings:$.findings.map((k)=>Hf(k,c,f))}}async function J(a,c){return new o(j(a,c)).readAll()}class rf{static async start(a){let{sessionId:c,projectPath:f,runtime:w,request:h,onEvent:g}=a;if(w.sessionId!==c||R.resolve(w.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(w.hasTurnOwner())throw Error("Cannot start a review during an active turn");await O.assertSessionWritable(c,f);let $=v(f,c);if(Z.has($))throw Error("Session already has an active review");let k=await J(f,c);if(U(k))throw Error("Session has an interrupted review that must be recovered");let l=h.instructions?.trim();if(l&&l.length>4000)throw Error("Review instructions exceed 4,000 characters");let x=await K.resolve(f,h),b=Lf(16),F=P("review"),m=new Date().toISOString(),L={reviewId:b,reviewerSessionId:F,target:x.info,startedAt:m},W=new _(f);await W.saveReviewStart(c,L),await W.saveMessage(c,"user",S(h),null,{codeReview:{reviewId:b,phase:"started",targetKind:x.info.kind,targetDigest:x.info.digest}}),await O.updateSessionMetadata(c,f,{taskStatus:"running",taskStatusReason:`Reviewing ${x.info.label}`,taskPromptSummary:S(h),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),Z.add($);let H=this.execute({...a,target:x,reviewId:b,reviewerSessionId:F,instructions:l,store:W,onEvent:g}).finally(()=>{Z.delete($)});return{reviewId:b,completion:H}}static async execute(a){let{sessionId:c,projectPath:f,runtime:w,request:h,signal:g,onEvent:$,target:k,reviewId:l,reviewerSessionId:x,instructions:b,store:F}=a,m;try{let W=[k.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${k.info.digest}`,`Changed file count: ${k.info.fileCount}`,b?`Additional review instructions:
|
package/package.json
CHANGED
package/dist/chunk-byrk9d45.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{k as a,l as b,m as c,n as d,o as e}from"./chunk-hdbxph08.js";import"./chunk-k17d0ysy.js";import"./chunk-gmpsfkgg.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
package/dist/chunk-drqv15xs.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{xf as a,yf as b}from"./chunk-9q7egv5e.js";import"./chunk-k17d0ysy.js";import"./chunk-gmpsfkgg.js";export{a as globalOptions,b as cliConfig};
|