@inkeep/open-knowledge 0.4.0-beta.30 → 0.4.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/assets/skills/open-knowledge/SKILL.md +3 -3
  2. package/dist/cli.mjs +5 -5
  3. package/dist/constants-BHNW8Zq_.mjs +2 -0
  4. package/dist/{dist-H3Ld-L-a.mjs → dist-D3xMMmYf.mjs} +2 -2
  5. package/dist/{dist-Va4IjzRw.mjs → dist-DOIb_FW2.mjs} +13 -13
  6. package/dist/{dist-Cg4a9GjH.mjs → dist-YAZrJ15a.mjs} +1 -1
  7. package/dist/index.mjs +1 -1
  8. package/dist/{init-DrfKz58U.mjs → init-3-63uZzL.mjs} +3 -3
  9. package/dist/init-6drSK50y.mjs +1 -0
  10. package/dist/{loader-DKoWw50g.mjs → loader-BohnSRzb.mjs} +2 -2
  11. package/dist/loader-DY3uDuFe.mjs +1 -0
  12. package/dist/preview-BIFV91lQ.mjs +1 -0
  13. package/dist/{preview-D6nLHyS2.mjs → preview-KUL_V2fF.mjs} +2 -2
  14. package/dist/public/assets/{ActivityModeContent-CSzGBekb.js → ActivityModeContent-DbLaeHZ0.js} +1 -1
  15. package/dist/public/assets/{DocumentContext-HTIMnclU.js → DocumentContext-BoqbPYlX.js} +1 -1
  16. package/dist/public/assets/{GraphPanel-Bh6hilLJ.js → GraphPanel-D3k9jF0Q.js} +1 -1
  17. package/dist/public/assets/{SettingsDialog-Bn0Qb8Z-.js → SettingsDialog-UrpLReCS.js} +1 -1
  18. package/dist/public/assets/{SourceEditor-CLnmY3Yf.js → SourceEditor-HTGqnC5W.js} +1 -1
  19. package/dist/public/assets/{config-validation-events-CiSk03iO.js → config-validation-events--Lmna0va.js} +1 -1
  20. package/dist/public/assets/{doc-hash-BSwTWr6y.js → doc-hash-B4Tnobw5.js} +1 -1
  21. package/dist/public/assets/{index-6soyXw4M.js → index-CwEThoQY.js} +4 -4
  22. package/dist/public/assets/{target-navigation-intent-BpcRYgIB.js → target-navigation-intent-7etGAyzg.js} +1 -1
  23. package/dist/public/assets/{toggle-group-CZU3XaIH.js → toggle-group-MmUCNd9k.js} +1 -1
  24. package/dist/public/assets/{tooltip-DcfXr4mU.js → tooltip-D8vJ720z.js} +1 -1
  25. package/dist/public/assets/{typing-burst-detector-BbQifQft.js → typing-burst-detector-CvAtpmP1.js} +1 -1
  26. package/dist/public/index.html +8 -8
  27. package/dist/{src-DL2x7ekf.mjs → src-DWeGFSri.mjs} +2 -2
  28. package/dist/{start-CKupR8YG.mjs → start-BIWsMLqV.mjs} +2 -2
  29. package/dist/start-Cfbbhayh.mjs +1 -0
  30. package/package.json +1 -1
  31. package/dist/constants-BY_EleLO.mjs +0 -2
  32. package/dist/init-BpTa5nQL.mjs +0 -1
  33. package/dist/loader-BcdTtT9v.mjs +0 -1
  34. package/dist/preview-DfT6ddN-.mjs +0 -1
  35. package/dist/start-BPfRyvzL.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{$ as FolderConfigPutSuccessSchema,$n as toWikiLinkSlug,$t as SyncConflictContentSuccessSchema,A as CONFIG_DOC_NAMES,An as emptySkillState,Ar as record,At as RenamePathSuccessSchema,Bn as isOrphanMode,Br as $ZodObject,Bt as SearchRequestSchema,C as CC1ServerInfoPayloadSchema,Cn as createBasenameIndex,Cr as intersection,Ct as ORPHAN_MODES,D as CC1_CHANNEL_DISK_ACK,Dn as createWorkspaceSearchDocument,Dr as object$1,Dt as PrincipalSuccessSchema,E as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,En as createWorkspaceSearchCorpus,Er as number,Et as PagesSuccessSchema,F as CreateFolderRequestSchema,Fn as getParseHealth,Fr as datetime,Ft as SKILL_STATE_TARGETS,G as DiffSuccessSchema,Gn as readFmMap,Gr as safeParseAsync$1,Gt as SeedPlanSuccessSchema,H as DeadLinksSuccessSchema,Hn as mergeThreeWay,Hr as parse$1,Ht as SeedApplyRequestSchema,I as CreateFolderSuccessSchema,In as getWikiLinkText,Ir as toJSONSchema,It as SKILL_STATE_VERSION_RE,Jn as searchWorkspaceCorpus,Jr as normalizeParams,Jt as SkillStateSchema,K as DocumentListSuccessSchema,Kn as resolveAssetProjectPath,Kr as clone,Kt as ServerInfoSuccessSchema,L as CreatePageRequestSchema,Ln as humanFormat,Lt as SYSTEM_DOC_NAME,M as CONFIG_DOC_NAME_PROJECT,Mn as extractFrontmatterTags,Mr as union,Mt as RollbackRequestSchema,N as CONFIG_DOC_NAME_PROJECT_LOCAL,Nn as fnv1aDigest,Nr as unknown,Nt as RollbackSuccessSchema,O as CC1_CHANNEL_SERVER_INFO,On as defaultScheduler,Or as optional,Ot as ProblemDetailsSchema,P as CONFIG_DOC_NAME_USER,Pn as getHeadingSlug,Pt as SKILL_STATE_REL,Q as FolderConfigPutRequestSchema,Qn as toBridgeInvariantLog,Qt as SyncAbortMergeSuccessSchema,R as CreatePageSuccessSchema,Rn as iconFromClientName,Rr as describe$1,Rt as SaveVersionRequestSchema,S as CC1DiskAckPayloadSchema,Sn as colorFromSeed,Sr as discriminatedUnion,St as MetricsReconciliationSuccessSchema,T as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Tn as createTagInTextRegex,Tr as looseObject,Tt as PageHeadingsSuccessSchema,U as DeletePathRequestSchema,Un as normalizeBridge,Ur as parseAsync,Ut as SeedApplySuccessSchema,Vn as mediaKindForSidebarAssetExtension,Vr as $ZodType,Vt as SearchSuccessSchema,W as DeletePathSuccessSchema,Wn as prependFrontmatter,Wr as safeParse$1,Wt as SeedListPacksSuccessSchema,X as EmptyRequestSchema,Xn as stripFrontmatter,Xt as StreamingProblemEventSchema,Y as EXECUTABLE_BLOCKLIST_EXTENSIONS,Yn as sharedExtensions,Yr as $constructor,Yt as SpawnCursorSuccessSchema,Z as FolderConfigGetSuccessSchema,Zn as tagsMatchingPrefix,Zr as require_dist$2,Zt as SuggestLinksSuccessSchema,_ as BridgeMergeContentLossError,_n as applyFastDiff,_r as _null,_t as LocalOpOpenRequestSchema,a as AgentBurstDiffSuccessSchema,an as SyncTriggerSuccessSchema,ar as ConfigSchema$1,at as InstallSkillRequestSchema,b as CC1ConfigValidationRejectedPayloadSchema,bn as classifyMarkdownHref,br as boolean,bt as MetricsAgentPresenceSuccessSchema,c as AgentUndoRequestSchema,cn as TemplateDeleteSuccessSchema,cr as applyPatchToDocument,ct as LinkGraphSuccessSchema,d as AgentWriteMdSuccessSchema,dn as TemplatePutSuccessSchema,dr as validatePatchScopes,dt as LocalOpAuthIdentitySuccessSchema,en as SyncConflictsSuccessSchema,er as unwrapFrontmatterFences,et as ForwardLinksSuccessSchema,f as AgentWriteRequestSchema,fn as TestRescanBacklinksSuccessSchema,fr as withConfigSpan,ft as LocalOpAuthPatRequestSchema,g as BridgeInvariantViolationError,gn as WorkspaceSuccessSchema,gr as _enum,gt as LocalOpCloneRequestSchema,h as BacklinksSuccessSchema,hn as UploadRequestSchema,hr as ZodOptional$1,ht as LocalOpAuthStatusSuccessSchema,i as AgentActivitySuccessSchema,in as SyncTriggerRequestSchema,ir as CONFIG_SCHEMA_MAJOR_PATH,it as INLINE_RENDERABLE_EXTENSIONS,j as CONFIG_DOC_NAME_OKIGNORE,jn as expandTagToHierarchy,jr as string,jt as RescueListSuccessSchema,k as CC1_CONTRACT_VERSION,kn as detectAppliedToleranceClasses,kr as preprocess,kt as RenamePathRequestSchema,l as AgentUndoSuccessSchema,ln as TemplateGetSuccessSchema,lr as locateIssue,lt as LocalOpAuthEmptySuccessSchema,m as BacklinkCountsSuccessSchema,mn as UploadAssetSuccessSchema,mt as LocalOpAuthSetIdentityRequestSchema,nn as SyncResolveConflictSuccessSchema,nr as PluginKey,nt as HistoryVersionSuccessSchema,o as AgentPatchRequestSchema,on as TagsForNameSuccessSchema,or as LOCAL_DIR,ot as InstallSkillSuccessSchema,p as AgentWriteSuccessSchema,pn as TestResetSuccessSchema,pr as withConfigSpanSync,pt as LocalOpAuthPatSuccessSchema,q as DocumentReadSuccessSchema,qn as resolveInternalHref,qr as defineLazy,qt as SkillInstallStateSuccessSchema,r as ASSET_EXTENSIONS,rn as SyncStatusSchema,rr as Fragment,rt as HubsSuccessSchema,s as AgentPatchSuccessSchema,sn as TagsListSuccessSchema,sr as addConfigSpanEvent,st as InstalledAgentsSuccessSchema,t as AGENT_ICON_COLORS,tn as SyncResolveConflictRequestSchema,tr as getSchema,tt as HistorySuccessSchema,u as AgentWriteMdRequestSchema,un as TemplatePutRequestSchema,ur as toConfigIssue,ut as LocalOpAuthHostRequestSchema,v as CC1BranchSwitchedPayloadSchema,vn as applyIncrementalDiff,vt as LocalOpOpenSuccessSchema,w as CC1_CHANNEL_BRANCH_SWITCHED,wn as createCodeFenceTracker,wr as literal,wt as OrphansSuccessSchema,x as CC1DerivedViewPayloadSchema,xn as classifyWikiLinkTarget,xr as custom,xt as MetricsParseHealthSuccessSchema,y as CC1ConfigIgnoreNestedErrorPayloadSchema,yn as assertNeverProblemType,yr as array,yt as MarkdownManager,z as DEFAULT_DEDUP_MODE,zn as isKnownConfigError,zr as meta$1,zt as SaveVersionSuccessSchema}from"./dist-H3Ld-L-a.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BbkJd7ro.mjs";import{a as acquireProcessLock,c as isValidLockPid,f as readServerLock,g as updateProcessLockPort,m as releaseServerLock,n as RUNTIME_VERSION,o as acquireServerLock,p as releaseProcessLock,s as isProcessAlive,t as ProcessLockCollisionError,u as readProcessLock}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{a as require_src$15,i as esm_default,r as withParentLock,t as createGitInstance}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{r as diffLines,t as createPatch}from"./libesm-YL3Bqolr.mjs";import{n as mimes,t as build_default}from"./build-fAc55Z_L.mjs";import{t as b1}from"./chunk-YNYSPYQ5-Dq-BWW-f.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-CkMj9l7f.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-Vm1q1kLH.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-Cd7Fiqsb.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-DSqbA7Rj.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BQ5SUtd7.mjs";import"./chunk-DXB73IDG-DfmyzFzL.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-SLhNX8t9.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DQP-O5US.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-D4lSWh0K.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-_PX4ITYZ.mjs";import{n as n$1}from"./chunk-3THT3N7L-DrzOuTpA.mjs";import{t as n$2}from"./chunk-44UOCSGV-BbZqjKvt.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,closeSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import{Transform}from"node:stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import crypto$2 from"crypto";import*as zlib$2 from"zlib";import{access,constants,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,writeFile}from"node:fs/promises";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{Http2ServerRequest,constants as constants$1}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
