@inkeep/open-knowledge 0.24.0-beta.5 → 0.24.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{Fi as e,J as t,Oi as n,Vt as r,a as i,c as a,d as o,dn as s,f as c,g as l,h as u,i as d,ii as f,kn as p,l as m,m as h,n as g,o as _,on as v,p as y,r as b,s as x,t as S,tn as C,u as w,wn as T}from"./server-lock-CN2YHwpP-DiysUpvV.mjs";import{$ as E,$i as D,$n as O,$r as k,$t as A,A as j,Ai as M,An as N,Ar as P,At as F,B as I,Bi as L,Bn as R,Br as z,Bt as B,C as V,Ci as H,Cn as U,Cr as W,Ct as G,D as K,Di as q,Dn as J,Dr as Y,Dt as X,E as Z,Ei as Q,En as $,Er as ee,Et as te,F as ne,Fi as re,Fn as ie,Fr as ae,Ft as oe,G as se,Gi as ce,Gn as le,Gr as ue,Gt as de,H as fe,Hi as pe,Hn as me,Hr as he,Ht as ge,I as _e,Ii as ve,In as ye,Ir as be,It as xe,J as Se,Ji as Ce,Jn as we,Jr as Te,Jt as Ee,K as De,Ki as Oe,Kn as ke,Kr as Ae,Kt as je,L as Me,Li as Ne,Ln as Pe,Lr as Fe,Lt as Ie,M as Le,Mi as Re,Mn as ze,Mr as Be,Mt as Ve,N as He,Ni as Ue,Nn as We,Nr as Ge,Nt as Ke,O as qe,Oi as Je,On as Ye,Or as Xe,Ot as Ze,P as Qe,Pi as $e,Pn as et,Pr as tt,Pt as nt,Q as rt,Qi as it,Qn as at,Qr as ot,Qt as st,R as ct,Ri as lt,Rn as ut,Rr as dt,Rt as ft,S as pt,Si as mt,Sn as ht,Sr as gt,St as _t,T as vt,Ti as yt,Tn as bt,Tr as xt,Tt as St,U as Ct,Ui as wt,Un as Tt,Ur as Et,Ut as Dt,V as Ot,Vi as kt,Vn as At,Vr as jt,Vt as Mt,W as Nt,Wi as Pt,Wn as Ft,Wr as It,Wt as Lt,X as Rt,Xi as zt,Xn as Bt,Xr as Vt,Xt as Ht,Y as Ut,Yi as Wt,Yn as Gt,Yr as Kt,Yt as qt,Z as Jt,Zi as Yt,Zn as Xt,Zr as Zt,Zt as Qt,_ as $t,_a as en,_i as tn,_n as nn,_r as rn,_t as an,a as on,aa as sn,ai as cn,an as ln,ar as un,at as dn,b as fn,bi as pn,bn as mn,br as hn,bt as gn,c as _n,ci as vn,cn as yn,cr as bn,ct as xn,d as Sn,di as Cn,dn as wn,dr as Tn,dt as En,ea as Dn,ei as On,en as kn,er as An,et as jn,f as Mn,fi as Nn,fn as Pn,fr as Fn,ft as In,g as Ln,gi as Rn,gn as zn,gr as Bn,gt as Vn,h as Hn,hi as Un,hn as Wn,hr as Gn,ht as Kn,i as qn,ia as Jn,ii as Yn,in as Xn,ir as Zn,it as Qn,j as $n,ji as er,jn as tr,jr as nr,jt as rr,k as ir,ki as ar,kn as or,kr as sr,kt as cr,l as lr,li as ur,ln as dr,lr as fr,lt as pr,m as mr,mi as hr,mn as gr,mr as _r,mt as vr,n as yr,na as br,ni as xr,nn as Sr,nr as Cr,nt as wr,o as Tr,oi as Er,on as Dr,or as Or,ot as kr,p as Ar,pi as jr,pn as Mr,pr as Nr,pt as Pr,q as Fr,qi as Ir,qn as Lr,qr as Rr,qt as zr,r as Br,ra as Vr,ri as Hr,rn as Ur,rr as Wr,rt as Gr,s as Kr,si as qr,sn as Jr,sr as Yr,st as Xr,t as Zr,ta as Qr,ti as $r,tn as ei,tr as ti,tt as ni,u as ri,ui as ii,un as ai,ur as oi,ut as si,v as ci,va as li,vi as ui,vn as di,vr as fi,vt as pi,w as mi,wi as hi,wn as gi,wr as _i,wt as vi,x as yi,xi as bi,xn as xi,xr as Si,xt as Ci,y as wi,yi as Ti,yn as Ei,yr as Di,yt as Oi,z as ki,zi as Ai,zn as ji,zr as Mi,zt as Ni}from"./dist-OXU4D9x4.mjs";export{Zr as AGENT_ID_MAX_LEN,yr as AGENT_ID_RE,Br as AGENT_WRITE_ORIGIN,qn as AgentFocusBroadcaster,on as AgentPresenceBroadcaster,Tr as AgentSessionCapacityError,Kr as AgentSessionManager,_n as AutoStartDisabledError,lr as BUNDLE_IDS,ri as BUNDLE_SCOPE,Sn as BUNDLE_SKILL_NAME,Mn as BacklinkIndex,Ar as CC1Broadcaster,t as CC1_CONTRACT_VERSION,mr as CONFIG_FILENAME,Hn as CONFLICT_MARKER_RE,Ln as CURSOR_BUNDLE_PATHS_BY_PLATFORM,$t as ConfigSchema,ci as DEFAULT_CHECKPOINT_RETENTION,wi as DEFAULT_EMBEDDINGS_DIMENSIONS,fn as DEFAULT_PACK_ID,yi as EMBEDDINGS_API_KEY_ENV,pt as FILE_SYSTEM_WRITER,V as FILE_WATCHER_ORIGIN,mi as FileEmbeddingsBackend,vt as GIT_PREFLIGHT_FAIL_SPAN_NAME,Z as GIT_UPSTREAM_WRITER,en as GitDirAccessError,K as GitNotAvailableError,qe as GitTooOldError,ir as HOCUSPOCUS_AUTH_REJECTION_REASONS,j as HocuspocusAuthRejection,$n as HocuspocusAuthTokenSchema,Le as INSTALLED_AGENTS_SCHEMES,r as LINEAGE_EPOCH_KEY,He as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Qe as LOG_MD_TEMPLATE,ne as MANAGED_RENAME_ORIGIN,_e as MAX_AGENT_SESSIONS,Me as MCP_CONNECTION_ID_HEADER,C as MCP_SERVER_NAME,ct as MIN_GIT_VERSION,ki as MISSING_OK_CONFIG_MESSAGE,li as MalformedGitPointerError,I as McpLogger,Ot as MissingOkConfigError,fe as OBSERVER_SYNC_ORIGIN,Ct as OK_OKIGNORE_TEMPLATE,v as ORPHAN_MODES,Nt as PANE_TARGET_TTL_MS,s as PROTOCOL_VERSION,se as PinoLogger,S as ProcessLockCollisionError,De as ProjectGitInitError,Fr as ROLLBACK_ORIGIN,Se as ROOT_GITIGNORE_TEMPLATE,g as RUNTIME_VERSION,Ut as SERVICE_WRITER,Rt as SKILL_INSTALL_EVENTS_FILE_REL,T as SKILL_STATE_TARGETS,Jt as STARTER_FOLDERS,rt as STARTER_FOLDER_FRONTMATTER_FILENAME,E as STARTER_PACKS,jn as STARTER_PACK_IDS,ni as STARTER_TEMPLATES,wr as STATE_MANIFEST_FILENAME,b as STATE_SCHEMA_VERSION,p as SYSTEM_DOC_NAME,Gr as SeedPrerequisiteError,Qn as SeedRootDirError,d as ServerLockCollisionError,dn as SingleFileNotAFileError,kr as SingleFileNotFoundError,Xr as SingleFileNotMarkdownError,xn as StateManifestError,pr as TagIndex,si as USER_GLOBAL_BUNDLE_IDS,En as UiLockCollisionError,In as __getShowAllWalkStatsForTesting,Pr as __resetShowAllWalkStatsForTesting,i as acquireProcessLock,_ as acquireServerLock,vr as acquireUiLock,Kn as applyAgentMarkdownWrite,Vn as applyExternalChange,an as applySeed,pi as armPaneTarget,Oi as assertCompatibleStateManifest,gn as assertGitAvailable,Ci as assertNeverDiskEvent,_t as attachIdleShutdown,G as bootServer,vi as buildAndOpenSkill,St as buildConfigYmlContent,te as buildExecResult,X as buildSkillZip,Ze as buildStarterFolderFrontmatterYaml,cr as buildWipTree,F as bundleSkillMdPath,rr as classifyEvents,Ve as classifyFsPath,Ke as clearArmedPaneTarget,nt as clearContributors,oe as clearEmbeddingsKeyFromAllBackends,xe as coercePackId,f as colorFromSeed,Ie as commitUpstreamImport,ft as commitWip,Ni as commitWipFromTree,B as compareSemver,Mt as containsConflictMarkers,ge as contentHash,Dt as contributorCount,Lt as countShadowObjects,de as countStaleAgentWipRefs,je as countWipRefs,zr as createApiExtension,Ee as createAssetServeMiddleware,qt as createContentFilter,Ht as createContentFilterAsync,Qt as createEmbeddingsSecretStore,st as createEphemeralProjectDir,A as createExternalChangeHandler,kn as createFileLogger,ei as createLiveDerivedIndexExtension,Sr as createMcpHttpHandler,Ur as createOsProbe,Xn as createPersistenceExtension,ln as createServer,Dr as createServerObserverExtension,Jr as createStreamingErrorWriter,yn as createTestLogger,dr as describeStoredEmbeddingsKey,ai as detectClaudeDesktopPresence,wn as detectGit,Pn as detectProjectShape,Mr as discoverLockDirs,gr as emitPreflightFailureSpan,Wn as encodeDocName,zn as encodeFolderRoute,nn as encodeSkillRoute,di as ensureProjectGit,Ei as errorResponse,mn as evictStaleTrackerEntries,xi as extractOkBinaryPath,ht as extractWikiLinksFromMarkdown,U as fallbackPaths,gi as findEnclosingGitRoot,bt as findEnclosingProjectRoot,$ as flushFileLogger,J as formatAuthRejectionWire,Ye as formatContributors,or as formatContributorsFrom,N as formatPackRationale,tr as gcCheckpointRefs,ze as getCurrentMcpLogger,We as getLocalDir,et as getLogFilePath,ie as getLogger,ye as getLogsDir,Pe as getMeter,ut as getMetrics,ji as getTracer,R as handleCollabSocketError,At as handleSpawnCursor,me as hasGcLogLatch,n as iconFromClientName,Tt as incrementCollabSocketFilteredError,Ft as incrementServerObserverFire,le as initContent,ke as initShadowRepo,Lr as initTelemetry,we as initToleranceTelemetryWriter,Gt as installPrettyZodErrors,Bt as installTestLoggers,Xt as installUserSkill,at as isAllowedApiOrigin,O as isAllowedWorkspaceHostHeader,An as isConfigDoc,ti as isHocuspocusAuthRejectionReason,Cr as isKnownPackId,Wr as isLinkIndexExcludedDoc,Zn as isLoopbackAddress,un as isManagedArtifactDoc,e as isOrphanMode,Or as isPairedWriteOrigin,Yr as isPathWithinDir,x as isProcessAlive,bn as isProjectRoot,fr as isProjectSkillManaged,oi as isReservedForUserTree,Tn as isSelfWrite,Fn as isSystemDoc,Nr as isToleranceTelemetryEnabled,a as isValidLockPid,_r as lastKnownHash,Gn as listRescueCheckpoints,Bn as listStarterPacks,rn as loadPrincipal,m as lockFilePath,fi as loggerFactory,Di as logsCurrentPath,hn as logsPreviousPath,Si as makeLazyEmbeddingsKeyStore,gt as mountMcpAndApi,W as normalizeFsPath,_i as packageVersionMajorMinor,xt as parseAuthRejectionWire,ee as parseGitVersion,Y as parseHocuspocusAuthToken,Xe as parseKeepaliveConnectionId,sr as pathToDocName,P as planSeed,nr as prepareSingleFileOpen,Be as processCommand,Ge as processUsage,tt as readAllTargets,ae as readArmedPaneTarget,be as readBranchFromHead,w as readProcessLock,o as readProcessLockDetailed,Fe as readProjectLocalSemanticConfig,c as readServerLock,dt as readServerPackageVersion,Mi as readSkillInstallStateSnapshot,z as readSkillManagement,jt as readStateManifest,he as readTargetRecordedAt,Et as readTargetVersion,It as readUiLock,ue as reconcile,Ae as recordContributor,Rr as recordSkillInstallEvent,Te as registerAllTools,Kt as registerWrite,y as releaseProcessLock,h as releaseServerLock,Vt as releaseUiLock,Zt as removeLastKnownHash,ot as resetMetrics,k as resolveBundledSkillDir,On as resolveContentDir,$r as resolveCursorBinaryDefault,xr as resolveCursorSpawnInvocation,Hr as resolveLockDir,Yn as resolvePack,cn as resolvePackageVersion,Er as resolveUiInfo,qr as restoreContributors,vn as restoreLifecycleFromConflictsJson,ur as rewriteMarkdownLinksForDocumentRename,ii as rewriteWikiLinksForDocumentRename,Cn as runAuthReposSubprocess,Nn as runAuthStatusSubprocess,jr as runCloneSubprocess,hr as runDeviceFlowSubprocess,Un as runWithMcpLogger,Rn as safeContentPath,tn as safeSubdir,ui as safetyCheckpoint,Ti as sanitizeClientName,pn as saveInMemoryCheckpoint,bi as saveVersion,mt as seedBasenameIndex,H as serializeError,hi as setActiveSpanAttributes,yt as shadowGit,Q as shutdownTelemetry,q as skillManagementPath,Je as spansCurrentPath,ar as spansPreviousPath,M as spawnDetached,er as splitMarkdownBlocks,Re as startWatcher,Ue as streamingProblemEvent,$e as swapContributors,re as teardownToleranceTelemetryWriter,ve as toBroadcasterKey,Ne as tracedAppendFileSync,lt as tracedLinkSync,Ai as tracedMkdir,L as tracedMkdirSync,kt as tracedRename,pe as tracedRenameSync,wt as tracedRmSync,Pt as tracedRmdirSync,ce as tracedUnlinkSync,Oe as tracedWriteFile,Ir as tracedWriteFileSync,Ce as updateLastKnownHash,u as updateProcessLockPort,l as updateServerLockPort,Wt as updateUiLockPort,zt as validateAgentId,Yt as validateCloneInputs,it as validateSkillZip,D as withSpan,Dn as withSpanSync,Qr as writeRootGitignoreForNewRepo,br as writeSkillManagement,Vr as writeStateManifest,Jn as writeTargetVersion,sn as writeTracker};
1
+ import{Fi as e,J as t,Oi as n,Vt as r,a as i,c as a,d as o,dn as s,f as c,g as l,h as u,i as d,ii as f,kn as p,l as m,m as h,n as g,o as _,on as v,p as y,r as b,s as x,t as S,tn as C,u as w,wn as T}from"./server-lock-CN2YHwpP-DiysUpvV.mjs";import{$ as E,$i as D,$n as O,$r as k,$t as A,A as j,Ai as M,An as N,Ar as P,At as F,B as I,Bi as L,Bn as R,Br as z,Bt as B,C as V,Ci as H,Cn as U,Cr as W,Ct as G,D as K,Di as q,Dn as J,Dr as Y,Dt as X,E as Z,Ei as Q,En as $,Er as ee,Et as te,F as ne,Fi as re,Fn as ie,Fr as ae,Ft as oe,G as se,Gi as ce,Gn as le,Gr as ue,Gt as de,H as fe,Hi as pe,Hn as me,Hr as he,Ht as ge,I as _e,Ii as ve,In as ye,Ir as be,It as xe,J as Se,Ji as Ce,Jn as we,Jr as Te,Jt as Ee,K as De,Ki as Oe,Kn as ke,Kr as Ae,Kt as je,L as Me,Li as Ne,Ln as Pe,Lr as Fe,Lt as Ie,M as Le,Mi as Re,Mn as ze,Mr as Be,Mt as Ve,N as He,Ni as Ue,Nn as We,Nr as Ge,Nt as Ke,O as qe,Oi as Je,On as Ye,Or as Xe,Ot as Ze,P as Qe,Pi as $e,Pn as et,Pr as tt,Pt as nt,Q as rt,Qi as it,Qn as at,Qr as ot,Qt as st,R as ct,Ri as lt,Rn as ut,Rr as dt,Rt as ft,S as pt,Si as mt,Sn as ht,Sr as gt,St as _t,T as vt,Ti as yt,Tn as bt,Tr as xt,Tt as St,U as Ct,Ui as wt,Un as Tt,Ur as Et,Ut as Dt,V as Ot,Vi as kt,Vn as At,Vr as jt,Vt as Mt,W as Nt,Wi as Pt,Wn as Ft,Wr as It,Wt as Lt,X as Rt,Xi as zt,Xn as Bt,Xr as Vt,Xt as Ht,Y as Ut,Yi as Wt,Yn as Gt,Yr as Kt,Yt as qt,Z as Jt,Zi as Yt,Zn as Xt,Zr as Zt,Zt as Qt,_ as $t,_a as en,_i as tn,_n as nn,_r as rn,_t as an,a as on,aa as sn,ai as cn,an as ln,ar as un,at as dn,b as fn,bi as pn,bn as mn,br as hn,bt as gn,c as _n,ci as vn,cn as yn,cr as bn,ct as xn,d as Sn,di as Cn,dn as wn,dr as Tn,dt as En,ea as Dn,ei as On,en as kn,er as An,et as jn,f as Mn,fi as Nn,fn as Pn,fr as Fn,ft as In,g as Ln,gi as Rn,gn as zn,gr as Bn,gt as Vn,h as Hn,hi as Un,hn as Wn,hr as Gn,ht as Kn,i as qn,ia as Jn,ii as Yn,in as Xn,ir as Zn,it as Qn,j as $n,ji as er,jn as tr,jr as nr,jt as rr,k as ir,ki as ar,kn as or,kr as sr,kt as cr,l as lr,li as ur,ln as dr,lr as fr,lt as pr,m as mr,mi as hr,mn as gr,mr as _r,mt as vr,n as yr,na as br,ni as xr,nn as Sr,nr as Cr,nt as wr,o as Tr,oi as Er,on as Dr,or as Or,ot as kr,p as Ar,pi as jr,pn as Mr,pr as Nr,pt as Pr,q as Fr,qi as Ir,qn as Lr,qr as Rr,qt as zr,r as Br,ra as Vr,ri as Hr,rn as Ur,rr as Wr,rt as Gr,s as Kr,si as qr,sn as Jr,sr as Yr,st as Xr,t as Zr,ta as Qr,ti as $r,tn as ei,tr as ti,tt as ni,u as ri,ui as ii,un as ai,ur as oi,ut as si,v as ci,va as li,vi as ui,vn as di,vr as fi,vt as pi,w as mi,wi as hi,wn as gi,wr as _i,wt as vi,x as yi,xi as bi,xn as xi,xr as Si,xt as Ci,y as wi,yi as Ti,yn as Ei,yr as Di,yt as Oi,z as ki,zi as Ai,zn as ji,zr as Mi,zt as Ni}from"./dist-CPWuFcMi.mjs";export{Zr as AGENT_ID_MAX_LEN,yr as AGENT_ID_RE,Br as AGENT_WRITE_ORIGIN,qn as AgentFocusBroadcaster,on as AgentPresenceBroadcaster,Tr as AgentSessionCapacityError,Kr as AgentSessionManager,_n as AutoStartDisabledError,lr as BUNDLE_IDS,ri as BUNDLE_SCOPE,Sn as BUNDLE_SKILL_NAME,Mn as BacklinkIndex,Ar as CC1Broadcaster,t as CC1_CONTRACT_VERSION,mr as CONFIG_FILENAME,Hn as CONFLICT_MARKER_RE,Ln as CURSOR_BUNDLE_PATHS_BY_PLATFORM,$t as ConfigSchema,ci as DEFAULT_CHECKPOINT_RETENTION,wi as DEFAULT_EMBEDDINGS_DIMENSIONS,fn as DEFAULT_PACK_ID,yi as EMBEDDINGS_API_KEY_ENV,pt as FILE_SYSTEM_WRITER,V as FILE_WATCHER_ORIGIN,mi as FileEmbeddingsBackend,vt as GIT_PREFLIGHT_FAIL_SPAN_NAME,Z as GIT_UPSTREAM_WRITER,en as GitDirAccessError,K as GitNotAvailableError,qe as GitTooOldError,ir as HOCUSPOCUS_AUTH_REJECTION_REASONS,j as HocuspocusAuthRejection,$n as HocuspocusAuthTokenSchema,Le as INSTALLED_AGENTS_SCHEMES,r as LINEAGE_EPOCH_KEY,He as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Qe as LOG_MD_TEMPLATE,ne as MANAGED_RENAME_ORIGIN,_e as MAX_AGENT_SESSIONS,Me as MCP_CONNECTION_ID_HEADER,C as MCP_SERVER_NAME,ct as MIN_GIT_VERSION,ki as MISSING_OK_CONFIG_MESSAGE,li as MalformedGitPointerError,I as McpLogger,Ot as MissingOkConfigError,fe as OBSERVER_SYNC_ORIGIN,Ct as OK_OKIGNORE_TEMPLATE,v as ORPHAN_MODES,Nt as PANE_TARGET_TTL_MS,s as PROTOCOL_VERSION,se as PinoLogger,S as ProcessLockCollisionError,De as ProjectGitInitError,Fr as ROLLBACK_ORIGIN,Se as ROOT_GITIGNORE_TEMPLATE,g as RUNTIME_VERSION,Ut as SERVICE_WRITER,Rt as SKILL_INSTALL_EVENTS_FILE_REL,T as SKILL_STATE_TARGETS,Jt as STARTER_FOLDERS,rt as STARTER_FOLDER_FRONTMATTER_FILENAME,E as STARTER_PACKS,jn as STARTER_PACK_IDS,ni as STARTER_TEMPLATES,wr as STATE_MANIFEST_FILENAME,b as STATE_SCHEMA_VERSION,p as SYSTEM_DOC_NAME,Gr as SeedPrerequisiteError,Qn as SeedRootDirError,d as ServerLockCollisionError,dn as SingleFileNotAFileError,kr as SingleFileNotFoundError,Xr as SingleFileNotMarkdownError,xn as StateManifestError,pr as TagIndex,si as USER_GLOBAL_BUNDLE_IDS,En as UiLockCollisionError,In as __getShowAllWalkStatsForTesting,Pr as __resetShowAllWalkStatsForTesting,i as acquireProcessLock,_ as acquireServerLock,vr as acquireUiLock,Kn as applyAgentMarkdownWrite,Vn as applyExternalChange,an as applySeed,pi as armPaneTarget,Oi as assertCompatibleStateManifest,gn as assertGitAvailable,Ci as assertNeverDiskEvent,_t as attachIdleShutdown,G as bootServer,vi as buildAndOpenSkill,St as buildConfigYmlContent,te as buildExecResult,X as buildSkillZip,Ze as buildStarterFolderFrontmatterYaml,cr as buildWipTree,F as bundleSkillMdPath,rr as classifyEvents,Ve as classifyFsPath,Ke as clearArmedPaneTarget,nt as clearContributors,oe as clearEmbeddingsKeyFromAllBackends,xe as coercePackId,f as colorFromSeed,Ie as commitUpstreamImport,ft as commitWip,Ni as commitWipFromTree,B as compareSemver,Mt as containsConflictMarkers,ge as contentHash,Dt as contributorCount,Lt as countShadowObjects,de as countStaleAgentWipRefs,je as countWipRefs,zr as createApiExtension,Ee as createAssetServeMiddleware,qt as createContentFilter,Ht as createContentFilterAsync,Qt as createEmbeddingsSecretStore,st as createEphemeralProjectDir,A as createExternalChangeHandler,kn as createFileLogger,ei as createLiveDerivedIndexExtension,Sr as createMcpHttpHandler,Ur as createOsProbe,Xn as createPersistenceExtension,ln as createServer,Dr as createServerObserverExtension,Jr as createStreamingErrorWriter,yn as createTestLogger,dr as describeStoredEmbeddingsKey,ai as detectClaudeDesktopPresence,wn as detectGit,Pn as detectProjectShape,Mr as discoverLockDirs,gr as emitPreflightFailureSpan,Wn as encodeDocName,zn as encodeFolderRoute,nn as encodeSkillRoute,di as ensureProjectGit,Ei as errorResponse,mn as evictStaleTrackerEntries,xi as extractOkBinaryPath,ht as extractWikiLinksFromMarkdown,U as fallbackPaths,gi as findEnclosingGitRoot,bt as findEnclosingProjectRoot,$ as flushFileLogger,J as formatAuthRejectionWire,Ye as formatContributors,or as formatContributorsFrom,N as formatPackRationale,tr as gcCheckpointRefs,ze as getCurrentMcpLogger,We as getLocalDir,et as getLogFilePath,ie as getLogger,ye as getLogsDir,Pe as getMeter,ut as getMetrics,ji as getTracer,R as handleCollabSocketError,At as handleSpawnCursor,me as hasGcLogLatch,n as iconFromClientName,Tt as incrementCollabSocketFilteredError,Ft as incrementServerObserverFire,le as initContent,ke as initShadowRepo,Lr as initTelemetry,we as initToleranceTelemetryWriter,Gt as installPrettyZodErrors,Bt as installTestLoggers,Xt as installUserSkill,at as isAllowedApiOrigin,O as isAllowedWorkspaceHostHeader,An as isConfigDoc,ti as isHocuspocusAuthRejectionReason,Cr as isKnownPackId,Wr as isLinkIndexExcludedDoc,Zn as isLoopbackAddress,un as isManagedArtifactDoc,e as isOrphanMode,Or as isPairedWriteOrigin,Yr as isPathWithinDir,x as isProcessAlive,bn as isProjectRoot,fr as isProjectSkillManaged,oi as isReservedForUserTree,Tn as isSelfWrite,Fn as isSystemDoc,Nr as isToleranceTelemetryEnabled,a as isValidLockPid,_r as lastKnownHash,Gn as listRescueCheckpoints,Bn as listStarterPacks,rn as loadPrincipal,m as lockFilePath,fi as loggerFactory,Di as logsCurrentPath,hn as logsPreviousPath,Si as makeLazyEmbeddingsKeyStore,gt as mountMcpAndApi,W as normalizeFsPath,_i as packageVersionMajorMinor,xt as parseAuthRejectionWire,ee as parseGitVersion,Y as parseHocuspocusAuthToken,Xe as parseKeepaliveConnectionId,sr as pathToDocName,P as planSeed,nr as prepareSingleFileOpen,Be as processCommand,Ge as processUsage,tt as readAllTargets,ae as readArmedPaneTarget,be as readBranchFromHead,w as readProcessLock,o as readProcessLockDetailed,Fe as readProjectLocalSemanticConfig,c as readServerLock,dt as readServerPackageVersion,Mi as readSkillInstallStateSnapshot,z as readSkillManagement,jt as readStateManifest,he as readTargetRecordedAt,Et as readTargetVersion,It as readUiLock,ue as reconcile,Ae as recordContributor,Rr as recordSkillInstallEvent,Te as registerAllTools,Kt as registerWrite,y as releaseProcessLock,h as releaseServerLock,Vt as releaseUiLock,Zt as removeLastKnownHash,ot as resetMetrics,k as resolveBundledSkillDir,On as resolveContentDir,$r as resolveCursorBinaryDefault,xr as resolveCursorSpawnInvocation,Hr as resolveLockDir,Yn as resolvePack,cn as resolvePackageVersion,Er as resolveUiInfo,qr as restoreContributors,vn as restoreLifecycleFromConflictsJson,ur as rewriteMarkdownLinksForDocumentRename,ii as rewriteWikiLinksForDocumentRename,Cn as runAuthReposSubprocess,Nn as runAuthStatusSubprocess,jr as runCloneSubprocess,hr as runDeviceFlowSubprocess,Un as runWithMcpLogger,Rn as safeContentPath,tn as safeSubdir,ui as safetyCheckpoint,Ti as sanitizeClientName,pn as saveInMemoryCheckpoint,bi as saveVersion,mt as seedBasenameIndex,H as serializeError,hi as setActiveSpanAttributes,yt as shadowGit,Q as shutdownTelemetry,q as skillManagementPath,Je as spansCurrentPath,ar as spansPreviousPath,M as spawnDetached,er as splitMarkdownBlocks,Re as startWatcher,Ue as streamingProblemEvent,$e as swapContributors,re as teardownToleranceTelemetryWriter,ve as toBroadcasterKey,Ne as tracedAppendFileSync,lt as tracedLinkSync,Ai as tracedMkdir,L as tracedMkdirSync,kt as tracedRename,pe as tracedRenameSync,wt as tracedRmSync,Pt as tracedRmdirSync,ce as tracedUnlinkSync,Oe as tracedWriteFile,Ir as tracedWriteFileSync,Ce as updateLastKnownHash,u as updateProcessLockPort,l as updateServerLockPort,Wt as updateUiLockPort,zt as validateAgentId,Yt as validateCloneInputs,it as validateSkillZip,D as withSpan,Dn as withSpanSync,Qr as writeRootGitignoreForNewRepo,br as writeSkillManagement,Vr as writeStateManifest,Jn as writeTargetVersion,sn as writeTracker};
@@ -819,7 +819,7 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
819
819
 