1
+ import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{$ as FolderConfigPutSuccessSchema,$n as toWikiLinkSlug,$t as SyncConflictContentSuccessSchema,A as CONFIG_DOC_NAMES,An as emptySkillState,Ar as record,At as RenamePathSuccessSchema,Bn as isOrphanMode,Br as $ZodObject,Bt as SearchRequestSchema,C as CC1ServerInfoPayloadSchema,Cn as createBasenameIndex,Cr as intersection,Ct as ORPHAN_MODES,D as CC1_CHANNEL_DISK_ACK,Dn as createWorkspaceSearchDocument,Dr as object$1,Dt as PrincipalSuccessSchema,E as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,En as createWorkspaceSearchCorpus,Er as number,Et as PagesSuccessSchema,F as CreateFolderRequestSchema,Fn as getParseHealth,Fr as datetime,Ft as SKILL_STATE_TARGETS,G as DiffSuccessSchema,Gn as readFmMap,Gr as safeParseAsync$1,Gt as SeedPlanSuccessSchema,H as DeadLinksSuccessSchema,Hn as mergeThreeWay,Hr as parse$1,Ht as SeedApplyRequestSchema,I as CreateFolderSuccessSchema,In as getWikiLinkText,Ir as toJSONSchema,It as SKILL_STATE_VERSION_RE,Jn as searchWorkspaceCorpus,Jr as normalizeParams,Jt as SkillStateSchema,K as DocumentListSuccessSchema,Kn as resolveAssetProjectPath,Kr as clone,Kt as ServerInfoSuccessSchema,L as CreatePageRequestSchema,Ln as humanFormat,Lt as SYSTEM_DOC_NAME,M as CONFIG_DOC_NAME_PROJECT,Mn as extractFrontmatterTags,Mr as union,Mt as RollbackRequestSchema,N as CONFIG_DOC_NAME_PROJECT_LOCAL,Nn as fnv1aDigest,Nr as unknown,Nt as RollbackSuccessSchema,O as CC1_CHANNEL_SERVER_INFO,On as defaultScheduler,Or as optional,Ot as ProblemDetailsSchema,P as CONFIG_DOC_NAME_USER,Pn as getHeadingSlug,Pt as SKILL_STATE_REL,Q as FolderConfigPutRequestSchema,Qn as toBridgeInvariantLog,Qt as SyncAbortMergeSuccessSchema,R as CreatePageSuccessSchema,Rn as iconFromClientName,Rr as describe$1,Rt as SaveVersionRequestSchema,S as CC1DiskAckPayloadSchema,Sn as colorFromSeed,Sr as discriminatedUnion,St as MetricsReconciliationSuccessSchema,T as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Tn as createTagInTextRegex,Tr as looseObject,Tt as PageHeadingsSuccessSchema,U as DeletePathRequestSchema,Un as normalizeBridge,Ur as parseAsync,Ut as SeedApplySuccessSchema,Vn as mediaKindForSidebarAssetExtension,Vr as $ZodType,Vt as SearchSuccessSchema,W as DeletePathSuccessSchema,Wn as prependFrontmatter,Wr as safeParse$1,Wt as SeedListPacksSuccessSchema,X as EmptyRequestSchema,Xn as stripFrontmatter,Xt as StreamingProblemEventSchema,Y as EXECUTABLE_BLOCKLIST_EXTENSIONS,Yn as sharedExtensions,Yr as $constructor,Yt as SpawnCursorSuccessSchema,Z as FolderConfigGetSuccessSchema,Zn as tagsMatchingPrefix,Zr as require_dist$2,Zt as SuggestLinksSuccessSchema,_ as BridgeMergeContentLossError,_n as applyFastDiff,_r as _null,_t as LocalOpOpenRequestSchema,a as AgentBurstDiffSuccessSchema,an as SyncTriggerSuccessSchema,ar as ConfigSchema$1,at as InstallSkillRequestSchema,b as CC1ConfigValidationRejectedPayloadSchema,bn as classifyMarkdownHref,br as boolean,bt as MetricsAgentPresenceSuccessSchema,c as AgentUndoRequestSchema,cn as TemplateDeleteSuccessSchema,cr as applyPatchToDocument,ct as LinkGraphSuccessSchema,d as AgentWriteMdSuccessSchema,dn as TemplatePutSuccessSchema,dr as validatePatchScopes,dt as LocalOpAuthIdentitySuccessSchema,en as SyncConflictsSuccessSchema,er as unwrapFrontmatterFences,et as ForwardLinksSuccessSchema,f as AgentWriteRequestSchema,fn as TestRescanBacklinksSuccessSchema,fr as withConfigSpan,ft as LocalOpAuthPatRequestSchema,g as BridgeInvariantViolationError,gn as WorkspaceSuccessSchema,gr as _enum,gt as LocalOpCloneRequestSchema,h as BacklinksSuccessSchema,hn as UploadRequestSchema,hr as ZodOptional$1,ht as LocalOpAuthStatusSuccessSchema,i as AgentActivitySuccessSchema,in as SyncTriggerRequestSchema,ir as CONFIG_SCHEMA_MAJOR_PATH,it as INLINE_RENDERABLE_EXTENSIONS,j as CONFIG_DOC_NAME_OKIGNORE,jn as expandTagToHierarchy,jr as string,jt as RescueListSuccessSchema,k as CC1_CONTRACT_VERSION,kn as detectAppliedToleranceClasses,kr as preprocess,kt as RenamePathRequestSchema,l as AgentUndoSuccessSchema,ln as TemplateGetSuccessSchema,lr as locateIssue,lt as LocalOpAuthEmptySuccessSchema,m as BacklinkCountsSuccessSchema,mn as UploadAssetSuccessSchema,mt as LocalOpAuthSetIdentityRequestSchema,nn as SyncResolveConflictSuccessSchema,nr as PluginKey,nt as HistoryVersionSuccessSchema,o as AgentPatchRequestSchema,on as TagsForNameSuccessSchema,or as LOCAL_DIR,ot as InstallSkillSuccessSchema,p as AgentWriteSuccessSchema,pn as TestResetSuccessSchema,pr as withConfigSpanSync,pt as LocalOpAuthPatSuccessSchema,q as DocumentReadSuccessSchema,qn as resolveInternalHref,qr as defineLazy,qt as SkillInstallStateSuccessSchema,r as ASSET_EXTENSIONS,rn as SyncStatusSchema,rr as Fragment,rt as HubsSuccessSchema,s as AgentPatchSuccessSchema,sn as TagsListSuccessSchema,sr as addConfigSpanEvent,st as InstalledAgentsSuccessSchema,t as AGENT_ICON_COLORS,tn as SyncResolveConflictRequestSchema,tr as getSchema,tt as HistorySuccessSchema,u as AgentWriteMdRequestSchema,un as TemplatePutRequestSchema,ur as toConfigIssue,ut as LocalOpAuthHostRequestSchema,v as CC1BranchSwitchedPayloadSchema,vn as applyIncrementalDiff,vt as LocalOpOpenSuccessSchema,w as CC1_CHANNEL_BRANCH_SWITCHED,wn as createCodeFenceTracker,wr as literal,wt as OrphansSuccessSchema,x as CC1DerivedViewPayloadSchema,xn as classifyWikiLinkTarget,xr as custom,xt as MetricsParseHealthSuccessSchema,y as CC1ConfigIgnoreNestedErrorPayloadSchema,yn as assertNeverProblemType,yr as array,yt as MarkdownManager,z as DEFAULT_DEDUP_MODE,zn as isKnownConfigError,zr as meta$1,zt as SaveVersionSuccessSchema}from"./dist-D3xMMmYf.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BbkJd7ro.mjs";import{a as acquireProcessLock,c as isValidLockPid,f as readServerLock,g as updateProcessLockPort,m as releaseServerLock,n as RUNTIME_VERSION,o as acquireServerLock,p as releaseProcessLock,s as isProcessAlive,t as ProcessLockCollisionError,u as readProcessLock}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{a as require_src$15,i as esm_default,r as withParentLock,t as createGitInstance}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{r as diffLines,t as createPatch}from"./libesm-YL3Bqolr.mjs";import{n as mimes,t as build_default}from"./build-fAc55Z_L.mjs";import{t as b1}from"./chunk-YNYSPYQ5-Dq-BWW-f.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-CkMj9l7f.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-Vm1q1kLH.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-Cd7Fiqsb.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-DSqbA7Rj.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BQ5SUtd7.mjs";import"./chunk-DXB73IDG-DfmyzFzL.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-SLhNX8t9.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DQP-O5US.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-D4lSWh0K.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-_PX4ITYZ.mjs";import{n as n$1}from"./chunk-3THT3N7L-DrzOuTpA.mjs";import{t as n$2}from"./chunk-44UOCSGV-BbZqjKvt.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,closeSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import{Transform}from"node:stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import crypto$2 from"crypto";import*as zlib$2 from"zlib";import{access,constants,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,writeFile}from"node:fs/promises";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{Http2ServerRequest,constants as constants$1}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
2
2
  `)){let e=s.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let s=JSON.parse(e.slice(17));if(typeof s==`object`&&s&&`id`in s&&typeof s.id==`string`&&`name`in s&&typeof s.name==`string`&&`docs`in s&&Array.isArray(s.docs)&&s.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in s)||typeof s.colorSeed==`string`)){let e=s;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(s)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let s;try{s=JSON.parse(e.slice(18))}catch{return null}if(typeof s!=`object`||!s)return null;let g=s,S=g.kind,w=g.metadata;if(typeof w!=`object`||!w)return null;let E=typeof g.docName==`string`?g.docName:null,D=typeof g.size==`number`&&Number.isFinite(g.size)?g.size:null;if(S===`bridge-merge-loss`){let e=w;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:E,size:D,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(S===`external-change-rescue`){let e=w;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:E,size:D,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}return null}return null}function formatCheckpointBodyLine(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${OK_CHECKPOINT_PREFIX}${JSON.stringify(t)}`}const OK_ACTOR_PREFIX=`ok-actor: `;function formatOkActor(e){let{summaries:t,previous_paths:s,...g}=e,S={...g};return t&&t.length>0&&(S.summaries=t),s&&s.length>0&&(S.previous_paths=s),`${OK_ACTOR_PREFIX}${JSON.stringify(S)}`}function parseOkActorObject(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,s=typeof e.agent_session==`string`?e.agent_session:null,g;if(typeof e.writer_id==`string`&&e.writer_id.length>0)g=e.writer_id;else if(s)g=`agent-${s}`;else if(t)g=t;else switch(e.display_name){case`File System`:g=`file-system`;break;case`Git (upstream)`:g=`git-upstream`;break;default:g=`openknowledge-service`}let S=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,w=parsePreviousPaths(e);return{v:1,writer_id:g,principal:t,agent_session:s,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...S&&S.length>0?{summaries:S}:{},...w&&w.length>0?{previous_paths:w}:{}}}function parsePreviousPaths(e){if(!(`previous_paths`in e)||!Array.isArray(e.previous_paths))return;let t=[];for(let s of e.previous_paths){if(typeof s!=`object`||!s)continue;let e=s;typeof e.from!=`string`||typeof e.to!=`string`||t.push({from:e.from,to:e.to})}return t}function parseOkActors(e){if(!e)return[];let t=[];for(let s of e.split(`
4
4
  `)){let e=s.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let g;try{g=JSON.parse(e.slice(10))}catch{continue}if(typeof g!=`object`||!g)continue;let S=parseOkActorObject(g);S&&t.push(S)}return t}function okActorToShadowContributor(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function readContributors(e){let t=parseOkActors(e);return t.length>0?t.map(okActorToShadowContributor):parseContributors(e)}function formatWipSubject(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function formatReconcileSubject(e){return`reconcile: ${e}`}function formatRollbackSubject(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function formatParkSubject(e,t){return`park: ${e} -> ${t}`}function formatRenameSubject(e,t){return`rename: ${e} -> ${t}`}function formatCheckpointSubject(e){return`checkpoint: ${e}`}function formatImportSubject(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const SUBJECT_LINE_BREAK_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function stripLineBreaks(e){return e.replace(SUBJECT_LINE_BREAK_RE,` `)}function composeCommitSubject(e,t){let s=stripLineBreaks(e);if(t.length===0)return s;if(t.length>=2)return`${s} (${t.length} edits)`;let[g]=t;if(g===void 0)return s;let S=stripLineBreaks(g),w=`${s} — ${S}`;if(w.length<=72)return w;let E=`${s} — `,D=72-E.length-1;return D<=0?w.slice(0,72):`${E}${S.slice(0,D)}…`}function parseWriterId(e){return WRITER_ID_RE.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var require_err_helpers=__commonJSMin$1(((e,t)=>{let s=e=>e&&typeof e.message==`string`,g=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return s(t)?t:void 0}else return s(t)?t:void 0},S=(e,t)=>{if(!s(e))return``;let w=e.stack||``;if(t.has(e))return w+`
@@ -1508,10 +1508,10 @@ tags: [published]
1508
1508
  (Final version. Treat as immutable; if you need to revise, fork to a new draft.)
1509
1509
  `},STARTER_PACKS={"knowledge-base":{id:`knowledge-base`,name:`Knowledge base`,description:`Source-grounded canonical articles. Three layers — sources → research → articles — wired to the ingest / research / consolidate MCP tools.`,defaultSubfolder:`brain`,folders:KNOWLEDGE_BASE_FOLDERS,templates:KNOWLEDGE_BASE_TEMPLATES,rootFiles:{"log.md":KNOWLEDGE_BASE_LOG_MD}},"software-lifecycle":{id:`software-lifecycle`,name:`Software lifecycle`,description:`Proposals, decisions, specs, postmortems, guides — the doc lifecycle for an engineering team or OSS project.`,defaultSubfolder:`project-docs`,folders:SOFTWARE_LIFECYCLE_FOLDERS,templates:SOFTWARE_LIFECYCLE_TEMPLATES},"plain-notes":{id:`plain-notes`,name:`Plain notes`,description:`Just notes/ + daily/. The "I just want to write" escape hatch — no posture imposed, link freely.`,defaultSubfolder:void 0,folders:PLAIN_NOTES_FOLDERS,templates:PLAIN_NOTES_TEMPLATES},worldbuilding:{id:`worldbuilding`,name:`Worldbuilding`,description:`Encyclopedia for fiction: characters, settings, themes, factions, lore. The graph is the product — agent excels at auto-stub creation and dead-link sweeps.`,defaultSubfolder:`world`,folders:WORLDBUILDING_FOLDERS,templates:WORLDBUILDING_TEMPLATES},"writing-pipeline":{id:`writing-pipeline`,name:`Writing pipeline`,description:`Three-stage drafting flow: ideas → drafts → published. Lean by default; CRDT history covers per-file revisions.`,defaultSubfolder:`writing`,folders:WRITING_PIPELINE_FOLDERS,templates:WRITING_PIPELINE_TEMPLATES}},STARTER_PACK_IDS=Object.keys(STARTER_PACKS);function resolvePack(e){return e&&STARTER_PACKS[e]||STARTER_PACKS[DEFAULT_PACK_ID]}function isKnownPackId(e){return typeof e==`string`&&STARTER_PACK_IDS.includes(e)}function coercePackId(e){return isKnownPackId(e)?e:void 0}function deriveFolderSummary(e){let t=e.trim(),s=(/^([^.!?]+[.!?])/.exec(t)?.[1]??t).trim();return s.length<=140?s:`${s.slice(0,137)}…`}function listStarterPacks(){return STARTER_PACK_IDS.map(e=>{let t=STARTER_PACKS[e];return{id:t.id,name:t.name,description:t.description,defaultSubfolder:t.defaultSubfolder,folders:t.folders.map(e=>({path:e.path,summary:deriveFolderSummary(e.description)}))}})}const STARTER_FOLDERS=KNOWLEDGE_BASE_FOLDERS,STARTER_TEMPLATES=KNOWLEDGE_BASE_TEMPLATES,LOG_MD_TEMPLATE=KNOWLEDGE_BASE_LOG_MD,STARTER_FOLDER_FRONTMATTER_FILENAME=`frontmatter.yml`;function buildStarterFolderFrontmatterYaml(e){let t=[];t.push(`title: ${yamlScalar(e.title)}`),t.push(`description: ${yamlScalar(e.description)}`),t.push(`tags:`);for(let s of e.tags)t.push(` - ${yamlScalar(s)}`);return`${t.join(`
1510
1510
  `)}\n`}function yamlScalar(e){return e===``?`""`:/[:#\n"'\\]|^\s|\s$/.test(e)?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e}function resolveFileContent(e,t){let s=/^([^/]+)\/\.ok\/frontmatter\.yml$/.exec(e);if(s){let e=t.folders.find(e=>e.path===s[1]);return e?buildStarterFolderFrontmatterYaml(e):void 0}let g=/^([^/]+)\/\.ok\/templates\/([^/]+)\.md$/.exec(e);if(g){let e=g[2]??``;return t.templates[e]}if(!e.includes(`/`)&&t.rootFiles?.[e]!==void 0)return t.rootFiles[e]}async function applySeed(e,t={}){let s=Date.now(),g=resolve(t.projectDir??process.cwd()),S=resolvePack(t.packId??`knowledge-base`),w=0,E=[],D=[];for(let t of e.created)try{let e=assertEntryPathInProject(g,t.path);D.push({entry:t,absPath:e})}catch(e){E.push({path:typeof t.path==`string`?t.path:String(t.path),error:e instanceof SeedRootDirError||e instanceof Error?e.message:String(e)})}for(let{entry:e,absPath:t}of D.filter(e=>e.entry.kind===`folder`))try{mkdirSync(t,{recursive:!0}),w+=1}catch(t){E.push({path:e.path,error:t instanceof Error?t.message:String(t)})}for(let{entry:e,absPath:t}of D.filter(e=>e.entry.kind===`file`)){let s=e.template??e.path,g=resolveFileContent(s,S);if(g===void 0){E.push({path:e.path,error:`No content template registered for template id "${s}" in pack "${S.id}"`});continue}if(!existsSync(t))try{writeFileSync(t,g,`utf-8`),w+=1}catch(t){E.push({path:e.path,error:t instanceof Error?t.message:String(t)})}}return{applied:w,errors:E,durationMs:Date.now()-s}}const PERSONAL_TEMPLATES={"daily-journal":`---
1511
- title: {{date}}
1511
+ title: '{{date}}'
1512
1512
  description: Daily journal entry — universal template, works in any vault.
1513
- date: {{date}}
1514
- author: {{user}}
1513
+ date: '{{date}}'
1514
+ author: '{{user}}'
1515
1515
  mood:
1516
1516
  weather:
1517
1517
  top3: []
@@ -1536,8 +1536,8 @@ tags: [daily, journal]
1536
1536
  `,"meeting-notes":`---
1537
1537
  title: Meeting — <topic>
1538
1538
  description: One file per meeting. Update title with the actual topic after instantiation.
1539
- date: {{date}}
1540
- author: {{user}}
1539
+ date: '{{date}}'
1540
+ author: '{{user}}'
1541
1541
  attendees: []
1542
1542
  agenda: []
1543
1543
  decisions: []
@@ -1561,10 +1561,10 @@ tags: [meeting]
1561
1561
 
1562
1562
  (Concrete TODOs with owners — also in frontmatter for sweeps.)
1563
1563
  `,"weekly-review":`---
1564
- title: Week of {{date}}
1564
+ title: 'Week of {{date}}'
1565
1565
  description: Friday sweep — what shipped, what stalled, what's next.
1566
- week_of: {{date}}
1567
- author: {{user}}
1566
+ week_of: '{{date}}'
1567
+ author: '{{user}}'
1568
1568
  shipped: []
1569
1569
  stalled: []
1570
1570
  next_week: []
@@ -1614,10 +1614,10 @@ tags: [reading]
1614
1614
 
1615
1615
  (Other reading this links to — \`[[wiki-links]]\` to other entries.)
1616
1616
  `,"gym-log":`---
1617
- title: {{date}} — <workout type>
1617
+ title: '{{date}} — <workout type>'
1618
1618
  description: Per-workout log entry.
1619
- date: {{date}}
1620
- author: {{user}}
1619
+ date: '{{date}}'
1620
+ author: '{{user}}'
1621
1621
  workout_type:
1622
1622
  duration_min:
1623
1623
  lifts: []
@@ -2365,4 +2365,4 @@ In headless mode, write the recap into the research article's "Further reading"
2365
2365
  `).split(`
2366
2366
  `),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:s}of e)try{let e=readFileSync(s,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let s;try{s=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1}=e,J=getLogger(`server`);function Y(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||J.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ee=randomUUID(),te=getLocalDir(s);if(acquireServerLock(te,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:te,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(te),e}let ne=createBasenameIndex(),ae=(e,t)=>ne.resolveEmbed(e,t),oe=(e,s)=>{let g=ne.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g),w=resolve(t);if(S!==w&&!S.startsWith(`${w}/`))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},se,ce,ue,de,fe,me,ge,_e=null,ve=null,ye=null,Ce=null,we=new Set,Te=!1,De,je,Me,Pe=new Promise((e,t)=>{je=e,Me=t});function Ie(e){_e?.signal(e)}let Re=2e3,ze=null;function Be(){ze!==null&&clearTimeout(ze),ze=setTimeout(()=>{ze=null,ce.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let Ve=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ue=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||Ve.setRenamed(e,t)},We=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(Ve.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ve.setDeleted(e)}},Ge=e=>{isSystemDoc(e)||isConfigDoc(e)||Ve.delete(e)};try{se=createContentFilter({projectDir:s,contentDir:t,onAfterRebuild:()=>{ce.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{ue.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let e=Ft?.pruneFileIndexNowExcluded()??0;e>0&&getLogger(`server-factory`).info({pruned:e},`[content-filter] pruned now-excluded entries from fileIndex`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] fileIndex prune failed after onAfterRebuild`)}}}),ce=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:se}),ue=new TagIndex({contentDir:t,contentFilter:se});try{ue.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}de={current:F},fe=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:de,contentRoot:L,backlinkIndex:ce,configHomedirOverride:k,getCurrentBranch:()=>It?.getLastKnownBranch()??null,resolveEmbed:ae,resolveSize:oe,getPrincipal:()=>Ce,onAgentCommit:()=>_e?.signal(`session-activity`),onDiskFlush:(e,t)=>_e?.emitDiskAck(e,t),onConfigRejected:(e,t)=>_e?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),me=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[fe.extension]});let B=me.shouldUnloadDocument.bind(me);me.shouldUnloadDocument=e=>{if((Te||we.has(e))&&B(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},De=async e=>{we.add(e);try{await me.unloadDocument(e)}finally{we.delete(e)}},_e=new CC1Broadcaster(me),ve=new AgentFocusBroadcaster(me),ye=new AgentPresenceBroadcaster(me),ge=new AgentSessionManager(me);let q=createLiveDerivedIndexExtension({backlinkIndex:ce,tagIndex:ue,signalChannel:Ie});me.configuration.extensions.push(q),me.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==ee)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ee}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(Ce&&s.principalId===Ce.id?E.principalId=Ce.id:Ce?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Ce.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),me.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,s=t.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s))throw Error(`config-doc admission requires loopback peer (peer=${s}, doc=${e.documentName})`);let g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let J=resolve(t);function Y(e){if(!isSafeDocName(e))return null;let t=resolve(J,`${e}${getDocExtension(e)}`);return!t.startsWith(`${J}/`)&&t!==J?null:t}me.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Ve,resolveFilePath:Y,fileExists:existsSync})}}),me.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let te=createApiExtension({hocuspocus:me,sessionManager:ge,contentDir:t,contentFilter:se,serverInstanceId:ee,getFileIndex:()=>Ft?Ft.getFileIndex():new Map,getFolderIndex:()=>Ft?Ft.getFolderIndex():new Map,getAliasMap:()=>Ft?Ft.getAliasMap():new Map,enableTestRoutes:j,shadowRef:de,flushGitCommit:()=>fe.flushPendingGitCommit(),flushContributors:()=>fe.flushContributors(),getCurrentBranch:()=>It?.getLastKnownBranch()??null,getDiskAckSVs:()=>_e?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:ce,tagIndex:ue,signalChannel:Ie,agentFocusBroadcaster:ve,agentPresenceBroadcaster:ye,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Lt,localOpCliArgs:H,projectDir:s,resolveEmbed:ae,getPrincipal:()=>Ce,forceUnloadDocument:De,ready:Pe,recentlyRemovedDocs:Ve});me.configuration.extensions.push(te),me.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:de,contentRoot:L,getCurrentBranch:()=>It?.getLastKnownBranch()??null,resolveEmbed:ae,resolveSize:oe}))}catch(e){throw releaseServerLock(te),e}let Ke=null,Xe=new Map,$e=[];function nt(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function rt(e){let t=me.documents.get(e);if(!t)return null;let{frontmatter:s,body:g}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(s,g)}let it=(e,t)=>applyExternalChange(me,e,t,ae,oe),at=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of me.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=me.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,ae,s)},FILE_WATCHER_ORIGIN)}catch(t){J.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},st=null,vt=e=>{e&&(st===null&&(st=new Set,setImmediate(()=>{let e=st;if(st=null,e)try{for(let t of e)at(t)}catch(t){J.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),st.add(e))};function Tt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Et(e){try{switch(e.kind){case`create`:J.info({docName:e.docName},`[reconcile] create: ${e.docName}`),ce.updateDocumentFromMarkdown(e.docName,e.content),Be(),ue.updateDocumentFromMarkdown(e.docName,e.content),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),Ge(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=me.documents.get(t);if(!g){ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`);return}let S=getReconciledBase(t)??``,w=rt(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(J.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`);break;case`clean`:try{it(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`merged`:try{it(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`conflicts`:try{it(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=me.documents.get(t);if(!s){ce.deleteDocument(t),Be(),ue.deleteDocument(t),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),We(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=rt(t)??``,w=S!==g;if(w&&de.current){let e=de.current,s=It?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{J.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),ce.deleteDocument(t),Be(),ue.deleteDocument(t),J.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),me.closeConnections(t),await De(s),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),We(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:s,content:g}=e,S=me.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),ce.renameDocument(t,s,g),Be(),ue.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}J.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),Ue(t,s),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:s,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,s=me.documents.get(t);if(!s)return;let g=s.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),J.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ne.add(e.relativePath),Ie(`files`),vt(basename(e.relativePath));break;case`asset-delete`:ne.remove(e.relativePath),Ie(`files`),vt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Ie(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Tt(e);J.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Dt=[];async function jt(e){if(isBatchInProgress()){Dt.push(e);return}await Et(e)}async function Mt(){let e=Dt.splice(0,Dt.length);for(let t of e)await Et(t)}let Ft=null,It=null,Lt=null,Rt=null;async function zt(e){if(me.documents.size===0)return;let t=!1,s=new Promise(e=>{me.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(me.documents.keys());me.closeConnections(),me.flushPendingStores();for(let e of me.documents.values())e.getConnectionsCount()===0&&me.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(me.documents.keys()),S=[],E=[];if(de.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=rt(e);if(t===null){J.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=nt(de.current.gitDir,e);if(!s){J.warn({docName:e,gitDir:de.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),J.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),J.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else J.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function Bt(){return Rt||(Rt=(async()=>{let e=Date.now(),t=[];Te=!0,ze!==null&&(clearTimeout(ze),ze=null);let g,S=await Promise.race([Pe.then(()=>`completed`,e=>(J.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&J.warn({},`[server] init did not complete within 5s during shutdown`);let w=me.documents.size;try{try{try{It&&=(await It.unsubscribe(),null),Ft&&=(await Ft.unsubscribe(),null);for(let{docName:e,cleanup:t}of $e)try{await t()}catch(t){J.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}$e.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{_e?.destroy(),ye?.destroy(),Ke&&=(await Ke.disconnect(),null);for(let[e,t]of Xe)try{await t.disconnect()}catch(t){J.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Xe.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ge.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await zt(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await fe.flushPendingGitCommit(),await fe.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Lt&&=(await Lt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(de.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(de.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(de.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?J.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):J.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(te)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Rt)}let Vt=[];async function Ht(){try{Ce=await loadPrincipal(s),J.info({principalId:Ce.id},`[server] principal loaded`)}catch(e){J.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!de.current)try{de.current=await initShadowRepo(s),J.info({gitDir:de.current.gitDir},`[server] history repo initialized at ${de.current.gitDir}`)}catch(e){J.error({err:e},`[server] history repo init failed`),Vt.push(`shadow-repo`)}if(de.current){let e=null;try{e=loadRenameLogIndex(de.current.gitDir),sweepLazyPopOrphans(de.current.gitDir,e),setRenameLogIndex(de.current.gitDir,e),J.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){J.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(de.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){J.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(de.current)try{await shadowGit(de.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){J.warn({},`[server] history repo appears corrupted — reinitializing`);try{de.current=await initShadowRepo(s)}catch(e){J.error({err:e},`[server] history repo reinit failed`),de.current=void 0,Vt.includes(`shadow-repo`)||Vt.push(`shadow-repo`)}}else J.error({err:e},`[server] history repo check failed (transient?)`)}if(de.current)try{let e=resolve(de.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==t){let e=`main`;try{let t=(await esm_default({baseDir:s,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}J.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(de.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){J.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else J.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){J.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){J.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,s);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,s=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;J.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){J.error({err:e},`[server] managed rename recovery failed`),Vt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&J.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){J.error({err:e},`[server] upload-tempfile sweep failed`),Vt.push(`upload-tempfile-sweep`)}try{Ke=await me.openDirectConnection(SYSTEM_DOC_NAME),_e?.emitServerInfo(ee,getActiveBranch())}catch(e){J.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Vt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await me.openDirectConnection(e);Xe.set(e,t)}catch(t){J.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Vt.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,s)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,s)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,s,k)]]);for(let t of CONFIG_DOC_NAMES){let s=e.get(t);if(s)try{J.info({docName:t,path:s},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(s,e=>{let s=me.documents.get(t);J.info({docName:t,hasDocument:s!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,t,e,fe.configPersistenceCtx);if(J.info({docName:t,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=Y();Lt?.setEnabled(e).catch(t=>{J.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});$e.push({docName:t,cleanup:e}),J.info({docName:t,path:s},`[config-file-watcher] started`)}catch(e){J.warn({err:e,docName:t,path:s},`[config-file-watcher] failed to start for ${t}`),Vt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=J;S.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let w=await startMultiPathConfigFileWatcher([e,g],(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(me.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,fe.configPersistenceCtx);S.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){S.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let w=await se.rebuildIgnorePatterns();if(w.ok)S.info({changedPath:relative(s,t),patternCount:w.patternCount,nestedFileCount:w.nestedFileCount,durationMs:w.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),_e?.signal(`files`);else{let e=relative(s,t)||`.`;S.warn({changedPath:e,error:w.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),_e?.emitConfigIgnoreNestedError(e,w.error.message)}})().catch(e=>{S.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});$e.push({docName:`__ignore-files__`,cleanup:w}),S.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`)}catch(e){J.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Vt.push(`ignore-files-watcher`)}let g=resolveGitDir(s),S=g?readBranchFromHead(g)??`main`:`main`;switchReconciledBaseScope(S),ce.switchBranch(S);try{{let e=getActiveBranch();try{if(await ce.loadFromDisk(e)){let t=await ce.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&J.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await ce.rebuildFromDisk(e);ce.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){J.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Ft=await startWatcher(t,jt,se),ue.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:se,basenameIndex:ne,onSkip:(t,s,g)=>{e++,J.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during seed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Vt.push(`basename-index-partial`))}catch(e){J.error({err:e},`[basename-index] startup seed failed`),Vt.push(`basename-index`)}}catch(e){J.error({err:e},`[server] disk bridge watcher failed to start`),Vt.push(`file-watcher`)}try{It=await startHeadWatcher(s,async({trigger:e})=>{if(J.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),me.flushPendingStores(),await fe.flushPendingGitCommit(),setBatchInProgress(!0),de.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of me.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=rt(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(de.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),J.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){J.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Dt.length,g=e.newBranch??`main`;if(J.info({kind:e.batchKind,headMoved:e.headMoved,docs:s,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${s}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)setBatchInProgress(!1),await Mt(),await fe.flushDeferredStores(`within-branch`);else{incrementBranchSwitch(),Dt.splice(0,Dt.length),switchReconciledBaseScope(g),ze!==null&&(clearTimeout(ze),ze=null),ce.switchBranch(g),se.rebuildDirCount();try{let e=0;ne.clear(),seedBasenameIndex({contentDir:t,contentFilter:se,basenameIndex:ne,onSkip:(t,s,S)=>{e++,J.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Vt.includes(`basename-index-partial`)||Vt.push(`basename-index-partial`))}catch(e){J.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of me.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=rt(e)??``;if(S!==t&&de.current){let t=de.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{J.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),J.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);it(e,w),setReconciledBase(e,w),J.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){J.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}J.info({branch:g,docCount:me.documents.size},`[branch-switch] loaded branch ${g} (${me.documents.size} docs)`);try{if(await ce.loadFromDisk(g)){let e=await ce.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&J.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await ce.rebuildFromDisk(g);ce.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){J.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(ue.init(),de.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of me.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(de.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:it(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:it(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){J.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&J.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&de.current)try{let t=shadowGit(de.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
2367
2367
  `))e&&await t.raw(`update-ref`,`-d`,e);J.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){J.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await fe.flushDeferredStores(`discard-stale`),_e?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&de.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(de.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),J.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){J.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){J.error({err:e},`[server] HEAD watcher failed to start`),Vt.push(`head-watcher`)}let w=H?.[0]??`open-knowledge`,E=[`-c`,`credential.helper=!${H&&H.length>1?H.join(` `):w} auth git-credential`];try{Lt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:se,contentRoot:L,syncEnabled:Y(),credentialArgs:E,cc1Broadcaster:_e,setBatchInProgress:e=>{setBatchInProgress(e),e||fe.flushDeferredStores(`within-branch`).catch(e=>{J.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{J.info({state:e},`[sync] state → ${e}`)},onAutoDisable:async e=>{J.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||J.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 Lt.start()}catch(e){J.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Lt=null}Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}return Ht().then(je,Me),{hocuspocus:me,sessionManager:ge,cc1Broadcaster:_e,agentFocusBroadcaster:ve,agentPresenceBroadcaster:ye,contentFilter:se,basenameIndex:ne,serverInstanceId:ee,destroy:Bt,ready:Pe,degraded:Vt,lockDir:te,get syncEngine(){return Lt}}}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;async function bootServer(e){initTelemetry();let{kind:t,gitdir:s}=computeWorktreeAttributes(e.projectDir??e.contentDir),g={"ok.worktree.kind":t};return s!==null&&(g[`ok.worktree.gitdir`]=normalizeFsPath(s)),withSpan(`ok.boot`,{attributes:g},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-D7DXNVql-B5nINglj.mjs`).then(e=>e.a),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=findLegacyRuntimeFiles(F);L.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${L.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let B=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}),{hocuspocus:H,destroy:q,ready:J,degraded:Y,lockDir:ee,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:ae}=B,oe=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),se=e.port??0,ce=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${oe}:${se}`,log:S}),ue=D();ue.headersTimeout=3e4,ue.requestTimeout=6e4;let de=e.serveContentAssets?createAssetServeMiddleware({contentFilter:B.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,fe=mountMcpAndApi({httpServer:ue,hocuspocus:H,mcpHttpHandler:ce,log:S,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:ae,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:de}),me=null;g!==null&&(me=attachIdleShutdown({httpServer:ue,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await q()})})),await new Promise((t,s)=>{let g=e=>s(e);ue.once(`error`,g),ue.listen(e.port,e.host,()=>{ue.removeListener(`error`,g),t()})});let ge=ue.address(),_e=typeof ge==`object`&&ge?ge.port:e.port??0;if(se=_e,O(ee,_e),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ee,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let ve=!1,ye=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)}};return{httpServer:ue,destroy:async()=>{if(ve)return;ve=!0;let e=[],t=async(t,s)=>{try{await ye(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{me?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>fe.shutdown()),await t(`mcpHttpHandler.close`,()=>ce.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{fe.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ue.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ue.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>q()),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},lockDir:ee,contentDir:e.contentDir,port:_e,ready:J,degraded:Y,didAutoInit:k,serverInstance:B}}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 ANCESTOR_WALK_DEPTH_LIMIT$1=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT$1;){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 ANCESTOR_WALK_DEPTH_LIMIT=30,OK_CONFIG_MARKER=`.ok/config.yml`;function findEnclosingProjectRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,OK_CONFIG_MARKER))}catch{e=!1}if(e)return{rootPath:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.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};console.log(`[project-git] detected partial .git/ — running git init to repair`),S=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let w=``;try{w=(await execFileAsync(`git`,[`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)`,w);return S?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{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}}export{applySeed as $,runAuthReposSubprocess as $n,incrementCollabSocketFilteredError as $t,MissingOkConfigError as A,readServerPackageVersion as An,updateUiLockPort as Ar,createServer$1 as At,STARTER_FOLDER_FRONTMATTER_FILENAME as B,registerWrite as Bn,McpServer as Br,findEnclosingGitRoot as Bt,LOG_MD_TEMPLATE as C,parseHocuspocusAuthToken as Cn,tracedRenameSync as Cr,createContentFilter as Ct,MCP_SERVER_NAME as D,planSeed as Dn,tracedWriteFile as Dr,createMcpHttpHandler as Dt,MCP_CONNECTION_ID_HEADER as E,planPersonalTemplates as En,tracedUnlinkSync as Er,createLiveDerivedIndexExtension as Et,ProjectGitInitError as F,readUiLock as Fn,withSpanSync as Fr,detectProjectShape as Ft,SeedPrerequisiteError as G,resolveContentDir as Gn,isJSONRPCResultResponse as Gr,getCurrentMcpLogger as Gt,STARTER_PACK_IDS as H,removeLastKnownHash as Hn,LATEST_PROTOCOL_VERSION as Hr,formatAuthRejectionWire as Ht,ROLLBACK_ORIGIN as I,reconcile as In,writePersonalTemplates as Ir,ensureProjectGit as It,TagIndex as J,resolveLockDir as Jn,writeConfigPatch as Jr,getMeter as Jt,SeedRootDirError as K,resolveCursorBinaryDefault as Kn,readConfigSafely as Kr,getLocalDir as Kt,SERVICE_WRITER as L,recordContributor as Ln,writeStateManifest as Lr,errorResponse as Lt,PERSONAL_TEMPLATES as M,readStateManifest as Mn,validateCloneInputs as Mr,createStreamingErrorWriter as Mt,PERSONAL_TEMPLATE_NAMES as N,readTargetRecordedAt as Nn,validateSkillZip as Nr,createTestLogger as Nt,MISSING_OK_CONFIG_MESSAGE as O,readAllTargets as On,tracedWriteFileSync as Or,createOsProbe as Ot,PinoLogger as P,readTargetVersion as Pn,withSpan as Pr,detectClaudeDesktopPresence as Pt,applyExternalChange as Q,rewriteWikiLinksForDocumentRename as Qn,handleSpawnCursor as Qt,SKILL_INSTALL_EVENTS_FILE_REL as R,recordSkillInstallEvent as Rn,writeTargetVersion as Rr,evictStaleTrackerEntries as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,parseAuthRejectionWire as Sn,tracedRename as Sr,createAssetServeMiddleware as St,MAX_AGENT_SESSIONS as T,pathToDocName as Tn,tracedRmdirSync as Tr,createExternalChangeHandler as Tt,STARTER_TEMPLATES as U,resetMetrics as Un,isInitializedNotification as Ur,formatContributors as Ut,STARTER_PACKS as V,releaseUiLock as Vn,JSONRPCMessageSchema as Vr,findEnclosingProjectRoot as Vt,STATE_MANIFEST_FILENAME as W,resolveBundledSkillDir as Wn,isJSONRPCRequest as Wr,gcCheckpointRefs as Wt,acquireUiLock as X,resolvePackageVersion as Xn,MalformedGitPointerError as Xr,getTracer as Xt,UiLockCollisionError as Y,resolvePack as Yn,GitDirAccessError as Yr,getMetrics as Yt,applyAgentMarkdownWrite as Z,rewriteMarkdownLinksForDocumentRename as Zn,handleCollabSocketError as Zt,GIT_UPSTREAM_WRITER as _,listStarterPacks as _n,toBroadcasterKey as _r,commitWipFromTree as _t,AgentPresenceBroadcaster as a,isAllowedApiOrigin as an,safeSubdir as ar,buildExecResult as at,HocuspocusAuthTokenSchema as b,mountMcpAndApi as bn,tracedMkdir as br,contributorCount as bt,BacklinkIndex as c,isHocuspocusAuthRejectionReason as cn,saveInMemoryCheckpoint as cr,buildSkillZip as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,isPairedWriteOrigin as dn,setActiveSpanAttributes as dr,classifyEvents as dt,incrementServerObserverFire as en,runAuthStatusSubprocess as er,assertCompatibleStateManifest as et,ConfigSchema as f,isPathWithinDir as fn,shadowGit as fr,classifyFsPath as ft,FILE_WATCHER_ORIGIN as g,listRescueCheckpoints as gn,streamingProblemEvent as gr,commitWip as gt,FILE_SYSTEM_WRITER as h,lastKnownHash as hn,startWatcher as hr,commitUpstreamImport as ht,AgentFocusBroadcaster as i,installUserSkill as in,safeContentPath as ir,buildAndOpenSkill as it,OBSERVER_SYNC_ORIGIN as j,readSkillInstallStateSnapshot as jn,validateAgentId as jr,createServerObserverExtension as jt,McpLogger as k,readBranchFromHead as kn,updateLastKnownHash as kr,createPersistenceExtension as kt,CC1Broadcaster as l,isKnownPackId as ln,saveVersion as lr,buildStarterFolderFrontmatterYaml as lt,DEFAULT_PACK_ID as m,isSystemDoc as mn,splitMarkdownBlocks as mr,coercePackId as mt,AGENT_ID_RE as n,initTelemetry as nn,runDeviceFlowSubprocess as nr,attachIdleShutdown as nt,AgentSessionCapacityError as o,isAllowedWorkspaceHostHeader as on,safetyCheckpoint as or,buildInstructions as ot,DEFAULT_CHECKPOINT_RETENTION as p,isSelfWrite as pn,shutdownTelemetry as pr,clearContributors as pt,StateManifestError as q,resolveCursorSpawnInvocation as qn,resolveConfigPath as qr,getLogger as qt,AGENT_WRITE_ORIGIN as r,installTestLoggers as rn,runWithMcpLogger as rr,bootServer as rt,AgentSessionManager as s,isConfigDoc as sn,sanitizeClientName as sr,buildReadResult as st,AGENT_ID_MAX_LEN as t,initShadowRepo as tn,runCloneSubprocess as tr,assertNeverDiskEvent as tt,CONFLICT_MARKER_RE as u,isLoopbackAddress as un,seedBasenameIndex as ur,buildWipTree as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,loadPrincipal as vn,tracedAppendFileSync as vr,containsConflictMarkers as vt,MANAGED_RENAME_ORIGIN as w,parseKeepaliveConnectionId as wn,tracedRmSync as wr,createContentFilterAsync as wt,INSTALLED_AGENTS_SCHEMES as x,normalizeFsPath as xn,tracedMkdirSync as xr,createApiExtension as xt,HocuspocusAuthRejection as y,loggerFactory as yn,tracedLinkSync as yr,contentHash as yt,STARTER_FOLDERS as z,registerAllTools as zn,writeTracker as zr,extractWikiLinksFromMarkdown as zt};
2368
- //# sourceMappingURL=dist-Va4IjzRw.mjs.map
2368
+ //# sourceMappingURL=dist-DOIb_FW2.mjs.map
@@ -1 +1 @@
1
- import{Bn as e,Ct as t,Ft as n,Lt as r,Rn as i,Sn as a,k as o}from"./dist-H3Ld-L-a.mjs";import{_ as s,a as c,c as l,d as u,f as d,g as f,i as p,l as m,m as h,n as g,o as _,p as v,r as y,s as b,t as x,u as S}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{$ as C,$n as w,$t as T,A as E,An as D,Ar as O,At as k,B as A,Bn as j,Bt as M,C as N,Cn as P,Cr as F,Ct as I,D as L,Dn as R,Dr as z,Dt as B,E as V,En as H,Er as U,Et as W,F as G,Fn as K,Fr as q,Ft as J,G as Y,Gn as X,Gt as Z,H as Q,Hn as $,Ht as ee,I as te,In as ne,Ir as re,It as ie,J as ae,Jn as oe,Jt as se,K as ce,Kn as le,Kt as ue,L as de,Ln as fe,Lr as pe,Lt as me,M as he,Mn as ge,Mr as _e,Mt as ve,N as ye,Nn as be,Nr as xe,Nt as Se,O as Ce,On as we,Or as Te,Ot as Ee,P as De,Pn as Oe,Pr as ke,Pt as Ae,Q as je,Qn as Me,Qt as Ne,R as Pe,Rn as Fe,Rr as Ie,Rt as Le,S as Re,Sn as ze,Sr as Be,St as Ve,T as He,Tn as Ue,Tr as We,Tt as Ge,U as Ke,Un as qe,Ut as Je,V as Ye,Vn as Xe,Vt as Ze,W as Qe,Wn as $e,Wt as et,X as tt,Xn as nt,Xr as rt,Xt as it,Y as at,Yn as ot,Yr as st,Yt as ct,Z as lt,Zn as ut,Zt as dt,_ as ft,_n as pt,_r as mt,_t as ht,a as gt,an as _t,ar as vt,at as yt,b as bt,bn as xt,br as St,bt as Ct,c as wt,cn as Tt,cr as Et,ct as Dt,d as Ot,dn as kt,dr as At,dt as jt,en as Mt,er as Nt,et as Pt,f as Ft,fn as It,fr as Lt,ft as Rt,g as zt,gn as Bt,gr as Vt,gt as Ht,h as Ut,hn as Wt,hr as Gt,ht as Kt,i as qt,in as Jt,ir as Yt,it as Xt,j as Zt,jn as Qt,jr as $t,jt as en,k as tn,kn as nn,kr as rn,kt as an,l as on,ln as sn,lr as cn,lt as ln,m as un,mn as dn,mr as fn,mt as pn,n as mn,nn as hn,nr as gn,nt as _n,o as vn,on as yn,or as bn,ot as xn,p as Sn,pn as Cn,pr as wn,pt as Tn,q as En,qn as Dn,qt as On,r as kn,rn as An,rr as jn,rt as Mn,s as Nn,sn as Pn,sr as Fn,st as In,t as Ln,tn as Rn,tr as zn,tt as Bn,u as Vn,un as Hn,ur as Un,ut as Wn,v as Gn,vn as Kn,vr as qn,vt as Jn,w as Yn,wn as Xn,wr as Zn,wt as Qn,x as $n,xn as er,xr as tr,xt as nr,y as rr,yn as ir,yr as ar,yt as or,z as sr,zn as cr,zr as lr,zt as ur}from"./dist-Va4IjzRw.mjs";export{Ln as AGENT_ID_MAX_LEN,mn as AGENT_ID_RE,kn as AGENT_WRITE_ORIGIN,qt as AgentFocusBroadcaster,gt as AgentPresenceBroadcaster,vn as AgentSessionCapacityError,Nn as AgentSessionManager,wt as BacklinkIndex,on as CC1Broadcaster,o as CC1_CONTRACT_VERSION,Vn as CONFLICT_MARKER_RE,Ot as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Ft as ConfigSchema,Sn as DEFAULT_CHECKPOINT_RETENTION,un as DEFAULT_PACK_ID,Ut as FILE_SYSTEM_WRITER,zt as FILE_WATCHER_ORIGIN,ft as GIT_UPSTREAM_WRITER,st as GitDirAccessError,Gn as HOCUSPOCUS_AUTH_REJECTION_REASONS,rr as HocuspocusAuthRejection,bt as HocuspocusAuthTokenSchema,$n as INSTALLED_AGENTS_SCHEMES,Re as LIVE_DERIVED_INDEX_DEBOUNCE_MS,N as LOG_MD_TEMPLATE,Yn as MANAGED_RENAME_ORIGIN,He as MAX_AGENT_SESSIONS,V as MCP_CONNECTION_ID_HEADER,L as MCP_SERVER_NAME,Ce as MISSING_OK_CONFIG_MESSAGE,rt as MalformedGitPointerError,tn as McpLogger,E as MissingOkConfigError,Zt as OBSERVER_SYNC_ORIGIN,t as ORPHAN_MODES,he as PERSONAL_TEMPLATES,ye as PERSONAL_TEMPLATE_NAMES,De as PinoLogger,x as ProcessLockCollisionError,G as ProjectGitInitError,te as ROLLBACK_ORIGIN,g as RUNTIME_VERSION,de as SERVICE_WRITER,Pe as SKILL_INSTALL_EVENTS_FILE_REL,n as SKILL_STATE_TARGETS,sr as STARTER_FOLDERS,A as STARTER_FOLDER_FRONTMATTER_FILENAME,Ye as STARTER_PACKS,Q as STARTER_PACK_IDS,Ke as STARTER_TEMPLATES,Qe as STATE_MANIFEST_FILENAME,y as STATE_SCHEMA_VERSION,r as SYSTEM_DOC_NAME,Y as SeedPrerequisiteError,ce as SeedRootDirError,p as ServerLockCollisionError,En as StateManifestError,ae as TagIndex,at as UiLockCollisionError,c as acquireProcessLock,_ as acquireServerLock,tt as acquireUiLock,lt as applyAgentMarkdownWrite,je as applyExternalChange,C as applySeed,Pt as assertCompatibleStateManifest,Bn as assertNeverDiskEvent,_n as attachIdleShutdown,Mn as bootServer,Xt as buildAndOpenSkill,yt as buildExecResult,xn as buildInstructions,In as buildReadResult,Dt as buildSkillZip,ln as buildStarterFolderFrontmatterYaml,Wn as buildWipTree,jt as classifyEvents,Rt as classifyFsPath,Tn as clearContributors,pn as coercePackId,a as colorFromSeed,Kt as commitUpstreamImport,Ht as commitWip,ht as commitWipFromTree,Jn as containsConflictMarkers,or as contentHash,Ct as contributorCount,nr as createApiExtension,Ve as createAssetServeMiddleware,I as createContentFilter,Qn as createContentFilterAsync,Ge as createExternalChangeHandler,W as createLiveDerivedIndexExtension,B as createMcpHttpHandler,Ee as createOsProbe,an as createPersistenceExtension,k as createServer,en as createServerObserverExtension,ve as createStreamingErrorWriter,Se as createTestLogger,Ae as detectClaudeDesktopPresence,J as detectProjectShape,ie as ensureProjectGit,me as errorResponse,Le as evictStaleTrackerEntries,ur as extractWikiLinksFromMarkdown,M as findEnclosingGitRoot,Ze as findEnclosingProjectRoot,ee as formatAuthRejectionWire,Je as formatContributors,et as gcCheckpointRefs,Z as getCurrentMcpLogger,ue as getLocalDir,On as getLogger,se as getMeter,ct as getMetrics,it as getTracer,dt as handleCollabSocketError,Ne as handleSpawnCursor,i as iconFromClientName,T as incrementCollabSocketFilteredError,Mt as incrementServerObserverFire,Rn as initShadowRepo,hn as initTelemetry,An as installTestLoggers,Jt as installUserSkill,_t as isAllowedApiOrigin,yn as isAllowedWorkspaceHostHeader,Pn as isConfigDoc,Tt as isHocuspocusAuthRejectionReason,sn as isKnownPackId,Hn as isLoopbackAddress,e as isOrphanMode,kt as isPairedWriteOrigin,It as isPathWithinDir,b as isProcessAlive,Cn as isSelfWrite,dn as isSystemDoc,l as isValidLockPid,Wt as lastKnownHash,Bt as listRescueCheckpoints,pt as listStarterPacks,Kn as loadPrincipal,m as lockFilePath,ir as loggerFactory,xt as mountMcpAndApi,er as normalizeFsPath,ze as parseAuthRejectionWire,P as parseHocuspocusAuthToken,Xn as parseKeepaliveConnectionId,Ue as pathToDocName,H as planPersonalTemplates,R as planSeed,we as readAllTargets,nn as readBranchFromHead,S as readProcessLock,u as readProcessLockDetailed,d as readServerLock,D as readServerPackageVersion,Qt as readSkillInstallStateSnapshot,ge as readStateManifest,be as readTargetRecordedAt,Oe as readTargetVersion,K as readUiLock,ne as reconcile,fe as recordContributor,Fe as recordSkillInstallEvent,cr as registerAllTools,j as registerWrite,v as releaseProcessLock,h as releaseServerLock,Xe as releaseUiLock,$ as removeLastKnownHash,qe as resetMetrics,$e as resolveBundledSkillDir,X as resolveContentDir,le as resolveCursorBinaryDefault,Dn as resolveCursorSpawnInvocation,oe as resolveLockDir,ot as resolvePack,nt as resolvePackageVersion,ut as rewriteMarkdownLinksForDocumentRename,Me as rewriteWikiLinksForDocumentRename,w as runAuthReposSubprocess,Nt as runAuthStatusSubprocess,zn as runCloneSubprocess,gn as runDeviceFlowSubprocess,jn as runWithMcpLogger,Yt as safeContentPath,vt as safeSubdir,bn as safetyCheckpoint,Fn as sanitizeClientName,Et as saveInMemoryCheckpoint,cn as saveVersion,Un as seedBasenameIndex,At as setActiveSpanAttributes,Lt as shadowGit,wn as shutdownTelemetry,fn as splitMarkdownBlocks,Gt as startWatcher,Vt as streamingProblemEvent,mt as toBroadcasterKey,qn as tracedAppendFileSync,ar as tracedLinkSync,St as tracedMkdir,tr as tracedMkdirSync,Be as tracedRename,F as tracedRenameSync,Zn as tracedRmSync,We as tracedRmdirSync,U as tracedUnlinkSync,z as tracedWriteFile,Te as tracedWriteFileSync,rn as updateLastKnownHash,f as updateProcessLockPort,s as updateServerLockPort,O as updateUiLockPort,$t as validateAgentId,_e as validateCloneInputs,xe as validateSkillZip,ke as withSpan,q as withSpanSync,re as writePersonalTemplates,pe as writeStateManifest,Ie as writeTargetVersion,lr as writeTracker};
1
+ import{Bn as e,Ct as t,Ft as n,Lt as r,Rn as i,Sn as a,k as o}from"./dist-D3xMMmYf.mjs";import{_ as s,a as c,c as l,d as u,f as d,g as f,i as p,l as m,m as h,n as g,o as _,p as v,r as y,s as b,t as x,u as S}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{$ as C,$n as w,$t as T,A as E,An as D,Ar as O,At as k,B as A,Bn as j,Bt as M,C as N,Cn as P,Cr as F,Ct as I,D as L,Dn as R,Dr as z,Dt as B,E as V,En as H,Er as U,Et as W,F as G,Fn as K,Fr as q,Ft as J,G as Y,Gn as X,Gt as Z,H as Q,Hn as $,Ht as ee,I as te,In as ne,Ir as re,It as ie,J as ae,Jn as oe,Jt as se,K as ce,Kn as le,Kt as ue,L as de,Ln as fe,Lr as pe,Lt as me,M as he,Mn as ge,Mr as _e,Mt as ve,N as ye,Nn as be,Nr as xe,Nt as Se,O as Ce,On as we,Or as Te,Ot as Ee,P as De,Pn as Oe,Pr as ke,Pt as Ae,Q as je,Qn as Me,Qt as Ne,R as Pe,Rn as Fe,Rr as Ie,Rt as Le,S as Re,Sn as ze,Sr as Be,St as Ve,T as He,Tn as Ue,Tr as We,Tt as Ge,U as Ke,Un as qe,Ut as Je,V as Ye,Vn as Xe,Vt as Ze,W as Qe,Wn as $e,Wt as et,X as tt,Xn as nt,Xr as rt,Xt as it,Y as at,Yn as ot,Yr as st,Yt as ct,Z as lt,Zn as ut,Zt as dt,_ as ft,_n as pt,_r as mt,_t as ht,a as gt,an as _t,ar as vt,at as yt,b as bt,bn as xt,br as St,bt as Ct,c as wt,cn as Tt,cr as Et,ct as Dt,d as Ot,dn as kt,dr as At,dt as jt,en as Mt,er as Nt,et as Pt,f as Ft,fn as It,fr as Lt,ft as Rt,g as zt,gn as Bt,gr as Vt,gt as Ht,h as Ut,hn as Wt,hr as Gt,ht as Kt,i as qt,in as Jt,ir as Yt,it as Xt,j as Zt,jn as Qt,jr as $t,jt as en,k as tn,kn as nn,kr as rn,kt as an,l as on,ln as sn,lr as cn,lt as ln,m as un,mn as dn,mr as fn,mt as pn,n as mn,nn as hn,nr as gn,nt as _n,o as vn,on as yn,or as bn,ot as xn,p as Sn,pn as Cn,pr as wn,pt as Tn,q as En,qn as Dn,qt as On,r as kn,rn as An,rr as jn,rt as Mn,s as Nn,sn as Pn,sr as Fn,st as In,t as Ln,tn as Rn,tr as zn,tt as Bn,u as Vn,un as Hn,ur as Un,ut as Wn,v as Gn,vn as Kn,vr as qn,vt as Jn,w as Yn,wn as Xn,wr as Zn,wt as Qn,x as $n,xn as er,xr as tr,xt as nr,y as rr,yn as ir,yr as ar,yt as or,z as sr,zn as cr,zr as lr,zt as ur}from"./dist-DOIb_FW2.mjs";export{Ln as AGENT_ID_MAX_LEN,mn as AGENT_ID_RE,kn as AGENT_WRITE_ORIGIN,qt as AgentFocusBroadcaster,gt as AgentPresenceBroadcaster,vn as AgentSessionCapacityError,Nn as AgentSessionManager,wt as BacklinkIndex,on as CC1Broadcaster,o as CC1_CONTRACT_VERSION,Vn as CONFLICT_MARKER_RE,Ot as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Ft as ConfigSchema,Sn as DEFAULT_CHECKPOINT_RETENTION,un as DEFAULT_PACK_ID,Ut as FILE_SYSTEM_WRITER,zt as FILE_WATCHER_ORIGIN,ft as GIT_UPSTREAM_WRITER,st as GitDirAccessError,Gn as HOCUSPOCUS_AUTH_REJECTION_REASONS,rr as HocuspocusAuthRejection,bt as HocuspocusAuthTokenSchema,$n as INSTALLED_AGENTS_SCHEMES,Re as LIVE_DERIVED_INDEX_DEBOUNCE_MS,N as LOG_MD_TEMPLATE,Yn as MANAGED_RENAME_ORIGIN,He as MAX_AGENT_SESSIONS,V as MCP_CONNECTION_ID_HEADER,L as MCP_SERVER_NAME,Ce as MISSING_OK_CONFIG_MESSAGE,rt as MalformedGitPointerError,tn as McpLogger,E as MissingOkConfigError,Zt as OBSERVER_SYNC_ORIGIN,t as ORPHAN_MODES,he as PERSONAL_TEMPLATES,ye as PERSONAL_TEMPLATE_NAMES,De as PinoLogger,x as ProcessLockCollisionError,G as ProjectGitInitError,te as ROLLBACK_ORIGIN,g as RUNTIME_VERSION,de as SERVICE_WRITER,Pe as SKILL_INSTALL_EVENTS_FILE_REL,n as SKILL_STATE_TARGETS,sr as STARTER_FOLDERS,A as STARTER_FOLDER_FRONTMATTER_FILENAME,Ye as STARTER_PACKS,Q as STARTER_PACK_IDS,Ke as STARTER_TEMPLATES,Qe as STATE_MANIFEST_FILENAME,y as STATE_SCHEMA_VERSION,r as SYSTEM_DOC_NAME,Y as SeedPrerequisiteError,ce as SeedRootDirError,p as ServerLockCollisionError,En as StateManifestError,ae as TagIndex,at as UiLockCollisionError,c as acquireProcessLock,_ as acquireServerLock,tt as acquireUiLock,lt as applyAgentMarkdownWrite,je as applyExternalChange,C as applySeed,Pt as assertCompatibleStateManifest,Bn as assertNeverDiskEvent,_n as attachIdleShutdown,Mn as bootServer,Xt as buildAndOpenSkill,yt as buildExecResult,xn as buildInstructions,In as buildReadResult,Dt as buildSkillZip,ln as buildStarterFolderFrontmatterYaml,Wn as buildWipTree,jt as classifyEvents,Rt as classifyFsPath,Tn as clearContributors,pn as coercePackId,a as colorFromSeed,Kt as commitUpstreamImport,Ht as commitWip,ht as commitWipFromTree,Jn as containsConflictMarkers,or as contentHash,Ct as contributorCount,nr as createApiExtension,Ve as createAssetServeMiddleware,I as createContentFilter,Qn as createContentFilterAsync,Ge as createExternalChangeHandler,W as createLiveDerivedIndexExtension,B as createMcpHttpHandler,Ee as createOsProbe,an as createPersistenceExtension,k as createServer,en as createServerObserverExtension,ve as createStreamingErrorWriter,Se as createTestLogger,Ae as detectClaudeDesktopPresence,J as detectProjectShape,ie as ensureProjectGit,me as errorResponse,Le as evictStaleTrackerEntries,ur as extractWikiLinksFromMarkdown,M as findEnclosingGitRoot,Ze as findEnclosingProjectRoot,ee as formatAuthRejectionWire,Je as formatContributors,et as gcCheckpointRefs,Z as getCurrentMcpLogger,ue as getLocalDir,On as getLogger,se as getMeter,ct as getMetrics,it as getTracer,dt as handleCollabSocketError,Ne as handleSpawnCursor,i as iconFromClientName,T as incrementCollabSocketFilteredError,Mt as incrementServerObserverFire,Rn as initShadowRepo,hn as initTelemetry,An as installTestLoggers,Jt as installUserSkill,_t as isAllowedApiOrigin,yn as isAllowedWorkspaceHostHeader,Pn as isConfigDoc,Tt as isHocuspocusAuthRejectionReason,sn as isKnownPackId,Hn as isLoopbackAddress,e as isOrphanMode,kt as isPairedWriteOrigin,It as isPathWithinDir,b as isProcessAlive,Cn as isSelfWrite,dn as isSystemDoc,l as isValidLockPid,Wt as lastKnownHash,Bt as listRescueCheckpoints,pt as listStarterPacks,Kn as loadPrincipal,m as lockFilePath,ir as loggerFactory,xt as mountMcpAndApi,er as normalizeFsPath,ze as parseAuthRejectionWire,P as parseHocuspocusAuthToken,Xn as parseKeepaliveConnectionId,Ue as pathToDocName,H as planPersonalTemplates,R as planSeed,we as readAllTargets,nn as readBranchFromHead,S as readProcessLock,u as readProcessLockDetailed,d as readServerLock,D as readServerPackageVersion,Qt as readSkillInstallStateSnapshot,ge as readStateManifest,be as readTargetRecordedAt,Oe as readTargetVersion,K as readUiLock,ne as reconcile,fe as recordContributor,Fe as recordSkillInstallEvent,cr as registerAllTools,j as registerWrite,v as releaseProcessLock,h as releaseServerLock,Xe as releaseUiLock,$ as removeLastKnownHash,qe as resetMetrics,$e as resolveBundledSkillDir,X as resolveContentDir,le as resolveCursorBinaryDefault,Dn as resolveCursorSpawnInvocation,oe as resolveLockDir,ot as resolvePack,nt as resolvePackageVersion,ut as rewriteMarkdownLinksForDocumentRename,Me as rewriteWikiLinksForDocumentRename,w as runAuthReposSubprocess,Nt as runAuthStatusSubprocess,zn as runCloneSubprocess,gn as runDeviceFlowSubprocess,jn as runWithMcpLogger,Yt as safeContentPath,vt as safeSubdir,bn as safetyCheckpoint,Fn as sanitizeClientName,Et as saveInMemoryCheckpoint,cn as saveVersion,Un as seedBasenameIndex,At as setActiveSpanAttributes,Lt as shadowGit,wn as shutdownTelemetry,fn as splitMarkdownBlocks,Gt as startWatcher,Vt as streamingProblemEvent,mt as toBroadcasterKey,qn as tracedAppendFileSync,ar as tracedLinkSync,St as tracedMkdir,tr as tracedMkdirSync,Be as tracedRename,F as tracedRenameSync,Zn as tracedRmSync,We as tracedRmdirSync,U as tracedUnlinkSync,z as tracedWriteFile,Te as tracedWriteFileSync,rn as updateLastKnownHash,f as updateProcessLockPort,s as updateServerLockPort,O as updateUiLockPort,$t as validateAgentId,_e as validateCloneInputs,xe as validateSkillZip,ke as withSpan,q as withSpanSync,re as writePersonalTemplates,pe as writeStateManifest,Ie as writeTargetVersion,lr as writeTracker};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{c as e,d as t,f as n,i as r,l as i,m as a,p as o,t as s,u as c}from"./init-DrfKz58U.mjs";import{n as l}from"./loader-DKoWw50g.mjs";import{n as u}from"./preview-D6nLHyS2.mjs";import{t as d}from"./src-DL2x7ekf.mjs";export{c as ALL_EDITOR_IDS,t as EDITOR_LABELS,n as EDITOR_TARGETS,s as detectInstalledEditors,a as initContent,l as loadConfig,u as previewContent,r as readExistingMcpEntry,o as resolveProjectRoot,e as writeEditorMcpConfig,d as writeProjectAiIntegrations,i as writeUserMcpConfigs};
1
+ import{c as e,d as t,f as n,i as r,l as i,m as a,p as o,t as s,u as c}from"./init-3-63uZzL.mjs";import{n as l}from"./loader-BohnSRzb.mjs";import{n as u}from"./preview-KUL_V2fF.mjs";import{t as d}from"./src-DWeGFSri.mjs";export{c as ALL_EDITOR_IDS,t as EDITOR_LABELS,n as EDITOR_TARGETS,s as detectInstalledEditors,a as initContent,l as loadConfig,u as previewContent,r as readExistingMcpEntry,o as resolveProjectRoot,e as writeEditorMcpConfig,d as writeProjectAiIntegrations,i as writeUserMcpConfigs};
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{r,t as i}from"./esm-CEs3LWY3.mjs";import{J as a,ir as o,n as s,or as c}from"./dist-H3Ld-L-a.mjs";import{D as l,F as u,It as d,Pt as f,Wn as p,in as m}from"./dist-Va4IjzRw.mjs";import{n as h,t as g}from"./constants-BY_EleLO.mjs";import{t as _}from"./is-object-C-4FJ0rP.mjs";import{i as v,o as y,r as b,s as x,t as S}from"./colors-BtKMHmBX.mjs";import{t as ee}from"./preview-D6nLHyS2.mjs";import{execFileSync as te}from"node:child_process";import ne,{basename as re,dirname as C,isAbsolute as ie,join as w,posix as ae,relative as T,resolve as E,sep as D,win32 as oe}from"node:path";import{cpSync as se,existsSync as O,lstatSync as ce,mkdirSync as k,readFileSync as A,realpathSync as le,rmSync as ue,writeFileSync as j}from"node:fs";import M from"node:process";import{homedir as N}from"node:os";import{AsyncLocalStorage as de,AsyncResource as fe}from"node:async_hooks";import{stripVTControlCharacters as pe,styleText as P}from"node:util";import*as me from"node:readline";function he(){return M.platform.startsWith(`win`)?!!M.env.CI||!!M.env.WT_SESSION||!!M.env.TERMINUS_SUBLIME||M.env.ConEmuTask===`{cmd::Cmder}`||M.env.TERM_PROGRAM===`Terminus-Sublime`||M.env.TERM_PROGRAM===`vscode`||M.env.TERM===`xterm-256color`||M.env.TERM===`alacritty`||M.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:M.env.TERM!==`linux`}const ge={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},_e={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},ve={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},ye={...ge,..._e},be={...ge,...ve},F=he()?ye:be;Object.entries(_e);var xe=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Se=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),Ce=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,we=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Te=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ee=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,De=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Oe=/\t{1,1000}/y,ke=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Ae=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,je=/\p{M}+/gu,Me={limit:1/0,ellipsis:``},Ne=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Ne(i,Me,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ae,l],[Te,0],[Ee,o],[Oe,s],[ke,c],[De,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(je,``)){let t=e.codePointAt(0)||0;if(S=Ce(t)?2:we(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===De?Se(e.slice(p,n.lastIndex)):n===ke?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Pe={limit:1/0,ellipsis:``,ellipsisWidth:0},I=(e,t={})=>Ne(e,Pe,t).width,Fe=`]8;;`,Ie=RegExp(`(?:\\[(?<code>\\d+)m|\\${Fe}(?<uri>.*))`,`y`),Le=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Re=e=>`[${e}m`,ze=e=>`${Fe}${e}`,Be=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:I(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=I(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Fe,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ve=e=>{let t=e.split(` `),n=t.length;for(;n&&!I(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},He=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=I(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=I(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Be(s,r,t),c=I(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Be(s,r,t),c=I(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Be(s,r,t),c=I(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ve(e)));let l=s.join(`
1
+ import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{r,t as i}from"./esm-CEs3LWY3.mjs";import{J as a,ir as o,n as s,or as c}from"./dist-D3xMMmYf.mjs";import{D as l,F as u,It as d,Pt as f,Wn as p,in as m}from"./dist-DOIb_FW2.mjs";import{n as h,t as g}from"./constants-BHNW8Zq_.mjs";import{t as _}from"./is-object-C-4FJ0rP.mjs";import{i as v,o as y,r as b,s as x,t as S}from"./colors-BtKMHmBX.mjs";import{t as ee}from"./preview-KUL_V2fF.mjs";import{execFileSync as te}from"node:child_process";import ne,{basename as re,dirname as C,isAbsolute as ie,join as w,posix as ae,relative as T,resolve as E,sep as D,win32 as oe}from"node:path";import{cpSync as se,existsSync as O,lstatSync as ce,mkdirSync as k,readFileSync as A,realpathSync as le,rmSync as ue,writeFileSync as j}from"node:fs";import M from"node:process";import{homedir as N}from"node:os";import{AsyncLocalStorage as de,AsyncResource as fe}from"node:async_hooks";import{stripVTControlCharacters as pe,styleText as P}from"node:util";import*as me from"node:readline";function he(){return M.platform.startsWith(`win`)?!!M.env.CI||!!M.env.WT_SESSION||!!M.env.TERMINUS_SUBLIME||M.env.ConEmuTask===`{cmd::Cmder}`||M.env.TERM_PROGRAM===`Terminus-Sublime`||M.env.TERM_PROGRAM===`vscode`||M.env.TERM===`xterm-256color`||M.env.TERM===`alacritty`||M.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:M.env.TERM!==`linux`}const ge={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},_e={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},ve={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},ye={...ge,..._e},be={...ge,...ve},F=he()?ye:be;Object.entries(_e);var xe=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Se=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),Ce=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,we=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Te=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ee=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,De=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Oe=/\t{1,1000}/y,ke=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Ae=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,je=/\p{M}+/gu,Me={limit:1/0,ellipsis:``},Ne=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Ne(i,Me,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ae,l],[Te,0],[Ee,o],[Oe,s],[ke,c],[De,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(je,``)){let t=e.codePointAt(0)||0;if(S=Ce(t)?2:we(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===De?Se(e.slice(p,n.lastIndex)):n===ke?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Pe={limit:1/0,ellipsis:``,ellipsisWidth:0},I=(e,t={})=>Ne(e,Pe,t).width,Fe=`]8;;`,Ie=RegExp(`(?:\\[(?<code>\\d+)m|\\${Fe}(?<uri>.*))`,`y`),Le=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Re=e=>`[${e}m`,ze=e=>`${Fe}${e}`,Be=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:I(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=I(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Fe,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ve=e=>{let t=e.split(` `),n=t.length;for(;n&&!I(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},He=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=I(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=I(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Be(s,r,t),c=I(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Be(s,r,t),c=I(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Be(s,r,t),c=I(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ve(e)));let l=s.join(`
2
2
  `),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===`›`){Ie.lastIndex=e+1;let t=Ie.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
3
3
  `){a&&(r+=ze(``));let e=i?Le(i):void 0;i&&e&&(r+=Re(e))}else t===`
4
4
  `&&(i&&Le(i)&&(r+=Re(i)),a&&(r+=ze(a)))}return r},Ue=/\r?\n/;function We(e,t,n){return String(e).normalize().split(Ue).map(e=>He(e,t,n)).join(`
@@ -404,5 +404,5 @@ last-spawn-error.log
404
404
  `)?n:`${n}\n`,`utf-8`)}function ur(e,t){let n;try{n=le(t)}catch{n=E(t)}let r;try{r=ce(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(r?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run \`ok init\`, or pass \`--no-mcp\` to skip MCP config writes.`);let i=C(e);for(;i.length>1&&i!==D;){let t;try{t=le(i)}catch(e){if(e.code===`ENOENT`){i=C(i);continue}throw e}let r=T(n,t);if(r===``||!r.startsWith(`..`)&&!ie(r))return;throw Error(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run, or pass \`--no-mcp\`.`)}}const dr=e=>e!==`project`,fr=e=>e!==`user`;async function pr(){let e=await rn({message:`Where should the MCP server be configured?
405
405
  `,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function mr(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??pr)():`both`}const hr=`0.0.1`,gr=`open-knowledge-ui`;function _r(e,t={}){let n=w(e,`.claude`,`launch.json`),r=t.mode===`dev`?{name:gr,runtimeExecutable:`node`,runtimeArgs:[Yn(),`ui`],port:3e3}:{name:gr,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:3e3};try{if(ur(n,e),!O(n))return k(C(n),{recursive:!0}),j(n,`${JSON.stringify({version:hr,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=A(n,`utf-8`).trim(),i=t?JSON.parse(t):{};if(!_(i))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let a=Array.isArray(i.configurations)?i.configurations:[],o=a.findIndex(e=>_(e)&&e.name===gr);o>=0?a[o]=r:a.push(r);let s={...i,version:i.version??hr,configurations:a};return j(n,`${JSON.stringify(s,null,2)}\n`,`utf-8`),{action:o>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function vr(e,t,n){try{return O(e.detectPath?.(t,n)??C(e.configPath(t,n)))}catch{return!1}}function $(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}if(!i&&!n.skipAvailabilityCheck&&!vr(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{ur(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}let s;try{s=e.format===`toml`?sr(o):or(o)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let c=s[e.topLevelKey]??{},l=c[a],u;try{u=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let d={...s,[e.topLevelKey]:{...c,[a]:u}};try{e.format===`toml`?lr(o,d):cr(o,d)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:l===void 0?`written`:`overwritten`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}function yr(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=p(),i=C(n);ur(i,t);let a=O(n)?`overwritten`:`written`;return ue(i,{recursive:!0,force:!0}),k(C(i),{recursive:!0}),se(r,i,{recursive:!0}),{editorId:e.id,label:e.label,action:a,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function br(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!O(n)))return{editorId:e.id,label:e.label,path:n}}async function xr(e){let t=ar(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>$(t,``,n,e.home))}function Sr(e,t,n){let r;try{r=e.configPath(t,n)}catch{return null}let i;try{i=e.format===`toml`?sr(r):or(r)}catch{return null}let a=i[e.topLevelKey];if(!_(a))return null;let o=a[e.serverName(t)];return _(o)?o:null}async function Cr(e={}){let t=Kn(E(e.cwd??process.cwd()),{homeDir:e.home}),n=t.projectRoot,r=!O(w(n,`.ok`));t.ancestorPromoted?console.log(`[ok] Opened existing project at ${n}`):t.gitRootPromoted&&r&&console.log(`[ok] Initialized OK at ${n} (scoped to ${t.defaultContentDir}/)`);let i={mode:e.devMcp?`dev`:`published`},a=await d(n),o;try{o=Un(n,{contentDir:t.defaultContentDir})}catch(t){let r=Q.claude.configPath(n,e.home);return{projectRoot:n,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:a.didInit,claudeDesktopDetected:!1,mcpAction:`failed`,mcpPath:r,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`}}let s=await mr({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),c=e.editors??Tr(n,e.home),l=e.editors??J.filter(e=>Q[e].projectConfigPath!==void 0),u=ar(c),p=ar(l),h=e.mcp===!1||s===null,g=Array.from(new Map([...u,...h?[]:p].map(e=>[e.id,e])).values()),_=u.filter(t=>vr(t,n,e.home)),v=[],y=[],b=new Set;for(let t of g){if(h){let r=``;try{r=t.configPath(n,e.home)}catch{}v.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:r,serverName:t.serverName(n)});continue}if(dr(s)&&u.includes(t)&&v.push($(t,n,i,e.home)),fr(s)&&p.includes(t)&&t.projectConfigPath){let r=t.projectConfigPath(n),a=$(t,n,i,e.home,r);v.push(a),(a.action===`written`||a.action===`overwritten`)&&(b.add(r),y.push(yr(t,n)))}}let x=!h&&s!==null&&fr(s)?p.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,S=h?[]:_.map(e=>br(e,n)).filter(e=>e!==void 0).filter(e=>!b.has(e.path)),ee=_.some(e=>e.id===`claude`)&&!h?_r(n,i):void 0,te=await(e.installUserSkill??m)({home:e.home}),ne=f({home:e.home}),re=h?`skipped-flag`:`skipped-missing`,C=v.find(e=>e.editorId===`claude`)??v[0]??{action:re,configPath:Q.claude.configPath(n,e.home)};return{projectRoot:n,contentCreated:o.created,contentUpdated:o.updated,contentSkipped:o.skipped,editors:v,projectSkills:y,legacyProjectConfigs:S,launchJson:ee,skillInstall:te,didGitInit:a.didInit,claudeDesktopDetected:ne,mcpAction:C.action,mcpPath:C.configPath,mcpError:`error`in C?C.error:void 0,projectScopeUnsupportedLabels:x}}function wr(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),s=e=>{let n=e.configPath.startsWith(t)?T(t,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${n} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${n} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${n} FAILED: ${e.error}`}};e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`);let c=w(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(S(`Content scaffolded at ${c}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(S(`Content already present at ${c}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)if(n.push(S(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`);else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(S(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(S(`MCP server configuration:`));for(let r of e.editors){let i=r.configPath.startsWith(t)?T(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),a=r.serverName===`open-knowledge`?``:` (${r.serverName})`,o=r.configScope===`project`?` (project)`:``,c=`${r.label}${o}`,l=` `.repeat(Math.max(1,20-c.length)),u=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${c}${l}${i} ${y(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${y(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${b(`FAILED`)}: ${r.error}`);break;case`skipped-flag`:break}r.editorId===`claude`&&e.launchJson&&n.push(s(e.launchJson))}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(e.projectSkills.length>0){n.push(``),n.push(S(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?T(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${y(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${y(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${b(`FAILED`)}: ${r.error}`);break}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${T(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(S(`User-global skill:`)),e.skillInstall){case`installed`:n.push(` open-knowledge ${y(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${y(`already installed at current version`)}`);break;case`failed`:n.push(` ${x(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${x(` npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy`)}`);break}if(e.claudeDesktopDetected&&(n.push(``),n.push(`Claude Desktop App detected. To enable in Claude Chat & Cowork, run: ${S(`ok install-skill`)}`)),e.preview?(n.push(``),n.push(ee(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${y(`✓`)} ${S(`Next steps:`)}`),n.push(` 1. Open your editor (${v(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${v(`ok seed`)}`),n.push(` 4. Use the three MCP workflow tools as you build the wiki:`),n.push(` - ${v(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${v(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${v(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
406
406
  `)}function Tr(e,t){let n=[];for(let r of J)vr(Q[r],e,t)&&n.push(r);return n}function Er(){return new i(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).addOption(new r(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).action(async e=>{let t=process.cwd(),n;try{n=await Cr({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope})}catch(e){if(e instanceof u){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
407
- `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-DfT6ddN-.mjs`),{loadConfig:t}=await import(`./loader-BcdTtT9v.mjs`),{resolveContentDir:r}=await import(`./dist-Cg4a9GjH.mjs`),{config:i}=t(n.projectRoot),a=r(i,n.projectRoot);n.preview=e({projectDir:n.projectRoot,contentDir:a})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${wr(n,n.projectRoot)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{We as C,Ge as S,F as T,at as _,mr as a,ut as b,$ as c,Y as d,Q as f,it as g,st as h,Sr as i,xr as l,Un as m,wr as n,Cr as o,Kn as p,Er as r,_r as s,Tr as t,J as u,ct as v,xe as w,tt as x,ot as y};
408
- //# sourceMappingURL=init-DrfKz58U.mjs.map
407
+ `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-BIFV91lQ.mjs`),{loadConfig:t}=await import(`./loader-DY3uDuFe.mjs`),{resolveContentDir:r}=await import(`./dist-YAZrJ15a.mjs`),{config:i}=t(n.projectRoot),a=r(i,n.projectRoot);n.preview=e({projectDir:n.projectRoot,contentDir:a})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${wr(n,n.projectRoot)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{We as C,Ge as S,F as T,at as _,mr as a,ut as b,$ as c,Y as d,Q as f,it as g,st as h,Sr as i,xr as l,Un as m,wr as n,Cr as o,Kn as p,Er as r,_r as s,Tr as t,J as u,ct as v,xe as w,tt as x,ot as y};
408
+ //# sourceMappingURL=init-3-63uZzL.mjs.map
@@ -0,0 +1 @@
1
+ import{o as e}from"./init-3-63uZzL.mjs";export{e as runInit};
@@ -1,4 +1,4 @@
1
- import{Ln as e,Zr as t,lr as n}from"./dist-H3Ld-L-a.mjs";import{Kr as r,f as i}from"./dist-Va4IjzRw.mjs";import{t as a}from"./constants-BY_EleLO.mjs";import{t as o}from"./is-object-C-4FJ0rP.mjs";import{resolve as s}from"node:path";import{existsSync as c,readFileSync as l}from"node:fs";import{homedir as u}from"node:os";import{realpath as d}from"node:fs/promises";async function f(e){let t=s(e);try{return await d(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}var p=t();function m(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];o(a)&&o(i)?n[r]=m(i,a):a!==void 0&&(n[r]=a)}return n}function h(e){if(!c(e))return{value:null,path:e,source:null,doc:null};let t;try{t=l(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,p.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return o(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}const g=[`include`,`exclude`];function _(e){let t="Run `ok config migrate` to strip the obsolete key from config.yml automatically, or remove it by hand.";return e===`exclude`?[`Move these patterns to .okignore at the project root (gitignore syntax, 1:1 migration).`,t].join(` `):[`content.include has been removed.`,`For subdirectory scoping, set content.dir in .ok/config.yml instead.`,`For pattern-based filtering, use .okignore (gitignore syntax — exclude-only; do not copy include patterns directly).`,t].join(` `)}function v(e){let t=e.value;if(!o(t))return[];let r=t.content;if(!o(r))return[];let i=[];for(let t of g)if(t in r){let r=[`content`,t],a;e.doc!==null&&e.source!==null&&(a=n({file:e.path,source:e.source,doc:e.doc,path:r})),i.push({code:`REMOVED_KEY`,path:r,redirect:_(t),...a===void 0?{}:{source:a}})}return i}function y(e,t){return e.map(e=>{let r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=n({file:t.path,source:t.source,doc:t.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function b(t){let n=t??process.cwd(),o=[],c=s(u(),`.ok`,a),l=r({absPath:c}),d={};l.valid&&l.source!==void 0?(d=m(d,l.value),o.push(c)):l.valid;let f=s(n,`.ok`,a),p=h(f);if(p.value!==null){let t=v(p);if(t.length>0)throw Error(t.map(e).join(`
1
+ import{Ln as e,Zr as t,lr as n}from"./dist-D3xMMmYf.mjs";import{Kr as r,f as i}from"./dist-DOIb_FW2.mjs";import{t as a}from"./constants-BHNW8Zq_.mjs";import{t as o}from"./is-object-C-4FJ0rP.mjs";import{resolve as s}from"node:path";import{existsSync as c,readFileSync as l}from"node:fs";import{homedir as u}from"node:os";import{realpath as d}from"node:fs/promises";async function f(e){let t=s(e);try{return await d(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}var p=t();function m(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];o(a)&&o(i)?n[r]=m(i,a):a!==void 0&&(n[r]=a)}return n}function h(e){if(!c(e))return{value:null,path:e,source:null,doc:null};let t;try{t=l(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,p.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return o(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}const g=[`include`,`exclude`];function _(e){let t="Run `ok config migrate` to strip the obsolete key from config.yml automatically, or remove it by hand.";return e===`exclude`?[`Move these patterns to .okignore at the project root (gitignore syntax, 1:1 migration).`,t].join(` `):[`content.include has been removed.`,`For subdirectory scoping, set content.dir in .ok/config.yml instead.`,`For pattern-based filtering, use .okignore (gitignore syntax — exclude-only; do not copy include patterns directly).`,t].join(` `)}function v(e){let t=e.value;if(!o(t))return[];let r=t.content;if(!o(r))return[];let i=[];for(let t of g)if(t in r){let r=[`content`,t],a;e.doc!==null&&e.source!==null&&(a=n({file:e.path,source:e.source,doc:e.doc,path:r})),i.push({code:`REMOVED_KEY`,path:r,redirect:_(t),...a===void 0?{}:{source:a}})}return i}function y(e,t){return e.map(e=>{let r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=n({file:t.path,source:t.source,doc:t.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function b(t){let n=t??process.cwd(),o=[],c=s(u(),`.ok`,a),l=r({absPath:c}),d={};l.valid&&l.source!==void 0?(d=m(d,l.value),o.push(c)):l.valid;let f=s(n,`.ok`,a),p=h(f);if(p.value!==null){let t=v(p);if(t.length>0)throw Error(t.map(e).join(`
2
2
 
3
3
  `));d=m(d,p.value),o.push(f)}x(d,[`upload`,`maxBytes`],`streaming uploads have no user-facing cap`),x(d,[`github`,`oauthAppClientId`],`use the OPEN_KNOWLEDGE_GITHUB_CLIENT_ID env var instead`),x(d,[`server`,`host`],`use the --host flag or HOST env var instead`),x(d,[`server`,`openOnAgentEdit`]),x(d,[`mcp`,`autoStart`],`to disable auto-start, set OK_MCP_AUTOSTART=0`),x(d,[`mcp`,`tools`,`read_document`,`historyDepth`]),x(d,[`mcp`,`tools`,`grep`,`maxResults`]),x(d,[`mcp`,`tools`,`search`,`maxResults`]);let g=i.safeParse(d);if(!g.success){let t={code:`SCHEMA_INVALID`,issues:y(g.error.issues,p)};throw Error(e(t))}return{config:g.data,sources:o}}function x(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){if(!o(r))return;r=r[t[e]]}if(!o(r))return;let i=t[t.length-1];if(r[i]===void 0)return;let a=t.join(`.`);console.warn(`[config] ${a} is no longer user-configurable; ${n??`the value is hardcoded in @inkeep/open-knowledge-core`}. Remove the key to silence this warning.`)}function S(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=f(e.startupCwd);return async o=>{let s=await f(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,S as t};
4
- //# sourceMappingURL=loader-DKoWw50g.mjs.map
4
+ //# sourceMappingURL=loader-BohnSRzb.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e}from"./loader-BohnSRzb.mjs";export{e as loadConfig};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./preview-KUL_V2fF.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1,3 +1,3 @@
1
- import{Ct as e}from"./dist-Va4IjzRw.mjs";import"./constants-BY_EleLO.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);return a.push(``),r(t(i,`.ok`,`config.yml`))?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
1
+ import{Ct as e}from"./dist-DOIb_FW2.mjs";import"./constants-BHNW8Zq_.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);return a.push(``),r(t(i,`.ok`,`config.yml`))?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
2
2
  `)}export{c as n,l as t};
3
- //# sourceMappingURL=preview-D6nLHyS2.mjs.map
3
+ //# sourceMappingURL=preview-KUL_V2fF.mjs.map
@@ -1,2 +1,2 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ActivityPanelDiffView-DeDaG2lq.js","./chunk-CFjPhJqf.js","./compiler-runtime-CVnuRdak.js","./ActivityPanelDiffView-legcy4jI.css"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./preload-helper-2ej06EnG.js";import{n,r,t as i}from"./compiler-runtime-CVnuRdak.js";import{Sn as a,bn as o,n as s,nt as c,on as l,r as u,xn as d}from"./DocumentContext-HTIMnclU.js";import{At as f,G as p,W as m,p as h}from"./doc-hash-BSwTWr6y.js";import{C as g,t as _}from"./button-C1nwPVFQ.js";import{f as v,i as y,m as b,r as x,t as S}from"./agent-presence-BrTlNKmt.js";import{p as C}from"./dist-OTL8-1C2.js";import{i as w,n as T,t as E}from"./tooltip-DcfXr4mU.js";import{a as D,c as O,i as k,o as ee,s as te,t as ne}from"./dialog-BFN-ujuF.js";var re=g(`rewind`,[[`path`,{d:`M12 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 12 18z`,key:`2a1g8i`}],[`path`,{d:`M22 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 22 18z`,key:`rg3s36`}]]),A=i(),j=e(n(),1),ie=500,ae=64;async function oe(e){let t=`/api/agent-activity?agentId=${encodeURIComponent(e)}`,n=await fetch(t),r;try{r=await n.json()}catch(e){throw new c(`Could not parse /api/agent-activity response.`,{cause:e,status:n.status})}if(!n.ok){let e=f.safeParse(r);throw e.success?Error(e.data.title):new c(`/api/agent-activity returned a non-RFC-9457 error response.`,{cause:e.error,status:n.status})}let i=m.safeParse(r);if(!i.success)throw new c(`/api/agent-activity returned a body that did not match AgentActivitySuccessSchema.`,{cause:i.error,status:n.status});return i.data}async function se(e,t,n){let r=`/api/agent-burst-diff?agentId=${encodeURIComponent(e)}&docName=${encodeURIComponent(t)}&stackIndex=${n}`,i=await fetch(r),a;try{a=await i.json()}catch(e){throw new c(`Could not parse /api/agent-burst-diff response.`,{cause:e,status:i.status})}if(!i.ok){let e=f.safeParse(a);throw e.success?Error(e.data.title):new c(`/api/agent-burst-diff returned a non-RFC-9457 error response.`,{cause:e.error,status:i.status})}let o=p.safeParse(a);if(!o.success)throw new c(`/api/agent-burst-diff returned a body that did not match AgentBurstDiffSuccessSchema.`,{cause:o.error,status:i.status});return o.data.diff}function ce(e){let t=(0,A.c)(23),{systemProvider:n}=s(),[r,i]=(0,j.useState)(null),[a,o]=(0,j.useState)(`idle`),[c,l]=(0,j.useState)(null),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=new y(ae),t[0]=u):u=t[0];let d=(0,j.useRef)(u),f=(0,j.useRef)(0),p;t[1]===n?p=t[2]:(p=e=>{let t=f.current+=1;o(`loading`),l(null),oe(e).then(r=>{if(f.current!==t)return;let a=ue(n,e);i({...r,writingDocs:a}),o(`ready`)}).catch(e=>{f.current===t&&(l(e instanceof Error?e.message:String(e)),o(`error`))})},t[1]=n,t[2]=p);let m=p,g;t[3]!==e||t[4]!==m?(g=()=>{if(!e){f.current+=1,i(null),o(`idle`),l(null),d.current.clear();return}d.current.clear(),m(e);let t=null,n=h(n=>{n.includes(`session-activity`)&&(t&&clearTimeout(t),t=setTimeout(()=>{t=null,m(e)},ie))});return()=>{t&&clearTimeout(t),n()}},t[3]=e,t[4]=m,t[5]=g):g=t[5];let _;t[6]===e?_=t[7]:(_=[e],t[6]=e,t[7]=_),(0,j.useEffect)(g,_);let v,b;t[8]!==e||t[9]!==n?(v=()=>{if(!e||!n)return;let t=()=>{if(!n.awareness)return;let t=ue(n,e);i(e=>!e||le(e.writingDocs,t)?e:{...e,writingDocs:t})},r=n.awareness;if(!r||typeof r.on!=`function`){t();return}r.on(`update`,t),t();let a=setInterval(t,1e3);return()=>{clearInterval(a),typeof r.off==`function`&&r.off(`update`,t)}},b=[e,n],t[8]=e,t[9]=n,t[10]=v,t[11]=b):(v=t[10],b=t[11]),(0,j.useEffect)(v,b);let x;t[12]===e?x=t[13]:(x=async(t,n)=>{if(!e)return``;let r=`${t}\0${n}`,i=d.current.get(r);if(i!==void 0)return i;let a=await se(e,t,n);return d.current.set(r,a),a},t[12]=e,t[13]=x);let S=x,C;t[14]!==e||t[15]!==m?(C=()=>{e&&m(e)},t[14]=e,t[15]=m,t[16]=C):C=t[16];let w=C,T;return t[17]!==r||t[18]!==c||t[19]!==S||t[20]!==w||t[21]!==a?(T={data:r,status:a,error:c,reload:w,fetchBurstDiff:S},t[17]=r,t[18]=c,t[19]=S,t[20]=w,t[21]=a,t[22]=T):T=t[22],T}function le(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ue(e,t){let n=new Set;if(!e)return n;let r=e.awareness;if(!S(r))return n;let i=[t,t.startsWith(`agent-`)?t.slice(6):`agent-${t}`];for(let e of r.getStates().values()){let t=e.agentPresence;if(t)for(let e of i){let r=t[e];r&&r.mode===`writing`&&r.currentDoc&&n.add(r.currentDoc)}}return n}var M=r(),de=(0,j.lazy)(async()=>({default:(await t(()=>import(`./ActivityPanelDiffView-DeDaG2lq.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)).ActivityPanelDiffView}));function fe(e,t){let n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function pe(e){let t=(0,A.c)(38),{burst:n,docName:r,fetchBurstDiff:i}=e,[o,s]=(0,j.useState)(!1),[c,l]=(0,j.useState)(null),[u,f]=(0,j.useState)(null),[p,m]=(0,j.useState)(!1),[h,g]=(0,j.useState)(N),_,v;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(_=()=>{let e=setInterval(()=>g(Date.now()),3e4);return()=>clearInterval(e)},v=[],t[0]=_,t[1]=v):(_=t[0],v=t[1]),(0,j.useEffect)(_,v);let y;t[2]!==n.stackIndex||t[3]!==c||t[4]!==r||t[5]!==o||t[6]!==i||t[7]!==p?(y=()=>{let e=!o;s(e),e&&c===null&&!p&&(m(!0),f(null),i(r,n.stackIndex).then(e=>{l(e),m(!1)}).catch(e=>{f(e instanceof Error?e.message:String(e)),m(!1)}))},t[2]=n.stackIndex,t[3]=c,t[4]=r,t[5]=o,t[6]=i,t[7]=p,t[8]=y):y=t[8];let b=y,x=`${o?`Collapse`:`Expand`} burst ${n.stackIndex+1} diff`,S;t[9]===o?S=t[10]:(S=o?(0,M.jsx)(a,{className:`size-3 shrink-0`,"aria-hidden":`true`}):(0,M.jsx)(d,{className:`size-3 shrink-0`,"aria-hidden":`true`}),t[9]=o,t[10]=S);let C;t[11]!==n.ts||t[12]!==h?(C=fe(n.ts,h),t[11]=n.ts,t[12]=h,t[13]=C):C=t[13];let w;t[14]===C?w=t[15]:(w=(0,M.jsx)(`span`,{className:`font-mono`,children:C}),t[14]=C,t[15]=w);let T;t[16]===n.additions?T=t[17]:(T=(0,M.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additions]}),t[16]=n.additions,t[17]=T);let E;t[18]===n.deletions?E=t[19]:(E=(0,M.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletions]}),t[18]=n.deletions,t[19]=E);let D;t[20]!==T||t[21]!==E?(D=(0,M.jsxs)(`span`,{className:`ml-auto font-mono`,children:[T,` `,E]}),t[20]=T,t[21]=E,t[22]=D):D=t[22];let O;t[23]!==o||t[24]!==D||t[25]!==x||t[26]!==S||t[27]!==w||t[28]!==b?(O=(0,M.jsxs)(`button`,{type:`button`,onClick:b,className:`flex w-full items-center gap-2 px-4 py-1.5 text-xs text-muted-foreground hover:bg-muted/40`,"aria-expanded":o,"aria-label":x,children:[S,w,D]}),t[23]=o,t[24]=D,t[25]=x,t[26]=S,t[27]=w,t[28]=b,t[29]=O):O=t[29];let k;t[30]!==c||t[31]!==o||t[32]!==u||t[33]!==p?(k=o?(0,M.jsx)(`div`,{className:`bg-muted/20`,children:p?(0,M.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`Loading diff…`}):u?(0,M.jsxs)(`div`,{className:`px-4 py-2 text-xs text-destructive`,children:[`Failed: `,u]}):c===null?(0,M.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`No diff.`}):(0,M.jsx)(j.Suspense,{fallback:(0,M.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`Loading diff…`}),children:(0,M.jsx)(de,{diff:c})})}):null,t[30]=c,t[31]=o,t[32]=u,t[33]=p,t[34]=k):k=t[34];let ee;return t[35]!==O||t[36]!==k?(ee=(0,M.jsxs)(`div`,{className:`border-t border-border/50`,children:[O,k]}),t[35]=O,t[36]=k,t[37]=ee):ee=t[37],ee}function N(){return Date.now()}function me(e,t){let n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:`${Math.round(n/36e5)}h ago`}function P(e){let t=(0,A.c)(93),{file:n,sessionAlive:r,isWriting:i,onNavigate:o,onUndoLast:s,onUndoAll:c,fetchBurstDiff:l}=e,[u,f]=(0,j.useState)(!1),[p,m]=(0,j.useState)(!1),[h,g]=(0,j.useState)(!1),[y,b]=(0,j.useState)(ge),x,S;if(t[0]===Symbol.for(`react.memo_cache_sentinel`)?(x=()=>{let e=setInterval(()=>b(Date.now()),3e4);return()=>clearInterval(e)},S=[],t[0]=x,t[1]=S):(x=t[0],S=t[1]),(0,j.useEffect)(x,S),n.bursts.length===0)return null;let C=!r||n.bursts.length===0||h,ie=r?n.bursts.length===0?`Nothing to undo on this file`:null:`Session ended — undo unavailable`,ae;t[2]!==C||t[3]!==n.docName||t[4]!==s?(ae=e=>{e.stopPropagation(),!C&&(g(!0),Promise.resolve(s(n.docName)).finally(()=>g(!1)))},t[2]=C,t[3]=n.docName,t[4]=s,t[5]=ae):ae=t[5];let oe=ae,se;t[6]===C?se=t[7]:(se=e=>{e.stopPropagation(),!C&&m(!0)},t[6]=C,t[7]=se);let ce=se,le;t[8]!==C||t[9]!==n.docName||t[10]!==c?(le=()=>{m(!1),!C&&(g(!0),Promise.resolve(c(n.docName)).finally(()=>g(!1)))},t[8]=C,t[9]=n.docName,t[10]=c,t[11]=le):le=t[11];let ue=le,de;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(de=()=>f(he),t[12]=de):de=t[12];let fe=u?`Collapse ${n.docName}`:`Expand ${n.docName}`,N;t[13]===u?N=t[14]:(N=u?(0,M.jsx)(a,{className:`size-4`,"aria-hidden":`true`}):(0,M.jsx)(d,{className:`size-4`,"aria-hidden":`true`}),t[13]=u,t[14]=N);let P;t[15]!==u||t[16]!==fe||t[17]!==N?(P=(0,M.jsx)(`button`,{type:`button`,onClick:de,className:`flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted`,"aria-expanded":u,"aria-label":fe,"data-testid":`activity-panel-file-row-carrot`,children:N}),t[15]=u,t[16]=fe,t[17]=N,t[18]=P):P=t[18];let F;t[19]!==n.docName||t[20]!==o?(F=()=>o(n.docName),t[19]=n.docName,t[20]=o,t[21]=F):F=t[21];let _e=`Navigate to ${n.docName}`,I;t[22]!==n.docName||t[23]!==F||t[24]!==_e?(I=(0,M.jsx)(`button`,{type:`button`,onClick:F,className:`min-w-0 flex-1 truncate text-left text-foreground hover:underline focus-visible:outline-ring`,"aria-label":_e,"data-testid":`activity-panel-file-row-filename`,title:n.docName,children:n.docName}),t[22]=n.docName,t[23]=F,t[24]=_e,t[25]=I):I=t[25];let ve=`Undo last edit on ${n.docName}`,ye;t[26]===Symbol.for(`react.memo_cache_sentinel`)?(ye=(0,M.jsx)(v,{className:`size-3.5`,"aria-hidden":`true`}),t[26]=ye):ye=t[26];let L;t[27]!==C||t[28]!==oe||t[29]!==ve?(L=(0,M.jsx)(w,{asChild:!0,children:(0,M.jsx)(_,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:oe,disabled:C,"aria-label":ve,"data-testid":`activity-panel-undo-last`,children:ye})}),t[27]=C,t[28]=oe,t[29]=ve,t[30]=L):L=t[30];let be=ie??`Undo last edit`,R;t[31]===be?R=t[32]:(R=(0,M.jsx)(T,{side:`bottom`,children:be}),t[31]=be,t[32]=R);let z;t[33]!==L||t[34]!==R?(z=(0,M.jsxs)(E,{children:[L,R]}),t[33]=L,t[34]=R,t[35]=z):z=t[35];let xe=`Undo all edits on ${n.docName}`,Se;t[36]===Symbol.for(`react.memo_cache_sentinel`)?(Se=(0,M.jsx)(re,{className:`size-3.5`,"aria-hidden":`true`}),t[36]=Se):Se=t[36];let B;t[37]!==C||t[38]!==ce||t[39]!==xe?(B=(0,M.jsx)(w,{asChild:!0,children:(0,M.jsx)(_,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:ce,disabled:C,"aria-label":xe,"data-testid":`activity-panel-undo-all`,children:Se})}),t[37]=C,t[38]=ce,t[39]=xe,t[40]=B):B=t[40];let Ce=ie??`Undo all edits`,V;t[41]===Ce?V=t[42]:(V=(0,M.jsx)(T,{side:`bottom`,children:Ce}),t[41]=Ce,t[42]=V);let H;t[43]!==B||t[44]!==V?(H=(0,M.jsxs)(E,{children:[B,V]}),t[43]=B,t[44]=V,t[45]=H):H=t[45];let U;t[46]===n.additionsTotal?U=t[47]:(U=(0,M.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additionsTotal]}),t[46]=n.additionsTotal,t[47]=U);let W;t[48]===n.deletionsTotal?W=t[49]:(W=(0,M.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletionsTotal]}),t[48]=n.deletionsTotal,t[49]=W);let G;t[50]!==U||t[51]!==W?(G=(0,M.jsxs)(`span`,{className:`shrink-0 font-mono text-xs`,children:[U,` `,W]}),t[50]=U,t[51]=W,t[52]=G):G=t[52];let K;t[53]!==n.lastTs||t[54]!==y?(K=me(n.lastTs,y),t[53]=n.lastTs,t[54]=y,t[55]=K):K=t[55];let q;t[56]===K?q=t[57]:(q=(0,M.jsx)(`span`,{className:`shrink-0 font-mono text-[11px] text-muted-foreground`,children:K}),t[56]=K,t[57]=q);let J;t[58]===i?J=t[59]:(J=i?(0,M.jsx)(`span`,{className:`shrink-0 text-[11px] text-primary animate-pulse`,role:`status`,children:`writing…`}):null,t[58]=i,t[59]=J);let Y;t[60]!==I||t[61]!==z||t[62]!==H||t[63]!==G||t[64]!==q||t[65]!==J||t[66]!==P?(Y=(0,M.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 text-sm`,children:[P,I,z,H,G,q,J]}),t[60]=I,t[61]=z,t[62]=H,t[63]=G,t[64]=q,t[65]=J,t[66]=P,t[67]=Y):Y=t[67];let X;t[68]!==u||t[69]!==l||t[70]!==n.bursts||t[71]!==n.docName?(X=u?(0,M.jsx)(`div`,{children:n.bursts.map(e=>(0,M.jsx)(pe,{burst:e,docName:n.docName,fetchBurstDiff:l},`${n.docName}:${e.stackIndex}`))}):null,t[68]=u,t[69]=l,t[70]=n.bursts,t[71]=n.docName,t[72]=X):X=t[72];let we;t[73]===Symbol.for(`react.memo_cache_sentinel`)?(we=(0,M.jsx)(O,{children:`Undo all edits on this file?`}),t[73]=we):we=t[73];let Z;t[74]===n.docName?Z=t[75]:(Z=(0,M.jsx)(`span`,{className:`font-mono text-foreground`,children:n.docName}),t[74]=n.docName,t[75]=Z);let Te=n.bursts.length===1?``:`s`,Q;t[76]!==n.bursts.length||t[77]!==Z||t[78]!==Te?(Q=(0,M.jsxs)(te,{children:[we,(0,M.jsxs)(D,{children:[`This will revert every change this agent has made to`,` `,Z,` in their current session (`,n.bursts.length,` burst`,Te,`). Other files and other writers are not affected.`]})]}),t[76]=n.bursts.length,t[77]=Z,t[78]=Te,t[79]=Q):Q=t[79];let Ee;t[80]===Symbol.for(`react.memo_cache_sentinel`)?(Ee=(0,M.jsx)(_,{type:`button`,variant:`outline`,onClick:()=>m(!1),"data-testid":`activity-panel-undo-all-cancel`,children:`Cancel`}),t[80]=Ee):Ee=t[80];let $;t[81]===ue?$=t[82]:($=(0,M.jsxs)(ee,{children:[Ee,(0,M.jsx)(_,{type:`button`,variant:`destructive`,onClick:ue,"data-testid":`activity-panel-undo-all-confirm`,children:`Undo all`})]}),t[81]=ue,t[82]=$);let De;t[83]!==Q||t[84]!==$?(De=(0,M.jsxs)(k,{className:`sm:max-w-md`,children:[Q,$]}),t[83]=Q,t[84]=$,t[85]=De):De=t[85];let Oe;t[86]!==p||t[87]!==De?(Oe=(0,M.jsx)(ne,{open:p,onOpenChange:m,children:De}),t[86]=p,t[87]=De,t[88]=Oe):Oe=t[88];let ke;return t[89]!==Y||t[90]!==X||t[91]!==Oe?(ke=(0,M.jsxs)(`div`,{className:`border-b border-border`,"data-testid":`activity-panel-file-row`,children:[Y,X,Oe]}),t[89]=Y,t[90]=X,t[91]=Oe,t[92]=ke):ke=t[92],ke}function he(e){return!e}function ge(){return Date.now()}async function F(e){let t=await fetch(`/api/agent-undo`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,agentId:e.connectionId})});if(!t.ok)throw Error(`agent-undo failed: HTTP ${t.status}`)}function _e(e){return`#/${e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`)}`}function I(e){typeof window>`u`||(window.location.hash=_e(e))}function ve(){let e=(0,A.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,M.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,role:`status`,"aria-busy":`true`,children:[(0,M.jsx)(l,{className:`mr-2 size-4 animate-spin`,"aria-hidden":`true`}),(0,M.jsx)(`span`,{className:`text-sm`,children:`Loading agent activity…`})]}),e[0]=t):t=e[0],t}function ye(e){let t=(0,A.c)(9),{error:n,onRetry:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,M.jsx)(o,{className:`size-6 text-destructive`,"aria-hidden":`true`}),t[0]=i):i=t[0];let a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,M.jsx)(`p`,{className:`text-sm font-medium`,children:`Failed to load activity`}),t[1]=a):a=t[1];let s;t[2]===n?s=t[3]:(s=(0,M.jsxs)(`div`,{className:`space-y-1`,children:[a,(0,M.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:n})]}),t[2]=n,t[3]=s);let c;t[4]===r?c=t[5]:(c=(0,M.jsx)(_,{type:`button`,variant:`outline`,size:`sm`,onClick:r,children:`Retry`}),t[4]=r,t[5]=c);let l;return t[6]!==s||t[7]!==c?(l=(0,M.jsxs)(`div`,{className:`flex flex-col items-center gap-3 p-6 text-center`,role:`alert`,"data-testid":`activity-panel-error`,children:[i,s,c]}),t[6]=s,t[7]=c,t[8]=l):l=t[8],l}function L(){let e=(0,A.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,M.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,"data-testid":`activity-panel-empty`,children:(0,M.jsx)(`p`,{className:`text-sm italic`,children:`No edits yet.`})}),e[0]=t):t=e[0],t}function be(e){let t=(0,A.c)(8),{onExit:n}=e,r;t[0]===n?r=t[1]:(r=(0,M.jsx)(R,{onClick:n}),t[0]=n,t[1]=r);let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,M.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:`Agent activity`}),t[2]=i):i=t[2];let a;t[3]===r?a=t[4]:(a=(0,M.jsxs)(`div`,{className:`flex shrink-0 flex-row items-center gap-2 border-b border-border px-3 py-2`,children:[r,i]}),t[3]=r,t[4]=a);let o;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,M.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-6 text-muted-foreground`,children:(0,M.jsx)(`p`,{className:`text-center text-sm italic`,children:`Click an agent's avatar in the presence bar to view their session.`})}),t[5]=o):o=t[5];let s;return t[6]===a?s=t[7]:(s=(0,M.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel-no-agent`,"aria-label":`Agent activity`,children:[a,o]}),t[6]=a,t[7]=s),s}function R(e){let t=(0,A.c)(6),{onClick:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,M.jsx)(b,{}),t[0]=r):r=t[0];let i;t[1]===n?i=t[2]:(i=(0,M.jsx)(w,{asChild:!0,children:(0,M.jsx)(_,{type:`button`,variant:`ghost`,size:`icon`,className:`size-7 shrink-0`,onClick:n,"aria-label":`Back to document view`,"data-testid":`docpanel-exit-agent-mode`,children:r})}),t[1]=n,t[2]=i);let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,M.jsx)(T,{side:`bottom`,children:`Back to document view`}),t[3]=a):a=t[3];let o;return t[4]===i?o=t[5]:(o=(0,M.jsxs)(E,{children:[i,a]}),t[4]=i,t[5]=o),o}function z(e){let t=(0,A.c)(9),{lastTs:n}=e,[r]=(0,j.useState)(xe),i;t[0]!==n||t[1]!==r?(i=n?Se(r-n):null,t[0]=n,t[1]=r,t[2]=i):i=t[2];let a=i,o;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,M.jsx)(`span`,{className:`font-medium`,children:`Session ended`}),t[3]=o):o=t[3];let s;t[4]===a?s=t[5]:(s=a?(0,M.jsxs)(`span`,{children:[` · `,a]}):null,t[4]=a,t[5]=s);let c;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,M.jsx)(`div`,{className:`mt-1 opacity-80`,children:`Undo buttons are disabled — per-session state has been garbage-collected.`}),t[6]=c):c=t[6];let l;return t[7]===s?l=t[8]:(l=(0,M.jsxs)(`div`,{className:`border-b border-border bg-muted/40 px-4 py-3 text-xs text-muted-foreground`,"data-testid":`activity-panel-session-ended`,children:[o,s,c]}),t[7]=s,t[8]=l),l}function xe(){return Date.now()}function Se(e){let t=Math.max(0,e);return t<6e4?`${Math.round(t/1e3)}s ago`:t<36e5?`${Math.round(t/6e4)}m ago`:`${Math.round(t/36e5)}h ago`}function B(e){let t=(0,A.c)(10),{agent:n,size:r}=e,i=r===void 0?28:r,a;t[0]!==n.color||t[1]!==i?(a={backgroundColor:n.color,width:i,height:i},t[0]=n.color,t[1]=i,t[2]=a):a=t[2];let o=i*.57,s=i*.57,c;t[3]!==n.icon||t[4]!==o||t[5]!==s?(c=(0,M.jsx)(x,{icon:n.icon,width:o,height:s}),t[3]=n.icon,t[4]=o,t[5]=s,t[6]=c):c=t[6];let l;return t[7]!==a||t[8]!==c?(l=(0,M.jsx)(`span`,{className:`inline-flex shrink-0 items-center justify-center rounded-full text-white ring-2 ring-background`,style:a,"aria-hidden":`true`,children:c}),t[7]=a,t[8]=c,t[9]=l):l=t[9],l}function Ce(e){let t=(0,A.c)(20),{data:n,status:r,error:i,reload:a,fetchBurstDiff:o,onExit:s,onNavigate:c,onUndoLast:l,onUndoAll:u}=e,d=n?.files?.[0]?.lastTs??null,f;t[0]===s?f=t[1]:(f=(0,M.jsx)(R,{onClick:s}),t[0]=s,t[1]=f);let p;t[2]===n?p=t[3]:(p=n?.agent?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(B,{agent:n.agent}),(0,M.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,M.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:n.agent.displayName}),(0,M.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[n.sessionAlive?`Active`:`Ended`,n.files.length>0?` · ${n.files.length} file${n.files.length===1?``:`s`}`:``]})]})]}):(0,M.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,M.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:`Agent activity`})}),t[2]=n,t[3]=p);let m;t[4]!==f||t[5]!==p?(m=(0,M.jsxs)(`div`,{className:`flex flex-row items-center gap-2 border-b border-border px-3 py-2 shrink-0`,children:[f,p]}),t[4]=f,t[5]=p,t[6]=m):m=t[6];let h;t[7]!==n||t[8]!==i||t[9]!==o||t[10]!==d||t[11]!==c||t[12]!==u||t[13]!==l||t[14]!==a||t[15]!==r?(h=(0,M.jsx)(`div`,{className:`flex-1 overflow-y-auto`,"data-testid":`activity-panel-body`,children:r===`loading`&&n===null?(0,M.jsx)(ve,{}):r===`error`&&i?(0,M.jsx)(ye,{error:i,onRetry:a}):n===null?(0,M.jsx)(L,{}):(0,M.jsxs)(M.Fragment,{children:[n.sessionAlive?null:(0,M.jsx)(z,{lastTs:d}),n.files.length===0?(0,M.jsx)(L,{}):n.files.map(e=>(0,M.jsx)(P,{file:e,sessionAlive:n.sessionAlive,isWriting:n.writingDocs.has(e.docName),onNavigate:c,onUndoLast:l,onUndoAll:u,fetchBurstDiff:o},e.docName))]})}),t[7]=n,t[8]=i,t[9]=o,t[10]=d,t[11]=c,t[12]=u,t[13]=l,t[14]=a,t[15]=r,t[16]=h):h=t[16];let g;return t[17]!==m||t[18]!==h?(g=(0,M.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel`,"aria-label":`Agent activity`,children:[m,h]}),t[17]=m,t[18]=h,t[19]=g):g=t[19],g}function V(){let e=(0,A.c)(22),{docPanelAgentId:t,closeActivityPanel:n}=s(),{openDocumentTransition:r}=u(),{data:i,status:a,error:o,reload:c,fetchBurstDiff:l}=ce(t);if(t===null){let t;return e[0]===n?t=e[1]:(t=(0,M.jsx)(be,{onExit:n}),e[0]=n,e[1]=t),t}let d;e[2]===r?d=e[3]:(d=e=>{r(e),I(e)},e[2]=r,e[3]=d);let f=d,p;e[4]!==i||e[5]!==t||e[6]!==c?(p=async e=>{try{await F({connectionId:t,docName:e,scope:`last`,agentName:i?.agent?.displayName}),c()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);C.error(`Undo failed: ${n}`),c()}},e[4]=i,e[5]=t,e[6]=c,e[7]=p):p=e[7];let m=p,h;e[8]!==i||e[9]!==t||e[10]!==c?(h=async e=>{try{await F({connectionId:t,docName:e,scope:`file`,agentName:i?.agent?.displayName}),C.success(`Undone all edits on ${e}`),c()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);C.error(`Undo all failed: ${n}`),c()}},e[8]=i,e[9]=t,e[10]=c,e[11]=h):h=e[11];let g=h,_;return e[12]!==n||e[13]!==i||e[14]!==o||e[15]!==l||e[16]!==f||e[17]!==g||e[18]!==m||e[19]!==c||e[20]!==a?(_=(0,M.jsx)(Ce,{data:i,status:a,error:o,reload:c,fetchBurstDiff:l,onExit:n,onNavigate:f,onUndoLast:m,onUndoAll:g}),e[12]=n,e[13]=i,e[14]=o,e[15]=l,e[16]=f,e[17]=g,e[18]=m,e[19]=c,e[20]=a,e[21]=_):_=e[21],_}export{V as ActivityModeContent};
2
+ import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./preload-helper-2ej06EnG.js";import{n,r,t as i}from"./compiler-runtime-CVnuRdak.js";import{Sn as a,bn as o,n as s,nt as c,on as l,r as u,xn as d}from"./DocumentContext-BoqbPYlX.js";import{At as f,G as p,W as m,p as h}from"./doc-hash-B4Tnobw5.js";import{C as g,t as _}from"./button-C1nwPVFQ.js";import{f as v,i as y,m as b,r as x,t as S}from"./agent-presence-BrTlNKmt.js";import{p as C}from"./dist-OTL8-1C2.js";import{i as w,n as T,t as E}from"./tooltip-D8vJ720z.js";import{a as D,c as O,i as k,o as ee,s as te,t as ne}from"./dialog-BFN-ujuF.js";var re=g(`rewind`,[[`path`,{d:`M12 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 12 18z`,key:`2a1g8i`}],[`path`,{d:`M22 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 22 18z`,key:`rg3s36`}]]),A=i(),j=e(n(),1),ie=500,ae=64;async function oe(e){let t=`/api/agent-activity?agentId=${encodeURIComponent(e)}`,n=await fetch(t),r;try{r=await n.json()}catch(e){throw new c(`Could not parse /api/agent-activity response.`,{cause:e,status:n.status})}if(!n.ok){let e=f.safeParse(r);throw e.success?Error(e.data.title):new c(`/api/agent-activity returned a non-RFC-9457 error response.`,{cause:e.error,status:n.status})}let i=m.safeParse(r);if(!i.success)throw new c(`/api/agent-activity returned a body that did not match AgentActivitySuccessSchema.`,{cause:i.error,status:n.status});return i.data}async function se(e,t,n){let r=`/api/agent-burst-diff?agentId=${encodeURIComponent(e)}&docName=${encodeURIComponent(t)}&stackIndex=${n}`,i=await fetch(r),a;try{a=await i.json()}catch(e){throw new c(`Could not parse /api/agent-burst-diff response.`,{cause:e,status:i.status})}if(!i.ok){let e=f.safeParse(a);throw e.success?Error(e.data.title):new c(`/api/agent-burst-diff returned a non-RFC-9457 error response.`,{cause:e.error,status:i.status})}let o=p.safeParse(a);if(!o.success)throw new c(`/api/agent-burst-diff returned a body that did not match AgentBurstDiffSuccessSchema.`,{cause:o.error,status:i.status});return o.data.diff}function ce(e){let t=(0,A.c)(23),{systemProvider:n}=s(),[r,i]=(0,j.useState)(null),[a,o]=(0,j.useState)(`idle`),[c,l]=(0,j.useState)(null),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=new y(ae),t[0]=u):u=t[0];let d=(0,j.useRef)(u),f=(0,j.useRef)(0),p;t[1]===n?p=t[2]:(p=e=>{let t=f.current+=1;o(`loading`),l(null),oe(e).then(r=>{if(f.current!==t)return;let a=ue(n,e);i({...r,writingDocs:a}),o(`ready`)}).catch(e=>{f.current===t&&(l(e instanceof Error?e.message:String(e)),o(`error`))})},t[1]=n,t[2]=p);let m=p,g;t[3]!==e||t[4]!==m?(g=()=>{if(!e){f.current+=1,i(null),o(`idle`),l(null),d.current.clear();return}d.current.clear(),m(e);let t=null,n=h(n=>{n.includes(`session-activity`)&&(t&&clearTimeout(t),t=setTimeout(()=>{t=null,m(e)},ie))});return()=>{t&&clearTimeout(t),n()}},t[3]=e,t[4]=m,t[5]=g):g=t[5];let _;t[6]===e?_=t[7]:(_=[e],t[6]=e,t[7]=_),(0,j.useEffect)(g,_);let v,b;t[8]!==e||t[9]!==n?(v=()=>{if(!e||!n)return;let t=()=>{if(!n.awareness)return;let t=ue(n,e);i(e=>!e||le(e.writingDocs,t)?e:{...e,writingDocs:t})},r=n.awareness;if(!r||typeof r.on!=`function`){t();return}r.on(`update`,t),t();let a=setInterval(t,1e3);return()=>{clearInterval(a),typeof r.off==`function`&&r.off(`update`,t)}},b=[e,n],t[8]=e,t[9]=n,t[10]=v,t[11]=b):(v=t[10],b=t[11]),(0,j.useEffect)(v,b);let x;t[12]===e?x=t[13]:(x=async(t,n)=>{if(!e)return``;let r=`${t}\0${n}`,i=d.current.get(r);if(i!==void 0)return i;let a=await se(e,t,n);return d.current.set(r,a),a},t[12]=e,t[13]=x);let S=x,C;t[14]!==e||t[15]!==m?(C=()=>{e&&m(e)},t[14]=e,t[15]=m,t[16]=C):C=t[16];let w=C,T;return t[17]!==r||t[18]!==c||t[19]!==S||t[20]!==w||t[21]!==a?(T={data:r,status:a,error:c,reload:w,fetchBurstDiff:S},t[17]=r,t[18]=c,t[19]=S,t[20]=w,t[21]=a,t[22]=T):T=t[22],T}function le(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ue(e,t){let n=new Set;if(!e)return n;let r=e.awareness;if(!S(r))return n;let i=[t,t.startsWith(`agent-`)?t.slice(6):`agent-${t}`];for(let e of r.getStates().values()){let t=e.agentPresence;if(t)for(let e of i){let r=t[e];r&&r.mode===`writing`&&r.currentDoc&&n.add(r.currentDoc)}}return n}var M=r(),de=(0,j.lazy)(async()=>({default:(await t(()=>import(`./ActivityPanelDiffView-DeDaG2lq.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)).ActivityPanelDiffView}));function fe(e,t){let n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function pe(e){let t=(0,A.c)(38),{burst:n,docName:r,fetchBurstDiff:i}=e,[o,s]=(0,j.useState)(!1),[c,l]=(0,j.useState)(null),[u,f]=(0,j.useState)(null),[p,m]=(0,j.useState)(!1),[h,g]=(0,j.useState)(N),_,v;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(_=()=>{let e=setInterval(()=>g(Date.now()),3e4);return()=>clearInterval(e)},v=[],t[0]=_,t[1]=v):(_=t[0],v=t[1]),(0,j.useEffect)(_,v);let y;t[2]!==n.stackIndex||t[3]!==c||t[4]!==r||t[5]!==o||t[6]!==i||t[7]!==p?(y=()=>{let e=!o;s(e),e&&c===null&&!p&&(m(!0),f(null),i(r,n.stackIndex).then(e=>{l(e),m(!1)}).catch(e=>{f(e instanceof Error?e.message:String(e)),m(!1)}))},t[2]=n.stackIndex,t[3]=c,t[4]=r,t[5]=o,t[6]=i,t[7]=p,t[8]=y):y=t[8];let b=y,x=`${o?`Collapse`:`Expand`} burst ${n.stackIndex+1} diff`,S;t[9]===o?S=t[10]:(S=o?(0,M.jsx)(a,{className:`size-3 shrink-0`,"aria-hidden":`true`}):(0,M.jsx)(d,{className:`size-3 shrink-0`,"aria-hidden":`true`}),t[9]=o,t[10]=S);let C;t[11]!==n.ts||t[12]!==h?(C=fe(n.ts,h),t[11]=n.ts,t[12]=h,t[13]=C):C=t[13];let w;t[14]===C?w=t[15]:(w=(0,M.jsx)(`span`,{className:`font-mono`,children:C}),t[14]=C,t[15]=w);let T;t[16]===n.additions?T=t[17]:(T=(0,M.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additions]}),t[16]=n.additions,t[17]=T);let E;t[18]===n.deletions?E=t[19]:(E=(0,M.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletions]}),t[18]=n.deletions,t[19]=E);let D;t[20]!==T||t[21]!==E?(D=(0,M.jsxs)(`span`,{className:`ml-auto font-mono`,children:[T,` `,E]}),t[20]=T,t[21]=E,t[22]=D):D=t[22];let O;t[23]!==o||t[24]!==D||t[25]!==x||t[26]!==S||t[27]!==w||t[28]!==b?(O=(0,M.jsxs)(`button`,{type:`button`,onClick:b,className:`flex w-full items-center gap-2 px-4 py-1.5 text-xs text-muted-foreground hover:bg-muted/40`,"aria-expanded":o,"aria-label":x,children:[S,w,D]}),t[23]=o,t[24]=D,t[25]=x,t[26]=S,t[27]=w,t[28]=b,t[29]=O):O=t[29];let k;t[30]!==c||t[31]!==o||t[32]!==u||t[33]!==p?(k=o?(0,M.jsx)(`div`,{className:`bg-muted/20`,children:p?(0,M.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`Loading diff…`}):u?(0,M.jsxs)(`div`,{className:`px-4 py-2 text-xs text-destructive`,children:[`Failed: `,u]}):c===null?(0,M.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`No diff.`}):(0,M.jsx)(j.Suspense,{fallback:(0,M.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`Loading diff…`}),children:(0,M.jsx)(de,{diff:c})})}):null,t[30]=c,t[31]=o,t[32]=u,t[33]=p,t[34]=k):k=t[34];let ee;return t[35]!==O||t[36]!==k?(ee=(0,M.jsxs)(`div`,{className:`border-t border-border/50`,children:[O,k]}),t[35]=O,t[36]=k,t[37]=ee):ee=t[37],ee}function N(){return Date.now()}function me(e,t){let n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:`${Math.round(n/36e5)}h ago`}function P(e){let t=(0,A.c)(93),{file:n,sessionAlive:r,isWriting:i,onNavigate:o,onUndoLast:s,onUndoAll:c,fetchBurstDiff:l}=e,[u,f]=(0,j.useState)(!1),[p,m]=(0,j.useState)(!1),[h,g]=(0,j.useState)(!1),[y,b]=(0,j.useState)(ge),x,S;if(t[0]===Symbol.for(`react.memo_cache_sentinel`)?(x=()=>{let e=setInterval(()=>b(Date.now()),3e4);return()=>clearInterval(e)},S=[],t[0]=x,t[1]=S):(x=t[0],S=t[1]),(0,j.useEffect)(x,S),n.bursts.length===0)return null;let C=!r||n.bursts.length===0||h,ie=r?n.bursts.length===0?`Nothing to undo on this file`:null:`Session ended — undo unavailable`,ae;t[2]!==C||t[3]!==n.docName||t[4]!==s?(ae=e=>{e.stopPropagation(),!C&&(g(!0),Promise.resolve(s(n.docName)).finally(()=>g(!1)))},t[2]=C,t[3]=n.docName,t[4]=s,t[5]=ae):ae=t[5];let oe=ae,se;t[6]===C?se=t[7]:(se=e=>{e.stopPropagation(),!C&&m(!0)},t[6]=C,t[7]=se);let ce=se,le;t[8]!==C||t[9]!==n.docName||t[10]!==c?(le=()=>{m(!1),!C&&(g(!0),Promise.resolve(c(n.docName)).finally(()=>g(!1)))},t[8]=C,t[9]=n.docName,t[10]=c,t[11]=le):le=t[11];let ue=le,de;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(de=()=>f(he),t[12]=de):de=t[12];let fe=u?`Collapse ${n.docName}`:`Expand ${n.docName}`,N;t[13]===u?N=t[14]:(N=u?(0,M.jsx)(a,{className:`size-4`,"aria-hidden":`true`}):(0,M.jsx)(d,{className:`size-4`,"aria-hidden":`true`}),t[13]=u,t[14]=N);let P;t[15]!==u||t[16]!==fe||t[17]!==N?(P=(0,M.jsx)(`button`,{type:`button`,onClick:de,className:`flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted`,"aria-expanded":u,"aria-label":fe,"data-testid":`activity-panel-file-row-carrot`,children:N}),t[15]=u,t[16]=fe,t[17]=N,t[18]=P):P=t[18];let F;t[19]!==n.docName||t[20]!==o?(F=()=>o(n.docName),t[19]=n.docName,t[20]=o,t[21]=F):F=t[21];let _e=`Navigate to ${n.docName}`,I;t[22]!==n.docName||t[23]!==F||t[24]!==_e?(I=(0,M.jsx)(`button`,{type:`button`,onClick:F,className:`min-w-0 flex-1 truncate text-left text-foreground hover:underline focus-visible:outline-ring`,"aria-label":_e,"data-testid":`activity-panel-file-row-filename`,title:n.docName,children:n.docName}),t[22]=n.docName,t[23]=F,t[24]=_e,t[25]=I):I=t[25];let ve=`Undo last edit on ${n.docName}`,ye;t[26]===Symbol.for(`react.memo_cache_sentinel`)?(ye=(0,M.jsx)(v,{className:`size-3.5`,"aria-hidden":`true`}),t[26]=ye):ye=t[26];let L;t[27]!==C||t[28]!==oe||t[29]!==ve?(L=(0,M.jsx)(w,{asChild:!0,children:(0,M.jsx)(_,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:oe,disabled:C,"aria-label":ve,"data-testid":`activity-panel-undo-last`,children:ye})}),t[27]=C,t[28]=oe,t[29]=ve,t[30]=L):L=t[30];let be=ie??`Undo last edit`,R;t[31]===be?R=t[32]:(R=(0,M.jsx)(T,{side:`bottom`,children:be}),t[31]=be,t[32]=R);let z;t[33]!==L||t[34]!==R?(z=(0,M.jsxs)(E,{children:[L,R]}),t[33]=L,t[34]=R,t[35]=z):z=t[35];let xe=`Undo all edits on ${n.docName}`,Se;t[36]===Symbol.for(`react.memo_cache_sentinel`)?(Se=(0,M.jsx)(re,{className:`size-3.5`,"aria-hidden":`true`}),t[36]=Se):Se=t[36];let B;t[37]!==C||t[38]!==ce||t[39]!==xe?(B=(0,M.jsx)(w,{asChild:!0,children:(0,M.jsx)(_,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:ce,disabled:C,"aria-label":xe,"data-testid":`activity-panel-undo-all`,children:Se})}),t[37]=C,t[38]=ce,t[39]=xe,t[40]=B):B=t[40];let Ce=ie??`Undo all edits`,V;t[41]===Ce?V=t[42]:(V=(0,M.jsx)(T,{side:`bottom`,children:Ce}),t[41]=Ce,t[42]=V);let H;t[43]!==B||t[44]!==V?(H=(0,M.jsxs)(E,{children:[B,V]}),t[43]=B,t[44]=V,t[45]=H):H=t[45];let U;t[46]===n.additionsTotal?U=t[47]:(U=(0,M.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additionsTotal]}),t[46]=n.additionsTotal,t[47]=U);let W;t[48]===n.deletionsTotal?W=t[49]:(W=(0,M.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletionsTotal]}),t[48]=n.deletionsTotal,t[49]=W);let G;t[50]!==U||t[51]!==W?(G=(0,M.jsxs)(`span`,{className:`shrink-0 font-mono text-xs`,children:[U,` `,W]}),t[50]=U,t[51]=W,t[52]=G):G=t[52];let K;t[53]!==n.lastTs||t[54]!==y?(K=me(n.lastTs,y),t[53]=n.lastTs,t[54]=y,t[55]=K):K=t[55];let q;t[56]===K?q=t[57]:(q=(0,M.jsx)(`span`,{className:`shrink-0 font-mono text-[11px] text-muted-foreground`,children:K}),t[56]=K,t[57]=q);let J;t[58]===i?J=t[59]:(J=i?(0,M.jsx)(`span`,{className:`shrink-0 text-[11px] text-primary animate-pulse`,role:`status`,children:`writing…`}):null,t[58]=i,t[59]=J);let Y;t[60]!==I||t[61]!==z||t[62]!==H||t[63]!==G||t[64]!==q||t[65]!==J||t[66]!==P?(Y=(0,M.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 text-sm`,children:[P,I,z,H,G,q,J]}),t[60]=I,t[61]=z,t[62]=H,t[63]=G,t[64]=q,t[65]=J,t[66]=P,t[67]=Y):Y=t[67];let X;t[68]!==u||t[69]!==l||t[70]!==n.bursts||t[71]!==n.docName?(X=u?(0,M.jsx)(`div`,{children:n.bursts.map(e=>(0,M.jsx)(pe,{burst:e,docName:n.docName,fetchBurstDiff:l},`${n.docName}:${e.stackIndex}`))}):null,t[68]=u,t[69]=l,t[70]=n.bursts,t[71]=n.docName,t[72]=X):X=t[72];let we;t[73]===Symbol.for(`react.memo_cache_sentinel`)?(we=(0,M.jsx)(O,{children:`Undo all edits on this file?`}),t[73]=we):we=t[73];let Z;t[74]===n.docName?Z=t[75]:(Z=(0,M.jsx)(`span`,{className:`font-mono text-foreground`,children:n.docName}),t[74]=n.docName,t[75]=Z);let Te=n.bursts.length===1?``:`s`,Q;t[76]!==n.bursts.length||t[77]!==Z||t[78]!==Te?(Q=(0,M.jsxs)(te,{children:[we,(0,M.jsxs)(D,{children:[`This will revert every change this agent has made to`,` `,Z,` in their current session (`,n.bursts.length,` burst`,Te,`). Other files and other writers are not affected.`]})]}),t[76]=n.bursts.length,t[77]=Z,t[78]=Te,t[79]=Q):Q=t[79];let Ee;t[80]===Symbol.for(`react.memo_cache_sentinel`)?(Ee=(0,M.jsx)(_,{type:`button`,variant:`outline`,onClick:()=>m(!1),"data-testid":`activity-panel-undo-all-cancel`,children:`Cancel`}),t[80]=Ee):Ee=t[80];let $;t[81]===ue?$=t[82]:($=(0,M.jsxs)(ee,{children:[Ee,(0,M.jsx)(_,{type:`button`,variant:`destructive`,onClick:ue,"data-testid":`activity-panel-undo-all-confirm`,children:`Undo all`})]}),t[81]=ue,t[82]=$);let De;t[83]!==Q||t[84]!==$?(De=(0,M.jsxs)(k,{className:`sm:max-w-md`,children:[Q,$]}),t[83]=Q,t[84]=$,t[85]=De):De=t[85];let Oe;t[86]!==p||t[87]!==De?(Oe=(0,M.jsx)(ne,{open:p,onOpenChange:m,children:De}),t[86]=p,t[87]=De,t[88]=Oe):Oe=t[88];let ke;return t[89]!==Y||t[90]!==X||t[91]!==Oe?(ke=(0,M.jsxs)(`div`,{className:`border-b border-border`,"data-testid":`activity-panel-file-row`,children:[Y,X,Oe]}),t[89]=Y,t[90]=X,t[91]=Oe,t[92]=ke):ke=t[92],ke}function he(e){return!e}function ge(){return Date.now()}async function F(e){let t=await fetch(`/api/agent-undo`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,agentId:e.connectionId})});if(!t.ok)throw Error(`agent-undo failed: HTTP ${t.status}`)}function _e(e){return`#/${e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`)}`}function I(e){typeof window>`u`||(window.location.hash=_e(e))}function ve(){let e=(0,A.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,M.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,role:`status`,"aria-busy":`true`,children:[(0,M.jsx)(l,{className:`mr-2 size-4 animate-spin`,"aria-hidden":`true`}),(0,M.jsx)(`span`,{className:`text-sm`,children:`Loading agent activity…`})]}),e[0]=t):t=e[0],t}function ye(e){let t=(0,A.c)(9),{error:n,onRetry:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,M.jsx)(o,{className:`size-6 text-destructive`,"aria-hidden":`true`}),t[0]=i):i=t[0];let a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,M.jsx)(`p`,{className:`text-sm font-medium`,children:`Failed to load activity`}),t[1]=a):a=t[1];let s;t[2]===n?s=t[3]:(s=(0,M.jsxs)(`div`,{className:`space-y-1`,children:[a,(0,M.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:n})]}),t[2]=n,t[3]=s);let c;t[4]===r?c=t[5]:(c=(0,M.jsx)(_,{type:`button`,variant:`outline`,size:`sm`,onClick:r,children:`Retry`}),t[4]=r,t[5]=c);let l;return t[6]!==s||t[7]!==c?(l=(0,M.jsxs)(`div`,{className:`flex flex-col items-center gap-3 p-6 text-center`,role:`alert`,"data-testid":`activity-panel-error`,children:[i,s,c]}),t[6]=s,t[7]=c,t[8]=l):l=t[8],l}function L(){let e=(0,A.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,M.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,"data-testid":`activity-panel-empty`,children:(0,M.jsx)(`p`,{className:`text-sm italic`,children:`No edits yet.`})}),e[0]=t):t=e[0],t}function be(e){let t=(0,A.c)(8),{onExit:n}=e,r;t[0]===n?r=t[1]:(r=(0,M.jsx)(R,{onClick:n}),t[0]=n,t[1]=r);let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,M.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:`Agent activity`}),t[2]=i):i=t[2];let a;t[3]===r?a=t[4]:(a=(0,M.jsxs)(`div`,{className:`flex shrink-0 flex-row items-center gap-2 border-b border-border px-3 py-2`,children:[r,i]}),t[3]=r,t[4]=a);let o;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,M.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-6 text-muted-foreground`,children:(0,M.jsx)(`p`,{className:`text-center text-sm italic`,children:`Click an agent's avatar in the presence bar to view their session.`})}),t[5]=o):o=t[5];let s;return t[6]===a?s=t[7]:(s=(0,M.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel-no-agent`,"aria-label":`Agent activity`,children:[a,o]}),t[6]=a,t[7]=s),s}function R(e){let t=(0,A.c)(6),{onClick:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,M.jsx)(b,{}),t[0]=r):r=t[0];let i;t[1]===n?i=t[2]:(i=(0,M.jsx)(w,{asChild:!0,children:(0,M.jsx)(_,{type:`button`,variant:`ghost`,size:`icon`,className:`size-7 shrink-0`,onClick:n,"aria-label":`Back to document view`,"data-testid":`docpanel-exit-agent-mode`,children:r})}),t[1]=n,t[2]=i);let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,M.jsx)(T,{side:`bottom`,children:`Back to document view`}),t[3]=a):a=t[3];let o;return t[4]===i?o=t[5]:(o=(0,M.jsxs)(E,{children:[i,a]}),t[4]=i,t[5]=o),o}function z(e){let t=(0,A.c)(9),{lastTs:n}=e,[r]=(0,j.useState)(xe),i;t[0]!==n||t[1]!==r?(i=n?Se(r-n):null,t[0]=n,t[1]=r,t[2]=i):i=t[2];let a=i,o;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,M.jsx)(`span`,{className:`font-medium`,children:`Session ended`}),t[3]=o):o=t[3];let s;t[4]===a?s=t[5]:(s=a?(0,M.jsxs)(`span`,{children:[` · `,a]}):null,t[4]=a,t[5]=s);let c;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,M.jsx)(`div`,{className:`mt-1 opacity-80`,children:`Undo buttons are disabled — per-session state has been garbage-collected.`}),t[6]=c):c=t[6];let l;return t[7]===s?l=t[8]:(l=(0,M.jsxs)(`div`,{className:`border-b border-border bg-muted/40 px-4 py-3 text-xs text-muted-foreground`,"data-testid":`activity-panel-session-ended`,children:[o,s,c]}),t[7]=s,t[8]=l),l}function xe(){return Date.now()}function Se(e){let t=Math.max(0,e);return t<6e4?`${Math.round(t/1e3)}s ago`:t<36e5?`${Math.round(t/6e4)}m ago`:`${Math.round(t/36e5)}h ago`}function B(e){let t=(0,A.c)(10),{agent:n,size:r}=e,i=r===void 0?28:r,a;t[0]!==n.color||t[1]!==i?(a={backgroundColor:n.color,width:i,height:i},t[0]=n.color,t[1]=i,t[2]=a):a=t[2];let o=i*.57,s=i*.57,c;t[3]!==n.icon||t[4]!==o||t[5]!==s?(c=(0,M.jsx)(x,{icon:n.icon,width:o,height:s}),t[3]=n.icon,t[4]=o,t[5]=s,t[6]=c):c=t[6];let l;return t[7]!==a||t[8]!==c?(l=(0,M.jsx)(`span`,{className:`inline-flex shrink-0 items-center justify-center rounded-full text-white ring-2 ring-background`,style:a,"aria-hidden":`true`,children:c}),t[7]=a,t[8]=c,t[9]=l):l=t[9],l}function Ce(e){let t=(0,A.c)(20),{data:n,status:r,error:i,reload:a,fetchBurstDiff:o,onExit:s,onNavigate:c,onUndoLast:l,onUndoAll:u}=e,d=n?.files?.[0]?.lastTs??null,f;t[0]===s?f=t[1]:(f=(0,M.jsx)(R,{onClick:s}),t[0]=s,t[1]=f);let p;t[2]===n?p=t[3]:(p=n?.agent?(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(B,{agent:n.agent}),(0,M.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,M.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:n.agent.displayName}),(0,M.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[n.sessionAlive?`Active`:`Ended`,n.files.length>0?` · ${n.files.length} file${n.files.length===1?``:`s`}`:``]})]})]}):(0,M.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,M.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:`Agent activity`})}),t[2]=n,t[3]=p);let m;t[4]!==f||t[5]!==p?(m=(0,M.jsxs)(`div`,{className:`flex flex-row items-center gap-2 border-b border-border px-3 py-2 shrink-0`,children:[f,p]}),t[4]=f,t[5]=p,t[6]=m):m=t[6];let h;t[7]!==n||t[8]!==i||t[9]!==o||t[10]!==d||t[11]!==c||t[12]!==u||t[13]!==l||t[14]!==a||t[15]!==r?(h=(0,M.jsx)(`div`,{className:`flex-1 overflow-y-auto`,"data-testid":`activity-panel-body`,children:r===`loading`&&n===null?(0,M.jsx)(ve,{}):r===`error`&&i?(0,M.jsx)(ye,{error:i,onRetry:a}):n===null?(0,M.jsx)(L,{}):(0,M.jsxs)(M.Fragment,{children:[n.sessionAlive?null:(0,M.jsx)(z,{lastTs:d}),n.files.length===0?(0,M.jsx)(L,{}):n.files.map(e=>(0,M.jsx)(P,{file:e,sessionAlive:n.sessionAlive,isWriting:n.writingDocs.has(e.docName),onNavigate:c,onUndoLast:l,onUndoAll:u,fetchBurstDiff:o},e.docName))]})}),t[7]=n,t[8]=i,t[9]=o,t[10]=d,t[11]=c,t[12]=u,t[13]=l,t[14]=a,t[15]=r,t[16]=h):h=t[16];let g;return t[17]!==m||t[18]!==h?(g=(0,M.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel`,"aria-label":`Agent activity`,children:[m,h]}),t[17]=m,t[18]=h,t[19]=g):g=t[19],g}function V(){let e=(0,A.c)(22),{docPanelAgentId:t,closeActivityPanel:n}=s(),{openDocumentTransition:r}=u(),{data:i,status:a,error:o,reload:c,fetchBurstDiff:l}=ce(t);if(t===null){let t;return e[0]===n?t=e[1]:(t=(0,M.jsx)(be,{onExit:n}),e[0]=n,e[1]=t),t}let d;e[2]===r?d=e[3]:(d=e=>{r(e),I(e)},e[2]=r,e[3]=d);let f=d,p;e[4]!==i||e[5]!==t||e[6]!==c?(p=async e=>{try{await F({connectionId:t,docName:e,scope:`last`,agentName:i?.agent?.displayName}),c()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);C.error(`Undo failed: ${n}`),c()}},e[4]=i,e[5]=t,e[6]=c,e[7]=p):p=e[7];let m=p,h;e[8]!==i||e[9]!==t||e[10]!==c?(h=async e=>{try{await F({connectionId:t,docName:e,scope:`file`,agentName:i?.agent?.displayName}),C.success(`Undone all edits on ${e}`),c()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);C.error(`Undo all failed: ${n}`),c()}},e[8]=i,e[9]=t,e[10]=c,e[11]=h):h=e[11];let g=h,_;return e[12]!==n||e[13]!==i||e[14]!==o||e[15]!==l||e[16]!==f||e[17]!==g||e[18]!==m||e[19]!==c||e[20]!==a?(_=(0,M.jsx)(Ce,{data:i,status:a,error:o,reload:c,fetchBurstDiff:l,onExit:n,onNavigate:f,onUndoLast:m,onUndoAll:g}),e[12]=n,e[13]=i,e[14]=o,e[15]=l,e[16]=f,e[17]=g,e[18]=m,e[19]=c,e[20]=a,e[21]=_):_=e[21],_}export{V as ActivityModeContent};