820
820
  `}function buildWorkflowHandler(e,t,s,g){return async S=>{let w=typeof S.cwd==`string`?S.cwd:void 0,E=await resolveProjectConfigContext(t.resolveCwd,t.config,w);if(!E.ok)return textResult(`Error: ${E.error}`,!0);let D=S[s],O=typeof D==`string`?D:``;return textPlusStructured(`${buildWorkflowFrame(e)}${g(O,E.config.content.dir)}`,{previewUrl:null})}}async function resolveServerUrl(e,t){return typeof e==`function`?await e(t):e}async function resolveConfig(e,t){return typeof e==`function`?await e(t):e}async function resolveProjectConfigContext(e,t,s){let g;try{g=await e(s)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let S=s===void 0?g:resolve(s);try{let e=await resolveConfig(t,g);return{ok:!0,cwd:g,executionCwd:S,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function resolveProjectServerContext(e,t,s,g){let S=await resolveProjectConfigContext(e,t,g);if(!S.ok)return S;let{cwd:w,executionCwd:E,config:D}=S;try{return{ok:!0,cwd:w,executionCwd:E,config:D,url:await resolveServerUrl(s,w)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function okReservedPathRedirect(e){let t=e.replace(/^\/+/,``);return t!==`.ok`&&!t.startsWith(`.ok/`)?null:t.startsWith(`.ok/skills/`)?"Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes `.ok/skills/<name>/SKILL.md`. To author or improve a skill, use the `open-knowledge-write-skill` skill.":t.startsWith(`.ok/templates/`)?"Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.":"Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target."}function normalizeDocName(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let s=e,g=t;for(;g.endsWith(`.mdx`)||g.endsWith(`.md`);)s=s.slice(0,g.endsWith(`.mdx`)?-4:-3),g=s.toLowerCase();let S=validateDocName(s);return S.ok?{ok:!0,docName:s}:{ok:!1,error:`Error: "${e}" is invalid — ${S.reason}.`}}function normalizeResponse(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...s}=t;return{ok:!0,...s}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let s=t;if(typeof s.type==`string`&&typeof s.title==`string`){let{type:e,title:t,status:g,instance:S,detail:w,...E}=s;return{...E,ok:!1,error:t,type:e,...typeof g==`number`?{status:g}:{},...typeof S==`string`?{instance:S}:{},...typeof w==`string`?{detail:w}:{}}}let{ok:g,error:S,...w}=s,E=typeof S==`string`?S:typeof s.message==`string`?s.message:`Server returned HTTP ${e.status}`;return{...w,ok:!1,error:E}}async function httpGet(e,t){let s;try{s=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let g;try{g=await s.json()}catch(e){let t=e instanceof Error?e.message:String(e);return s.ok?{ok:!1,httpStatus:s.status,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,httpStatus:s.status,error:`Server returned HTTP ${s.status} with non-JSON body: ${t}`}}return{...normalizeResponse(s,g),httpStatus:s.status}}async function httpSend(e,t,s,g){let S;if(g!==void 0)try{S=JSON.stringify(g)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}let w;try{w=await fetch(`${t}${s}`,{method:e,headers:S===void 0?void 0:{"Content-Type":`application/json`},body:S,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let E;try{E=await w.json()}catch(e){let t=e instanceof Error?e.message:String(e);return w.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${w.status} with non-JSON body: ${t}`}}return normalizeResponse(w,E)}function httpPost(e,t,s){return httpSend(`POST`,e,t,s)}function httpPut(e,t,s){return httpSend(`PUT`,e,t,s)}function httpDelete(e,t){return httpSend(`DELETE`,e,t)}function parseRenameCollidingPairs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:s,to:g}=e;return typeof t==`string`&&typeof s==`string`&&typeof g==`string`?[{existing:t,incoming:s,to:g}]:[]}):[]}function readFolderFrontmatter(e,t){let s=nestedOkPath(e,t,`frontmatter.yml`);if(!existsSync(s))return{};let g=readFrontmatterYaml(s);return g==null?{}:coerceWellKnown(g)}function coerceWellKnown(e){let t={};for(let[s,g]of Object.entries(e))t[s]=g;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const warnedPaths=new Set;function readFrontmatterYaml(e){let t;try{t=readFileSync(e,`utf-8`)}catch{return null}let s;try{s=(0,import_dist$1.parse)(t)}catch(t){if(!warnedPaths.has(e)){warnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-folder-frontmatter] malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${s}`)}return null}return typeof s!=`object`||!s||Array.isArray(s)?null:(warnedPaths.delete(e),s)}function nestedOkPath(e,t,s){let g=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return g===``||g===`.`?join(e,`.ok`,s):join(e,g,`.ok`,s)}function parentFolderOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}const GIT_TIMEOUT_MS$2=5e3;function projectHasGitDir(e){try{return statSync(resolve(e,`.git`)).isDirectory()}catch{return!1}}function openProjectGit(e){return esm_default({baseDir:resolve(e),timeout:{block:GIT_TIMEOUT_MS$2}})}async function readProjectGitLog(e,t,s=5){if(!projectHasGitDir(e))return{commits:[],source:`git-absent`};let g=openProjectGit(e),S=``;try{S=await g.raw(`log`,`-${Math.max(1,s)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let w=[];for(let e of S.split(`
821
821
  `)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let s=e.indexOf(`|`,t+1);if(s<0)continue;let g=e.indexOf(`|`,s+1);g<0||w.push({hash:e.slice(0,t),date:e.slice(t+1,s),authorName:e.slice(s+1,g),subject:e.slice(g+1)})}return{commits:w,source:`git`}}const GIT_TIMEOUT_MS$1=5e3;async function currentProjectBranch(e){try{let t=(await esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS$1}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function openShadowGit(e,t){return esm_default({baseDir:t,timeout:{block:GIT_TIMEOUT_MS$1}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function writerIdFromRef(e,t){let s=getWipRefPattern(t);return e.startsWith(s)?e.slice(s.length):e}async function logOnRef(e,t,s,g,S){let w=``;try{w=await e.raw(`log`,t,`-${Math.max(1,S*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,s)}catch{return[]}let E=writerIdFromRef(t,g),D=parseWriterId(E),O=[];for(let e of w.split(``)){let t=e.trimStart();if(!t)continue;let[s=``,S=``,w=``,k=``,j=``]=t.split(`\0`),F=s.trim();F.length===40&&O.push({hash:F,date:S,writerName:w,message:k,contributors:readContributors(j),writerId:E,isAgent:D.isAgent,writerClassification:D.classification,branch:g})}return O}async function checkpointAncestryFallback(e,t,s,g,S){let w=``;try{w=(await e.raw(`for-each-ref`,`--sort=-creatordate`,`--count=1`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)).trim()}catch{return[]}if(!w)return[];let E=``;try{E=await e.raw(`log`,w,`-${Math.max(g*3,20)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,s)}catch{return[]}let D=[];for(let e of E.split(``)){if(D.length>=g)break;let s=e.trimStart();if(!s)continue;let[w=``,E=``,O=``,k=``,j=``]=s.split(`\0`),F=w.trim();if(F.length!==40||S.has(F)||k.startsWith(`checkpoint:`)||k.startsWith(`park:`)||k.startsWith(`import:`)||k.startsWith(`upstream:`))continue;let L=parseOkActor(j),B=L?.writer_id??``,H=parseWriterId(B);S.add(F),D.push({hash:F,date:E,writerName:L?.display_name??O,message:k,contributors:readContributors(j),writerId:B,isAgent:H.isAgent,writerClassification:H.classification,branch:t})}return D}async function readShadowLog(e,t,s=5){let g=getShadowRepoPath(e);if(!g)return{commits:[],source:`shadow-repo-absent`};let S=await currentProjectBranch(e);if(!S)return{commits:[],source:`shadow-repo`};let w=openShadowGit(g,resolve(e)),E=``;try{E=await w.raw(`for-each-ref`,getWipRefPattern(S),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let D=E.split(`
822
- `).map(e=>e.trim()).filter(Boolean),O=(D.length===0?[]:await Promise.all(D.map(e=>logOnRef(w,e,t,S,s)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s);if(O.length<s){let e=new Set(O.map(e=>e.hash)),g=await checkpointAncestryFallback(w,S,t,s-O.length,e);g.length>0&&(O=[...O,...g].sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s))}return{commits:O,source:`shadow-repo`}}function resolveTemplatesAvailable(e,t,s={}){let g=normalizeFolderPath(t),S=g===``?[]:g.split(`/`),w=new Set,E=[];collectFromFolder(e,g,`local`,w,E);for(let t=S.length-1;t>=1;t--)collectFromFolder(e,S.slice(0,t).join(`/`),`inherited`,w,E);return S.length>0&&collectFromFolder(e,``,`inherited`,w,E),E}function resolveProjectTemplates(e){let t=[],s=new Map,g=e=>{let t=s.get(e);return t||(t=new Set,s.set(e,t)),t},S=0,w=!1,E=[``];for(;E.length>0;){let s=E.shift()??``;if(S++>=PROJECT_TEMPLATE_SCAN_CAP){w=!0,console.warn(`[ok-templates] project scan hit the ${PROJECT_TEMPLATE_SCAN_CAP}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${E.length}.`);break}collectFromFolder(e,s,`local`,g(s),t);let D=s?join(e,s):e,O;try{O=readdirSync(D).sort()}catch(e){if(e?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(D)){templateMetaWarnedPaths.add(D);let t=e instanceof Error?e.message:String(e);console.warn(`[ok-templates] failed to read directory ${D} during project scan — skipped. Reason: ${t}`)}continue}for(let e of O){if(PROJECT_TEMPLATE_DIR_SKIP.has(e)||e.startsWith(`.`))continue;let t=join(D,e),g;try{g=statSync(t)}catch{continue}if(!g.isDirectory())continue;let S=s?posix.join(s,e):e;E.push(S)}}return{templates:t,truncated:w}}const PROJECT_TEMPLATE_SCAN_CAP=2e3,PROJECT_TEMPLATE_DIR_SKIP=new Set([`node_modules`,`dist`,`build`]);function collectFromFolder(e,t,s,g,S){let w=t?join(e,t,`.ok`,`templates`):join(e,`.ok`,`templates`);if(!existsSync(w))return;let E;try{E=readdirSync(w)}catch{return}for(let e of E){if(!e.endsWith(`.md`))continue;let E=e.slice(0,-3);if(g.has(E))continue;let D=join(w,e),O;try{O=statSync(D)}catch{continue}if(!O.isFile())continue;let k=readTemplateMeta(D),j={name:E,path:t?posix.join(t,`.ok`,`templates`,e):posix.join(`.ok`,`templates`,e),source_folder:t,scope:s};k.title!==void 0&&(j.title=k.title),k.description!==void 0&&(j.description=k.description),g.add(E),S.push(j)}}function normalizeFolderPath(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const templateMetaWarnedPaths=new Set;function readTemplateMeta(e){let t;try{t=readFileSync(e,`utf-8`)}catch(t){if(t?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] failed to read template at ${e} — metadata skipped. Reason: ${s}`)}return{}}let{identity:s}=parseTemplateFile(t);typeof s.title!=`string`&&!templateMetaWarnedPaths.has(e)&&(templateMetaWarnedPaths.add(e),console.warn(`[ok-templates] template at ${e} has no title — YAML may be malformed or the title is missing.`));let g={};return typeof s.title==`string`&&(g.title=s.title),typeof s.description==`string`&&(g.description=s.description),g}function parseFrontmatterRaw(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return null;try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i;function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${s}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.backlinks??s.results??s.links;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e,s=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;s&&S.push({source:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let s=[...new Set(t)],g=[];for(let e=0;e<s.length;e+=BACKLINK_COUNT_CHUNK)g.push(s.slice(e,e+BACKLINK_COUNT_CHUNK));let S=await Promise.all(g.map(async t=>{let s=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return s.ok?s.counts??{}:null})),w=new Map,E=!1;for(let e of S)if(e){E=!0;for(let[t,s]of Object.entries(e))typeof s==`number`&&Number.isFinite(s)&&w.set(t,s)}return E?w:null}async function fetchForwardLinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.forwardLinks??s.links??s.results;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){S.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let s=typeof t.docName==`string`?t.docName:void 0;s&&S.push({kind:`doc`,docName:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}function liftOwnFrontmatter(e){let t=e??{};return{title:typeof t.title==`string`?t.title:void 0,description:typeof t.description==`string`?t.description:void 0,tags:Array.isArray(t.tags)?t.tags.filter(e=>typeof e==`string`):[],frontmatter:t}}async function enrichPath(e,t,s={}){let g=resolveWithinRoot(t.projectDir,e);if(!g.ok)throw Error(`enrichPath: ${g.reason}`);let S=g.rel,w=g.abs,E=t.historyDepth??5,D=s.includeRichFields===!0,O=readFrontmatter(w);if(!D){let e=liftOwnFrontmatter(await O);return{path:S,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[k,j,F,L,B]=await Promise.all([O,fetchBacklinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),readShadowLog(t.projectDir,S,E).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,S,E).catch(()=>({commits:[],source:`git`}))]),H=liftOwnFrontmatter(k);return{path:S,title:H.title,description:H.description,tags:H.tags,frontmatter:H.frontmatter,backlinkCount:j?.length??null,backlinks:j,forwardLinkCount:F?.length??null,forwardLinks:F,history:L.commits,historySource:L.source,projectHistory:B.commits,projectHistorySource:B.source}}async function scanDirectory(e,t){let s={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},g=0,S=[{path:e,depth:0}];for(;S.length>0;){let e=S.shift();if(!e)break;if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}let w;try{w=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let E of w){if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}g++;let w=E.name;if(E.isDirectory()){if(DIR_SKIP.has(w)||w.startsWith(`.`))continue;e.depth===0&&s.childDirCount++,S.push({path:`${e.path}/${w}`,depth:e.depth+1})}else if(E.isFile()&&WIKI_EXT_RE.test(w)){s.recursiveMdCount++,e.depth===0&&s.directMdCount++;let g=`${e.path}/${w}`;try{let e=await stat$1(g);(!s.mostRecent||e.mtimeMs>s.mostRecent.mtimeMs)&&(s.mostRecent={absPath:g,relPath:relative(t,g).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return s}async function enrichDirectory(e,t){let s=resolveWithinRoot(t.projectDir,e);if(!s.ok)throw Error(`enrichDirectory: ${s.reason}`);let g=s.rel,S=s.abs,w=await scanDirectory(S,t.projectDir),E;if(w.mostRecent){let e=await readFrontmatter(w.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;E={path:w.mostRecent.relPath,title:t??basename(w.mostRecent.relPath),updatedAt:new Date(w.mostRecent.mtimeMs).toISOString()}}let D={path:g,type:`directory`,directMdCount:w.directMdCount,recursiveMdCount:w.recursiveMdCount,childDirCount:w.childDirCount,mostRecentMd:E,truncated:w.truncated},O=readFolderFrontmatter(t.projectDir,g);O.title!==void 0&&(D.title=O.title),O.description!==void 0&&(D.description=O.description),(O.tags?.length??0)>0&&(D.tags=O.tags);let k=resolveTemplatesAvailable(t.projectDir,g);return k.length>0&&(D.templates_available=k),D}async function enrichDirectoryRecursive(e,t,s){let g=await enrichDirectory(e,s);if(t<=1)return g;let S=g.path,w=resolve(s.projectDir,S),E;try{E=await readdir(w,{withFileTypes:!0})}catch{return g}let D=[];for(let e of E){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let g=await enrichDirectoryRecursive(S?`${S}/${e.name}`:e.name,t-1,s);D.push(g)}return D.length>0&&(g.subfolders=D),g}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function mergePatch(e,t){let s={...e};for(let[e,g]of Object.entries(t))if(g!==void 0){if(isEmpty$2(g)){delete s[e];continue}s[e]=g}return s}function isEmpty$2(e){return isFrontmatterValueEmpty(e)}function applyFolderFrontmatterPatch(e){if(!isAbsolute(e.anchorDir))return{ok:!1,error:{code:`BAD_CONTENT_DIR`,message:`anchorDir must be absolute`}};let t=resolve(e.anchorDir),s=e.folderRel.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(s.split(`/`).some(e=>e===`..`))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Folder path escapes the content directory: ${e.folderRel}`}};let g=s===``?t:resolve(t,s);if(g!==t&&!g.startsWith(t+sep))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder escapes the content directory: ${g}`}};let S=join(g,`.ok`),w=join(S,`frontmatter.yml`);try{let s=readExistingFrontmatter(w),g=Object.keys(e.patch).length===0?{}:mergePatch(s,e.patch);if(Object.keys(g).length===0)return existsSync(w)?(unlinkSync(w),autoCleanOkDir(S),{ok:!0,path:relPathOf$2(t,w),action:`deleted`}):{ok:!0,path:relPathOf$2(t,w),action:`noop`};mkdirSync(S,{recursive:!0});let E=(0,import_dist$1.stringify)(g),D=`${w}.tmp.${process.pid}.${Date.now()}`;return writeFileSync(D,E,`utf-8`),renameSync(D,w),{ok:!0,path:relPathOf$2(t,w),action:`written`}}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write folder frontmatter for "${s||`.`}": ${e.message}`}}}}function readExistingFrontmatter(e){if(!existsSync(e))return{};let t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:{...t}}function autoCleanOkDir(e){if(!existsSync(e))return;let t;try{t=readdirSync(e)}catch{return}if(t.length===0)try{rmdirSync(e)}catch{}}function relPathOf$2(e,t){return t.startsWith(e+sep)?t.slice(e.length+1).split(sep).join(`/`):t}const NAME_MAX=64,DESCRIPTION_MAX=1024,RESERVED_NAME_WORDS=[`anthropic`,`claude`],BODY_SOFT_MAX_LINES=500,SKILL_FILE=`SKILL.md`;function composeSkillContent(e){let t=validateName(e.name);if(!t.ok)return{ok:!1,error:t.error};let s=validateFrontmatter(e.frontmatter,e.name);if(!s.ok)return{ok:!1,error:s.error};let g=`---\n${serializeFrontmatter(e.frontmatter)}---\n${e.body}`,S=[],w=e.body.split(`
822
+ `).map(e=>e.trim()).filter(Boolean),O=(D.length===0?[]:await Promise.all(D.map(e=>logOnRef(w,e,t,S,s)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s);if(O.length<s){let e=new Set(O.map(e=>e.hash)),g=await checkpointAncestryFallback(w,S,t,s-O.length,e);g.length>0&&(O=[...O,...g].sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s))}return{commits:O,source:`shadow-repo`}}function resolveTemplatesAvailable(e,t,s={}){let g=normalizeFolderPath(t),S=g===``?[]:g.split(`/`),w=new Set,E=[];collectFromFolder(e,g,`local`,w,E);for(let t=S.length-1;t>=1;t--)collectFromFolder(e,S.slice(0,t).join(`/`),`inherited`,w,E);return S.length>0&&collectFromFolder(e,``,`inherited`,w,E),E}function resolveProjectTemplates(e){let t=[],s=new Map,g=e=>{let t=s.get(e);return t||(t=new Set,s.set(e,t)),t},S=0,w=!1,E=[``];for(;E.length>0;){let s=E.shift()??``;if(S++>=PROJECT_TEMPLATE_SCAN_CAP){w=!0,console.warn(`[ok-templates] project scan hit the ${PROJECT_TEMPLATE_SCAN_CAP}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${E.length}.`);break}collectFromFolder(e,s,`local`,g(s),t);let D=s?join(e,s):e,O;try{O=readdirSync(D).sort()}catch(e){if(e?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(D)){templateMetaWarnedPaths.add(D);let t=e instanceof Error?e.message:String(e);console.warn(`[ok-templates] failed to read directory ${D} during project scan — skipped. Reason: ${t}`)}continue}for(let e of O){if(PROJECT_TEMPLATE_DIR_SKIP.has(e)||e.startsWith(`.`))continue;let t=join(D,e),g;try{g=statSync(t)}catch{continue}if(!g.isDirectory())continue;let S=s?posix.join(s,e):e;E.push(S)}}return{templates:t,truncated:w}}const PROJECT_TEMPLATE_SCAN_CAP=2e3,PROJECT_TEMPLATE_DIR_SKIP=new Set([`node_modules`,`dist`,`build`]);function collectFromFolder(e,t,s,g,S){let w=t?join(e,t,`.ok`,`templates`):join(e,`.ok`,`templates`);if(!existsSync(w))return;let E;try{E=readdirSync(w)}catch{return}for(let e of E){if(!e.endsWith(`.md`))continue;let E=e.slice(0,-3);if(g.has(E))continue;let D=join(w,e),O;try{O=statSync(D)}catch{continue}if(!O.isFile())continue;let k=readTemplateMeta(D),j={name:E,path:t?posix.join(t,`.ok`,`templates`,e):posix.join(`.ok`,`templates`,e),source_folder:t,scope:s};k.title!==void 0&&(j.title=k.title),k.description!==void 0&&(j.description=k.description),g.add(E),S.push(j)}}function normalizeFolderPath(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const templateMetaWarnedPaths=new Set;function readTemplateMeta(e){let t;try{t=readFileSync(e,`utf-8`)}catch(t){if(t?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] failed to read template at ${e} — metadata skipped. Reason: ${s}`)}return{}}let{identity:s}=parseTemplateFile(t);typeof s.title!=`string`&&!templateMetaWarnedPaths.has(e)&&(templateMetaWarnedPaths.add(e),console.warn(`[ok-templates] template at ${e} has no title — YAML may be malformed or the title is missing.`));let g={};return typeof s.title==`string`&&(g.title=s.title),typeof s.description==`string`&&(g.description=s.description),g}function parseFrontmatterRaw(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return null;try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i,HUB_MIN_INBOUND=5;function computeGraphRole(e,t){if(e===null||t===null)return null;let s=e,g=t;return s===0&&g===0?`orphan`:s>=HUB_MIN_INBOUND?`hub`:s>0&&g>0?`connector`:`leaf`}function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${s}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.backlinks??s.results??s.links;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e,s=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;s&&S.push({source:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let s=[...new Set(t)],g=[];for(let e=0;e<s.length;e+=BACKLINK_COUNT_CHUNK)g.push(s.slice(e,e+BACKLINK_COUNT_CHUNK));let S=await Promise.all(g.map(async t=>{let s=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return s.ok?s.counts??{}:null})),w=new Map,E=!1;for(let e of S)if(e){E=!0;for(let[t,s]of Object.entries(e))typeof s==`number`&&Number.isFinite(s)&&w.set(t,s)}return E?w:null}async function fetchForwardLinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.forwardLinks??s.links??s.results;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){S.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let s=typeof t.docName==`string`?t.docName:void 0;s&&S.push({kind:`doc`,docName:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}function liftOwnFrontmatter(e){let t=e??{};return{title:typeof t.title==`string`?t.title:void 0,description:typeof t.description==`string`?t.description:void 0,tags:Array.isArray(t.tags)?t.tags.filter(e=>typeof e==`string`):[],frontmatter:t}}async function enrichPath(e,t,s={}){let g=resolveWithinRoot(t.projectDir,e);if(!g.ok)throw Error(`enrichPath: ${g.reason}`);let S=g.rel,w=g.abs,E=t.historyDepth??5,D=s.includeRichFields===!0,O=readFrontmatter(w);if(!D){let e=liftOwnFrontmatter(await O);return{path:S,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null,graphRole:null}}let[k,j,F,L,B]=await Promise.all([O,fetchBacklinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),readShadowLog(t.projectDir,S,E).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,S,E).catch(()=>({commits:[],source:`git`}))]),H=liftOwnFrontmatter(k);return{path:S,title:H.title,description:H.description,tags:H.tags,frontmatter:H.frontmatter,backlinkCount:j?.length??null,backlinks:j,forwardLinkCount:F?.length??null,forwardLinks:F,history:L.commits,historySource:L.source,projectHistory:B.commits,projectHistorySource:B.source,graphRole:computeGraphRole(j?.length??null,F?.length??null)}}async function scanDirectory(e,t){let s={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},g=0,S=[{path:e,depth:0}];for(;S.length>0;){let e=S.shift();if(!e)break;if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}let w;try{w=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let E of w){if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}g++;let w=E.name;if(E.isDirectory()){if(DIR_SKIP.has(w)||w.startsWith(`.`))continue;e.depth===0&&s.childDirCount++,S.push({path:`${e.path}/${w}`,depth:e.depth+1})}else if(E.isFile()&&WIKI_EXT_RE.test(w)){s.recursiveMdCount++,e.depth===0&&s.directMdCount++;let g=`${e.path}/${w}`;try{let e=await stat$1(g);(!s.mostRecent||e.mtimeMs>s.mostRecent.mtimeMs)&&(s.mostRecent={absPath:g,relPath:relative(t,g).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return s}async function enrichDirectory(e,t){let s=resolveWithinRoot(t.projectDir,e);if(!s.ok)throw Error(`enrichDirectory: ${s.reason}`);let g=s.rel,S=s.abs,w=await scanDirectory(S,t.projectDir),E;if(w.mostRecent){let e=await readFrontmatter(w.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;E={path:w.mostRecent.relPath,title:t??basename(w.mostRecent.relPath),updatedAt:new Date(w.mostRecent.mtimeMs).toISOString()}}let D={path:g,type:`directory`,directMdCount:w.directMdCount,recursiveMdCount:w.recursiveMdCount,childDirCount:w.childDirCount,mostRecentMd:E,truncated:w.truncated},O=readFolderFrontmatter(t.projectDir,g);O.title!==void 0&&(D.title=O.title),O.description!==void 0&&(D.description=O.description),(O.tags?.length??0)>0&&(D.tags=O.tags);let k=resolveTemplatesAvailable(t.projectDir,g);return k.length>0&&(D.templates_available=k),D}async function enrichDirectoryRecursive(e,t,s){let g=await enrichDirectory(e,s);if(t<=1)return g;let S=g.path,w=resolve(s.projectDir,S),E;try{E=await readdir(w,{withFileTypes:!0})}catch{return g}let D=[];for(let e of E){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let g=await enrichDirectoryRecursive(S?`${S}/${e.name}`:e.name,t-1,s);D.push(g)}return D.length>0&&(g.subfolders=D),g}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function mergePatch(e,t){let s={...e};for(let[e,g]of Object.entries(t))if(g!==void 0){if(isEmpty$2(g)){delete s[e];continue}s[e]=g}return s}function isEmpty$2(e){return isFrontmatterValueEmpty(e)}function applyFolderFrontmatterPatch(e){if(!isAbsolute(e.anchorDir))return{ok:!1,error:{code:`BAD_CONTENT_DIR`,message:`anchorDir must be absolute`}};let t=resolve(e.anchorDir),s=e.folderRel.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(s.split(`/`).some(e=>e===`..`))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Folder path escapes the content directory: ${e.folderRel}`}};let g=s===``?t:resolve(t,s);if(g!==t&&!g.startsWith(t+sep))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder escapes the content directory: ${g}`}};let S=join(g,`.ok`),w=join(S,`frontmatter.yml`);try{let s=readExistingFrontmatter(w),g=Object.keys(e.patch).length===0?{}:mergePatch(s,e.patch);if(Object.keys(g).length===0)return existsSync(w)?(unlinkSync(w),autoCleanOkDir(S),{ok:!0,path:relPathOf$2(t,w),action:`deleted`}):{ok:!0,path:relPathOf$2(t,w),action:`noop`};mkdirSync(S,{recursive:!0});let E=(0,import_dist$1.stringify)(g),D=`${w}.tmp.${process.pid}.${Date.now()}`;return writeFileSync(D,E,`utf-8`),renameSync(D,w),{ok:!0,path:relPathOf$2(t,w),action:`written`}}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write folder frontmatter for "${s||`.`}": ${e.message}`}}}}function readExistingFrontmatter(e){if(!existsSync(e))return{};let t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:{...t}}function autoCleanOkDir(e){if(!existsSync(e))return;let t;try{t=readdirSync(e)}catch{return}if(t.length===0)try{rmdirSync(e)}catch{}}function relPathOf$2(e,t){return t.startsWith(e+sep)?t.slice(e.length+1).split(sep).join(`/`):t}const NAME_MAX=64,DESCRIPTION_MAX=1024,RESERVED_NAME_WORDS=[`anthropic`,`claude`],BODY_SOFT_MAX_LINES=500,SKILL_FILE=`SKILL.md`;function composeSkillContent(e){let t=validateName(e.name);if(!t.ok)return{ok:!1,error:t.error};let s=validateFrontmatter(e.frontmatter,e.name);if(!s.ok)return{ok:!1,error:s.error};let g=`---\n${serializeFrontmatter(e.frontmatter)}---\n${e.body}`,S=[],w=e.body.split(`
823
823
  `).length;return w>BODY_SOFT_MAX_LINES&&S.push(`SKILL.md body is ${w} lines — keep it under ${BODY_SOFT_MAX_LINES} for performance (every line is a recurring token cost). Move detail into one-level-deep references/.`),{ok:!0,content:g,warnings:S}}function applySkillWrite(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=composeSkillContent({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!s.ok)return{ok:!1,error:s.error};let{content:g,warnings:S}=s,{skillDir:w,filePath:E}=skillPaths(e.skillsRoot,e.name);try{mkdirSync(w,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create skill directory at ${relPathOf$1(e.skillsRoot,w)}: ${t.message}`}}}let D=!existsSync(E),O=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(O,g,`utf-8`),renameSync(O,E)}catch(t){try{unlinkSync(O)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill at ${relPathOf$1(e.skillsRoot,E)}: ${t.message}`}}}return{ok:!0,path:relPathOf$1(e.skillsRoot,E),created:D,warnings:S}}const BUNDLE_FILE_MAX_BYTES=256*1024;function resolveBundleFileAbs(e,t){if(typeof t!=`string`||t.length===0||t.includes(`\0`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path.`}};let s=t.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);if(s.length<2||s.some(e=>e===`..`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path: ${t}`}};if(s[0]!==`references`&&s[0]!==`scripts`)return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file must be under references/ or scripts/: ${t}`}};let g=join(e,...s);return g!==e&&!g.startsWith(e+sep)?{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file escapes the skill dir: ${t}`}}:{ok:!0,abs:g}}function countBundleFiles(e){let t=0,s=g=>{let S;try{S=readdirSync(g)}catch{return}for(let w of S){let S=join(g,w),E;try{E=statSync(S).isDirectory()}catch{continue}E?s(S):g===e&&w===SKILL_FILE||t++}};return s(e),t}function applySkillBundleFileWrite(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillDir:g,filePath:S}=skillPaths(e.skillsRoot,e.name);if(!existsSync(S))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill "${e.name}" — create it (write its SKILL.md) before adding bundle files.`}};let w=resolveBundleFileAbs(g,e.relPath);if(!w.ok)return{ok:!1,error:w.error};let{abs:E}=w,D=Buffer.byteLength(e.content,`utf-8`);if(D>262144)return{ok:!1,error:{code:`FILE_TOO_LARGE`,message:`Skill file ${e.relPath} is ${D} bytes — the per-file cap is ${BUNDLE_FILE_MAX_BYTES}.`}};let O=!existsSync(E);if(O&&countBundleFiles(g)>=50)return{ok:!1,error:{code:`TOO_MANY_FILES`,message:`Skill "${e.name}" already holds 50 bundle files (the cap) — delete one before adding another.`}};try{mkdirSync(join(E,`..`),{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create directory for ${e.relPath}: ${t.message}`}}}let k=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(k,e.content,`utf-8`),renameSync(k,E)}catch(t){try{unlinkSync(k)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill file ${e.relPath}: ${t.message}`}}}return{ok:!0,path:relPathOf$1(e.skillsRoot,E),created:O}}function applySkillBundleFileDelete(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillDir:g}=skillPaths(e.skillsRoot,e.name),S=resolveBundleFileAbs(g,e.relPath);if(!S.ok)return{ok:!1,error:S.error};let{abs:w}=S,E=existsSync(w);if(E){try{unlinkSync(w)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill file ${e.relPath}: ${t.message}`}}}let t=join(w,`..`);if(t!==g&&isEmpty$1(t))try{rmdirSync(t)}catch{}}return{ok:!0,path:relPathOf$1(e.skillsRoot,w),existed:E}}function applySkillDelete(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillsRoot:g}=t,{skillDir:S}=skillPaths(e.skillsRoot,e.name),w=existsSync(S);if(w)try{rmSync(S,{recursive:!0,force:!0})}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill at ${relPathOf$1(e.skillsRoot,S)}: ${t.message}`}}}return cleanEmptyDirs(g),{ok:!0,path:relPathOf$1(e.skillsRoot,S),existed:w}}async function applySkillMove(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.fromName);if(!s.ok)return{ok:!1,error:s.error};let g=validateName(e.toName);if(!g.ok)return{ok:!1,error:g.error};let S=skillPaths(e.skillsRoot,e.fromName),w=skillPaths(e.skillsRoot,e.toName);if(S.skillDir===w.skillDir)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same skill.`}};if(!existsSync(S.skillDir))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill at ${relPathOf$1(e.skillsRoot,S.skillDir)}.`}};if(existsSync(w.skillDir))return{ok:!1,error:{code:`SKILL_EXISTS`,message:`A skill already exists at ${relPathOf$1(e.skillsRoot,w.skillDir)}.`}};let E;try{E=await e.relocate(S.skillDir,w.skillDir)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move skill: ${e.message}`}}}return{ok:!0,fromPath:relPathOf$1(e.skillsRoot,S.skillDir),toPath:relPathOf$1(e.skillsRoot,w.skillDir),committed:E}}function validateBase(e){return isAbsolute(e)?{ok:!0,skillsRoot:e}:{ok:!1,error:{code:`BAD_SKILLS_ROOT`,message:`skillsRoot must be absolute`}}}function validateName(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name is required.`}}:e.length>NAME_MAX?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must be ≤${NAME_MAX} characters.`}}:SKILL_NAME_REGEX.test(e)?RESERVED_NAME_WORDS.some(t=>e.includes(t))?{ok:!1,error:{code:`RESERVED_NAME`,message:`Skill name may not contain reserved words (${RESERVED_NAME_WORDS.join(`, `)}).`}}:{ok:!0}:{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must match /^[a-z0-9-]+$/ (got: ${JSON.stringify(e)}). Lowercase letters, digits, hyphens — no slashes, dots, spaces, or uppercase.`}}}function validateFrontmatter(e,t){return!e||typeof e!=`object`?{ok:!1,error:{code:`BAD_FRONTMATTER`,message:`Skill frontmatter (name, description) is required.`}}:typeof e.name!=`string`||e.name.length===0?{ok:!1,error:{code:`SKILL_NAME_REQUIRED`,message:`Skill frontmatter.name is required.`}}:e.name===t?containsXmlTag(e.name)?{ok:!1,error:{code:`XML_TAG_IN_NAME`,message:"Skill frontmatter.name may not contain XML tags (`<...>`)."}}:typeof e.description!=`string`||e.description.length===0?{ok:!1,error:{code:`SKILL_DESCRIPTION_REQUIRED`,message:`Skill frontmatter.description is required — it is the primary triggering surface (when to use the skill).`}}:e.description.length>DESCRIPTION_MAX?{ok:!1,error:{code:`DESCRIPTION_TOO_LONG`,message:`Skill frontmatter.description must be ≤${DESCRIPTION_MAX} characters (got ${e.description.length}).`}}:containsXmlTag(e.description)?{ok:!1,error:{code:`XML_TAG_IN_DESCRIPTION`,message:"Skill frontmatter.description may not contain XML tags (`<...>`) — they break the Cowork parser and skill loader."}}:{ok:!0}:{ok:!1,error:{code:`NAME_DIR_MISMATCH`,message:`Skill frontmatter.name (${JSON.stringify(e.name)}) must equal the skill directory name (${JSON.stringify(t)}).`}}}function skillPaths(e,t){let s=join(e,t);return{skillDir:s,filePath:join(s,SKILL_FILE)}}function cleanEmptyDirs(e){if(existsSync(e)&&isEmpty$1(e))try{rmdirSync(e)}catch{}let t=normalize(join(e,`..`));if(t.endsWith(`${sep}.ok`)&&existsSync(t)&&isEmpty$1(t))try{rmdirSync(t)}catch{}}function relPathOf$1(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function serializeFrontmatter(e){return(0,import_dist$1.stringify)({name:e.name,description:e.description})}function isEmpty$1(e){try{return readdirSync(e).length===0}catch{return!1}}const SUBSTITUTION_ALLOWLIST=[`date`,`user`],TOKEN_PATTERN=/\{\{([^{}\n]+?)\}\}/g;function validateSubstitution(e){let t=[];for(let s of e.matchAll(TOKEN_PATTERN)){let e=(s[1]??``).trim();isAllowedToken(e)||t.push({token:e,offset:s.index??0})}return t}function applySubstitution(e,t){return e.replace(TOKEN_PATTERN,(e,s)=>{let g=s.trim();return isAllowedToken(g)?t[g]:e})}function isAllowedToken(e){return SUBSTITUTION_ALLOWLIST.includes(e)}function todayIsoUtc(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}const NAME_RE=TEMPLATE_NAME_REGEX;function composeTemplateContent(e){if(!NAME_RE.test(e.name))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(e.name)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let t=validateTitle(e.frontmatter.title);if(!t.ok)return{ok:!1,error:t.error};let s=validateSubstitutionAllowlist(e.body);if(!s.ok)return{ok:!1,error:s.error};let g=validateNoReservedDocKey(e.body);if(!g.ok)return{ok:!1,error:g.error};let S={};e.frontmatter.title!==void 0&&(S.title=e.frontmatter.title),e.frontmatter.description!==void 0&&(S.description=e.frontmatter.description),Array.isArray(e.frontmatter.tags)&&e.frontmatter.tags.length>0&&(S.tags=e.frontmatter.tags);let w=composeTemplateFile(S,e.body),E=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&E.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,content:w,warnings:E}}function applyTemplateWrite(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let s=composeTemplateContent({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!s.ok)return{ok:!1,error:s.error};let{content:g,warnings:S}=s,{templatesDir:w,filePath:E}=templatePaths(e.projectDir,t.folderRel,e.name);try{mkdirSync(w,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${relPathOf(e.projectDir,w)}: ${t.message}`}}}let D=!existsSync(E),O=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(O,g,`utf-8`),renameSync(O,E)}catch(t){try{unlinkSync(O)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${relPathOf(e.projectDir,E)}: ${t.message}`}}}return{ok:!0,path:relPathOf(e.projectDir,E),created:D,warnings:S}}function applyTemplateDelete(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:s,okDir:g,filePath:S}=templatePaths(e.projectDir,t.folderRel,e.name),w=existsSync(S);if(w)try{unlinkSync(S)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${relPathOf(e.projectDir,S)}: ${t.message}`}}}return{ok:!0,path:relPathOf(e.projectDir,S),existed:w,cleanedEmpty:cleanEmptyOkDirs(s,g)}}function cleanEmptyOkDirs(e,t){let s=!1,g=!1;if(existsSync(e)&&isEmpty(e))try{rmdirSync(e),s=!0}catch{}if(existsSync(t)&&isEmpty(t))try{rmdirSync(t),g=!0}catch{}return{templatesDir:s,okDir:g}}async function applyTemplateMove(e){let t=validateInputs(e.projectDir,e.fromFolder,e.fromName);if(!t.ok)return{ok:!1,error:t.error};let s=validateInputs(e.projectDir,e.toFolder,e.toName);if(!s.ok)return{ok:!1,error:s.error};let g=templatePaths(e.projectDir,t.folderRel,e.fromName),S=templatePaths(e.projectDir,s.folderRel,e.toName);if(g.filePath===S.filePath)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same template.`}};if(!existsSync(g.filePath))return{ok:!1,error:{code:`TEMPLATE_NOT_FOUND`,message:`No template at ${relPathOf(e.projectDir,g.filePath)}.`}};if(existsSync(S.filePath))return{ok:!1,error:{code:`TEMPLATE_EXISTS`,message:`A template already exists at ${relPathOf(e.projectDir,S.filePath)}.`}};try{mkdirSync(S.templatesDir,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create destination template directory at ${relPathOf(e.projectDir,S.templatesDir)}: ${t.message}`}}}let w;try{w=await e.relocate(g.filePath,S.filePath)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move template: ${e.message}`}}}let E=cleanEmptyOkDirs(g.templatesDir,g.okDir);return{ok:!0,fromPath:relPathOf(e.projectDir,g.filePath),toPath:relPathOf(e.projectDir,S.filePath),committed:w,cleanedEmpty:E}}function validateInputs(e,t,s){if(!isAbsolute(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!NAME_RE.test(s))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(s)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let g=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(g.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let S=g?resolve(e,g):e,w=resolve(e);return!S.startsWith(w+sep)&&S!==w?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${S}`}}:{ok:!0,folderRel:g}}function validateTitle(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function validateSubstitutionAllowlist(e){let t=validateSubstitution(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function templatePaths(e,t,s){let g=t?join(e,t,`.ok`):join(e,`.ok`),S=join(g,`templates`);return{okDir:g,templatesDir:S,filePath:join(S,`${s}.md`)}}function relPathOf(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function validateNoReservedDocKey(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return{ok:!0};let s=unwrapFrontmatterFences(t);return RegExp(`^template:`,`m`).test(s)?{ok:!1,error:{code:`TEMPLATE_RESERVED_KEY`,message:`Template starter content may not declare a top-level \`${TEMPLATE_IDENTITY_KEY}:\` frontmatter key — it is reserved for the template's identity.`}}:{ok:!0}}function isEmpty(e){try{return readdirSync(e).length===0}catch{return!1}}var RingBuffer=class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let s=1;s<=t;s++){let t=(this.writeIndex-s+this.capacity)%this.capacity,g=this.store[t];g!==void 0&&e.push(g)}return e}get size(){return this.filled?this.capacity:this.writeIndex}};const embedProbeRing=new RingBuffer(256);function recordEmbedProbe(e){embedProbeRing.push(e)}const CURSOR_UA_RE=UA_PATTERNS.cursor,CODEX_UA_RE=UA_PATTERNS.codex,CLAUDE_UA_RE=UA_PATTERNS[`claude-desktop`],CURSOR_REFERER_STRATEGY_LITERAL=`?strategy=C_iframe`,EMPTY_DETECTION={app:null,signals_fired:[]};function deriveDetection(e){if(!e)return{...EMPTY_DETECTION};let t=[],s=e.ua,g=e.referer,S=!!s&&CURSOR_UA_RE.test(s),w=!!g&&g.includes(CURSOR_REFERER_STRATEGY_LITERAL);if(S&&t.push(`cursor_ua_regex`),w&&t.push(`cursor_referer_strategy_iframe`),S||w)return{app:`cursor`,signals_fired:t};let E=!!s&&CODEX_UA_RE.test(s);if(E&&t.push(`codex_ua_regex`),E)return{app:`codex`,signals_fired:t};let D=!!s&&CLAUDE_UA_RE.test(s);return D&&t.push(`claude_ua_regex`),D?{app:`claude`,signals_fired:t}:{...EMPTY_DETECTION}}const log$14=getLogger(`embeddings`);let _tokens=null,_errors=null,_requestDuration=null,_queryTotal=null,_queryEmbedDuration=null;function tokensCounter(){return _tokens||=getMeter().createCounter(`ok.embeddings.tokens_total`,{description:`Embeddings tokens billed, by role. Bounded label: role ∈ {query, document}. Makes spend legible; never includes content.`}),_tokens}function errorsCounter(){return _errors||=getMeter().createCounter(`ok.embeddings.provider_errors_total`,{description:`Embeddings provider failures, by reason. Bounded label: reason ∈ {rate_limit, timeout, http_error, network, dims_mismatch, malformed_response}.`}),_errors}function requestDurationHist(){return _requestDuration||=getMeter().createHistogram(`ok.embeddings.request_duration_ms`,{description:`Wall-clock duration of one embeddings API request. Bounded label: role.`,unit:`ms`}),_requestDuration}function queryTotalCounter(){return _queryTotal||=getMeter().createCounter(`ok.search.semantic_query_total`,{description:`Semantic-requested searches, by outcome and caller surface. Bounded labels: outcome ∈ {applied, no_match, warming, incapable, provider_error}, source ∈ {omnibar, mcp, http}. The omnibar/mcp split separates interactive cost from agent cost.`}),_queryTotal}function queryEmbedDurationHist(){return _queryEmbedDuration||=getMeter().createHistogram(`ok.search.semantic_query_embed_ms`,{description:`Wall-clock latency of the per-query embed on the semantic search path.`,unit:`ms`}),_queryEmbedDuration}function recordEmbeddingTokens(e,t){t>0&&tokensCounter().add(t,{role:e})}function recordEmbeddingProviderError(e){errorsCounter().add(1,{reason:e})}function recordEmbeddingRequestDuration(e,t){requestDurationHist().record(Math.max(0,t),{role:e})}function recordSemanticQuery(e){queryTotalCounter().add(1,{outcome:e.outcome,source:e.source}),e.queryEmbedMs!==null&&queryEmbedDurationHist().record(Math.max(0,e.queryEmbedMs)),log$14.debug({outcome:e.outcome,source:e.source,capable:e.capable,embedded:e.embedded,total:e.total,coverage:e.total>0?e.embedded/e.total:0,queryEmbedMs:e.queryEmbedMs,vectorContributors:e.vectorContributors},`[search] semantic query`)}const DEFAULT_EMBEDDINGS_DIMENSIONS=1536,EMBEDDINGS_API_KEY_ENV=`OK_EMBEDDINGS_API_KEY`;var EmbeddingDimsMismatchError=class extends Error{name=`EmbeddingDimsMismatchError`;constructor(e,t){super(`embeddings provider returned ${t}-dim vectors, expected ${e}. Set search.semantic.dimensions to ${t} (or point at the right model).`),this.expected=e,this.got=t}},MalformedEmbeddingResponseError=class extends Error{name=`MalformedEmbeddingResponseError`;constructor(e,t){super(`embeddings response had ${t} vectors, expected ${e}`)}};function cosineSimilarity(e,t){let s=0,g=Math.min(e.length,t.length);for(let S=0;S<g;S++)s+=e[S]*t[S];return s}function normalizeInPlace(e){let t=0;for(let s=0;s<e.length;s++)t+=e[s]*e[s];if(t=Math.sqrt(t),t>0)for(let s=0;s<e.length;s++)e[s]/=t;return e}const DEFAULTS={maxBatchSize:96,maxBatchChars:96e3,docTimeoutMs:3e4,queryTimeoutMs:8e3,maxRetries:4,backoffBaseMs:500};function normalizeProviderId(e){try{let t=new URL(e),s=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${s}`}catch{return e.trim().replace(/\/+$/,``)}}function assertSafeEmbeddingsBaseUrl(e){let t;try{t=new URL(e)}catch{throw Error(`embeddings baseUrl is not a valid URL: ${e}`)}if(t.protocol===`https:`)return;let s=t.hostname.toLowerCase(),g=s===`localhost`||s===`127.0.0.1`||s===`::1`||s===`[::1]`;if(!(t.protocol===`http:`&&g))throw Error(`refusing to send the embeddings API key to a non-HTTPS endpoint (${t.protocol}//${t.host}); use https:// (http:// is allowed only for localhost)`)}const RETRYABLE_STATUS=new Set([408,409,429,500,502,503,504]);function defaultSleep$1(e){return new Promise(t=>setTimeout(t,e))}function createOpenAiEmbedder(e,t={}){let s=t.fetchImpl??fetch,g=t.sleep??defaultSleep$1,S=t.maxBatchSize??DEFAULTS.maxBatchSize,w=t.maxBatchChars??DEFAULTS.maxBatchChars,E=t.maxRetries??DEFAULTS.maxRetries,D=t.backoffBaseMs??DEFAULTS.backoffBaseMs,O=t.docTimeoutMs??DEFAULTS.docTimeoutMs,k=t.queryTimeoutMs??DEFAULTS.queryTimeoutMs;assertSafeEmbeddingsBaseUrl(e.baseUrl);let j=e.dimensions??1536,F=`${e.baseUrl.replace(/\/+$/,``)}/embeddings`;function L(e){let t=[],s=[],g=0;for(let E of e)s.length>0&&(s.length>=S||g+E.length>w)&&(t.push(s),s=[],g=0),s.push(E),g+=E.length;return s.length>0&&t.push(s),t}async function B(t,g,S,w){let E=new AbortController,D=setTimeout(()=>E.abort(),w),O=performance.now();try{let w=await s(F,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.apiKey}`},body:t,signal:E.signal});if(recordEmbeddingRequestDuration(S,performance.now()-O),!w.ok){await w.text().catch(()=>``);let e=w.status===429?`rate_limit`:`http_error`,t=Error(`embeddings request failed: HTTP ${w.status}`);return RETRYABLE_STATUS.has(w.status)?{kind:`retry`,reason:e,error:t}:{kind:`fatal`,reason:e,error:t}}let D=await w.json(),k=q(D,g,j);return recordEmbeddingTokens(S,D.usage?.total_tokens??0),{kind:`ok`,vectors:k}}catch(e){if(e instanceof EmbeddingDimsMismatchError)return{kind:`fatal`,reason:`dims_mismatch`,error:e};if(e instanceof MalformedEmbeddingResponseError)return{kind:`fatal`,reason:`malformed_response`,error:e};let t=e instanceof Error&&e.name===`AbortError`,s=e instanceof Error?e:Error(String(e));return{kind:`retry`,reason:t?`timeout`:`network`,error:s}}finally{clearTimeout(D)}}async function H(t,s){let S=s===`query`?k:O,w=s===`query`?`query`:`document`,j=JSON.stringify({model:e.model,input:t,encoding_format:`float`,...e.dimensions===void 0?{}:{dimensions:e.dimensions}}),F=0;for(;;){let e=await B(j,t.length,w,S);if(e.kind===`ok`)return e.vectors;if(recordEmbeddingProviderError(e.reason),e.kind===`fatal`||F>=E)throw e.error;F+=1;let s=D*2**(F-1);await g(Math.round(s/2+s/2*Math.random()))}}function q(e,t,s){let g=e.data;if(!Array.isArray(g)||g.length!==t)throw new MalformedEmbeddingResponseError(t,g?.length??0);let S=[...g].sort((e,t)=>(e.index??0)-(t.index??0)),w=[];for(let e of S){let g=e.embedding;if(!Array.isArray(g))throw new MalformedEmbeddingResponseError(t,0);if(g.length!==s)throw new EmbeddingDimsMismatchError(s,g.length);w.push(normalizeInPlace(Float32Array.from(g)))}return w}return{providerId:normalizeProviderId(e.baseUrl),modelId:e.model,dims:j,async embed(e,{role:t}){if(e.length===0)return[];let s=[];for(let g of L(e))s.push(...await H(g,t));return s}}}async function loadOpenAiEmbedder(e){let t=(e.keyStore?await e.keyStore.get().catch(()=>null):null)??process.env.OK_EMBEDDINGS_API_KEY??null;return t?createOpenAiEmbedder({...e.config,apiKey:t},e.options):null}const SECRETS_KEY_FIELD=`OPENAI_API_KEY`,LEGACY_KEY_FIELD=`embeddings`;function secretsFilePath(e){return join(e??homedir(),`.ok`,`secrets.yml`)}var FileEmbeddingsBackend=class{backend=`file`;secretsFile;constructor(e){this.secretsFile=e??secretsFilePath()}tightenPermsIfLoose(){let e;try{e=statSync(this.secretsFile).mode&511}catch{return}if(e&63)try{chmodSync(this.secretsFile,384),process.stderr.write(`[embeddings] ${this.secretsFile} was readable beyond your user account (mode ${e.toString(8)}); tightened to 600. It stores an API key.\n`)}catch(t){let s=t instanceof Error?t.message:`unknown error`;process.stderr.write(`[embeddings] ${this.secretsFile} is readable beyond your user account (mode ${e.toString(8)}) and could not be tightened (${s}); your API key remains exposed — run: chmod 600 ${this.secretsFile}\n`)}}read(){if(!existsSync(this.secretsFile))return{};this.tightenPermsIfLoose();try{return(0,import_dist$1.parse)(readFileSync(this.secretsFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[embeddings] Failed to parse ${this.secretsFile}: ${t}. Starting with empty secrets.\n`),{}}}write(e){let t=dirname(this.secretsFile);existsSync(t)||tracedMkdirSync(t,{recursive:!0,mode:448}),tracedWriteFileSync(this.secretsFile,(0,import_dist$1.stringify)(e),{mode:384}),chmodSync(this.secretsFile,384)}get(){let e=this.read(),t=e[SECRETS_KEY_FIELD]??e[LEGACY_KEY_FIELD];return Promise.resolve(typeof t==`string`&&t!==``?t:null)}set(e){let t=this.read();return delete t[LEGACY_KEY_FIELD],t[SECRETS_KEY_FIELD]=e,this.write(t),Promise.resolve()}clear(){let e=this.read();if(SECRETS_KEY_FIELD in e||LEGACY_KEY_FIELD in e)if(delete e[SECRETS_KEY_FIELD],delete e[LEGACY_KEY_FIELD],Object.keys(e).length===0)try{tracedUnlinkSync(this.secretsFile)}catch{}else this.write(e);return Promise.resolve()}};function createEmbeddingsSecretStore(e){return new FileEmbeddingsBackend(e)}function makeLazyEmbeddingsKeyStore(e){return new FileEmbeddingsBackend(e)}async function describeStoredEmbeddingsKey(e){return{file:await new FileEmbeddingsBackend(e).get()!=null}}async function clearEmbeddingsKeyFromAllBackends(e){let t=[],s=new FileEmbeddingsBackend(e);return await s.get()!=null&&(await s.clear(),t.push(`file`)),{touched:t}}function readProjectLocalSemanticConfig(e,t){let s=readConfigSafely({absPath:resolveConfigPath(`project-local`,e,t?.configHomedirOverride),sideline:!1,warn:t?.onWarn??(()=>{})}).value.search?.semantic;return{enabled:s?.enabled===!0,baseUrl:s?.baseUrl??`https://api.openai.com/v1`,model:s?.model??`text-embedding-3-small`,dimensions:s?.dimensions??void 0,similarityFloor:s?.similarityFloor??void 0}}const CHUNK_CONFIG_ID=`c8000-o400-m80`;function chunkDocument(e,t={}){let s=Math.max(1,t.targetChars??8e3),g=Math.max(0,Math.min(t.overlapChars??400,s-1)),S=t.maxChunks??80;if(e.trim().length===0)return[];if(e.length<=s)return[e.trim()];let w=[],E=0;for(;E<e.length&&w.length<S;){let t=Math.min(e.length,E+s);if(t<e.length){let g=Math.max(e.lastIndexOf(` `,t),e.lastIndexOf(`
824
824
  `,t));g>E+Math.floor(s/2)&&(t=g)}let S=e.slice(E,t).trim();if(S&&w.push(S),t>=e.length)break;let D=t-g;E=D>E?D:t}return w}const log$13=getLogger(`embeddings`),MANIFEST_SCHEMA_VERSION=1,VEC_SUBDIR=`vec`,MANIFEST_NAME=`manifest.json`;function hashContent(e){return createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function serializeVectors(e){let t=0;for(let s of e)t+=s.length;let s=new Float32Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function deserializeVectors(e,t){let s=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),g=new Float32Array(s);if(g.length%t!==0)throw Error(`vector blob length ${g.length} is not a multiple of dims ${t}`);let S=[];for(let e=0;e<g.length;e+=t)S.push(g.slice(e,e+t));return S}var VectorCache=class{cacheDir;vecDir;manifestPath;providerId;modelId;dims;chunkConfigId;entries=new Map;vectorsByHash=new Map;persistedHashes=new Set;dirty=!1;constructor(e){this.cacheDir=e.cacheDir,this.vecDir=e.cacheDir?join(e.cacheDir,VEC_SUBDIR):null,this.manifestPath=e.cacheDir?join(e.cacheDir,MANIFEST_NAME):null,this.providerId=e.providerId,this.modelId=e.modelId,this.dims=e.dims,this.chunkConfigId=e.chunkConfigId}async init(){if(!this.cacheDir||!this.manifestPath||!this.vecDir)return;let e=null;try{existsSync(this.manifestPath)&&(e=JSON.parse(await readFile$1(this.manifestPath,`utf-8`)))}catch(t){log$13.warn({err:t instanceof Error?t.message:String(t)},`[embeddings] unreadable cache manifest — rebuilding`),e=null}if(!(e!==null&&e.schemaVersion===MANIFEST_SCHEMA_VERSION&&e.providerId===this.providerId&&e.modelId===this.modelId&&e.dims===this.dims&&e.chunkConfigId===this.chunkConfigId)){e!==null&&log$13.info({hadModel:e.modelId,wantModel:this.modelId},`[embeddings] cache identity changed (provider/model/dims/chunking) — invalidating`),this.wipeDisk();return}if(e){for(let[t,s]of Object.entries(e.entries))if(s?.contentHash&&(this.entries.set(t,{contentHash:s.contentHash,mtimeMs:s.mtimeMs??0}),!this.vectorsByHash.has(s.contentHash)))try{let e=join(this.vecDir,`${s.contentHash}.bin`);if(existsSync(e)){let t=await readFile$1(e);this.vectorsByHash.set(s.contentHash,deserializeVectors(t,this.dims)),this.persistedHashes.add(s.contentHash)}}catch(e){log$13.warn({hash:s.contentHash,err:e instanceof Error?e.message:String(e)},`[embeddings] corrupt vector blob — will re-embed`)}}}isFresh(e,t){let s=this.entries.get(e);return s!==void 0&&s.mtimeMs===t&&this.vectorsByHash.has(s.contentHash)}link(e,t,s){if(!this.vectorsByHash.has(t))return!1;let g=this.entries.get(e);return(!g||g.contentHash!==t||g.mtimeMs!==s)&&(this.dirty=!0),this.entries.set(e,{contentHash:t,mtimeMs:s}),!0}store(e,t,s,g){this.vectorsByHash.set(t,g),this.entries.set(e,{contentHash:t,mtimeMs:s}),this.dirty=!0}getVectors(e){let t=this.entries.get(e);if(t)return this.vectorsByHash.get(t.contentHash)}get embeddedCount(){let e=0;for(let t of this.entries.values()){let s=this.vectorsByHash.get(t.contentHash);s&&s.length>0&&(e+=1)}return e}retain(e){for(let t of this.entries.keys())e.has(t)||(this.entries.delete(t),this.dirty=!0);let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of this.vectorsByHash.keys())t.has(e)||this.vectorsByHash.delete(e)}clearMemory(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.dirty=!1}async persist(){if(!(!this.cacheDir||!this.manifestPath||!this.vecDir)&&this.dirty)try{await tracedMkdir(this.vecDir,{recursive:!0});let e=new Set;for(let t of this.entries.values())e.add(t.contentHash);for(let t of e){if(this.persistedHashes.has(t))continue;let e=this.vectorsByHash.get(t);e&&(await tracedWriteFile(join(this.vecDir,`${t}.bin`),serializeVectors(e)),this.persistedHashes.add(t))}let t={schemaVersion:MANIFEST_SCHEMA_VERSION,providerId:this.providerId,modelId:this.modelId,dims:this.dims,chunkConfigId:this.chunkConfigId,entries:Object.fromEntries(this.entries)},s=`${this.manifestPath}.tmp`;await tracedWriteFile(s,JSON.stringify(t)),await tracedRename(s,this.manifestPath);for(let t of readdirSync(this.vecDir)){if(!t.endsWith(`.bin`))continue;let s=t.slice(0,-4);e.has(s)||(tracedUnlinkSync(join(this.vecDir,t)),this.persistedHashes.delete(s))}this.dirty=!1}catch(e){log$13.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to persist vector cache`)}}wipeDisk(){if(this.cacheDir)try{tracedRmSync(this.cacheDir,{recursive:!0,force:!0})}catch(e){log$13.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to wipe stale cache`)}}};const log$12=getLogger(`embeddings`);function errMsg(e){return e instanceof Error?e.message:String(e)}const EMBED_BATCH_CHUNK_LIMIT=96,MAX_CONSECUTIVE_EMBED_FAILURES=5;var SemanticSearchService=class{loadEmbedder;cacheDir;enabled;providerFingerprint;capable=!1;ready=!1;embedder=null;cache=null;warmPromise=null;embedChain=Promise.resolve();queuedDocs=null;constructor(e){this.loadEmbedder=e.loadEmbedder,this.cacheDir=e.cacheDir,this.enabled=e.enabled??!1,this.providerFingerprint=e.providerFingerprint??``}isEnabled(){return this.enabled}getStatus(){return{enabled:this.enabled,capable:this.capable,ready:this.ready,embeddedCount:this.cache?.embeddedCount??0}}applyConfig(e){e.providerFingerprint!==this.providerFingerprint&&(this.providerFingerprint=e.providerFingerprint,this.resetWarm()),e.enabled!==this.enabled&&(this.enabled=e.enabled,e.enabled||(this.cache?.clearMemory(),this.resetWarm()))}resetWarm(){this.warmPromise=null,this.ready=!1,this.capable=!1,this.embedder=null,this.cache=null}ensureWarm(){return!this.enabled||this.ready?Promise.resolve():(this.warmPromise||=this.warm(),this.warmPromise)}async warm(){try{let e=await this.loadEmbedder();if(!e){this.capable=!1,this.ready=!0,log$12.info({},`[embeddings] no embeddings key configured — semantic search degrades to lexical`);return}this.embedder=e,this.cache=new VectorCache({cacheDir:this.cacheDir,providerId:e.providerId,modelId:e.modelId,dims:e.dims,chunkConfigId:CHUNK_CONFIG_ID}),await this.cache.init(),this.capable=!0,this.ready=!0}catch(e){this.capable=!1,this.ready=!0,log$12.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] warm failed`)}}embedCorpus(e){return this.enabled?(this.queuedDocs=e,this.embedChain=this.embedChain.then(async()=>{let e=this.queuedDocs;if(e){this.queuedDocs=null;try{await this.runEmbedPass(e)}catch(e){log$12.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] embed pass failed`)}}}),this.embedChain):Promise.resolve()}async runEmbedPass(e){if(await this.ensureWarm(),!this.enabled||!this.embedder||!this.cache)return;let t=this.cache,s=this.embedder,g=e.filter(e=>e.kind===`page`),S=new Set(g.map(e=>e.id)),w=[];for(let e of g){if(!this.enabled)return;let s=e.modifiedTs;if(t.isFresh(e.id,s))continue;let g=hashContent(e.content);t.link(e.id,g,s)||w.push({doc:e,contentHash:g,chunks:chunkDocument(e.content)})}let E=0,D=(e,s)=>{t.store(e.doc.id,e.contentHash,e.doc.modifiedTs,s)},O=async e=>{let t=e.flatMap(e=>e.chunks);try{let g=t.length?await s.embed(t,{role:`document`}):[],S=0;for(let t of e)D(t,g.slice(S,S+t.chunks.length)),S+=t.chunks.length;return E=0,!0}catch(t){if(e.length===1)return log$12.warn({docId:e[0].doc.id,err:errMsg(t)},`[embeddings] failed to embed document`),E+=1,E<MAX_CONSECUTIVE_EMBED_FAILURES;for(let t of e){if(!this.enabled)return!1;try{D(t,t.chunks.length?await s.embed(t.chunks,{role:`document`}):[]),E=0}catch(e){if(log$12.warn({docId:t.doc.id,err:errMsg(e)},`[embeddings] failed to embed document`),E+=1,E>=MAX_CONSECUTIVE_EMBED_FAILURES)return!1}}return!0}},k=[],j=0;for(let e of w){if(!this.enabled)break;if(k.push(e),j+=Math.max(1,e.chunks.length),j>=EMBED_BATCH_CHUNK_LIMIT){let e=await O(k);if(k=[],j=0,!e)break}}k.length>0&&this.enabled&&await O(k),!(!this.enabled||this.cache!==t)&&(t.retain(S),await t.persist())}async queryScores(e,t){if(!this.enabled||!this.capable||!this.ready||!this.embedder||!this.cache||this.cache.embeddedCount===0)return null;let s=e.trim();if(!s)return null;let g;try{[g]=await this.embedder.embed([s],{role:`query`})}catch(e){return log$12.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] query embed failed — degrading to lexical`),null}if(!g)return null;let S=new Map;for(let e of t){let t=this.cache.getVectors(e.id);if(!t||t.length===0)continue;let s=-1/0;for(let e of t){let t=cosineSimilarity(g,e);t>s&&(s=t)}s>-1/0&&S.set(e.id,s)}return S}};const log$11=()=>getLogger(`http`);function successResponse(e,t,s,g,S={}){if(e.headersSent||e.writableEnded||e.destroyed){log$11().error({event:`api.success.double-write`,status:t,handler:S.handler},`successResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let w=s.safeParse(g);if(!w.success){log$11().error({event:`api.success.malformed-body`,issues:w.error.issues,bodyKeys:typeof g==`object`&&g?Object.keys(g):null,handler:S.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}let E;try{E=JSON.stringify(w.data)}catch(s){log$11().error({event:`api.success.unserializable-body`,bodyKeys:typeof w.data==`object`&&w.data!==null?Object.keys(w.data):null,handler:S.handler,originalStatus:t,err:s},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(E)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,s=e.now??Date.now,g=e.ttlMs??6e4;async function S(S){let w=t.get(S);if(w?.status===`resolved`&&w.expiresAt>s())return w.installed;if(w?.status===`inflight`)return w.promise;let E=(async()=>{try{let w=await e.probe(S);return t.set(S,{status:`resolved`,installed:w,expiresAt:s()+g}),w}catch{return t.set(S,{status:`resolved`,installed:!1,expiresAt:s()+g}),!1}})();return t.set(S,{status:`inflight`,promise:E}),E}async function w(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await S(e)]));return Object.fromEntries(e)}return{probeAll:w,probeWithCache:S}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let s=e.headers.origin;if(typeof s==`string`&&s.length>0)try{return isLoopbackHostname(new URL(s).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await s():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return s=>e===`darwin`?probeMacOs(s,t):e===`win32`?probeWindows(s,t):probeLinux(s,t)}function probeMacOs(e,t){let s=MACOS_APP_NAMES[e];function g(e){return new Promise(s=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}return(async()=>{for(let e of s)if(await g(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(s=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{s(!e)})})}function probeLinux(e,t){return new Promise(s=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let s=[],g=0,S=AbortSignal.timeout(t.timeoutMs),w=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));S.addEventListener(`abort`,w,{once:!0});try{for await(let S of e){if(g+=S.length,g>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);s.push(S)}return Buffer.concat(s)}finally{S.removeEventListener(`abort`,w)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,s,g={}){let S=e.safeParse(t);if(S.success)return{ok:!0,value:S.data};let w=S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(s,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:g.handler,detail:w}),{ok:!1}}function withValidation(e,t,s={}){return async(g,S)=>{if(s.method!==void 0&&g.method!==s.method){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:s.handler,extraHeaders:{Allow:s.method}});return}if(s.preBodyGate!==void 0&&!s.preBodyGate(g,S)){!S.headersSent&&!S.writableEnded&&!S.destroyed&&errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(s.skipBodyParse){let w=validateBody(e,{},S,s);if(!w.ok)return;await t(g,S,w.value);return}let w;try{w=await readRequestBody(g)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(S,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(S,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s.handler,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s.handler,cause:e});return}let E;try{E=w.length===0?{}:JSON.parse(w.toString(`utf8`))}catch(e){errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:s.handler,cause:e});return}let D=validateBody(e,E,S,s);D.ok&&await t(g,S,D.value)}}function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,s){return new Promise(g=>{let S=!1,w=e=>{S||(S=!0,g(e))},E=setTimeout(()=>w({ok:!1,reason:`timeout`}),s);try{let s=spawn(e,[...t],{detached:!0,stdio:`ignore`,shell:!1});s.once(`error`,e=>{clearTimeout(E),w(classifySpawnError(e))}),s.once(`spawn`,()=>{if(!S){try{s.unref()}catch{}clearTimeout(E),w({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(E),w(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let w=typeof S.path==`string`?S.path:``;if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(w,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let E=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!E){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let D=resolveCursorSpawnInvocation(E,w,s.platform),O=await(s.spawnDetached??spawnDetached)(D.exec,D.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(O.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(O.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(O.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let s of t){let t=s(e);try{return await access(t,constants$1.X_OK),t}catch(e){let s=e?.code;s!==`ENOENT`&&s!==`EACCES`&&s!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,s,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],{timeout:e,encoding:`utf-8`},(e,s)=>{if(e){t(null);return}let g=s.split(/\r?\n/)[0]?.trim();t(g&&g.length>0?g:null)})})}function resolveCursorSpawnInvocation(e,t,s){return s===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:s===`win32`&&/\.(cmd|bat)$/i.test(e)?{exec:process.env.ComSpec||`cmd.exe`,args:[`/d`,`/c`,e,t]}:{exec:e,args:[t]}}function isPathWithinDir(e,t,s){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(s===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let g=s===`win32`?win32:posix;try{let S=g.resolve(e),w=g.resolve(t);if(s===`win32`){let e=g.parse(S).root.toLowerCase(),t=g.parse(w).root.toLowerCase();if(!e||!t||e!==t)return!1}if(S===w)return!0;let E=g.relative(w,S);return E===``||E===`.`?!0:!(E===`..`||E.startsWith(`..${g.sep}`)||s===`win32`&&(/^[a-zA-Z]:[\\/]/.test(E)||E.startsWith(`\\\\`))||s!==`win32`&&E.startsWith(`/`))}catch(e){return console.warn(`[spawn-cursor] unexpected path-resolution error:`,e),!1}}const HANDLER=`handoff`,HANDOFF_MAX_BODY_BYTES=4*1024,HANDOFF_BODY_READ_TIMEOUT_MS=5e3,SPAWN_TIMEOUT_MS$1=2e3,WHICH_TIMEOUT_MS=500,QUIT_SETTLE_MS=3e3,APP_BUNDLE_SETTLE_MS=5e3,CURSOR_SETTLE_MS=1500,RECIPES={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},TARGET_VALUES=Object.keys(RECIPES),HandoffRequestSchema=object$1({target:_enum(TARGET_VALUES),url:string().min(1).max(4096),workspacePath:string().optional()}),HandoffSuccessSchema=object$1({}).loose();function defaultSleep(e){return new Promise(t=>setTimeout(t,e))}async function handleHandoffDispatch(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:HANDOFF_MAX_BODY_BYTES,timeoutMs:HANDOFF_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER,cause:e});return}let w=HandoffRequestSchema.safeParse(S);if(!w.success){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:HANDLER});return}let{target:E,url:D,workspacePath:O}=w.data,k=RECIPES[E];if(!D.startsWith(k.urlScheme)){errorResponse(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${k.urlScheme} for target ${E}.`,{handler:HANDLER});return}let j=s.sleep??defaultSleep,F=s.spawnDetached??spawnDetached,L=s.isSchemeRegistered??createOsProbe(s.platform);if(k.type===`app-bundle`){if(s.platform===`darwin`){k.quitFirst&&(await F(`/usr/bin/osascript`,[`-e`,`tell application "${k.appName}" to quit`],SPAWN_TIMEOUT_MS$1).catch(()=>void 0),await j(QUIT_SETTLE_MS));let e=await F(`/usr/bin/open`,[`-a`,k.appName],SPAWN_TIMEOUT_MS$1);if(!e.ok){emitSpawnFailure(t,E,e.reason);return}await j(APP_BUNDLE_SETTLE_MS)}else if(!await L(k.probeScheme)){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:E}});return}let e=resolveUrlOpenInvocation(D,s.platform),g=await F(e.exec,e.args,SPAWN_TIMEOUT_MS$1);if(!g.ok){emitSpawnFailure(t,E,g.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER});return}if(!O){errorResponse(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:HANDLER});return}if(!isPathWithinDir(O,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER});return}let B=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!B){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let H=resolveCursorSpawnInvocation(B,O,s.platform),q=await F(H.exec,H.args,SPAWN_TIMEOUT_MS$1);if(!q.ok){emitSpawnFailure(t,E,q.reason);return}await j(CURSOR_SETTLE_MS);let ee=resolveUrlOpenInvocation(D,s.platform),J=await F(ee.exec,ee.args,SPAWN_TIMEOUT_MS$1);if(!J.ok){emitSpawnFailure(t,E,J.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}function resolveUrlOpenInvocation(e,t){return t===`darwin`?{exec:`/usr/bin/open`,args:[e]}:t===`win32`?{exec:`rundll32.exe`,args:[`url.dll,FileProtocolHandler`,e]}:{exec:`xdg-open`,args:[e]}}function emitSpawnFailure(e,t,s){switch(s){case`not-installed`:errorResponse(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:t}});return;case`timeout`:errorResponse(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:HANDLER,extensions:{target:t}});return;case`spawn-error`:errorResponse(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:HANDLER,extensions:{target:t}});return;default:assertNeverReason(s)}}function assertNeverReason(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let s=[],g=new Set,S=t=>{!t||g.has(t)||t!==e&&(g.add(t),s.push(t))},w=buildLowerDocNameIndex(t),E=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES)return s;let e=E===``?null:basename$1(E);if(e&&(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES))return s;if(E===``)break;E=parentFolder(E)}return s}function lookup$1(e,t,s){return e.has(s)?s:t.get(s.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let s of e.keys()){let e=s.toLowerCase();t.has(e)||t.set(e,s)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}const logger$4=getLogger(`installed-skills-marker`),TRACED_FS_ADAPTER={writeFile:(e,t,s)=>tracedWriteFile(e,t,s),rename:(e,t)=>tracedRename(e,t)};function installedSkillsPath(e){return join(e,...INSTALLED_SKILLS_REL)}const markerWriteChains=new Map;function withMarkerLock(e,t){let s=installedSkillsPath(e),g=(markerWriteChains.get(s)??Promise.resolve()).then(t,t);return markerWriteChains.set(s,g.then(()=>void 0,()=>void 0)),g}function readInstalledSkills(e){let t=installedSkillsPath(e);if(!existsSync(t))return emptyInstalledSkills();try{return parseInstalledSkills(readFileSync(t,`utf-8`))??emptyInstalledSkills()}catch(e){return logger$4.warn({err:e,path:t},`installed-skills marker unreadable`),emptyInstalledSkills()}}async function writeInstalledSkills(e,t){let s=InstalledSkillsSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid installed-skills marker: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=installedSkillsPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s.data,null,2)}\n`,{fs:TRACED_FS_ADAPTER})}async function recordSkillInstall(e,t,s){return withMarkerLock(e,async()=>{let g=readInstalledSkills(e);await writeInstalledSkills(e,{...g,skills:{...g.skills,[t]:s}})})}async function removeSkillInstall(e,t){return withMarkerLock(e,async()=>{let s=readInstalledSkills(e),g=s.skills[t]??null;if(g===null)return null;let{[t]:S,...w}=s.skills;return await writeInstalledSkills(e,{...s,skills:w}),g})}const log$10=getLogger(`mermaid-validator`),MAX_FENCE_BYTES=1e5,MAX_FENCE_LINES=2e3,MAX_FENCES_PARSED=20,TOTAL_PARSE_BUDGET_MS=2e3,MAX_WARNINGS=10,MAX_MESSAGE_CHARS=500,MAX_FIRST_LINE_CHARS=200;let initPromise=null;function extractMermaidFences(e){let t=[],s=e.split(`
825
825
  `),g=e=>e.endsWith(`\r`)?e.slice(0,-1):e,S=0;for(;S<s.length;){let e=g(s[S]??``),w=e.match(/^ {0,3}(`{3,}|~{3,})[ \t]*([^\s`]*)/);if(!w){S++;continue}let E=w[1]??``,D=E[0]??"`";if(D==="`"&&e.slice(e.indexOf(E)+E.length).includes("`")){S++;continue}let O=w[2]??``,k=RegExp(`^ {0,3}\\${D}{${E.length},}[ \t]*$`),j=[],F=S+1;for(;F<s.length&&!k.test(g(s[F]??``));)j.push(s[F]??``),F++;if(O===`mermaid`){let e=j.join(`
@@ -1965,8 +1965,8 @@ Change history for this knowledge base, newest entry first. Add a dated entry (\
1965
1965
  `);function applySoftCap(e){let t=e.split(`
1966
1966
  `),s=t[t.length-1]===``?t.length-1:t.length;if(s<=SOFT_CAP_LINES&&e.length<=SOFT_CAP_BYTES)return{text:e,truncated:!1,omittedLines:0};let g=Math.min(s,SOFT_CAP_LINES),S=0,w=0;for(let e=0;e<g;e++){let s=t[e];if(S+=s.length+1,S>SOFT_CAP_BYTES)break;w++}let E=t.slice(0,w).join(`
1967
1967
  `),D=s-w;return{text:`${E}\n<truncated: ${D} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:D}}function detectBinaryArgs(e){let t=[];for(let s of e)if(s.command===`cat`)for(let e of s.args.slice(1))e.startsWith(`-`)||BINARY_EXT_RE.test(e)&&t.push(e);return t}function extractHeadTailLimit(e){for(let t=1;t<e.length;t++){let s=e[t],g=s.match(/^--lines=(\d+)$/);if(g)return Number(g[1]);if(s===`--lines`&&t+1<e.length){let s=Number(e[t+1]);if(Number.isFinite(s))return s}if(s===`-n`&&t+1<e.length){let s=Number(e[t+1]);if(Number.isFinite(s))return s}let S=s.match(/^-n(\d+)$/);if(S)return Number(S[1]);let w=s.match(/^-(\d+)$/);if(w)return Number(w[1])}return 10}function detectHeadTailTruncation(e,t){if(e.length<2)return null;let s=e[e.length-1];if(s.command!==`head`&&s.command!==`tail`)return null;let g=extractHeadTailLimit(s.args),S=t.split(`
1968
- `),w=S[S.length-1]===``?S.length-1:S.length;if(w<g)return null;let E=S.slice(0,w),D=new Set(E.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,O=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${s.command} -${g}\` cap (${w} lines, ${D} unique file${D===1?``:`s`}). The \`${O}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${s.command}\` or widen the cap.`}}function isDirectoryMeta(e){return e.type===`directory`}function formatDirectoryEntry(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`);let s=[];return s.push(`${e.recursiveMdCount} md file${e.recursiveMdCount===1?``:`s`}`),e.childDirCount>0&&s.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(s.join(`, `)),e.mostRecentMd&&t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path})`),e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function formatFileEntry(e){let t=[`**${e.title??e.path}** (${e.path})`];if(e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.backlinkCount!==null&&t.push(`backlinks: ${e.backlinkCount}`),e.forwardLinkCount!==null&&t.push(`forward links: ${e.forwardLinkCount}`),e.history&&e.history.length>0){let s=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${s.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let s=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${s.join(` · `)}`)}return`- ${t.join(` — `)}`}function buildStdoutProvenance(e,t,s,g){let S=null;for(let t=e.length-1;t>=0;t--){let s=e[t],g=s.command;if(g===`ls`||g===`cat`){S=s;break}if((g===`head`||g===`tail`)&&nonFlagArgs(argsOf(s)).length>0){S=s;break}}if(!S)return``;let w=nonFlagArgs(argsOf(S));if(S.command===`ls`){let e=w[w.length-1];if(!e||e===`.`)return``;let s=e.replace(/\/+/g,`/`);if(s.startsWith(`./`)&&(s=s.slice(2)),s.endsWith(`/`)&&(s=s.slice(0,-1)),!s)return``;let S=g(s);return t.has(S)?`${S}/:\n`:``}let E=w.filter(e=>/\.(md|mdx)$/.test(e)&&s.has(g(e)));return E.length===1?`==> ${g(E[0])} <==\n`:``}function formatEnrichedBlock(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let s of e)t.push(isDirectoryMeta(s)?formatDirectoryEntry(s):formatFileEntry(s));return t.join(`
1969
- `)}async function classifyPaths(e,t){let s=[],g=[];return await Promise.all(t.map(async t=>{try{let S=await stat$1(resolve(e,t));S.isDirectory()?g.push(t):S.isFile()&&s.push(t)}catch{/\.(md|mdx)$/i.test(t)&&s.push(t)}})),{files:s,dirs:g}}function errorCategoryResult(e,t){return textPlusStructured(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function withPreviewUrls(e,t){return e.map(e=>{let s=t(docNameFromPath(e.path));return{...e,previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}})}async function buildExecResult(e,t){let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return errorCategoryResult(`shell_construct_blocked`,`exec failed: ${s.error}`);let{cwd:g,executionCwd:S,config:w,url:E}=s,D=S===g?e=>e:e=>relative(g,resolve(S,e)),O=parseCommand(e.command);if(`error`in O)return errorCategoryResult(O.error.category,O.error.message);let k=augmentStagesWithExcludes(O.stages),j=serializeStages(k),F=await snapshotMtimes(S),L=createBashInstance(S),B=``,H=``;try{let e=await execBash(L,j);B=e.stdout,H=e.stderr}catch(e){return e instanceof StdoutOverflowError?errorCategoryResult(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`):errorCategoryResult(`shell_construct_blocked`,`exec failed: ${e instanceof Error?e.message:String(e)}`)}let q=await snapshotMtimes(S),ee=diffMtimes(F.snapshot,q.snapshot);if(ee.changed.length>0)return errorCategoryResult(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${ee.changed.join(`, `)}. This indicates a parser bug; the command has been logged.`);let J=applySoftCap(B),Y=extractReferencedPaths(B,k).filter(e=>resolveWithinRoot(S,e).ok).map(D),{files:te,dirs:ne}=await classifyPaths(g,Y),ae=k.length===1&&k[0].command===`cat`&&te.length===1,oe=await Promise.all(te.map(e=>enrichPath(e,{projectDir:g,serverUrl:E},{includeRichFields:ae}).catch(()=>({path:e,tags:[],frontmatter:{},backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null})))),se=await Promise.all(ne.map(e=>enrichDirectoryRecursive(e,1,{projectDir:g}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!ae&&E&&oe.length>0){let e=await fetchBacklinkCountsBatch(E,oe.map(e=>pathToDocName$1(e.path))).catch(()=>null);if(e)for(let t of oe){let s=e.get(pathToDocName$1(t.path));typeof s==`number`&&(t.backlinkCount=s)}}let ce=new Map(oe.map(e=>[e.path,e])),ue=new Map(se.map(e=>[e.path,e])),de=[];for(let e of Y){let t=ce.get(e);if(t){de.push(t);continue}let s=ue.get(e);s&&de.push(s)}let fe=detectBinaryArgs(k),me=[];fe.length>0&&me.push(`File${fe.length>1?`s`:``} ${fe.join(`, `)} appear${fe.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let ge=detectHeadTailTruncation(k,B);ge&&me.push(ge.banner),H&&me.push(`stderr: ${H.trim()}`);let _e=`${me.length>0?`${me.join(`
1968
+ `),w=S[S.length-1]===``?S.length-1:S.length;if(w<g)return null;let E=S.slice(0,w),D=new Set(E.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,O=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${s.command} -${g}\` cap (${w} lines, ${D} unique file${D===1?``:`s`}). The \`${O}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${s.command}\` or widen the cap.`}}function isDirectoryMeta(e){return e.type===`directory`}function formatDirectoryEntry(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];if(e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.templates_available&&e.templates_available.length>0){let s=e.templates_available.map(e=>e.description?`${e.name} — ${e.description} (${e.scope})`:`${e.name} (${e.scope})`).join(`, `);t.push(`templates: ${s}`)}let s=[];if(s.push(e.recursiveMdCount>e.directMdCount?`${e.directMdCount} md file${e.directMdCount===1?``:`s`} here (${e.recursiveMdCount} in tree)`:`${e.directMdCount} md file${e.directMdCount===1?``:`s`}`),e.childDirCount>0&&s.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(s.join(`, `)),e.mostRecentMd){let s=e.mostRecentMd.updatedAt?`, ${e.mostRecentMd.updatedAt.slice(0,10)}`:``;t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path}${s})`)}return e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function formatFileEntry(e){let t=[`**${e.title??e.path}** (${e.path})`];e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.graphRole&&t.push(`graph: ${e.graphRole}`);let s=typeof e.frontmatter.status==`string`?e.frontmatter.status:null,g=typeof e.frontmatter.type==`string`?e.frontmatter.type:null;if(s&&t.push(`status: ${s}`),g&&t.push(`type: ${g}`),e.backlinkCount!==null){let s=`backlinks: ${e.backlinkCount}`;if(e.backlinks&&e.backlinks.length>0){let t=e.backlinks.slice(0,5).map(e=>e.source);s+=` (${t.join(`, `)}${e.backlinks.length>5?`, …`:``})`}t.push(s)}if(e.forwardLinkCount!==null){let s=`forward links: ${e.forwardLinkCount}`;if(e.forwardLinks&&e.forwardLinks.length>0){let t=e.forwardLinks.slice(0,5).map(e=>e.kind===`doc`?e.docName:e.url);s+=` (${t.join(`, `)}${e.forwardLinks.length>5?`, …`:``})`}t.push(s)}if(e.history&&e.history.length>0){let s=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${s.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let s=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${s.join(` · `)}`)}return`- ${t.join(` — `)}`}function buildStdoutProvenance(e,t,s,g){let S=null;for(let t=e.length-1;t>=0;t--){let s=e[t],g=s.command;if(g===`ls`||g===`cat`){S=s;break}if((g===`head`||g===`tail`)&&nonFlagArgs(argsOf(s)).length>0){S=s;break}}if(!S)return``;let w=nonFlagArgs(argsOf(S));if(S.command===`ls`){let e=w[w.length-1];if(!e||e===`.`)return``;let s=e.replace(/\/+/g,`/`);if(s.startsWith(`./`)&&(s=s.slice(2)),s.endsWith(`/`)&&(s=s.slice(0,-1)),!s)return``;let S=g(s);return t.has(S)?`${S}/:\n`:``}let E=w.filter(e=>/\.(md|mdx)$/.test(e)&&s.has(g(e)));return E.length===1?`==> ${g(E[0])} <==\n`:``}function formatEnrichedBlock(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let s of e)t.push(isDirectoryMeta(s)?formatDirectoryEntry(s):formatFileEntry(s));return t.join(`
1969
+ `)}async function classifyPaths(e,t){let s=[],g=[];return await Promise.all(t.map(async t=>{try{let S=await stat$1(resolve(e,t));S.isDirectory()?g.push(t):S.isFile()&&s.push(t)}catch{/\.(md|mdx)$/i.test(t)&&s.push(t)}})),{files:s,dirs:g}}function errorCategoryResult(e,t){return textPlusStructured(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function withPreviewUrls(e,t){return e.map(e=>{let s=t(docNameFromPath(e.path));return{...e,previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}})}async function buildExecResult(e,t){let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return errorCategoryResult(`shell_construct_blocked`,`exec failed: ${s.error}`);let{cwd:g,executionCwd:S,config:w,url:E}=s,D=S===g?e=>e:e=>relative(g,resolve(S,e)),O=parseCommand(e.command);if(`error`in O)return errorCategoryResult(O.error.category,O.error.message);let k=augmentStagesWithExcludes(O.stages),j=serializeStages(k),F=await snapshotMtimes(S),L=createBashInstance(S),B=``,H=``;try{let e=await execBash(L,j);B=e.stdout,H=e.stderr}catch(e){return e instanceof StdoutOverflowError?errorCategoryResult(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`):errorCategoryResult(`shell_construct_blocked`,`exec failed: ${e instanceof Error?e.message:String(e)}`)}let q=await snapshotMtimes(S),ee=diffMtimes(F.snapshot,q.snapshot);if(ee.changed.length>0)return errorCategoryResult(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${ee.changed.join(`, `)}. This indicates a parser bug; the command has been logged.`);let J=applySoftCap(B),Y=extractReferencedPaths(B,k).filter(e=>resolveWithinRoot(S,e).ok).map(D),{files:te,dirs:ne}=await classifyPaths(g,Y),ae=k.length===1&&k[0].command===`cat`&&te.length===1,oe=await Promise.all(te.map(e=>enrichPath(e,{projectDir:g,serverUrl:E},{includeRichFields:ae}).catch(()=>({path:e,tags:[],frontmatter:{},backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null,graphRole:null})))),se=await Promise.all(ne.map(e=>enrichDirectoryRecursive(e,1,{projectDir:g}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!ae&&E&&oe.length>0){let e=await fetchBacklinkCountsBatch(E,oe.map(e=>pathToDocName$1(e.path))).catch(()=>null);if(e)for(let t of oe){let s=e.get(pathToDocName$1(t.path));typeof s==`number`&&(t.backlinkCount=s)}}let ce=new Map(oe.map(e=>[e.path,e])),ue=new Map(se.map(e=>[e.path,e])),de=[];for(let e of Y){let t=ce.get(e);if(t){de.push(t);continue}let s=ue.get(e);s&&de.push(s)}let fe=detectBinaryArgs(k),me=[];fe.length>0&&me.push(`File${fe.length>1?`s`:``} ${fe.join(`, `)} appear${fe.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let ge=detectHeadTailTruncation(k,B);ge&&me.push(ge.banner),H&&me.push(`stderr: ${H.trim()}`);let _e=`${me.length>0?`${me.join(`
1970
1970
  `)}\n\n`:``}${buildStdoutProvenance(k,ue,ce,D)+J.text}${formatEnrichedBlock(de)}`,{resolve:ve}=await buildListResolver({config:w,resolveCwd:async()=>g});return textPlusStructured(_e,{enrichedPaths:withPreviewUrls(de,ve),stdoutTruncated:J.truncated,cwd:S,...me.length>0?{warnings:me}:{}})}function register$13(e,t){e.registerTool(`exec`,{description:DESCRIPTION$13,inputSchema:{command:string().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:string().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},outputSchema:outputSchemaWithText({enrichedPaths:looseObjectArray.describe(`Per-referenced-file metadata: frontmatter, backlink/forward-link counts, recent shadow-repo activity, and a route-only previewUrl.`),stdoutTruncated:boolean().optional().describe(`True when stdout was truncated by the soft cap.`),warnings:array(string()).optional().describe(`Tool-level warnings — head/tail truncation, binary detection, stderr.`),cwd:string().optional().describe(`Absolute directory the command ran in.`),error:object$1({category:string(),message:string()}).optional().describe(`Present on failure — the error category + message.`)})},async e=>{try{return await buildExecResult(e,t)}catch(e){return errorCategoryResult(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const DESCRIPTION$12=["Resolve the browser-reachable preview URL for an OpenKnowledge project (optionally for a specific doc). Opening a preview counts as demand: when no OK server is running for the project, this call auto-starts one (same `OK_MCP_AUTOSTART` gate and spawn timeout as the read/write tools) and waits briefly for the preview UI to bind — a cold first call can take a few seconds; calls against a running system answer immediately.",``,"Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.",``,'This is THE way to open a doc OR a loose file in a browser, and the only way to force a browser when the OK Desktop app is installed (the `ok open` CLI prefers Desktop). Use it when YOUR host opens the URL itself: navigate your in-app / embedded browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Do not hunt for the URL via `ok ps`/`ok status` or by guessing a port — this tool returns it. Hosts with a preview pane (Claude Code Desktop) call `preview_start("open-knowledge-ui")` instead; a pure stdio CLI with no browser uses `ok open <doc>` to open in the OK Desktop app.',``,"Returns `{ url: null, baseUrl: null, running: false, autoOpen }` + a recovery hint only when no UI could be reached (auto-start disabled via `OK_MCP_AUTOSTART=0`, no spawn authority in this registration, or the UI did not bind in time) — the hint names the right command for the actual state.",``,"To open a single markdown file that may live OUTSIDE any Open Knowledge project (a loose file, or a doc in a different git worktree), pass `file` with an absolute path: the tool finds the running session whose content directory contains it and returns that session’s URL, then navigate your in-app browser there. `document`/`folder` are for a doc in the current project; `file` is the out-of-project form.",``,`**Parameters:**`,"- `document` (optional) — Extension-less doc path in the current project (e.g. `specs/foo/SPEC`). Omit for the UI root URL.","- `folder` (optional) — Folder path in the current project (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.","- `skill` (optional) — A skill to open in the editor: `{ name, scope? }` (scope `project` default). Returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`.","- `file` (optional) — Absolute path to a single markdown file, including one outside any project. Resolves to the running single-file / worktree session serving it. Mutually exclusive with `document`/`folder`/`skill`; `cwd` is ignored when set.","- `armPaneTarget` (optional) — When true with a `document`/`folder`/`skill`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. Independent of server state; omit it and the call writes nothing.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
1971
1971
  `),UI_BIND_WAIT_TIMEOUT_MS=3e3,UI_BIND_WAIT_POLL_MS=100,InputSchema$2={document:string().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),folder:string().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),skill:object$1({name:string().min(1).regex(SKILL_NAME_REGEX,`Skill name must be lowercase letters, digits, and hyphens only.`).describe("Skill name (the `.ok/skills/<name>` identity)."),scope:_enum(MANAGED_ARTIFACT_SCOPES).optional().describe("Skill scope; defaults to `project`.")}).optional().describe("Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`."),file:string().optional().describe("Absolute path to a single markdown file to open, including one OUTSIDE any Open Knowledge project. Resolves to the running single-file (or worktree) session whose content directory contains it and returns that session’s `url`. Mutually exclusive with `document` / `folder` / `skill`. When `file` is set, `cwd` is ignored."),armPaneTarget:boolean().optional().describe("When true with a `document` or `folder`, arm that target so a subsequent Claude-pane base-open (`preview_start`) lands there instead of the presence-driven default. TTL-bounded (~30s) so a stale arm cannot hijack a later open."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$4=outputSchemaWithText({url:string().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:string().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:boolean().describe(`Whether a UI is running for the project.`),autoOpen:boolean().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`."),okOpenCommand:string().nullable().optional().describe("Machine-readable form of the desktop-terminal steer: when this MCP server runs inside OK Desktop’s built-in terminal AND a doc/folder/skill target was given, the exact `ok open …` command to run to focus it in the OK Desktop window. Prefer running it over navigating `url`. `null`/absent in every other context (navigate `url` per your host instead).")}),NO_UI_SERVER_RUNNING_MESSAGE='The OK server is running but no UI has bound for this project yet. Retry in a few seconds, or start one: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',NO_SERVER_MESSAGE='No OpenKnowledge server is running for this project. Start it with `ok start` (also starts the preview UI), use `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',AUTOSTART_DISABLED_NOTE=` Auto-start is disabled (OK_MCP_AUTOSTART=0).`;function readUserAutoOpen(){try{return readConfigSafely({absPath:resolveConfigPath(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value.appearance?.preview?.autoOpen??!0}catch(e){return process.stderr.write(`[preview-url] readUserAutoOpen failed: ${e instanceof Error?e.message:String(e)}\n`),!0}}function noSingleFileSessionMessage(e){return`No Open Knowledge session is serving ${e} yet. On a host with a terminal, \`ok open ${e}\` starts one; otherwise open ${e} in the OK Desktop app. Then retry.`}function isServerLive(e){try{let t=readServerLock(e);return t!==null&&t.port>0&&isProcessAlive(t.pid)}catch(t){return process.stderr.write(`[preview-url] readServerLock failed at ${e} while checking server liveness: ${t instanceof Error?t.message:String(t)}\n`),!1}}function shellQuoteArg(e){return/^[A-Za-z0-9._/@%+-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function register$12(e,t){e.registerTool(`preview_url`,{description:DESCRIPTION$12,inputSchema:InputSchema$2,outputSchema:OutputSchema$4,annotations:{readOnlyHint:!1,idempotentHint:!0}},async e=>{if([e.document,e.folder,e.skill,e.file].filter(e=>e!=null).length>1)return{isError:!0,content:[{type:`text`,text:`Error: document, folder, skill, and file are mutually exclusive — pass at most one.`}]};if(e.file){if(!isAbsolute(e.file))return{isError:!0,content:[{type:`text`,text:`Error: file must be an absolute path (a loose file outside a project has no cwd to anchor a relative path).`}]};let s=(t.resolveUserAutoOpen??readUserAutoOpen)(),g=t.offCwdResolverDeps??createOffCwdResolverDeps(),S=await resolveOffCwdTarget(e.file,g);if(S===null&&t.ensureSingleFileSession&&await t.ensureSingleFileSession(e.file).catch(t=>(process.stderr.write(`[preview-url] ensureSingleFileSession failed for ${e.file}: ${t instanceof Error?t.message:String(t)}\n`),!1))&&(S=await resolveOffCwdTarget(e.file,g)),S!==null){let e=`${S.baseUrl}/#/${encodeDocName(S.docName)}`;return textPlusStructured(`Preview URL: ${e}`,{url:e,baseUrl:S.baseUrl,running:!0,autoOpen:s})}return textPlusStructured(noSingleFileSessionMessage(e.file),{url:null,baseUrl:null,running:!1,autoOpen:s})}let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=resolveLockDir(s.cwd),S={lockDir:g},w=s.config.appearance.preview.autoOpen,E=e.document?`#/${encodeDocName(e.document)}`:e.folder?`#/${encodeFolderRoute(e.folder)}`:e.skill?`#/${encodeSkillRoute(e.skill.scope??`project`,e.skill.name)}`:null,D=e.document?`ok open ${shellQuoteArg(e.document)}`:e.folder?`ok open ${shellQuoteArg(e.folder)}`:e.skill?`ok open ${e.skill.name} --skill${e.skill.scope===`global`?` --scope global`:``}`:null,O=t.isDesktopTerminal&&D?`You're in the OK Desktop terminal — run \`${D}\` to focus this in the OK Desktop window. Don't navigate the URL below or open a browser; it's for reference only.\n\n`:``;if(e.armPaneTarget&&E)try{armPaneTarget(g,E)}catch{}let k=e.armPaneTarget&&!E?` (note: armPaneTarget was set but no document/folder/skill was given, so nothing was armed)`:``,j=isServerLive(g),F=!1;if(t.serverUrl!==void 0)try{await resolveServerUrl(t.serverUrl,s.cwd)}catch(e){if(e instanceof AutoStartDisabledError)F=!0;else return{isError:!0,content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}]}}let{baseUrl:L}=resolveUiInfo(S);if(L===null&&!j&&isServerLive(g)&&(L=await awaitUiBaseUrl(S,{timeoutMs:t.uiBindWait?.timeoutMs??UI_BIND_WAIT_TIMEOUT_MS,pollIntervalMs:t.uiBindWait?.pollIntervalMs??UI_BIND_WAIT_POLL_MS})),L===null)return textPlusStructured(`${O}${isServerLive(g)?NO_UI_SERVER_RUNNING_MESSAGE:`${NO_SERVER_MESSAGE}${F?AUTOSTART_DISABLED_NOTE:``}`}${k}`,{url:null,baseUrl:null,running:!1,autoOpen:w,okOpenCommand:t.isDesktopTerminal?D:null});let B=E?`${L}/${E}`:L;return textPlusStructured(`${O}Preview URL: ${B}${k}`,{url:B,baseUrl:L,running:!0,autoOpen:w,okOpenCommand:t.isDesktopTerminal?D:null})})}const HistoryEntryOutputSchema=object$1({version:string().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:string().describe(`ISO timestamp of the entry.`),author:string().describe(`Author display name.`),authorEmail:string().describe(`Author email.`),kind:_enum([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:string().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:looseObjectArray.describe(`Per-contributor records parsed from the commit (writer id, name, docs, summaries).`),checkpoint:unknown().nullable().describe(`Checkpoint metadata when this entry is a checkpoint, else null.`)}),DESCRIPTION$11=[`[Requires: Hocuspocus server] List version history for a document, or the activity timeline for a folder.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.",``,"**Parameters (pass EXACTLY ONE of `document` / `folder` / `skill`):**","- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",'- `folder` — Folder path for the FOLDER timeline: attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter) — who created / edited / renamed / moved / deleted them, when. `""` = project root.',"- `skill` — Skill NAME to query version history for (the attributed `.ok/skills/<name>/` versions). PROJECT-scope skills only — global skills are unversioned. Pass an entry's `version` to `restore_version({ skill, version })`.","- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `kind` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
1972
1972
  `);function register$11(e,t){e.registerTool(`history`,{description:DESCRIPTION$11,inputSchema:{document:string().optional().describe("Document name to query history for. Mutually exclusive with `folder`."),folder:string().optional().describe('Folder path to query the FOLDER timeline for — attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter): created / edited / renamed / moved / deleted, by whom, when. Mutually exclusive with `document`. Use `""` for the project root.'),skill:string().optional().describe("Skill name to query version history for (`.ok/skills/<name>/`). Mutually exclusive with `document` / `folder`."),branch:string().optional().describe(`Branch name (default: current branch)`),limit:number().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:number().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),kind:_enum([`checkpoint`,`upstream`,`wip`]).optional().describe("Filter by entry type (`checkpoint` / `upstream` / `wip`)."),author:string().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:string().optional().describe(`Exclude entries by this author name or email`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({entries:array(HistoryEntryOutputSchema).describe("Timeline entries, newest first. Each carries a `version` for `restore_version`."),total:number().int().optional().describe(`Total entries available (pre-pagination).`),truncated:boolean().optional().describe(`Whether more entries exist beyond this returned page (the result was limit-capped).`),previewUrl:previewUrlOutputField,previewUrlSource:previewUrlSourceField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if((e.document===void 0?0:1)+(e.folder===void 0?0:1)+(e.skill===void 0?0:1)!=1)return textResult("Error: pass EXACTLY ONE of `document`, `folder`, or `skill`.",!0);let w=e.folder!==void 0,E=new URLSearchParams,D=null;if(w)E.set(`folder`,e.folder??``);else if(e.skill!==void 0){let t=projectSkillContentDocName(e.skill);E.set(`docName`,t),D=t}else{let t=normalizeDocName(e.document);if(!t.ok)return textResult(t.error,!0);E.set(`docName`,t.docName),D=t.docName}e.branch&&E.set(`branch`,e.branch),e.limit!=null&&E.set(`limit`,String(e.limit)),e.offset!=null&&E.set(`offset`,String(e.offset)),e.kind&&E.set(`type`,e.kind),e.author&&E.set(`author`,e.author),e.excludeAuthor&&E.set(`excludeAuthor`,e.excludeAuthor);let O=await httpGet(S,`/api/history?${E.toString()}`);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let{ok:k,...j}=O,F=(Array.isArray(j.entries)?j.entries:[]).map(e=>{let t=e;return{version:t.sha,timestamp:t.timestamp,author:t.author,authorEmail:t.authorEmail,kind:t.type,message:t.message,contributors:t.contributors,checkpoint:t.checkpoint??null}}),L=j.total,B=j.hasMore,H=D?await resolvePreviewUrlForTool(D,{config:t.config,resolveCwd:t.resolveCwd},g):null,q={entries:F,...typeof L==`number`?{total:L}:{},...typeof B==`boolean`?{truncated:B}:{}};return textPlusStructured(JSON.stringify(q,null,2),{...q,previewUrl:H?.url??null,...H?{previewUrlSource:H.source}:{}})})}const DESCRIPTION$10=[`[Requires: Hocuspocus server] Install an authored SKILL into your editors — the deliberate Draft → Installed step.`,``,"Projects the skill source at `.ok/skills/<name>/` verbatim into the editor host dirs your project is configured for (`.claude/skills/<name>/`, `.cursor/skills/<name>/`, `.codex/skills/<name>/`, `.opencode/skills/<name>/`). The source is validated FIRST — a SKILL.md with git conflict markers, missing/invalid frontmatter, XML tags in name/description, or a reserved `open-knowledge*` name is refused (never projected into your agent context). Records the install so it survives a relaunch.",``,`**Parameters:**`,`- \`name\` — ${SKILL_NAME_DESCRIBE}`,"- `targets` — Optional explicit editor ids (`claude` | `cursor` | `codex` | `opencode`). Omit to install into the editors this project is already configured for.","- `scope` — `project` (default, shared via git) or `global` (user-global, installed into every editor on this machine).",``,"After editing a skill, run `install` again to push the new version. After `delete({skill})`, the projection is removed automatically (uninstall)."].join(`
@@ -3251,4 +3251,4 @@ Incremental by default — don't re-read the whole repo.
3251
3251
  `))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await Ce.flushDeferredStores(`discard-stale`),De?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&ve.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(ve.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Ir.push(`head-watcher`)}function D(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=we.documents.get(S);if(!w)continue;let E=Mt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let O=buildSyncCredentialArgs(H);try{en=new SyncEngine({projectDir:s,contentDir:t,contentFilter:me,contentRoot:L,syncEnabled:ne(),credentialArgs:O,cc1Broadcaster:De,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||Ce.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:D,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await en.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),en=null}Xe(`files`),Xe(`backlinks`),Xe(`graph`),Xe(`tags`)}return Lr().then(We,Ge),{hocuspocus:we,sessionManager:Te,cc1Broadcaster:De,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:ye,contentFilter:me,basenameIndex:ue,serverInstanceId:se,destroy:Fr,ready:Ke,degraded:Ir,lockDir:ce,get syncEngine(){return en}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-8Lv6A-Xa-DCBoMd9v.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se}=H,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:S}),fe=D();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:q,mcpHttpHandler:de,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e,ephemeral:e.ephemeral}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;g!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);fe.once(`error`,g),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,g),t()})})}catch(e){if(ge)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let we=fe.address(),Te=typeof we==`object`&&we?we.port:e.port??0;if(ue=Te,O(te,Te),ge&&updateUiLockPort(te,Te),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let De=!1,je=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};ye=async()=>{if(De)return;De=!0;let e=[],t=async(t,s)=>{try{await je(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),de!==void 0&&await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:j,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:fe,destroy:ye,lockDir:te,contentDir:e.contentDir,port:Te,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
3252
3252
  `).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e,t){try{let{stdout:s}=await execFileAsync(e,[`rev-parse`,`--is-inside-work-tree`],{cwd:t});return s.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}let w;try{w=assertGitAvailable()}catch(e){throw e instanceof GitNotAvailableError||e instanceof GitTooOldError?(emitPreflightFailureSpan(e),log.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:e instanceof GitTooOldError?e.detected:``},e instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let E=w.resolvedPath;if(!S&&await isInsideExistingWorkTree(E,t))return{didInit:!1};let D=``;try{D=(await execFileAsync(E,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,D);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
3253
3253
  `,`utf-8`),t}export{STARTER_PACKS as $,withSpan as $i,isAllowedWorkspaceHostHeader as $n,resolveBundledSkillDir as $r,createExternalChangeHandler as $t,HocuspocusAuthRejection as A,spawnDetached as Ai,formatPackRationale as An,planSeed as Ar,bundleSkillMdPath as At,McpLogger as B,tracedMkdirSync as Bi,handleCollabSocketError as Bn,readSkillManagement as Br,compareSemver as Bt,FILE_WATCHER_ORIGIN as C,serializeError as Ci,fallbackPaths as Cn,normalizeFsPath as Cr,bootServer as Ct,GitNotAvailableError as D,skillManagementPath as Di,formatAuthRejectionWire as Dn,parseHocuspocusAuthToken as Dr,buildSkillZip as Dt,GIT_UPSTREAM_WRITER as E,shutdownTelemetry as Ei,flushFileLogger as En,parseGitVersion as Er,buildExecResult as Et,MANAGED_RENAME_ORIGIN as F,teardownToleranceTelemetryWriter as Fi,getLogger as Fn,readArmedPaneTarget as Fr,clearEmbeddingsKeyFromAllBackends as Ft,PinoLogger as G,tracedUnlinkSync as Gi,initContent as Gn,reconcile as Gr,countStaleAgentWipRefs as Gt,OBSERVER_SYNC_ORIGIN as H,tracedRenameSync as Hi,hasGcLogLatch as Hn,readTargetRecordedAt as Hr,contentHash as Ht,MAX_AGENT_SESSIONS as I,toBroadcasterKey as Ii,getLogsDir as In,readBranchFromHead as Ir,coercePackId as It,ROOT_GITIGNORE_TEMPLATE as J,updateLastKnownHash as Ji,initToleranceTelemetryWriter as Jn,registerAllTools as Jr,createAssetServeMiddleware as Jt,ProjectGitInitError as K,tracedWriteFile as Ki,initShadowRepo as Kn,recordContributor as Kr,countWipRefs as Kt,MCP_CONNECTION_ID_HEADER as L,tracedAppendFileSync as Li,getMeter as Ln,readProjectLocalSemanticConfig as Lr,commitUpstreamImport as Lt,INSTALLED_AGENTS_SCHEMES as M,startWatcher as Mi,getCurrentMcpLogger as Mn,processCommand as Mr,classifyFsPath as Mt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as N,streamingProblemEvent as Ni,getLocalDir as Nn,processUsage as Nr,clearArmedPaneTarget as Nt,GitTooOldError as O,spansCurrentPath as Oi,formatContributors as On,parseKeepaliveConnectionId as Or,buildStarterFolderFrontmatterYaml as Ot,LOG_MD_TEMPLATE as P,swapContributors as Pi,getLogFilePath as Pn,readAllTargets as Pr,clearContributors as Pt,STARTER_FOLDER_FRONTMATTER_FILENAME as Q,validateSkillZip as Qi,isAllowedApiOrigin as Qn,resetMetrics as Qr,createEphemeralProjectDir as Qt,MIN_GIT_VERSION as R,tracedLinkSync as Ri,getMetrics as Rn,readServerPackageVersion as Rr,commitWip as Rt,FILE_SYSTEM_WRITER as S,seedBasenameIndex as Si,extractWikiLinksFromMarkdown as Sn,mountMcpAndApi as Sr,attachIdleShutdown as St,GIT_PREFLIGHT_FAIL_SPAN_NAME as T,shadowGit as Ti,findEnclosingProjectRoot as Tn,parseAuthRejectionWire as Tr,buildConfigYmlContent as Tt,OK_OKIGNORE_TEMPLATE as U,tracedRmSync as Ui,incrementCollabSocketFilteredError as Un,readTargetVersion as Ur,contributorCount as Ut,MissingOkConfigError as V,tracedRename as Vi,handleSpawnCursor as Vn,readStateManifest as Vr,containsConflictMarkers as Vt,PANE_TARGET_TTL_MS as W,tracedRmdirSync as Wi,incrementServerObserverFire as Wn,readUiLock as Wr,countShadowObjects as Wt,SKILL_INSTALL_EVENTS_FILE_REL as X,validateAgentId as Xi,installTestLoggers as Xn,releaseUiLock as Xr,createContentFilterAsync as Xt,SERVICE_WRITER as Y,updateUiLockPort as Yi,installPrettyZodErrors as Yn,registerWrite as Yr,createContentFilter as Yt,STARTER_FOLDERS as Z,validateCloneInputs as Zi,installUserSkill as Zn,removeLastKnownHash as Zr,createEmbeddingsSecretStore as Zt,ConfigSchema as _,GitDirAccessError as _a,safeSubdir as _i,encodeSkillRoute as _n,loadPrincipal as _r,applySeed as _t,AgentPresenceBroadcaster as a,writeTracker as aa,resolvePackageVersion as ai,createServer$1 as an,isManagedArtifactDoc as ar,SingleFileNotAFileError as at,DEFAULT_PACK_ID as b,resolveGitDirDetailed as ba,saveInMemoryCheckpoint as bi,evictStaleTrackerEntries as bn,logsPreviousPath as br,assertGitAvailable as bt,AutoStartDisabledError as c,LATEST_PROTOCOL_VERSION as ca,restoreLifecycleFromConflictsJson as ci,createTestLogger as cn,isProjectRoot as cr,StateManifestError as ct,BUNDLE_SKILL_NAME as d,isJSONRPCResultResponse as da,runAuthReposSubprocess as di,detectGit as dn,isSelfWrite as dr,UiLockCollisionError as dt,withSpanSync as ea,resolveContentDir as ei,createFileLogger as en,isConfigDoc as er,STARTER_PACK_IDS as et,BacklinkIndex as f,atomicWriteFileSync as fa,runAuthStatusSubprocess as fi,detectProjectShape as fn,isSystemDoc as fr,__getShowAllWalkStatsForTesting as ft,CURSOR_BUNDLE_PATHS_BY_PLATFORM as g,writeConfigPatch as ga,safeContentPath as gi,encodeFolderRoute as gn,listStarterPacks as gr,applyExternalChange as gt,CONFLICT_MARKER_RE as h,withFileLockSync as ha,runWithMcpLogger as hi,encodeDocName as hn,listRescueCheckpoints as hr,applyAgentMarkdownWrite as ht,AgentFocusBroadcaster as i,writeTargetVersion as ia,resolvePack as ii,createPersistenceExtension as in,isLoopbackAddress as ir,SeedRootDirError as it,HocuspocusAuthTokenSchema as j,splitMarkdownBlocks as ji,gcCheckpointRefs as jn,prepareSingleFileOpen as jr,classifyEvents as jt,HOCUSPOCUS_AUTH_REJECTION_REASONS as k,spansPreviousPath as ki,formatContributorsFrom as kn,pathToDocName as kr,buildWipTree as kt,BUNDLE_IDS as l,isInitializedNotification as la,rewriteMarkdownLinksForDocumentRename as li,describeStoredEmbeddingsKey as ln,isProjectSkillManaged as lr,TagIndex as lt,CONFIG_FILENAME as m,resolveConfigPath as ma,runDeviceFlowSubprocess as mi,emitPreflightFailureSpan as mn,lastKnownHash as mr,acquireUiLock as mt,AGENT_ID_RE as n,writeSkillManagement as na,resolveCursorSpawnInvocation as ni,createMcpHttpHandler as nn,isKnownPackId as nr,STATE_MANIFEST_FILENAME as nt,AgentSessionCapacityError as o,McpServer as oa,resolveUiInfo as oi,createServerObserverExtension as on,isPairedWriteOrigin as or,SingleFileNotFoundError as ot,CC1Broadcaster as p,readConfigSafely as pa,runCloneSubprocess as pi,discoverLockDirs as pn,isToleranceTelemetryEnabled as pr,__resetShowAllWalkStatsForTesting as pt,ROLLBACK_ORIGIN as q,tracedWriteFileSync as qi,initTelemetry as qn,recordSkillInstallEvent as qr,createApiExtension as qt,AGENT_WRITE_ORIGIN as r,writeStateManifest as ra,resolveLockDir as ri,createOsProbe as rn,isLinkIndexExcludedDoc as rr,SeedPrerequisiteError as rt,AgentSessionManager as s,JSONRPCMessageSchema as sa,restoreContributors as si,createStreamingErrorWriter as sn,isPathWithinDir as sr,SingleFileNotMarkdownError as st,AGENT_ID_MAX_LEN as t,writeRootGitignoreForNewRepo as ta,resolveCursorBinaryDefault as ti,createLiveDerivedIndexExtension as tn,isHocuspocusAuthRejectionReason as tr,STARTER_TEMPLATES as tt,BUNDLE_SCOPE as u,isJSONRPCRequest as ua,rewriteWikiLinksForDocumentRename as ui,detectClaudeDesktopPresence as un,isReservedForUserTree as ur,USER_GLOBAL_BUNDLE_IDS as ut,DEFAULT_CHECKPOINT_RETENTION as v,MalformedGitPointerError as va,safetyCheckpoint as vi,ensureProjectGit as vn,loggerFactory as vr,armPaneTarget as vt,FileEmbeddingsBackend as w,setActiveSpanAttributes as wi,findEnclosingGitRoot as wn,packageVersionMajorMinor as wr,buildAndOpenSkill as wt,EMBEDDINGS_API_KEY_ENV as x,resolveShadowDir as xa,saveVersion as xi,extractOkBinaryPath as xn,makeLazyEmbeddingsKeyStore as xr,assertNeverDiskEvent as xt,DEFAULT_EMBEDDINGS_DIMENSIONS as y,parseCheckpoint as ya,sanitizeClientName as yi,errorResponse as yn,logsCurrentPath as yr,assertCompatibleStateManifest as yt,MISSING_OK_CONFIG_MESSAGE as z,tracedMkdir as zi,getTracer as zn,readSkillInstallStateSnapshot as zr,commitWipFromTree as zt};
3254
- //# sourceMappingURL=dist-OXU4D9x4.mjs.map
3254
+ //# sourceMappingURL=dist-CPWuFcMi.mjs.map
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{i as e,r as t,t as n}from"./gh-detect-DR8F3B_q.mjs";import{C as r,D as i,E as a,O as o,S as s,T as c,a as l,b as u,c as d,i as f,k as p,l as m,n as h,p as g,v as _,w as v,y}from"./init-mkjWLQRM.mjs";import{d as b,f as x,i as S,l as C,n as w,r as T,t as E,u as D}from"./src-DosXVNio.mjs";import{a as O,c as k,l as A,o as j,r as M,s as N,t as P,u as F}from"./write-project-skill-DkyeK6BK.mjs";import{n as I}from"./loader-DHGGeVYM.mjs";import{n as L}from"./preview-k5MwPUya.mjs";import{n as R,t as z}from"./mcp-migrate-event-D0NrGjvc.mjs";export{M as ALL_EDITOR_IDS,O as EDITOR_LABELS,j as EDITOR_TARGETS,N as HOSTS_WITH_USER_SKILL_DIR,h as LAUNCH_CONFIG_NAME,f as LAUNCH_UI_CHAIN_SENTINEL,l as LAUNCH_UI_CHAIN_V1,r as addOkPathsToGitExclude,P as assertProjectPathSafe,k as buildManagedServerEntry,T as buildMcpConfigDeclineEvent,z as buildMcpConfigMigrateEvent,d as classifyExistingMcpEntry,t as createTokenStore,n as detectGh,m as detectInstalledEditors,v as formatTrackedRemediation,c as getExcludedOkPaths,a as getOkArtifactPaths,A as isEntryUpToDate,F as isOwnManagedEntry,I as loadConfig,e as makeLazyProbeTokenStore,C as parseGitHubBlobUrl,D as parseGitHubShareUrl,b as parseGitHubTreeUrl,x as parseGitUrl,L as previewContent,i as probeTrackedOkPaths,g as readExistingMcpEntry,o as readSharingMode,p as removeOkPathsFromGitExclude,s as resolveProjectRoot,S as runStop,_ as scaffoldLaunchJson,R as truncatePriorEntry,w as validateLocalFolderForShare,y as writeEditorMcpConfig,E as writeProjectAiIntegrations,u as writeUserMcpConfigs};
1
+ import{i as e,r as t,t as n}from"./gh-detect-DR8F3B_q.mjs";import{C as r,D as i,E as a,O as o,S as s,T as c,a as l,b as u,c as d,i as f,k as p,l as m,n as h,p as g,v as _,w as v,y}from"./init-CZ_nELEP.mjs";import{d as b,f as x,i as S,l as C,n as w,r as T,t as E,u as D}from"./src-CWhVS7Hy.mjs";import{a as O,c as k,l as A,o as j,r as M,s as N,t as P,u as F}from"./write-project-skill-CkUa0amf.mjs";import{n as I}from"./loader-DzDqBeq5.mjs";import{n as L}from"./preview-B-Wfn8l6.mjs";import{n as R,t as z}from"./mcp-migrate-event-D0NrGjvc.mjs";export{M as ALL_EDITOR_IDS,O as EDITOR_LABELS,j as EDITOR_TARGETS,N as HOSTS_WITH_USER_SKILL_DIR,h as LAUNCH_CONFIG_NAME,f as LAUNCH_UI_CHAIN_SENTINEL,l as LAUNCH_UI_CHAIN_V1,r as addOkPathsToGitExclude,P as assertProjectPathSafe,k as buildManagedServerEntry,T as buildMcpConfigDeclineEvent,z as buildMcpConfigMigrateEvent,d as classifyExistingMcpEntry,t as createTokenStore,n as detectGh,m as detectInstalledEditors,v as formatTrackedRemediation,c as getExcludedOkPaths,a as getOkArtifactPaths,A as isEntryUpToDate,F as isOwnManagedEntry,I as loadConfig,e as makeLazyProbeTokenStore,C as parseGitHubBlobUrl,D as parseGitHubShareUrl,b as parseGitHubTreeUrl,x as parseGitUrl,L as previewContent,i as probeTrackedOkPaths,g as readExistingMcpEntry,o as readSharingMode,p as removeOkPathsFromGitExclude,s as resolveProjectRoot,S as runStop,_ as scaffoldLaunchJson,R as truncatePriorEntry,w as validateLocalFolderForShare,y as writeEditorMcpConfig,E as writeProjectAiIntegrations,u as writeUserMcpConfigs};