@inkeep/open-knowledge 0.15.1-beta.6 → 0.15.1-beta.7

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 (47) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +2 -2
  3. package/dist/cli.mjs +39 -39
  4. package/dist/constants-Bobe-usB.mjs +2 -0
  5. package/dist/dist-By70vg0t.mjs +1 -0
  6. package/dist/{dist-Bl_tym1Z.mjs → dist-CTSVLMDV.mjs} +9 -9
  7. package/dist/{gh-detect-DRHds4VZ.mjs → gh-detect-wbzQ2Z5B.mjs} +2 -2
  8. package/dist/index.mjs +1 -1
  9. package/dist/{init-Bjqbi7tq.mjs → init-Cm5GW5mh.mjs} +4 -4
  10. package/dist/init-D-d4SGw0.mjs +1 -0
  11. package/dist/loader-DGNS5l_B.mjs +1 -0
  12. package/dist/{loader-BkYww0cx.mjs → loader-Dkfxwsah.mjs} +3 -3
  13. package/dist/{preview-D9LzF-Fr.mjs → preview-B-cCcCju.mjs} +2 -2
  14. package/dist/preview-tihHY5hY.mjs +1 -0
  15. package/dist/public/assets/{ActivityModeContent-CcoGE_xm.js → ActivityModeContent-DYW6IyGe.js} +1 -1
  16. package/dist/public/assets/{DocumentContext-BYFYD2OR.js → DocumentContext-FDflxKx1.js} +1 -1
  17. package/dist/public/assets/{GraphPanel-B-5AaMRg.js → GraphPanel-BgmjHl8X.js} +1 -1
  18. package/dist/public/assets/{OpenInAgentMenuRequestContext-Df4A0AvJ.js → OpenInAgentMenuRequestContext-DbnEO7GU.js} +1 -1
  19. package/dist/public/assets/{SettingsDialogBody-DEjtbwaA.js → SettingsDialogBody-Cw9UBlHN.js} +1 -1
  20. package/dist/public/assets/{SourceEditor-DLdOP88L.js → SourceEditor-Dt3ubo6_.js} +1 -1
  21. package/dist/public/assets/{TerminalPanel-yOVM28DS.js → TerminalPanel-Cs1MTR-8.js} +1 -1
  22. package/dist/public/assets/{config-validation-events-CRgM6DHS.js → config-validation-events-fxmQuSvc.js} +1 -1
  23. package/dist/public/assets/{dist-CVCWWNPG.js → dist-BRazL6Zi.js} +48 -48
  24. package/dist/public/assets/{index-H6g-q9oP.js → index-DnhI2qSt.js} +4 -4
  25. package/dist/public/assets/{keyboard-shortcuts-Bg9IdvnR.js → keyboard-shortcuts-73a1LeH2.js} +1 -1
  26. package/dist/public/assets/{prop-types-BSgyUl9p.js → prop-types-C2NMu-PZ.js} +1 -1
  27. package/dist/public/assets/{target-navigation-intent-BMIQLSDV.js → target-navigation-intent-xCp4fypZ.js} +1 -1
  28. package/dist/public/index.html +8 -8
  29. package/dist/{repair-launch-json-hXlTjsfs.mjs → repair-launch-json-CV5266VW.mjs} +2 -2
  30. package/dist/{repair-mcp-configs-h-6B0X-K.mjs → repair-mcp-configs-CHXzSTzV.mjs} +2 -2
  31. package/dist/repair-skills-BQnVB088.mjs +1 -0
  32. package/dist/{repair-skills-GcwKI4g2.mjs → repair-skills-M719vrZS.mjs} +2 -2
  33. package/dist/{server-lock-BpjJj3OD-CrZDl-wH.mjs → server-lock-BpjJj3OD-DlYx_Xz-.mjs} +26 -26
  34. package/dist/server-lock-CyhBidkz-DUTkjNDG.mjs +1 -0
  35. package/dist/{src-BJmU1xUi.mjs → src-DKbIfvR1.mjs} +2 -2
  36. package/dist/start-BPtlwTTP.mjs +1 -0
  37. package/dist/{start-DL_BorjL.mjs → start-CY65wpTR.mjs} +2 -2
  38. package/dist/{write-project-skill-DyOqNMyv.mjs → write-project-skill-CD8uXqFq.mjs} +2 -2
  39. package/package.json +1 -1
  40. package/dist/constants-CzR7h6sJ.mjs +0 -2
  41. package/dist/dist-CPY1U8Js.mjs +0 -1
  42. package/dist/init-U6l1ZhLC.mjs +0 -1
  43. package/dist/loader-DTHLxJVE.mjs +0 -1
  44. package/dist/preview-BQT50xLD.mjs +0 -1
  45. package/dist/repair-skills-B4UCaBBt.mjs +0 -1
  46. package/dist/server-lock-CyhBidkz-DXuuHDkK.mjs +0 -1
  47. package/dist/start-83Z5Rbjk.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{a as __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM$2,t as __commonJSMin$2}from"./chunk-C94x7I9S.mjs";import{$ as CONFIG_DOC_NAME_PROJECT_LOCAL,$i as literal,$n as TemplateGetSuccessSchema,$r as prependFrontmatter,$t as MetricsParseHealthSuccessSchema,A as AgentWriteSuccessSchema,Ai as LOCAL_DIR,An as SemanticIndexStatusSchema,Ar as detectFmRegion,At as FrontmatterPatchSuccessSchema,B as CC1DerivedViewPayloadSchema,Bi as validatePatchScopes,Bn as SpawnCursorSuccessSchema,Br as getHeadingSlug,Bt as LINKABLE_ASSET_EXTENSIONS,C as AgentPatchRequestSchema,Ca as defineLazy,Ci as CONFIG_SCHEMA_MAJOR_PATH,Cn as SaveVersionSuccessSchema,Cr as createBasenameIndex,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdRequestSchema,Da as require_dist$1,Di as DEFAULT_LOGS_MAX_BYTES,Dn as SeedApplySuccessSchema,Dr as createWorkspaceSearchDocument,Dt as FolderConfigPutSuccessSchema,E as AgentUndoSuccessSchema,Ei as DEFAULT_EMBEDDINGS_MODEL,En as SeedApplyRequestSchema,Er as createWorkspaceSearchCorpus,Et as FolderConfigPutRequestSchema,F as BridgeInvariantViolationError,Fi as detectRemovedKeys,Fn as SharePublishOwnersResponseSchema,Fr as expandTagToHierarchy,Ft as INLINE_RENDERABLE_EXTENSIONS,G as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Gi as _enum,Gn as SyncResolveConflictRequestSchema,Gr as isFrontmatterValueEmpty,Gt as LocalOpAuthStatusSuccessSchema,H as CC1ServerInfoPayloadSchema,Hi as withConfigSpanSync,Hn as SuggestLinksSuccessSchema,Hr as getWikiLinkText,Ht as LocalOpAuthEmptySuccessSchema,I as BridgeMergeContentLossError,Ii as humanFormat,In as SharePublishRequestSchema,Ir as extractFrontmatterTags,It as InstallSkillRequestSchema,J as CC1_CONTRACT_VERSION,Ji as array,Jn as SyncTriggerRequestSchema,Jr as isValidBranchName,Jt as LocalOpEmbeddingsSetKeyRequestSchema,K as CC1_CHANNEL_DISK_ACK,Ki as _null,Kn as SyncResolveConflictSuccessSchema,Kr as isHiddenDocName,Kt as LocalOpCloneRequestSchema,L as CC1BranchSwitchedPayloadSchema,Li as isKnownConfigError,Ln as SharePublishResponseSchema,Lr as fnv1aDigest,Lt as InstallSkillSuccessSchema,M as BacklinkCountsSuccessSchema,Mn as ShareConstructUrlRequestSchema,Mr as emitToleranceFire,Mt as HistorySuccessSchema,N as BacklinksSuccessSchema,Ni as addConfigSpanEvent,Nn as ShareConstructUrlResponseSchema,Nr as emptySkillState,Nt as HistoryVersionSuccessSchema,O as AgentWriteMdSuccessSchema,Oi as DEFAULT_SPANS_MAX_BYTES,On as SeedListPacksSuccessSchema,Or as defaultScheduler,Ot as ForwardLinksSuccessSchema,P as BranchInfoResponseSchema,Pi as applyPatchToDocument,Pn as SharePublishNameCheckResponseSchema,Pr as encodeShareUrl,Pt as HubsSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT,Qi as intersection,Qn as TemplateDeleteSuccessSchema,Qr as parseFrontmatterYaml,Qt as MetricsAgentPresenceSuccessSchema,R as CC1ConfigIgnoreNestedErrorPayloadSchema,Ri as locateIssue,Rn as SkillInstallStateSuccessSchema,Rr as formatFileSize,Rt as InstalledAgentsSuccessSchema,S as AgentBurstDiffSuccessSchema,Sa as clone,Si as Fragment,Sn as SaveVersionRequestSchema,Sr as colorFromSeed,St as EXECUTABLE_BLOCKLIST_EXTENSIONS,T as AgentUndoRequestSchema,Ta as $constructor,Ti as DEFAULT_EMBEDDINGS_BASE_URL,Tn as SearchSuccessSchema,Tr as createTagInTextRegex,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_BRANCH_SWITCHED,Un as SyncConflictContentSuccessSchema,Ur as iconFromClientName,Ut as LocalOpAuthHostRequestSchema,V as CC1DiskAckPayloadSchema,Vi as withConfigSpan,Vn as StreamingProblemEventSchema,Vr as getParseHealth,Vt as LinkGraphSuccessSchema,W as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Wi as ZodOptional$1,Wn as SyncConflictsSuccessSchema,Wr as isBranchNotFoundGitError,Wt as LocalOpAuthSetIdentityRequestSchema,X as CONFIG_DOC_NAMES,Xi as custom,Xn as TagsForNameSuccessSchema,Xr as mergeThreeWay,Xt as LocalOpOkInitResponseSchema,Y as CLIENT_VERSION_HEADER,Yi as boolean,Yn as SyncTriggerSuccessSchema,Yr as mediaKindForSidebarAssetExtension,Yt as LocalOpOkInitRequestSchema,Z as CONFIG_DOC_NAME_OKIGNORE,Zi as discriminatedUnion,Zn as TagsListSuccessSchema,Zr as normalizeBridge,Zt as MarkdownManager,_ as AGENT_ICON_COLORS,_a as parse$1,_i as unwrapFrontmatterFences,_n as SKILL_STATE_REL,_r as applyPatchToFm,_t as DocumentListSuccessSchema,a as acquireProcessLock,aa as record,ai as renderInventoryFooter,an as PROTOCOL_VERSION,ar as TestFlushGitSuccessSchema,at as CreateFolderRequestSchema,b as AdvisoryWarningSchema,ba as safeParseAsync$1,bi as getSchema,br as classifyWikiLinkTarget,bt as DuplicatePathSuccessSchema,c as isValidLockPid,ca as unknown,ci as searchWorkspaceCorpus,cn as PrincipalSuccessSchema,cr as TestResetSuccessSchema,ct as CreatePageSuccessSchema,da as toJSONSchema,di as sharedExtensions,dn as RenamePathSuccessSchema,dr as UA_PATTERNS,ea as looseObject,ei as previewEmbedFence,en as MetricsReconciliationSuccessSchema,er as TemplateMoveRequestSchema,et as CONFIG_DOC_NAME_USER,f as readServerLock,fi as splitLeadingDocBoundary,fn as RescueListSuccessSchema,fr as UploadAssetSuccessSchema,ga as $ZodType,gi as toWikiLinkSlug,gn as SANDBOXED_HTML_EXTENSIONS,gr as applyIncrementalDiff,gt as DeletePathSuccessSchema,h as updateProcessLockPort,ha as $ZodObject,hi as toBridgeInvariantLog,hn as SANDBOXED_HTML_CSP,hr as applyFastDiff,ht as DeletePathRequestSchema,ia as preprocess,ii as reattachLeadingDocBoundary,in as PREVIEW_THEME_TOKENS,ir as TemplatesListSuccessSchema,it as ClientLogsSuccessSchema,j as ApiConfigSuccessSchema,ji as OK_PROJECT_MARKER,jn as ServerInfoSuccessSchema,jr as displayNameFromClientName,jt as FrontmatterValueSchema,k as AgentWriteRequestSchema,ki as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,kn as SeedPlanSuccessSchema,kr as detectAppliedToleranceClasses,kt as FrontmatterPatchRequestSchema,li as serializeFrontmatterMap,ln as ProblemDetailsSchema,lr as TrashCleanupRequestSchema,lt as DEFAULT_DEDUP_MODE,m as releaseServerLock,ma as meta$1,mi as tagsMatchingPrefix,mn as RollbackSuccessSchema,mr as WorkspaceSuccessSchema,mt as DeadLinksSuccessSchema,n as RUNTIME_VERSION,na as object$1,ni as projectMergeBoundarySpace,nn as OrphansSuccessSchema,nr as TemplatePutRequestSchema,nt as CheckoutResponseSchema,o as acquireServerLock,oa as string,oi as resolveAssetProjectPath,on as PageHeadingsSuccessSchema,or as TestRescanBacklinksSuccessSchema,ot as CreateFolderSuccessSchema,p as releaseProcessLock,pa as describe$1,pi as stripFrontmatter,pn as RollbackRequestSchema,pr as UploadRequestSchema,pt as DOCUMENT_OPEN_BYTE_LIMIT,q as CC1_CHANNEL_SERVER_INFO,qn as SyncStatusSchema,qr as isOrphanMode,qt as LocalOpEmbeddingsMutationSuccessSchema,ra as optional,ri as readFmMap,rn as PREVIEW_EMBED_STARTERS,rr as TemplatePutSuccessSchema,rt as ClientLogsRequestSchema,s as isProcessAlive,sa as union,si as resolveInternalHref,sn as PagesSuccessSchema,sr as TestRescanFilesSuccessSchema,st as CreatePageRequestSchema,t as ProcessLockCollisionError,ta as number,ti as projectFull,tn as ORPHAN_MODES,tr as TemplateMoveSuccessSchema,tt as CheckoutRequestSchema,u as readProcessLock,ua as datetime,ui as setToleranceTelemetryHook,un as RenamePathRequestSchema,ur as TrashCleanupSuccessSchema,va as parseAsync,vi as validateDocName,vn as SKILL_STATE_TARGETS,vr as assertNeverProblemType,vt as DocumentReadSuccessSchema,w as AgentPatchSuccessSchema,wa as normalizeParams,wi as ConfigSchema$1,wn as SearchRequestSchema,wr as createCodeFenceTracker,wt as EmptyRequestSchema,x as AgentActivitySuccessSchema,xa as prettifyError,xi as PluginKey,xn as SYSTEM_DOC_NAME,y as ASSET_EXTENSIONS,ya as safeParse$1,yi as withFences,yn as SKILL_STATE_VERSION_RE,yr as classifyMarkdownHref,yt as DuplicatePathRequestSchema,z as CC1ConfigValidationRejectedPayloadSchema,zi as toConfigIssue,zn as SkillStateSchema,zr as getAgentCanonicalDescriptors,zt as LINEAGE_EPOCH_KEY}from"./server-lock-BpjJj3OD-CrZDl-wH.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-BS2W3Uzl.mjs";import{a as require_src$15,i as simpleGit,n as withParentLock,r as esm_default,t as createGitInstance}from"./git-handle--dq7Gq14-BpH0pmv5.mjs";import{t as createPatch}from"./libesm-Ob3yvbRV.mjs";import{n as mimes,t as build_default}from"./build-DCHzh6iE.mjs";import{t as require_yazl}from"./yazl-Docqgl6q.mjs";import{t as b1}from"./chunk-YNYSPYQ5-gU4-j5DO.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-DbAN9IDm.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-NzTooVTc.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-C_wCK9HT.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-BVeTwIsz.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BkE4vqrf.mjs";import"./chunk-DXB73IDG-F_tmy-Lz.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-BwpNU33k.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DApqA6Ow.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-CmrD0Dg2.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-DaS5XS55.mjs";import{n as n$1}from"./chunk-3THT3N7L-B1WzJUh4.mjs";import{t as n$2}from"./chunk-44UOCSGV-BZ6LfyW2.mjs";import{t as import_websocket_server$1}from"./wrapper-BZO_sIci.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import*as U from"node:path";import{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import crypto$1 from"crypto";import crypto$1$1,{createHash,randomUUID as randomUUID$1,webcrypto as webcrypto$1}from"node:crypto";import*as zlib from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";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 __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM$2,t as __commonJSMin$2}from"./chunk-C94x7I9S.mjs";import{$ as CONFIG_DOC_NAME_PROJECT_LOCAL,$i as intersection,$n as TemplateDeleteSuccessSchema,$r as parseFrontmatterYaml,$t as MetricsParseHealthSuccessSchema,A as AgentWriteSuccessSchema,Ai as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,An as SeedPlanSuccessSchema,Ar as detectAppliedToleranceClasses,At as FrontmatterPatchSuccessSchema,B as CC1DerivedViewPayloadSchema,Bi as toConfigIssue,Bn as SkillStateSchema,Br as getAgentCanonicalDescriptors,Bt as LINKABLE_ASSET_EXTENSIONS,C as AgentPatchRequestSchema,Ca as clone,Ci as Fragment,Cn as SaveVersionRequestSchema,Cr as colorFromSeed,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdRequestSchema,Di as DEFAULT_EMBEDDINGS_MODEL,Dn as SeedApplyRequestSchema,Dr as createWorkspaceSearchCorpus,Dt as FolderConfigPutSuccessSchema,E as AgentUndoSuccessSchema,Ea as $constructor,Ei as DEFAULT_EMBEDDINGS_BASE_URL,En as SearchSuccessSchema,Er as createTagInTextRegex,Et as FolderConfigPutRequestSchema,F as BridgeInvariantViolationError,Fi as applyPatchToDocument,Fn as SharePublishNameCheckResponseSchema,Fr as encodeShareUrl,Ft as INLINE_RENDERABLE_EXTENSIONS,G as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Gi as ZodOptional$1,Gn as SyncConflictsSuccessSchema,Gr as isBranchNotFoundGitError,Gt as LocalOpAuthStatusSuccessSchema,H as CC1ServerInfoPayloadSchema,Hi as withConfigSpan,Hn as StreamingProblemEventSchema,Hr as getParseHealth,Ht as LocalOpAuthEmptySuccessSchema,I as BridgeMergeContentLossError,Ii as detectRemovedKeys,In as SharePublishOwnersResponseSchema,Ir as expandTagToHierarchy,It as InstallSkillRequestSchema,J as CC1_CONTRACT_VERSION,Jn as SyncStatusSchema,Jr as isOrphanMode,Jt as LocalOpEmbeddingsSetKeyRequestSchema,K as CC1_CHANNEL_DISK_ACK,Ki as _enum,Kn as SyncResolveConflictRequestSchema,Kr as isFrontmatterValueEmpty,Kt as LocalOpCloneRequestSchema,L as CC1BranchSwitchedPayloadSchema,Li as humanFormat,Ln as SharePublishRequestSchema,Lr as extractFrontmatterTags,Lt as InstallSkillSuccessSchema,M as BacklinkCountsSuccessSchema,Mi as OK_PROJECT_MARKER,Mn as ServerInfoSuccessSchema,Mr as displayNameFromClientName,Mt as HistorySuccessSchema,N as BacklinksSuccessSchema,Nn as ShareConstructUrlRequestSchema,Nr as emitToleranceFire,Nt as HistoryVersionSuccessSchema,O as AgentWriteMdSuccessSchema,Oa as require_dist$1,Oi as DEFAULT_LOGS_MAX_BYTES,On as SeedApplySuccessSchema,Or as createWorkspaceSearchDocument,Ot as ForwardLinksSuccessSchema,P as BranchInfoResponseSchema,Pi as addConfigSpanEvent,Pn as ShareConstructUrlResponseSchema,Pr as emptySkillState,Pt as HubsSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT,Qi as discriminatedUnion,Qn as TagsListSuccessSchema,Qr as normalizeBridge,Qt as MetricsAgentPresenceSuccessSchema,R as CC1ConfigIgnoreNestedErrorPayloadSchema,Ri as isKnownConfigError,Rn as SharePublishResponseSchema,Rr as fnv1aDigest,Rt as InstalledAgentsSuccessSchema,S as AgentBurstDiffSuccessSchema,Sa as prettifyError,Si as PluginKey,Sn as SYSTEM_DOC_NAME,St as EXECUTABLE_BLOCKLIST_EXTENSIONS,T as AgentUndoRequestSchema,Ta as normalizeParams,Ti as ConfigSchema$1,Tn as SearchRequestSchema,Tr as createCodeFenceTracker,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_BRANCH_SWITCHED,Ui as withConfigSpanSync,Un as SuggestLinksSuccessSchema,Ur as getWikiLinkText,Ut as LocalOpAuthHostRequestSchema,V as CC1DiskAckPayloadSchema,Vi as validatePatchScopes,Vn as SpawnCursorSuccessSchema,Vr as getHeadingSlug,Vt as LinkGraphSuccessSchema,W as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Wn as SyncConflictContentSuccessSchema,Wr as iconFromClientName,Wt as LocalOpAuthSetIdentityRequestSchema,X as CONFIG_DOC_NAMES,Xi as boolean,Xn as SyncTriggerSuccessSchema,Xr as mediaKindForSidebarAssetExtension,Xt as LocalOpOkInitResponseSchema,Y as CLIENT_VERSION_HEADER,Yi as array,Yn as SyncTriggerRequestSchema,Yr as isValidBranchName,Yt as LocalOpOkInitRequestSchema,Z as CONFIG_DOC_NAME_OKIGNORE,Zi as custom,Zn as TagsForNameSuccessSchema,Zr as mergeThreeWay,Zt as MarkdownManager,_ as AGENT_ICON_COLORS,_a as $ZodType,_i as toWikiLinkSlug,_n as SKILL_STATE_REL,_r as applyIncrementalDiff,_t as DocumentListSuccessSchema,a as acquireProcessLock,aa as preprocess,ai as reattachLeadingDocBoundary,an as PROTOCOL_VERSION,ar as TemplatesListSuccessSchema,at as CreateFolderRequestSchema,b as AdvisoryWarningSchema,ba as safeParse$1,bi as withFences,br as classifyMarkdownHref,bt as DuplicatePathSuccessSchema,c as isValidLockPid,ca as union,ci as resolveInternalHref,cn as PrincipalSuccessSchema,cr as TestRescanFilesSuccessSchema,ct as CreatePageSuccessSchema,da as datetime,di as setToleranceTelemetryHook,dn as RenamePathSuccessSchema,dr as TrashCleanupSuccessSchema,ea as literal,ei as prependFrontmatter,en as MetricsReconciliationSuccessSchema,er as TemplateGetSuccessSchema,et as CONFIG_DOC_NAME_USER,f as readServerLock,fa as toJSONSchema,fi as sharedExtensions,fn as RescueListSuccessSchema,fr as UA_PATTERNS,ga as $ZodObject,gi as toBridgeInvariantLog,gn as SANDBOXED_HTML_EXTENSIONS,gr as applyFastDiff,gt as DeletePathSuccessSchema,h as updateProcessLockPort,ha as meta$1,hi as tagsMatchingPrefix,hn as SANDBOXED_HTML_CSP,hr as WorkspaceSuccessSchema,ht as DeletePathRequestSchema,ia as optional,ii as readFmMap,in as PREVIEW_THEME_TOKENS,ir as TemplatePutSuccessSchema,it as ClientLogsSuccessSchema,j as ApiConfigSuccessSchema,ji as LOCAL_DIR,jn as SemanticIndexStatusSchema,jr as detectFmRegion,jt as FrontmatterValueSchema,k as AgentWriteRequestSchema,ki as DEFAULT_SPANS_MAX_BYTES,kn as SeedListPacksSuccessSchema,kr as defaultScheduler,kt as FrontmatterPatchRequestSchema,la as unknown,li as searchWorkspaceCorpus,ln as ProblemDetailsSchema,lr as TestResetSuccessSchema,lt as DEFAULT_DEDUP_MODE,m as releaseServerLock,ma as describe$1,mi as stripFrontmatter,mn as RollbackSuccessSchema,mr as UploadRequestSchema,mt as DeadLinksSuccessSchema,n as RUNTIME_VERSION,na as number,ni as projectFull,nn as OrphansSuccessSchema,nr as TemplateMoveSuccessSchema,nt as CheckoutResponseSchema,o as acquireServerLock,oa as record,oi as renderInventoryFooter,on as PageHeadingsSuccessSchema,or as TestFlushGitSuccessSchema,ot as CreateFolderSuccessSchema,p as releaseProcessLock,pi as splitLeadingDocBoundary,pn as RollbackRequestSchema,pr as UploadAssetSuccessSchema,pt as DOCUMENT_OPEN_BYTE_LIMIT,q as CC1_CHANNEL_SERVER_INFO,qi as _null,qn as SyncResolveConflictSuccessSchema,qr as isHiddenDocName,qt as LocalOpEmbeddingsMutationSuccessSchema,ra as object$1,ri as projectMergeBoundarySpace,rn as PREVIEW_EMBED_STARTERS,rr as TemplatePutRequestSchema,rt as ClientLogsRequestSchema,s as isProcessAlive,sa as string,si as resolveAssetProjectPath,sn as PagesSuccessSchema,sr as TestRescanBacklinksSuccessSchema,st as CreatePageRequestSchema,t as ProcessLockCollisionError,ta as looseObject,ti as previewEmbedFence,tn as ORPHAN_MODES,tr as TemplateMoveRequestSchema,tt as CheckoutRequestSchema,u as readProcessLock,ui as serializeFrontmatterMap,un as RenamePathRequestSchema,ur as TrashCleanupRequestSchema,va as parse$1,vi as unwrapFrontmatterFences,vn as SKILL_STATE_TARGETS,vr as applyPatchToFm,vt as DocumentReadSuccessSchema,w as AgentPatchSuccessSchema,wa as defineLazy,wi as CONFIG_SCHEMA_MAJOR_PATH,wn as SaveVersionSuccessSchema,wr as createBasenameIndex,wt as EmptyRequestSchema,x as AgentActivitySuccessSchema,xa as safeParseAsync$1,xi as getSchema,xn as SUPPORTED_DOC_EXTENSIONS,xr as classifyWikiLinkTarget,y as ASSET_EXTENSIONS,ya as parseAsync,yi as validateDocName,yn as SKILL_STATE_VERSION_RE,yr as assertNeverProblemType,yt as DuplicatePathRequestSchema,z as CC1ConfigValidationRejectedPayloadSchema,zi as locateIssue,zn as SkillInstallStateSuccessSchema,zr as formatFileSize,zt as LINEAGE_EPOCH_KEY}from"./server-lock-BpjJj3OD-DlYx_Xz-.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-BS2W3Uzl.mjs";import{a as require_src$15,i as simpleGit,n as withParentLock,r as esm_default,t as createGitInstance}from"./git-handle--dq7Gq14-BpH0pmv5.mjs";import{t as createPatch}from"./libesm-Ob3yvbRV.mjs";import{n as mimes,t as build_default}from"./build-DCHzh6iE.mjs";import{t as require_yazl}from"./yazl-Docqgl6q.mjs";import{t as b1}from"./chunk-YNYSPYQ5-gU4-j5DO.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-DbAN9IDm.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-NzTooVTc.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-C_wCK9HT.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-BVeTwIsz.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BkE4vqrf.mjs";import"./chunk-DXB73IDG-F_tmy-Lz.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-BwpNU33k.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DApqA6Ow.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-CmrD0Dg2.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-DaS5XS55.mjs";import{n as n$1}from"./chunk-3THT3N7L-B1WzJUh4.mjs";import{t as n$2}from"./chunk-44UOCSGV-BZ6LfyW2.mjs";import{t as import_websocket_server$1}from"./wrapper-BZO_sIci.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import*as U from"node:path";import{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import crypto$1 from"crypto";import crypto$1$1,{createHash,randomUUID as randomUUID$1,webcrypto as webcrypto$1}from"node:crypto";import*as zlib from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";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}if(S===`auto-consolidation`){let e=w;return typeof e.foldedRefs==`number`&&Number.isFinite(e.foldedRefs)&&typeof e.trigger==`string`?{kind:`auto-consolidation`,docName:E,size:D,metadata:{foldedRefs:e.foldedRefs,trigger:e.trigger}}: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 parseOkActor(e){if(!e)return null;for(let t of e.split(`
4
4
  `)){let e=t.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let s;try{s=JSON.parse(e.slice(10))}catch{return null}return typeof s!=`object`||!s?null:parseOkActorObject(s)}return null}function parseOkActors(e){if(!e)return[];let t=[];for(let s of e.split(`
@@ -767,7 +767,7 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
767
767
  `}){let g=e.split(/\r?\n/);for(let e=1;e<g.length;e+=1)g[e]=t+g[e];return g.join(s)}})),require_parse_factory_options=__commonJSMin(((e,t)=>{t.exports=D;let{LEVEL_NAMES:s}=require_constants(),g=require_colors(),S=require_handle_custom_levels_opts(),w=require_handle_custom_levels_names_opts(),E=require_get_level_label_data();function D(e){let t=e.crlf?`\r
768
768
  `:`
769
769
  `,D=` `,{customPrettifiers:O,errorLikeObjectKeys:k,hideObject:j,levelFirst:F,levelKey:L,levelLabel:B,messageFormat:H,messageKey:q,minimumLevel:ee,singleLine:J,timestampKey:Y,translateTime:te}=e,ne=e.errorProps.split(`,`),ae=typeof e.useOnlyCustomProps==`boolean`?e.useOnlyCustomProps:e.useOnlyCustomProps===`true`,oe=S(e.customLevels),se=w(e.customLevels),ce=E(ae,oe,se),ue;if(e.customColors)if(typeof e.customColors==`string`)ue=e.customColors.split(`,`).reduce((t,g)=>{let[S,w]=g.split(`:`),E=(ae?e.customLevels:se[S]!==void 0)?se[S]:s[S],D=E===void 0?S:E;return t.push([D,w]),t},[]);else if(typeof e.customColors==`object`)ue=Object.keys(e.customColors).reduce((t,g)=>{let[S,w]=[g,e.customColors[g]],E=(ae?e.customLevels:se[S]!==void 0)?se[S]:s[S],D=E===void 0?S:E;return t.push([D,w]),t},[]);else throw Error(`options.customColors must be of type string or object.`);let de={customLevels:oe,customLevelNames:se};ae===!0&&!e.customLevels&&(de.customLevels=void 0,de.customLevelNames=void 0);let fe=e.include===void 0?void 0:new Set(e.include.split(`,`)),me=!fe&&e.ignore?new Set(e.ignore.split(`,`)):void 0,ge=g(e.colorize,ue,ae),_e=e.colorizeObjects?ge:g(!1,[],!1);return{EOL:t,IDENT:` `,colorizer:ge,customColors:ue,customLevelNames:se,customLevels:oe,customPrettifiers:O,customProperties:de,errorLikeObjectKeys:k,errorProps:ne,getLevelLabelData:ce,hideObject:j,ignoreKeys:me,includeKeys:fe,levelFirst:F,levelKey:L,levelLabel:B,messageFormat:H,messageKey:q,minimumLevel:ee,objectColorizer:_e,singleLine:J,timestampKey:Y,translateTime:te,useOnlyCustomProps:ae}}})),require_fast_safe_stringify=__commonJSMin(((e,t)=>{t.exports=D,D.default=D,D.stable=F,D.stableStringify=F;var s=`[...]`,g=`[Circular]`,S=[],w=[];function E(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function D(e,t,s,g){g===void 0&&(g=E()),k(e,``,0,[],void 0,0,g);var D;try{D=w.length===0?JSON.stringify(e,t,s):JSON.stringify(e,B(t),s)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;S.length!==0;){var O=S.pop();O.length===4?Object.defineProperty(O[0],O[1],O[3]):O[0][O[1]]=O[2]}}return D}function O(e,t,s,g){var E=Object.getOwnPropertyDescriptor(g,s);E.get===void 0?(g[s]=e,S.push([g,s,t])):E.configurable?(Object.defineProperty(g,s,{value:e}),S.push([g,s,t,E])):w.push([t,s,e])}function k(e,t,S,w,E,D,j){D+=1;var F;if(typeof e==`object`&&e){for(F=0;F<w.length;F++)if(w[F]===e){O(g,e,t,E);return}if(j.depthLimit!==void 0&&D>j.depthLimit){O(s,e,t,E);return}if(j.edgesLimit!==void 0&&S+1>j.edgesLimit){O(s,e,t,E);return}if(w.push(e),Array.isArray(e))for(F=0;F<e.length;F++)k(e[F],F,F,w,e,D,j);else{var L=Object.keys(e);for(F=0;F<L.length;F++){var B=L[F];k(e[B],B,F,w,e,D,j)}}w.pop()}}function j(e,t){return e<t?-1:e>t?1:0}function F(e,t,s,g){g===void 0&&(g=E());var D=L(e,``,0,[],void 0,0,g)||e,O;try{O=w.length===0?JSON.stringify(D,t,s):JSON.stringify(D,B(t),s)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;S.length!==0;){var k=S.pop();k.length===4?Object.defineProperty(k[0],k[1],k[3]):k[0][k[1]]=k[2]}}return O}function L(e,t,w,E,D,k,F){k+=1;var B;if(typeof e==`object`&&e){for(B=0;B<E.length;B++)if(E[B]===e){O(g,e,t,D);return}try{if(typeof e.toJSON==`function`)return}catch{return}if(F.depthLimit!==void 0&&k>F.depthLimit){O(s,e,t,D);return}if(F.edgesLimit!==void 0&&w+1>F.edgesLimit){O(s,e,t,D);return}if(E.push(e),Array.isArray(e))for(B=0;B<e.length;B++)L(e[B],B,B,E,e,k,F);else{var H={},q=Object.keys(e).sort(j);for(B=0;B<q.length;B++){var ee=q[B];L(e[ee],ee,B,E,e,k,F),H[ee]=e[ee]}if(D!==void 0)S.push([D,t,e]),D[t]=H;else return H}E.pop()}}function B(e){return e=e===void 0?function(e,t){return t}:e,function(t,s){if(w.length>0)for(var g=0;g<w.length;g++){var S=w[g];if(S[1]===t&&S[0]===s){s=S[2],w.splice(g,1);break}}return e.call(this,t,s)}}})),require_prettify_error=__commonJSMin(((e,t)=>{t.exports=g;let s=require_join_lines_with_indentation();function g({keyName:e,lines:t,eol:g,ident:S}){let w=``,E=`${S}${e}: ${s({input:t,ident:S,eol:g})}${g}`.split(g);for(let e=0;e<E.length;e+=1){e!==0&&(w+=g);let t=E[e];if(/^\s*"stack"/.test(t)){let e=/^(\s*"stack":)\s*(".*"),?$/.exec(t);if(e&&e.length===3){let s=/^\s*/.exec(t)[0].length+4,S=` `.repeat(s),E=e[2];w+=e[1]+g+S+JSON.parse(E).replace(/\n/g,g+S)}else w+=t}else w+=t}return w}})),require_prettify_object=__commonJSMin(((e,t)=>{t.exports=E;let{LOGGER_KEYS:s}=require_constants(),g=require_fast_safe_stringify(),S=require_join_lines_with_indentation(),w=require_prettify_error();function E({log:e,excludeLoggerKeys:t=!0,skipKeys:E=[],context:D}){let{EOL:O,IDENT:k,customPrettifiers:j,errorLikeObjectKeys:F,objectColorizer:L,singleLine:B,colorizer:H}=D,q=[].concat(E);t===!0&&Array.prototype.push.apply(q,s);let ee=``,{plain:J,errors:Y}=Object.entries(e).reduce(({plain:t,errors:s},[g,S])=>{if(q.includes(g)===!1){let w=typeof j[g]==`function`?j[g](S,g,e,{colors:H.colors}):S;F.includes(g)?s[g]=w:t[g]=w}return{plain:t,errors:s}},{plain:{},errors:{}});return B?(Object.keys(J).length>0&&(ee+=L.greyMessage(g(J))),ee+=O,ee=ee.replace(/\\\\/gi,`\\`)):Object.entries(J).forEach(([e,t])=>{let s=typeof j[e]==`function`?t:g(t,null,2);if(s===void 0)return;s=s.replace(/\\\\/gi,`\\`);let w=S({input:s,ident:k,eol:O});ee+=`${k}${L.property(e)}:${w.startsWith(O)?``:` `}${w}${O}`}),Object.entries(Y).forEach(([e,t])=>{let s=typeof j[e]==`function`?t:g(t,null,2);s!==void 0&&(ee+=w({keyName:e,lines:s,eol:O,ident:k}))}),ee}})),require_prettify_error_log=__commonJSMin(((e,t)=>{t.exports=E;let{LOGGER_KEYS:s}=require_constants(),g=require_is_object(),S=require_join_lines_with_indentation(),w=require_prettify_object();function E({log:e,context:t}){let{EOL:E,IDENT:D,errorProps:O,messageKey:k}=t,j=e.stack,F=`${D}${S({input:j,ident:D,eol:E})}${E}`;if(O.length>0){let S=s.concat(k,`type`,`stack`),j;j=O[0]===`*`?Object.keys(e).filter(e=>S.includes(e)===!1):O.filter(e=>S.includes(e)===!1);for(let s=0;s<j.length;s+=1){let S=j[s];if(S in e){if(g(e[S])){let s=w({log:e[S],excludeLoggerKeys:!1,context:{...t,IDENT:D+D}});F=`${F}${D}${S}: {${E}${s}${D}}${E}`;continue}F=`${F}${D}${S}: ${e[S]}${E}`}}}return F}})),require_prettify_level=__commonJSMin(((e,t)=>{t.exports=g;let s=require_get_property_value();function g({log:e,context:t}){let{colorizer:g,customLevels:S,customLevelNames:w,levelKey:E,getLevelLabelData:D}=t,O=t.customPrettifiers?.level,k=s(e,E);if(k===void 0)return;let j=g(k,{customLevels:S,customLevelNames:w});if(O){let[t]=D(k);return O(k,E,e,{label:t,labelColorized:j,colors:g.colors})}return j}})),require_prettify_message=__commonJSMin(((e,t)=>{t.exports=w;let{LEVELS:s}=require_constants(),g=require_get_property_value(),S=require_interpret_conditionals();function w({log:e,context:t}){let{colorizer:w,customLevels:E,levelKey:D,levelLabel:O,messageFormat:k,messageKey:j,useOnlyCustomProps:F}=t;if(k&&typeof k==`string`){let t=S(k,e),j=String(t).replace(/{([^{}]+)}/g,function(t,S){let w;if(S===O&&(w=g(e,D))!==void 0)return(F?E===void 0:E[w]===void 0)?s[w]:E[w];let k=g(e,S);return k===void 0?``:k});return w.message(j)}if(k&&typeof k==`function`){let t=k(e,j,O,{colors:w.colors});return w.message(t)}if(j in e&&!(typeof e[j]!=`string`&&typeof e[j]!=`number`&&typeof e[j]!=`boolean`))return w.message(e[j])}})),require_prettify_metadata=__commonJSMin(((e,t)=>{t.exports=s;function s({log:e,context:t}){let{customPrettifiers:s,colorizer:g}=t,S=``;if(e.name||e.pid||e.hostname){if(S+=`(`,e.name&&(S+=s.name?s.name(e.name,`name`,e,{colors:g.colors}):e.name),e.pid){let t=s.pid?s.pid(e.pid,`pid`,e,{colors:g.colors}):e.pid;e.name&&e.pid?S+=`/`+t:S+=t}if(e.hostname){let t=s.hostname?s.hostname(e.hostname,`hostname`,e,{colors:g.colors}):e.hostname;S+=`${S===`(`?`on`:` on`} ${t}`}S+=`)`}if(e.caller){let t=s.caller?s.caller(e.caller,`caller`,e,{colors:g.colors}):e.caller;S+=`${S===``?``:` `}<${t}>`}if(S!==``)return S}})),require_prettify_time=__commonJSMin(((e,t)=>{t.exports=g;let s=require_format_time();function g({log:e,context:t}){let{timestampKey:g,translateTime:S}=t,w=t.customPrettifiers?.time,E=null;if(g in e?E=e[g]:`timestamp`in e&&(E=e.timestamp),E===null)return;let D=S?s(E,S):E;return w?w(D):`[${D}]`}})),require_utils=__commonJSMin(((e,t)=>{t.exports={buildSafeSonicBoom:require_build_safe_sonic_boom(),createDate:require_create_date(),deleteLogProperty:require_delete_log_property(),filterLog:require_filter_log(),formatTime:require_format_time(),getPropertyValue:require_get_property_value(),handleCustomLevelsNamesOpts:require_handle_custom_levels_names_opts(),handleCustomLevelsOpts:require_handle_custom_levels_opts(),interpretConditionals:require_interpret_conditionals(),isObject:require_is_object(),isValidDate:require_is_valid_date(),joinLinesWithIndentation:require_join_lines_with_indentation(),noop:require_noop(),parseFactoryOptions:require_parse_factory_options(),prettifyErrorLog:require_prettify_error_log(),prettifyError:require_prettify_error(),prettifyLevel:require_prettify_level(),prettifyMessage:require_prettify_message(),prettifyMetadata:require_prettify_metadata(),prettifyObject:require_prettify_object(),prettifyTime:require_prettify_time(),splitPropertyKey:require_split_property_key(),getLevelLabelData:require_get_level_label_data()}})),require_secure_json_parse=__commonJSMin(((e,t)=>{let s=typeof Buffer<`u`,g=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,S=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function w(e,t,w){w==null&&typeof t==`object`&&t&&(w=t,t=void 0),s&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let D=JSON.parse(e,t);if(typeof D!=`object`||!D)return D;let O=w&&w.protoAction||`error`,k=w&&w.constructorAction||`error`;if(O===`ignore`&&k===`ignore`)return D;if(O!==`ignore`&&k!==`ignore`){if(g.test(e)===!1&&S.test(e)===!1)return D}else if(O!==`ignore`&&k===`ignore`){if(g.test(e)===!1)return D}else if(S.test(e)===!1)return D;return E(D,{protoAction:O,constructorAction:k,safe:w&&w.safe})}function E(e,{protoAction:t=`error`,constructorAction:s=`error`,safe:g}={}){let S=[e];for(;S.length;){let e=S;S=[];for(let w of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(w,`__proto__`)){if(g===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete w.__proto__}if(s!==`ignore`&&Object.prototype.hasOwnProperty.call(w,`constructor`)&&w.constructor!==null&&typeof w.constructor==`object`&&Object.prototype.hasOwnProperty.call(w.constructor,`prototype`)){if(g===!0)return null;if(s===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete w.constructor}for(let e in w){let t=w[e];t&&typeof t==`object`&&S.push(t)}}}return e}function D(e,t,s){let{stackTraceLimit:g}=Error;Error.stackTraceLimit=0;try{return w(e,t,s)}finally{Error.stackTraceLimit=g}}function O(e,t){let{stackTraceLimit:s}=Error;Error.stackTraceLimit=0;try{return w(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=s}}t.exports=D,t.exports.default=D,t.exports.parse=D,t.exports.safeParse=O,t.exports.scan=E})),require_pretty=__commonJSMin(((e,t)=>{t.exports=q;let s=require_secure_json_parse(),g=require_is_object(),S=require_prettify_error_log(),w=require_prettify_level(),E=require_prettify_message(),D=require_prettify_metadata(),O=require_prettify_object(),k=require_prettify_time(),j=require_filter_log(),{LEVELS:F,LEVEL_KEY:L,LEVEL_NAMES:B}=require_constants(),H=e=>{try{return{value:s.parse(e,{protoAction:`remove`})}}catch(e){return{err:e}}};function q(e){let t;if(g(e))t=e;else{let s=H(e);if(s.err||!g(s.value))return e+this.EOL;t=s.value}if(this.minimumLevel){let e;e=this.useOnlyCustomProps?this.customLevels:this.customLevelNames[this.minimumLevel]!==void 0;let s;if(s=e?this.customLevelNames[this.minimumLevel]:B[this.minimumLevel],s||=typeof this.minimumLevel==`string`?B[this.minimumLevel]:B[F[this.minimumLevel].toLowerCase()],t[this.levelKey===void 0?L:this.levelKey]<s)return}let s=E({log:t,context:this.context});(this.ignoreKeys||this.includeKeys)&&(t=j({log:t,context:this.context}));let q=w({log:t,context:{...this.context,...this.context.customProperties}}),ee=D({log:t,context:this.context}),J=k({log:t,context:this.context}),Y=``;if(this.levelFirst&&q&&(Y=`${q}`),J&&Y===``?Y=`${J}`:J&&(Y=`${Y} ${J}`),!this.levelFirst&&q&&(Y=Y.length>0?`${Y} ${q}`:q),ee&&(Y=Y.length>0?`${Y} ${ee}:`:ee),Y.endsWith(`:`)===!1&&Y!==``&&(Y+=`:`),s!==void 0&&(Y=Y.length>0?`${Y} ${s}`:s),Y.length>0&&!this.singleLine&&(Y+=this.EOL),t.type===`Error`&&typeof t.stack==`string`){let e=S({log:t,context:this.context});this.singleLine&&(Y+=this.EOL),Y+=e}else if(this.hideObject===!1){let e=[this.messageKey,this.levelKey,this.timestampKey].map(e=>e.replaceAll(/\\/g,``)).filter(e=>typeof t[e]==`string`||typeof t[e]==`number`||typeof t[e]==`boolean`),s=O({log:t,skipKeys:e,context:this.context});this.singleLine&&!/^\s$/.test(s)&&(Y+=` `),Y+=s}return Y}})),require_pino_pretty=__commonJSMin(((e,t)=>{let{isColorSupported:s}=require_colorette(),g=require_pump(),{Transform:S}=__require(`node:stream`),w=require_pino_abstract_transport(),E=require_colors(),{ERROR_LIKE_KEYS:D,LEVEL_KEY:O,LEVEL_LABEL:k,MESSAGE_KEY:j,TIMESTAMP_KEY:F}=require_constants(),{buildSafeSonicBoom:L,parseFactoryOptions:B}=require_utils(),H=require_pretty(),q={colorize:s,colorizeObjects:!0,crlf:!1,customColors:null,customLevels:null,customPrettifiers:{},errorLikeObjectKeys:D,errorProps:``,hideObject:!1,ignore:`hostname`,include:void 0,levelFirst:!1,levelKey:O,levelLabel:k,messageFormat:null,messageKey:j,minimumLevel:void 0,outputStream:process.stdout,singleLine:!1,timestampKey:F,translateTime:!0,useOnlyCustomProps:!0};function ee(e){let t=B(Object.assign({},q,e));return H.bind({...t,context:t})}function J(e={}){let t=ee(e),s;return w(function(w){w.on(`message`,function s(g){!g||g.code!==`PINO_CONFIG`||(Object.assign(e,{messageKey:g.config.messageKey,errorLikeObjectKeys:Array.from(new Set([...e.errorLikeObjectKeys||D,g.config.errorKey])),customLevels:g.config.levels.values}),t=ee(e),w.off(`message`,s))});let E=new S({objectMode:!0,autoDestroy:!0,transform(e,s,g){g(null,t(e))}});return s=typeof e.destination==`object`&&typeof e.destination.write==`function`?e.destination:L({dest:e.destination||1,append:e.append,mkdir:e.mkdir,sync:e.sync}),w.on(`unknown`,function(e){s.write(e+`
770
- `)}),g(w,E,s),E},{parse:`lines`,close(e,t){s.on(`close`,()=>{t(e)})}})}t.exports=J,t.exports.build=J,t.exports.PinoPretty=J,t.exports.prettyFactory=ee,t.exports.colorizerFactory=E,t.exports.isColorSupported=s,t.exports.default=J})),import_pino=__toESM(require_pino(),1),import_pino_pretty=__toESM(require_pino_pretty(),1),RotatingAppender=class{#e;#t;#n;#r=Promise.resolve();#i=!1;constructor(e){this.#e=e.currentPath,this.#t=e.previousPath,this.#n=e.maxBytes}append(e){let t=this.#r.catch(()=>void 0).then(()=>this.#a(e));return this.#r=t,t}async drain(){await this.#r.catch(()=>void 0)}async#a(e){this.#i||=(await mkdir(dirname(this.#e),{recursive:!0}),!0),await writeFile(this.#e,e,{flag:`a`});let t;try{t=statSync(this.#e).size}catch{this.#i=!1;return}t>this.#n&&await rename(this.#e,this.#t)}};const TELEMETRY_SUBDIR=[`.ok`,`local`,`telemetry`],CURRENT_FILENAME=`spans-current.jsonl`,PREVIOUS_FILENAME=`spans-prev.jsonl`;function spansCurrentPath(e){return join(e,...TELEMETRY_SUBDIR,CURRENT_FILENAME)}function spansPreviousPath(e){return join(e,...TELEMETRY_SUBDIR,PREVIOUS_FILENAME)}var FileSpanExporter=class{#e;#t=!1;constructor(e){this.#e=new RotatingAppender({currentPath:spansCurrentPath(e.projectDir),previousPath:spansPreviousPath(e.projectDir),maxBytes:e.maxBytes})}export(e,t){if(this.#t){t({code:import_src.ExportResultCode.FAILED,error:Error(`FileSpanExporter: export called after shutdown`)});return}if(e.length===0){t({code:import_src.ExportResultCode.SUCCESS});return}let s=import_src$1.JsonTraceSerializer.serializeRequest(e);if(!s||s.byteLength===0){t({code:import_src.ExportResultCode.SUCCESS});return}let g=new Uint8Array(s.byteLength+1);g.set(s),g[s.byteLength]=10,this.#e.append(g).then(()=>t({code:import_src.ExportResultCode.SUCCESS}),e=>t({code:import_src.ExportResultCode.FAILED,error:e instanceof Error?e:Error(String(e))}))}async shutdown(){this.#t=!0,await this.#e.drain()}async forceFlush(){await this.#e.drain()}};const REDACTED_SENTINEL=`[REDACTED]`,KEY_BOUNDARY_CHARS=new Set([`.`,`/`,`_`]);function keyMatchesDenylist(e,t){if(t.has(e))return!0;for(let s of t){if(s.length===0||e.length<=s.length||!e.endsWith(s))continue;let t=e.charAt(e.length-s.length-1);if(KEY_BOUNDARY_CHARS.has(t))return!0}return!1}function scrubAttributes(e,t,s){for(let g of Object.keys(e)){let S=e[g];if(S!==void 0){if(keyMatchesDenylist(g.toLowerCase(),t)){e[g]=REDACTED_SENTINEL;continue}if(typeof S==`string`){let t=Buffer.byteLength(S,`utf-8`);t>s&&(e[g]=`[TRUNCATED:${t}]`)}}}}var ScrubbingSpanProcessor=class{#e;#t;constructor(e){this.#e=new Set(e.attributeDenylist.map(e=>e.toLowerCase())),this.#t=e.maxValueBytes??4096}onStart(e,t){}onEnd(e){scrubAttributes(e.attributes,this.#e,this.#t);for(let t of e.events)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t);for(let t of e.links)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t)}async forceFlush(){}async shutdown(){}};const LOGS_SUBDIR=[`.ok`,`local`,`logs`],LOGS_CURRENT_FILENAME=`server-current.jsonl`,LOGS_PREVIOUS_FILENAME=`server-prev.jsonl`;function logsCurrentPath(e){return join(e,...LOGS_SUBDIR,LOGS_CURRENT_FILENAME)}function logsPreviousPath(e){return join(e,...LOGS_SUBDIR,LOGS_PREVIOUS_FILENAME)}var PinoFileSink=class extends Writable{#e;constructor(e){super({decodeStrings:!1}),this.#e=new RotatingAppender({currentPath:logsCurrentPath(e.projectDir),previousPath:logsPreviousPath(e.projectDir),maxBytes:e.maxBytes})}_write(e,t,s){this.#e.append(e).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}async drain(){await this.#e.drain()}};function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}const VALID_LOG_LEVELS=new Set([`fatal`,`error`,`warn`,`info`,`debug`,`trace`,`silent`]);function logLevelRank(e){return e===`silent`?1/0:import_pino.default.levels.values[e]??import_pino.default.levels.values.info}function mostVerboseLevel(e,t){return logLevelRank(e)<=logLevelRank(t)?e:t}var PinoLogger=class{name;transportConfigs=[];fileSinkOpts;redactPaths;activeFileSink;pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),t.fileSink&&(this.fileSinkOpts=t.fileSink),t.redactPaths&&t.redactPaths.length>0&&(this.redactPaths=t.redactPaths,this.options={...this.options,redact:{paths:[...t.redactPaths],censor:`[REDACTED]`}}),this.pinoInstance=this.buildInstance()}resolveStreamLevels(){let e=this.options.level??`info`,t=process.env.OK_CONSOLE_LEVEL?.toLowerCase(),s=t&&VALID_LOG_LEVELS.has(t)?t:e;return{fileLevel:e,consoleLevel:s,instanceLevel:mostVerboseLevel(e,s)}}buildInstance(){this.activeFileSink=void 0;let{fileLevel:e,consoleLevel:t,instanceLevel:s}=this.resolveStreamLevels();if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));let g;try{g=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`})}catch(g){if(console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,g),this.fileSinkOpts){let t=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=t,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:t,level:e}]))}return(0,import_pino.default)({...this.options,level:t})}if(this.fileSinkOpts){let S=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=S,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:g,level:t},{stream:S,level:e}]))}return(0,import_pino.default)({...this.options,level:t},g)}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}reconfigure(e){e.options&&(this.options={...this.options,...e.options}),e.transportConfigs&&(this.transportConfigs=e.transportConfigs),e.fileSink&&(this.fileSinkOpts=e.fileSink),e.redactPaths&&e.redactPaths.length>0&&(this.redactPaths=e.redactPaths,this.options={...this.options,redact:{paths:[...e.redactPaths],censor:`[REDACTED]`}}),this.recreateInstance()}getPinoInstance(){return this.pinoInstance}async flushFileSink(){this.activeFileSink&&await this.activeFileSink.drain()}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){if(this.config=e,e.pinoConfig&&!e.defaultLogger&&!e.loggerFactory){for(let t of this.loggers.values())t.reconfigure(e.pinoConfig);return}this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let s;return s=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,s),s}reset(){this.config={},this.loggers.clear()}async flushAllFileSinks(){let e=[];for(let t of this.loggers.values())e.push(t.flushFileSink());await Promise.all(e)}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(s=>({...s,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:s,...g}=t;return g})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let s=t.getLocalState()??{},g=e(s.agentFocus??{});t.setLocalState({...s,agentFocus:g})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,mapDrivenSpliceApplied:0,mapDrivenSpliceFallback:{},observerAResidualMergeRuns:0,bridgeSplitBrainRederives:0,bridgeSplitBrainRederivesSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,reconcileOwnFlushSkips:0,reconcileInFlightFallthroughs:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0,authDocLineageMismatchCount:0,authDocLineageGuardErrors:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementMapDrivenSpliceApplied(){counters$1.mapDrivenSpliceApplied++}function incrementMapDrivenSpliceFallback(e){counters$1.mapDrivenSpliceFallback[e]=(counters$1.mapDrivenSpliceFallback[e]??0)+1}function incrementObserverAResidualMergeRuns(){counters$1.observerAResidualMergeRuns++}function incrementBridgeSplitBrainRederives(){counters$1.bridgeSplitBrainRederives++}function incrementBridgeSplitBrainRederivesSuppressed(){counters$1.bridgeSplitBrainRederivesSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementReconcileOwnFlushSkips(){counters$1.reconcileOwnFlushSkips++}function incrementReconcileInFlightFallthroughs(){counters$1.reconcileInFlightFallthroughs++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementAuthDocLineageMismatch(){counters$1.authDocLineageMismatchCount++}function incrementAuthDocLineageGuardError(){counters$1.authDocLineageGuardErrors++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied},mapDrivenSpliceFallback:{...counters$1.mapDrivenSpliceFallback}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.mapDrivenSpliceApplied=0,counters$1.mapDrivenSpliceFallback={},counters$1.observerAResidualMergeRuns=0,counters$1.bridgeSplitBrainRederives=0,counters$1.bridgeSplitBrainRederivesSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.reconcileOwnFlushSkips=0,counters$1.reconcileInFlightFallthroughs=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0,counters$1.authDocLineageMismatchCount=0,counters$1.authDocLineageGuardErrors=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let s=0;this.mutateAgentPresence(g=>{let S=Date.now(),w={};for(let[t,E]of Object.entries(g)){if(S-E.ts>=2e4&&t!==e){s++;continue}w[t]=E}return w[e]=t,w})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),s>0&&this.log.info({evictedCount:s,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(s=>{if(!s[e])return s;t=!0;let{[e]:g,...S}=s;return S})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let s=[],g=!1,S=this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;g=!0;let E=Date.now();return s.push({currentDoc:w.currentDoc,ts:E}),{...S,[e]:{...w,mode:t,ts:E}}}),w=s[0];S&&w?this.log.debug({agentId:e,action:`touchMode`,currentDoc:w.currentDoc,ts:w.ts,mode:t},`[agent-presence] touchMode`):g||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(s=>{let g=s[e];if(!g)return s;let S=Date.now();return t=S,{...s,[e]:{...g,ts:S}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let s=t.getLocalState()??{},g=e(s.agentPresence??{});return t.setLocalState({...s,agentPresence:g}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null,fileSpanExporter=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(e={}){let t=e.localSink!==void 0,s=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!s||tracerProvider)return noopResult();try{let g=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),S=new import_src$2.AsyncLocalStorageContextManager;context.setGlobalContextManager(S);let w=[],E=e.localSink?.attributeDenylist??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;w.push(new ScrubbingSpanProcessor({attributeDenylist:E})),t&&e.localSink!==void 0&&(fileSpanExporter=new FileSpanExporter({projectDir:e.localSink.projectDir,maxBytes:e.localSink.spansMaxBytes}),w.push(new import_src$7.SimpleSpanProcessor(fileSpanExporter))),s&&w.push(new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter));let D=new import_src$7.BasicTracerProvider({resource:g,spanProcessors:w});trace.setGlobalTracerProvider(D),tracerProvider=D;try{propagation.setGlobalPropagator(new import_src.W3CTraceContextPropagator)}catch(e){getLogger(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let O=null;s&&(O=new import_src$6.MeterProvider({resource:g,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]}),metrics.setGlobalMeterProvider(O)),meterProvider=O,getLogger(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:s,otlp_endpoint:s?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:g.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized`)}catch(e){let t=getLogger(`telemetry`);tracerProvider===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),meterProvider=null,fileSpanExporter=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),meterProvider=null)}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3,shutdownHooks=new Set;function onTelemetryShutdown(e){shutdownHooks.add(e)}async function shutdownTelemetry(){let e=getLogger(`telemetry`);for(let t of shutdownHooks)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!tracerProvider&&!meterProvider)return;let t=(fileSpanExporter?fileSpanExporter.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),s;await Promise.race([t.then(()=>(s!==void 0&&clearTimeout(s),!1)),new Promise(e=>{s=setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS),s.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,fileSpanExporter=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,s){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await s(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,s){return getTracer().startActiveSpan(e,t??{},e=>{try{return s(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,s,g){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:s,"body.bytes":t.length,"doc.name":e.guid}},()=>{let s=e.getXmlFragment(`default`),S=e.getText(`source`),w=S.toString(),{body:E}=stripFrontmatter(t),D=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":E.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(E,buildParseOpts(g))),O=schema.nodeFromJSON(D);w!==t&&applyFastDiff(S,w,t),updateYFragment(e,s,O,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,s){withSpanSync(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let g=e.getXmlFragment(`default`),S=e.getText(`source`),{body:w}=stripFrontmatter(t),E=mdManager.parseWithFallback(w,buildParseOpts(s)),D=schema.nodeFromJSON(E),O=S.toString();O!==t&&(S.delete(0,O.length),S.insert(0,t)),updateYFragment(e,g,D,{mapping:new Map,isOMark:new Map})})}function deriveFragmentFromYtext(e,t){let s=e.getXmlFragment(`default`),{body:g}=stripFrontmatter(e.getText(`source`).toString()),S=mdManager.parseWithFallback(g,buildParseOpts(t));updateYFragment(e,s,schema.nodeFromJSON(S),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(e)??0)+1;this.seqs.set(e,s);let g=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:s});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(e,s),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let g=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});s.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,s);let g=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:s,branch:e});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,s)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,g);let S=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:g,docName:e,sv:Buffer.from(t).toString(`base64`)});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,s]of this.latestDiskAckSVs)e[t]=Buffer.from(s).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g);let S=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:g,docName:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g);let S=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:g,path:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let s=extname(e).slice(1).toLowerCase();return s.length>0&&t.has(s)}function stripDocExtension(e){let t=e.toLowerCase();for(let s of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(s))return e.slice(0,-s.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let s=canonicalize(t);if(!s)throw Error(`registerDocExtension: unsupported extension "${t}"`);let g=docExtensionByName.get(e);if(!g)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let S=canonicalize(g);return S?S===s?{effective:g,changed:!1,shadowed:null}:rank(s)<rank(S)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g}):{effective:g,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$16=()=>getLogger(`http`);let _apiErrorCounter=null;function apiErrorCounter(){return _apiErrorCounter||=getMeter().createCounter(`ok.api.error.count`,{description:`API error responses by problem type and handler`,unit:`1`}),_apiErrorCounter}function errorResponse(e,t,s,g,S={}){let w=S.instance??`urn:uuid:${randomUUID$1()}`;if(e.headersSent||e.writableEnded||e.destroyed){log$16().error({event:`api.error.double-write`,instance:w,type:s,status:t,handler:S.handler},`errorResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let E={type:s,title:g,status:t,instance:w,detail:S.detail??void 0},D=ProblemDetailsSchema.safeParse(E);if(!D.success){log$16().error({event:`api.error.malformed-envelope`,issues:D.error.issues,body:E,handler:S.handler,originalStatus:t},`errorResponse produced an invalid ProblemDetails body — emitting fallback`);let s=500;apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}let O=S.extensions?{...S.extensions,...E}:E;apiErrorCounter().add(1,{type:s,...S.handler?{handler:S.handler}:{}});let k=t>=500?`error`:`warn`;log$16()[k]({event:`api.error`,instance:w,type:s,status:t,handler:S.handler,detail:S.detail,err:S.cause},g);let j;try{j=JSON.stringify(O)}catch(s){log$16().error({event:`api.error.unserializable-body`,bodyKeys:Object.keys(O),handler:S.handler,originalStatus:t,instance:w,err:s},`errorResponse wireBody is not JSON-serializable — emitting hardcoded fallback`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(j)}function streamingProblemEvent(e,t,s,g={}){let S=g.instance??`urn:uuid:${randomUUID$1()}`,w={type:`error`,problem:{type:t,title:s,status:e,instance:S,detail:g.detail??void 0}},E=StreamingProblemEventSchema.safeParse(w);if(!E.success){log$16().error({event:`api.streaming.malformed-envelope`,issues:E.error.issues,body:w,handler:g.handler,originalStatus:e},`streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback`);let t=500;return apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...g.handler?{handler:g.handler}:{}}),{type:`error`,problem:{type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:S}}}apiErrorCounter().add(1,{type:t,...g.handler?{handler:g.handler}:{}});let D=e>=500?`error`:`warn`;return log$16()[D]({event:`api.streaming.error`,instance:S,type:t,status:e,handler:g.handler,detail:g.detail,err:g.cause},s),w}function createStreamingErrorWriter(e,t){return(s,g,S,w={})=>{if(e.writableEnded||e.destroyed){log$16().error({event:`api.streaming.error.suppressed`,type:g,status:s,handler:t,detail:w.detail,err:w.cause},`createStreamingErrorWriter called after writableEnded/destroyed — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...t?{handler:t}:{}});return}let E=streamingProblemEvent(s,g,S,{handler:t,...w});try{e.write(`${JSON.stringify(E)}\n`)}catch(e){log$16().error({event:`api.streaming.error.write-failed`,type:g,status:s,handler:t,err:w.cause,writeErr:e},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const RESOLUTION_OPTIONS=[`mine`,`theirs`,`content`,`delete`];function isDocInConflict(e){return e.getMap(`lifecycle`).get(`status`)===`conflict`}var DocInConflictError=class extends Error{file;name=`DocInConflictError`;constructor(e){super(`Document is in conflict: ${e.file}`),this.file=e.file}};function respondDocInConflict(e,t,s){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:s,"doc.name":stripDocExtension(t.file)})),errorResponse(e,409,`urn:ok:error:doc-in-conflict`,`Document is in conflict.`,{handler:s,detail:`The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.`,extensions:{file:t.file,resolutionOptions:RESOLUTION_OPTIONS}})}const byteLength$1=e=>Buffer.byteLength(e,`utf8`);function capContent(e){let t=byteLength$1(e);return t<=51200?{kind:`inline`,content:e}:{kind:`truncated`,byteLength:t,hint:`Converged content exceeds the inline cap — re-read via exec("cat <doc>") for the full document.`}}function evaluateContentDivergence(e,t,s){if(e===t)return;let g=byteLength$1(t),S=byteLength$1(e);return{intendedBytes:g,actualBytes:S,byteDelta:S-g,divergenceType:`${s}-content-mismatch`,currentState:capContent(e)}}const DEFAULT_DIVERGENCE_HINT="The converged document differs from the bytes you composed. The write landed; `currentState` carries what is in the document now — re-read only if it is truncated.";function toContentDivergenceWarning(e,t=DEFAULT_DIVERGENCE_HINT){return{kind:`content-divergence`,intendedBytes:e.intendedBytes,actualBytes:e.actualBytes,byteDelta:e.byteDelta,divergenceType:e.divergenceType,currentState:e.currentState,hint:t}}const FIX_HINT='Frontmatter must be a top-level YAML mapping. Quote string values containing YAML-significant characters (`:`, `#`, leading `-`), e.g. `title: "Foo: bar"`.';var FrontmatterMalformedError=class extends Error{file;parseError;name=`FrontmatterMalformedError`;constructor(e){super(`Frontmatter YAML is malformed in ${e.file}: ${e.parseError}`),this.file=e.file,this.parseError=e.parseError}};function classifyParseError(e){return e===`top-level value is not a mapping`?`non-mapping-top-level`:e.startsWith(`value at "`)||e.startsWith(`schema validation failed:`)?`schema-rejection`:e.startsWith(`parse threw:`)||e.startsWith(`toJS threw:`)||e.length>0&&e!==`unknown YAML parse error`?`yaml-parse-error`:`unknown`}function respondFrontmatterMalformed(e,t,s){let g=classifyParseError(t.parseError);console.warn(JSON.stringify({event:`frontmatter-malformed-write-refused`,handler:s,class:g,"doc.name":stripDocExtension(t.file),parseError:t.parseError})),errorResponse(e,400,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,{handler:s,detail:`${t.parseError}. ${FIX_HINT}`,extensions:{file:t.file,parseError:t.parseError}})}let _editSurfaceCounter=null;function editSurfaceCounter(){return _editSurfaceCounter||=getMeter().createCounter(`ok.frontmatter.edit_surface_total`,{description:`Count of frontmatter edits by surface. Bounded label: source ∈ {source-mode, mcp-write, file-watcher}.`}),_editSurfaceCounter}function recordFrontmatterEditSurface(e){editSurfaceCounter().add(1,{source:e})}const log$15=getLogger(`agent-sessions`),AGENT_WRITE_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function docNameToFile(e){return e.endsWith(`.md`)||e.endsWith(`.mdx`)?e:`${stripDocExtension(e)}${getDocExtension(e)}`}function applyAgentMarkdownWrite(e,t,s,g){if(isDocInConflict(e))throw new DocInConflictError({file:docNameToFile(e.name)});return withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":s,"agent.markdown.bytes":t.length}},()=>{let S=applyAgentMarkdownWriteInner(e,t,s,g);return S!==void 0&&setActiveSpanAttributes({"agent.content_divergent":!0,"agent.intended_bytes":S.intendedBytes,"agent.actual_bytes":S.actualBytes,"agent.byte_delta":S.byteDelta,"agent.divergence_type":S.divergenceType}),S})}function applyAgentMarkdownWriteInner(e,t,s,g){try{let{frontmatter:S,body:w}=stripFrontmatter(e.getText(`source`).toString()),{frontmatter:E,body:D}=stripFrontmatter(t);if((s===`append`||s===`prepend`)&&D===``)return;let O,k;switch(s){case`replace`:O=E||S,k=D;break;case`patch`:O=E||S,k=D;break;case`prepend`:O=S,k=w.length>0?`${D.replace(/\n+$/,``)}\n\n${w.replace(/^\n+/,``)}`:D;break;case`append`:O=S,k=w.length>0?`${w.replace(/\n+$/,``)}\n\n${D.replace(/^\n+/,``)}`:D;break}if(O!==S){let t=parseFrontmatterYaml(unwrapFrontmatterFences(O));if(t.map===null)throw new FrontmatterMalformedError({file:docNameToFile(e.name),parseError:t.parseError??`unknown YAML parse error`});recordFrontmatterEditSurface(`mcp-write`)}let j=prependFrontmatter(O,k);return s===`replace`?replaceRawBody(e,j,g):composeAndWriteRawBody(e,j,`agent`,g),evaluateContentDivergence(e.getText(`source`).toString(),j,s)}catch(g){throw g instanceof FrontmatterMalformedError||log$15.error({err:g,docName:e.name,position:s,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),g}}function applyAgentUndo(e,t,s){let g=e.dc.document;if(isDocInConflict(g))throw new DocInConflictError({file:docNameToFile(g.name)});return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let g=applyAgentUndoInner(e,t,s);return setActiveSpanAttributes({"agent.undo_effective":g}),g})}function applyAgentUndoInner(e,t,s){let{dc:g,um:S,undoOrigin:w}=e,E=g.document,D=!1;return E.transact(()=>{if(t===`last`){if(S.undoStack.length===0)return;S.undo(),D=!0}else for(;S.undoStack.length>0;)S.undo(),D=!0;deriveFragmentFromYtext(E,s)},w),D}function createSessionOrigin(e,t,s,g,S){let w={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(w.agent_type=t),s!==void 0&&(w.principal=s),g!==void 0&&(w.display_name=g),S!==void 0&&(w.color_seed=S),Object.freeze(w);let E={source:`local`,skipStoreHooks:!1,context:w};return Object.freeze(E),E}function createUndoOrigin(e,t){let s={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(s.agent_type=t),Object.freeze(s);let g={source:`local`,skipStoreHooks:!1,context:s};return Object.freeze(g),g}const MAX_AGENT_SESSIONS=256;var AgentSessionCapacityError=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}},AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;maxSessions;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,s]of this.sessions)e.endsWith(t)&&(yield s)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,s){if(isSystemDoc(e)||isConfigDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let g=this.sessionKey(e,t),S=this.sessions.get(g);if(S)return S;let w=this.pendingSessions.get(g);if(w)return w;if(this.sessions.size+this.pendingSessions.size>=this.maxSessions)throw new AgentSessionCapacityError(this.maxSessions);let E=this._createSession(e,t,s);this.pendingSessions.set(g,E);try{let e=await E;return this.sessions.set(g,e),e}finally{this.pendingSessions.delete(g)}}async _createSession(e,t,s){let g=s?.clientName,S=t.startsWith(`agent-`)?t.slice(6):t,w=createSessionOrigin(S,g,s?.principalId,s?.displayName,s?.colorSeed),E=createUndoOrigin(S,g),D={session_id:S,...g===void 0?{}:{agent_type:g},...s?.clientName===void 0?{}:{client_name:s.clientName},...s?.principalId===void 0?{}:{principalId:s.principalId}},O=await this.hocuspocus.openDirectConnection(e,D),k=new UndoManager([O.document.getText(`source`),O.document.getMap(`agent-flash`)],{trackedOrigins:new Set([w]),captureTimeout:500,captureTransaction:e=>e.origin!==E,ignoreRemoteMapChanges:!0}),j=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return k.on(`stack-item-added`,j),k.on(`stack-item-updated`,j),log$15.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:O,origin:w,undoOrigin:E,um:k,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,s){try{try{t.um.destroy()}catch(e){log$15.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$15.error({err:e,...s},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=`claude-1`){let s=this.sessionKey(e,t),g=this.sessions.get(s);g&&(await this.cleanupSession(s,g,{docName:e,agentId:t}),log$15.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,s=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));s.length>0&&await Promise.allSettled(s.map(e=>this.pendingSessions.get(e)));let g=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of g){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,s=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of s){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,s,g){let S=e.doc;if(!S)return;let w=++_effectCounter,E=S.getMap(`agent-effects`),D=k=>{e.unobserve(D),S.off(`destroy`,O);let j=`${t}:${w}`,F={sessionId:t,timestamp:Date.now(),delta:k.delta,agent_type:g??`agent`,color_seed:s??t};try{S.transact(()=>{if(E.set(j,F),E.size>RING_BUFFER_LIMIT){let e=[...E.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,E.size-RING_BUFFER_LIMIT))E.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let s=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:s})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},O=()=>{e.unobserve(D)};e.observe(D),S.once(`destroy`,O)}function collectItemsInDeleteSet(e,t,s){iterateDeletedStructs(e,t,e=>{e instanceof Item&&s.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let s=[],g=[],S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=``,O=``,k=0,j=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,S=t.length,F=w.has(e),L=E.has(e);e.deleted?L&&(g.push({position:k,content:t,length:S}),D+=t,k+=S):(O+=t,F?s.push({position:j,content:t,length:S}):(D+=t,k+=S),j+=S)}return{insertions:s,deletions:g,before:D,after:O}}function synthesizeStackItemDiffText(e,t,s){let{before:g,after:S}=synthesizeStackItemDiff(e,t);return g===S?``:createPatch(s,g,S,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let s=t.doc,g=new Set,S=new Set;s&&s.transact(t=>{collectItemsInDeleteSet(t,e.insertions,g),collectItemsInDeleteSet(t,e.deletions,S)});let w=0,E=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&g.has(e)&&(w+=t),S.has(e)&&(E+=t)}return{additions:w,deletions:E}}function listAgentActivity(e,t){let s=[],g=null,S=!1;for(let w of e.sessionsForConnection(t)){if(S=!0,!g){let e=w.origin.context,s=typeof e?.agent_type==`string`?e.agent_type:void 0,S=typeof e?.color_seed==`string`?e.color_seed:t,E=iconFromClientName(s),D=AGENT_ICON_COLORS[E]??colorFromSeed(S);g={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:D,icon:E,connectionId:t}}let e=w.docName,E=w.um,D=w.dc.document.getText(`source`),O=[];for(let e=0;e<E.undoStack.length;e++){let t=E.undoStack[e],s=getBurstTs(t),{additions:g,deletions:S}=countStackItemChanges(t,D);O.push({stackIndex:e,ts:s,additions:g,deletions:S})}if(O.length===0)continue;O.sort((e,t)=>t.stackIndex-e.stackIndex);let k=O.reduce((e,t)=>e+t.additions,0),j=O.reduce((e,t)=>e+t.deletions,0),F=Math.max(...O.map(e=>e.ts));s.push({docName:e,additionsTotal:k,deletionsTotal:j,lastTs:F,bursts:O})}return S?(s.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:g,files:s}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const HocuspocusAuthTokenSchema=object$1({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional(),expectedDocLineageEpoch:string().optional(),clientProtocolVersion:number().optional(),clientRuntimeVersion:string().optional(),clientKind:string().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),s=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(s))return{kind:null,payload:void 0};if(t===-1)return{kind:s,payload:void 0};let g=e.slice(t+1);return{kind:s,payload:g.length>0?g:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,s){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof s==`string`&&s.length>0?s:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let s=HocuspocusAuthTokenSchema.safeParse(t);return s.success?s.data:void 0}const counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let s=getCounters(e);s.lastUserTxGen=++globalCounter,s.lastUserTxAtMs=Date.now()},s=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,s),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,s)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let s=counters.get(e);return s?s.settledGen>s.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let s=counters.get(e);return!s||s.lastUserTxAtMs===null?null:Math.max(0,t-s.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map,lastSplitBrainEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,s=Date.now()){let g=rateKey(e,t),S=lastEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)s-t>=w&&lastEmitMs.delete(e);return lastEmitMs.set(g,s),!0}function shouldEmitBridgeToleranceApplied(e,t,s=Date.now()){let g=toleranceRateKey(e,t),S=lastToleranceEmitMs.get(g),w=readDebounceMs();return S!==void 0&&s-S<w?!1:(lastToleranceEmitMs.set(g,s),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let s=e??`__nodoc__`,g=lastPathBEmitMs.get(s),S=readDebounceMs();if(g!==void 0&&t-g<S)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,s]of lastPathBEmitMs)t-s>=S&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(s,t),!0}function emitObserverAPathBFired(e,t){let s=shouldEmitObserverAPathBFired(e,t);return s||incrementObserverAPathBFiresSuppressed(),s}function shouldEmitBridgeSplitBrainRederive(e,t,s=Date.now()){let g=`${e}::${t??`__nodoc__`}`,S=lastSplitBrainEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastSplitBrainEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastSplitBrainEmitMs)s-t>=w&&lastSplitBrainEmitMs.delete(e);return lastSplitBrainEmitMs.set(g,s),!0}function emitBridgeSplitBrainRederive(e,t,s){let g=shouldEmitBridgeSplitBrainRederive(e,t,s);return g||incrementBridgeSplitBrainRederivesSuppressed(),g}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,s){let g=normalizeBridge(e),S=normalizeBridge(t);if(g===S){if(e!==t){let g=detectAppliedToleranceClasses(e,t),S=g.filter(e=>shouldEmitBridgeToleranceApplied(s.site,e,s.nowMs));g.length>0&&emitToleranceFire(g,e,t,s.docName);for(let e of S)incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:s.site,class:e}))}return!0}let w={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${g.slice(0,300)}\n frag: ${S.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(w);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let E=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(w,{verbose:E}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,s){let g={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return s&&Object.assign(g,s),g}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,s){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,s)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,s){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,s)})}function tracedAppendFileSync(e,t,s){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,s)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,s){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,s)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
770
+ `)}),g(w,E,s),E},{parse:`lines`,close(e,t){s.on(`close`,()=>{t(e)})}})}t.exports=J,t.exports.build=J,t.exports.PinoPretty=J,t.exports.prettyFactory=ee,t.exports.colorizerFactory=E,t.exports.isColorSupported=s,t.exports.default=J})),import_pino=__toESM(require_pino(),1),import_pino_pretty=__toESM(require_pino_pretty(),1),RotatingAppender=class{#e;#t;#n;#r=Promise.resolve();#i=!1;constructor(e){this.#e=e.currentPath,this.#t=e.previousPath,this.#n=e.maxBytes}append(e){let t=this.#r.catch(()=>void 0).then(()=>this.#a(e));return this.#r=t,t}async drain(){await this.#r.catch(()=>void 0)}async#a(e){this.#i||=(await mkdir(dirname(this.#e),{recursive:!0}),!0),await writeFile(this.#e,e,{flag:`a`});let t;try{t=statSync(this.#e).size}catch{this.#i=!1;return}t>this.#n&&await rename(this.#e,this.#t)}};const TELEMETRY_SUBDIR=[`.ok`,`local`,`telemetry`],CURRENT_FILENAME=`spans-current.jsonl`,PREVIOUS_FILENAME=`spans-prev.jsonl`;function spansCurrentPath(e){return join(e,...TELEMETRY_SUBDIR,CURRENT_FILENAME)}function spansPreviousPath(e){return join(e,...TELEMETRY_SUBDIR,PREVIOUS_FILENAME)}var FileSpanExporter=class{#e;#t=!1;constructor(e){this.#e=new RotatingAppender({currentPath:spansCurrentPath(e.projectDir),previousPath:spansPreviousPath(e.projectDir),maxBytes:e.maxBytes})}export(e,t){if(this.#t){t({code:import_src.ExportResultCode.FAILED,error:Error(`FileSpanExporter: export called after shutdown`)});return}if(e.length===0){t({code:import_src.ExportResultCode.SUCCESS});return}let s=import_src$1.JsonTraceSerializer.serializeRequest(e);if(!s||s.byteLength===0){t({code:import_src.ExportResultCode.SUCCESS});return}let g=new Uint8Array(s.byteLength+1);g.set(s),g[s.byteLength]=10,this.#e.append(g).then(()=>t({code:import_src.ExportResultCode.SUCCESS}),e=>t({code:import_src.ExportResultCode.FAILED,error:e instanceof Error?e:Error(String(e))}))}async shutdown(){this.#t=!0,await this.#e.drain()}async forceFlush(){await this.#e.drain()}};const REDACTED_SENTINEL=`[REDACTED]`,KEY_BOUNDARY_CHARS=new Set([`.`,`/`,`_`]);function keyMatchesDenylist(e,t){if(t.has(e))return!0;for(let s of t){if(s.length===0||e.length<=s.length||!e.endsWith(s))continue;let t=e.charAt(e.length-s.length-1);if(KEY_BOUNDARY_CHARS.has(t))return!0}return!1}function scrubAttributes(e,t,s){for(let g of Object.keys(e)){let S=e[g];if(S!==void 0){if(keyMatchesDenylist(g.toLowerCase(),t)){e[g]=REDACTED_SENTINEL;continue}if(typeof S==`string`){let t=Buffer.byteLength(S,`utf-8`);t>s&&(e[g]=`[TRUNCATED:${t}]`)}}}}var ScrubbingSpanProcessor=class{#e;#t;constructor(e){this.#e=new Set(e.attributeDenylist.map(e=>e.toLowerCase())),this.#t=e.maxValueBytes??4096}onStart(e,t){}onEnd(e){scrubAttributes(e.attributes,this.#e,this.#t);for(let t of e.events)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t);for(let t of e.links)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t)}async forceFlush(){}async shutdown(){}};const LOGS_SUBDIR=[`.ok`,`local`,`logs`],LOGS_CURRENT_FILENAME=`server-current.jsonl`,LOGS_PREVIOUS_FILENAME=`server-prev.jsonl`;function logsCurrentPath(e){return join(e,...LOGS_SUBDIR,LOGS_CURRENT_FILENAME)}function logsPreviousPath(e){return join(e,...LOGS_SUBDIR,LOGS_PREVIOUS_FILENAME)}var PinoFileSink=class extends Writable{#e;constructor(e){super({decodeStrings:!1}),this.#e=new RotatingAppender({currentPath:logsCurrentPath(e.projectDir),previousPath:logsPreviousPath(e.projectDir),maxBytes:e.maxBytes})}_write(e,t,s){this.#e.append(e).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}async drain(){await this.#e.drain()}};function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}const VALID_LOG_LEVELS=new Set([`fatal`,`error`,`warn`,`info`,`debug`,`trace`,`silent`]);function logLevelRank(e){return e===`silent`?1/0:import_pino.default.levels.values[e]??import_pino.default.levels.values.info}function mostVerboseLevel(e,t){return logLevelRank(e)<=logLevelRank(t)?e:t}var PinoLogger=class{name;transportConfigs=[];fileSinkOpts;redactPaths;activeFileSink;pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),t.fileSink&&(this.fileSinkOpts=t.fileSink),t.redactPaths&&t.redactPaths.length>0&&(this.redactPaths=t.redactPaths,this.options={...this.options,redact:{paths:[...t.redactPaths],censor:`[REDACTED]`}}),this.pinoInstance=this.buildInstance()}resolveStreamLevels(){let e=this.options.level??`info`,t=process.env.OK_CONSOLE_LEVEL?.toLowerCase(),s=t&&VALID_LOG_LEVELS.has(t)?t:e;return{fileLevel:e,consoleLevel:s,instanceLevel:mostVerboseLevel(e,s)}}buildInstance(){this.activeFileSink=void 0;let{fileLevel:e,consoleLevel:t,instanceLevel:s}=this.resolveStreamLevels();if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));let g;try{g=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`})}catch(g){if(console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,g),this.fileSinkOpts){let t=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=t,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:t,level:e}]))}return(0,import_pino.default)({...this.options,level:t})}if(this.fileSinkOpts){let S=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=S,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:g,level:t},{stream:S,level:e}]))}return(0,import_pino.default)({...this.options,level:t},g)}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}reconfigure(e){e.options&&(this.options={...this.options,...e.options}),e.transportConfigs&&(this.transportConfigs=e.transportConfigs),e.fileSink&&(this.fileSinkOpts=e.fileSink),e.redactPaths&&e.redactPaths.length>0&&(this.redactPaths=e.redactPaths,this.options={...this.options,redact:{paths:[...e.redactPaths],censor:`[REDACTED]`}}),this.recreateInstance()}getPinoInstance(){return this.pinoInstance}async flushFileSink(){this.activeFileSink&&await this.activeFileSink.drain()}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){if(this.config=e,e.pinoConfig&&!e.defaultLogger&&!e.loggerFactory){for(let t of this.loggers.values())t.reconfigure(e.pinoConfig);return}this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let s;return s=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,s),s}reset(){this.config={},this.loggers.clear()}async flushAllFileSinks(){let e=[];for(let t of this.loggers.values())e.push(t.flushFileSink());await Promise.all(e)}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(s=>({...s,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:s,...g}=t;return g})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let s=t.getLocalState()??{},g=e(s.agentFocus??{});t.setLocalState({...s,agentFocus:g})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,mapDrivenSpliceApplied:0,mapDrivenSpliceFallback:{},observerAResidualMergeRuns:0,bridgeSplitBrainRederives:0,bridgeSplitBrainRederivesSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,reconcileOwnFlushSkips:0,reconcileInFlightFallthroughs:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0,authDocLineageMismatchCount:0,authDocLineageGuardErrors:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementMapDrivenSpliceApplied(){counters$1.mapDrivenSpliceApplied++}function incrementMapDrivenSpliceFallback(e){counters$1.mapDrivenSpliceFallback[e]=(counters$1.mapDrivenSpliceFallback[e]??0)+1}function incrementObserverAResidualMergeRuns(){counters$1.observerAResidualMergeRuns++}function incrementBridgeSplitBrainRederives(){counters$1.bridgeSplitBrainRederives++}function incrementBridgeSplitBrainRederivesSuppressed(){counters$1.bridgeSplitBrainRederivesSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementReconcileOwnFlushSkips(){counters$1.reconcileOwnFlushSkips++}function incrementReconcileInFlightFallthroughs(){counters$1.reconcileInFlightFallthroughs++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementAuthDocLineageMismatch(){counters$1.authDocLineageMismatchCount++}function incrementAuthDocLineageGuardError(){counters$1.authDocLineageGuardErrors++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied},mapDrivenSpliceFallback:{...counters$1.mapDrivenSpliceFallback}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.mapDrivenSpliceApplied=0,counters$1.mapDrivenSpliceFallback={},counters$1.observerAResidualMergeRuns=0,counters$1.bridgeSplitBrainRederives=0,counters$1.bridgeSplitBrainRederivesSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.reconcileOwnFlushSkips=0,counters$1.reconcileInFlightFallthroughs=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0,counters$1.authDocLineageMismatchCount=0,counters$1.authDocLineageGuardErrors=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let s=0;this.mutateAgentPresence(g=>{let S=Date.now(),w={};for(let[t,E]of Object.entries(g)){if(S-E.ts>=2e4&&t!==e){s++;continue}w[t]=E}return w[e]=t,w})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),s>0&&this.log.info({evictedCount:s,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(s=>{if(!s[e])return s;t=!0;let{[e]:g,...S}=s;return S})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let s=[],g=!1,S=this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;g=!0;let E=Date.now();return s.push({currentDoc:w.currentDoc,ts:E}),{...S,[e]:{...w,mode:t,ts:E}}}),w=s[0];S&&w?this.log.debug({agentId:e,action:`touchMode`,currentDoc:w.currentDoc,ts:w.ts,mode:t},`[agent-presence] touchMode`):g||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(s=>{let g=s[e];if(!g)return s;let S=Date.now();return t=S,{...s,[e]:{...g,ts:S}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let s=t.getLocalState()??{},g=e(s.agentPresence??{});return t.setLocalState({...s,agentPresence:g}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null,fileSpanExporter=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(e={}){let t=e.localSink!==void 0,s=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!s||tracerProvider)return noopResult();try{let g=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),S=new import_src$2.AsyncLocalStorageContextManager;context.setGlobalContextManager(S);let w=[],E=e.localSink?.attributeDenylist??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;w.push(new ScrubbingSpanProcessor({attributeDenylist:E})),t&&e.localSink!==void 0&&(fileSpanExporter=new FileSpanExporter({projectDir:e.localSink.projectDir,maxBytes:e.localSink.spansMaxBytes}),w.push(new import_src$7.SimpleSpanProcessor(fileSpanExporter))),s&&w.push(new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter));let D=new import_src$7.BasicTracerProvider({resource:g,spanProcessors:w});trace.setGlobalTracerProvider(D),tracerProvider=D;try{propagation.setGlobalPropagator(new import_src.W3CTraceContextPropagator)}catch(e){getLogger(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let O=null;s&&(O=new import_src$6.MeterProvider({resource:g,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]}),metrics.setGlobalMeterProvider(O)),meterProvider=O,getLogger(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:s,otlp_endpoint:s?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:g.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized`)}catch(e){let t=getLogger(`telemetry`);tracerProvider===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),meterProvider=null,fileSpanExporter=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),meterProvider=null)}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3,shutdownHooks=new Set;function onTelemetryShutdown(e){shutdownHooks.add(e)}async function shutdownTelemetry(){let e=getLogger(`telemetry`);for(let t of shutdownHooks)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!tracerProvider&&!meterProvider)return;let t=(fileSpanExporter?fileSpanExporter.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),s;await Promise.race([t.then(()=>(s!==void 0&&clearTimeout(s),!1)),new Promise(e=>{s=setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS),s.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,fileSpanExporter=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,s){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await s(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,s){return getTracer().startActiveSpan(e,t??{},e=>{try{return s(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,s,g){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:s,"body.bytes":t.length,"doc.name":e.guid}},()=>{let s=e.getXmlFragment(`default`),S=e.getText(`source`),w=S.toString(),{body:E}=stripFrontmatter(t),D=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":E.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(E,buildParseOpts(g))),O=schema.nodeFromJSON(D);w!==t&&applyFastDiff(S,w,t),updateYFragment(e,s,O,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,s){withSpanSync(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let g=e.getXmlFragment(`default`),S=e.getText(`source`),{body:w}=stripFrontmatter(t),E=mdManager.parseWithFallback(w,buildParseOpts(s)),D=schema.nodeFromJSON(E),O=S.toString();O!==t&&(S.delete(0,O.length),S.insert(0,t)),updateYFragment(e,g,D,{mapping:new Map,isOMark:new Map})})}function deriveFragmentFromYtext(e,t){let s=e.getXmlFragment(`default`),{body:g}=stripFrontmatter(e.getText(`source`).toString()),S=mdManager.parseWithFallback(g,buildParseOpts(t));updateYFragment(e,s,schema.nodeFromJSON(S),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(e)??0)+1;this.seqs.set(e,s);let g=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:s});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(e,s),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let g=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});s.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,s);let g=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:s,branch:e});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,s)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,g);let S=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:g,docName:e,sv:Buffer.from(t).toString(`base64`)});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,s]of this.latestDiskAckSVs)e[t]=Buffer.from(s).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g);let S=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:g,docName:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g);let S=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:g,path:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let s=extname(e).slice(1).toLowerCase();return s.length>0&&t.has(s)}function stripDocExtension(e){let t=e.toLowerCase();for(let s of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(s))return e.slice(0,-s.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let s=canonicalize(t);if(!s)throw Error(`registerDocExtension: unsupported extension "${t}"`);let g=docExtensionByName.get(e);if(!g)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let S=canonicalize(g);return S?S===s?{effective:g,changed:!1,shadowed:null}:rank(s)<rank(S)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g}):{effective:g,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$16=()=>getLogger(`http`);let _apiErrorCounter=null;function apiErrorCounter(){return _apiErrorCounter||=getMeter().createCounter(`ok.api.error.count`,{description:`API error responses by problem type and handler`,unit:`1`}),_apiErrorCounter}function errorResponse(e,t,s,g,S={}){let w=S.instance??`urn:uuid:${randomUUID$1()}`;if(e.headersSent||e.writableEnded||e.destroyed){log$16().error({event:`api.error.double-write`,instance:w,type:s,status:t,handler:S.handler},`errorResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let E={type:s,title:g,status:t,instance:w,detail:S.detail??void 0},D=ProblemDetailsSchema.safeParse(E);if(!D.success){log$16().error({event:`api.error.malformed-envelope`,issues:D.error.issues,body:E,handler:S.handler,originalStatus:t},`errorResponse produced an invalid ProblemDetails body — emitting fallback`);let s=500;apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}let O=S.extensions?{...S.extensions,...E}:E;apiErrorCounter().add(1,{type:s,...S.handler?{handler:S.handler}:{}});let k=t>=500?`error`:`warn`;log$16()[k]({event:`api.error`,instance:w,type:s,status:t,handler:S.handler,detail:S.detail,err:S.cause},g);let j;try{j=JSON.stringify(O)}catch(s){log$16().error({event:`api.error.unserializable-body`,bodyKeys:Object.keys(O),handler:S.handler,originalStatus:t,instance:w,err:s},`errorResponse wireBody is not JSON-serializable — emitting hardcoded fallback`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(j)}function streamingProblemEvent(e,t,s,g={}){let S=g.instance??`urn:uuid:${randomUUID$1()}`,w={type:`error`,problem:{type:t,title:s,status:e,instance:S,detail:g.detail??void 0}},E=StreamingProblemEventSchema.safeParse(w);if(!E.success){log$16().error({event:`api.streaming.malformed-envelope`,issues:E.error.issues,body:w,handler:g.handler,originalStatus:e},`streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback`);let t=500;return apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...g.handler?{handler:g.handler}:{}}),{type:`error`,problem:{type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:S}}}apiErrorCounter().add(1,{type:t,...g.handler?{handler:g.handler}:{}});let D=e>=500?`error`:`warn`;return log$16()[D]({event:`api.streaming.error`,instance:S,type:t,status:e,handler:g.handler,detail:g.detail,err:g.cause},s),w}function createStreamingErrorWriter(e,t){return(s,g,S,w={})=>{if(e.writableEnded||e.destroyed){log$16().error({event:`api.streaming.error.suppressed`,type:g,status:s,handler:t,detail:w.detail,err:w.cause},`createStreamingErrorWriter called after writableEnded/destroyed — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...t?{handler:t}:{}});return}let E=streamingProblemEvent(s,g,S,{handler:t,...w});try{e.write(`${JSON.stringify(E)}\n`)}catch(e){log$16().error({event:`api.streaming.error.write-failed`,type:g,status:s,handler:t,err:w.cause,writeErr:e},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const RESOLUTION_OPTIONS=[`mine`,`theirs`,`content`,`delete`];function isDocInConflict(e){return e.getMap(`lifecycle`).get(`status`)===`conflict`}var DocInConflictError=class extends Error{file;name=`DocInConflictError`;constructor(e){super(`Document is in conflict: ${e.file}`),this.file=e.file}};function respondDocInConflict(e,t,s){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:s,"doc.name":stripDocExtension(t.file)})),errorResponse(e,409,`urn:ok:error:doc-in-conflict`,`Document is in conflict.`,{handler:s,detail:`The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.`,extensions:{file:t.file,resolutionOptions:RESOLUTION_OPTIONS}})}const byteLength$1=e=>Buffer.byteLength(e,`utf8`);function capContent(e){let t=byteLength$1(e);return t<=51200?{kind:`inline`,content:e}:{kind:`truncated`,byteLength:t,hint:`Converged content exceeds the inline cap — re-read via exec("cat <doc>") for the full document.`}}function evaluateContentDivergence(e,t,s){if(e===t)return;let g=byteLength$1(t),S=byteLength$1(e);return{intendedBytes:g,actualBytes:S,byteDelta:S-g,divergenceType:`${s}-content-mismatch`,currentState:capContent(e)}}const DEFAULT_DIVERGENCE_HINT="The converged document differs from the bytes you composed. The write landed; `currentState` carries what is in the document now — re-read only if it is truncated.";function toContentDivergenceWarning(e,t=DEFAULT_DIVERGENCE_HINT){return{kind:`content-divergence`,intendedBytes:e.intendedBytes,actualBytes:e.actualBytes,byteDelta:e.byteDelta,divergenceType:e.divergenceType,currentState:e.currentState,hint:t}}const FIX_HINT='Frontmatter must be a top-level YAML mapping. Quote string values containing YAML-significant characters (`:`, `#`, leading `-`), e.g. `title: "Foo: bar"`.';var FrontmatterMalformedError=class extends Error{file;parseError;name=`FrontmatterMalformedError`;constructor(e){super(`Frontmatter YAML is malformed in ${e.file}: ${e.parseError}`),this.file=e.file,this.parseError=e.parseError}};function classifyParseError(e){return e===`top-level value is not a mapping`?`non-mapping-top-level`:e.startsWith(`value at "`)||e.startsWith(`schema validation failed:`)?`schema-rejection`:e.startsWith(`parse threw:`)||e.startsWith(`toJS threw:`)||e.length>0&&e!==`unknown YAML parse error`?`yaml-parse-error`:`unknown`}function respondFrontmatterMalformed(e,t,s){let g=classifyParseError(t.parseError);console.warn(JSON.stringify({event:`frontmatter-malformed-write-refused`,handler:s,class:g,"doc.name":stripDocExtension(t.file),parseError:t.parseError})),errorResponse(e,400,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,{handler:s,detail:`${t.parseError}. ${FIX_HINT}`,extensions:{file:t.file,parseError:t.parseError}})}let _editSurfaceCounter=null;function editSurfaceCounter(){return _editSurfaceCounter||=getMeter().createCounter(`ok.frontmatter.edit_surface_total`,{description:`Count of frontmatter edits by surface. Bounded label: source ∈ {source-mode, mcp-write, file-watcher}.`}),_editSurfaceCounter}function recordFrontmatterEditSurface(e){editSurfaceCounter().add(1,{source:e})}const log$15=getLogger(`agent-sessions`),AGENT_WRITE_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function docNameToFile(e){return e.endsWith(`.md`)||e.endsWith(`.mdx`)?e:`${stripDocExtension(e)}${getDocExtension(e)}`}function applyAgentMarkdownWrite(e,t,s,g){if(isDocInConflict(e))throw new DocInConflictError({file:docNameToFile(e.name)});return withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":s,"agent.markdown.bytes":t.length}},()=>{let S=applyAgentMarkdownWriteInner(e,t,s,g);return S!==void 0&&setActiveSpanAttributes({"agent.content_divergent":!0,"agent.intended_bytes":S.intendedBytes,"agent.actual_bytes":S.actualBytes,"agent.byte_delta":S.byteDelta,"agent.divergence_type":S.divergenceType}),S})}function applyAgentMarkdownWriteInner(e,t,s,g){try{let{frontmatter:S,body:w}=stripFrontmatter(e.getText(`source`).toString()),{frontmatter:E,body:D}=stripFrontmatter(t);if((s===`append`||s===`prepend`)&&D===``)return;let O,k;switch(s){case`replace`:O=E||S,k=D;break;case`patch`:O=E||S,k=D;break;case`prepend`:O=S,k=w.length>0?`${D.replace(/\n+$/,``)}\n\n${w.replace(/^\n+/,``)}`:D;break;case`append`:O=S,k=w.length>0?`${w.replace(/\n+$/,``)}\n\n${D.replace(/^\n+/,``)}`:D;break}if(O!==S){let t=parseFrontmatterYaml(unwrapFrontmatterFences(O));if(t.map===null)throw new FrontmatterMalformedError({file:docNameToFile(e.name),parseError:t.parseError??`unknown YAML parse error`});recordFrontmatterEditSurface(`mcp-write`)}let j=prependFrontmatter(O,k);return s===`replace`?replaceRawBody(e,j,g):composeAndWriteRawBody(e,j,`agent`,g),evaluateContentDivergence(e.getText(`source`).toString(),j,s)}catch(g){throw g instanceof FrontmatterMalformedError||log$15.error({err:g,docName:e.name,position:s,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),g}}function applyAgentUndo(e,t,s){let g=e.dc.document;if(isDocInConflict(g))throw new DocInConflictError({file:docNameToFile(g.name)});return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let g=applyAgentUndoInner(e,t,s);return setActiveSpanAttributes({"agent.undo_effective":g}),g})}function applyAgentUndoInner(e,t,s){let{dc:g,um:S,undoOrigin:w}=e,E=g.document,D=!1;return E.transact(()=>{if(t===`last`){if(S.undoStack.length===0)return;S.undo(),D=!0}else for(;S.undoStack.length>0;)S.undo(),D=!0;deriveFragmentFromYtext(E,s)},w),D}function createSessionOrigin(e,t,s,g,S){let w={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(w.agent_type=t),s!==void 0&&(w.principal=s),g!==void 0&&(w.display_name=g),S!==void 0&&(w.color_seed=S),Object.freeze(w);let E={source:`local`,skipStoreHooks:!1,context:w};return Object.freeze(E),E}function createUndoOrigin(e,t){let s={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(s.agent_type=t),Object.freeze(s);let g={source:`local`,skipStoreHooks:!1,context:s};return Object.freeze(g),g}const MAX_AGENT_SESSIONS=256;var AgentSessionCapacityError=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}},AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;maxSessions;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,s]of this.sessions)e.endsWith(t)&&(yield s)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,s){if(isSystemDoc(e)||isConfigDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let g=this.sessionKey(e,t),S=this.sessions.get(g);if(S)return S;let w=this.pendingSessions.get(g);if(w)return w;if(this.sessions.size+this.pendingSessions.size>=this.maxSessions)throw new AgentSessionCapacityError(this.maxSessions);let E=this._createSession(e,t,s);this.pendingSessions.set(g,E);try{let e=await E;return this.sessions.set(g,e),e}finally{this.pendingSessions.delete(g)}}async _createSession(e,t,s){let g=s?.clientName,S=t.startsWith(`agent-`)?t.slice(6):t,w=createSessionOrigin(S,g,s?.principalId,s?.displayName,s?.colorSeed),E=createUndoOrigin(S,g),D={session_id:S,...g===void 0?{}:{agent_type:g},...s?.clientName===void 0?{}:{client_name:s.clientName},...s?.principalId===void 0?{}:{principalId:s.principalId}},O=await this.hocuspocus.openDirectConnection(e,D),k=new UndoManager([O.document.getText(`source`),O.document.getMap(`agent-flash`)],{trackedOrigins:new Set([w]),captureTimeout:500,captureTransaction:e=>e.origin!==E,ignoreRemoteMapChanges:!0}),j=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return k.on(`stack-item-added`,j),k.on(`stack-item-updated`,j),log$15.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:O,origin:w,undoOrigin:E,um:k,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,s){try{try{t.um.destroy()}catch(e){log$15.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$15.error({err:e,...s},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=`claude-1`){let s=this.sessionKey(e,t),g=this.sessions.get(s);g&&(await this.cleanupSession(s,g,{docName:e,agentId:t}),log$15.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,s=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));s.length>0&&await Promise.allSettled(s.map(e=>this.pendingSessions.get(e)));let g=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of g){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,s=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of s){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,s,g){let S=e.doc;if(!S)return;let w=++_effectCounter,E=S.getMap(`agent-effects`),D=k=>{e.unobserve(D),S.off(`destroy`,O);let j=`${t}:${w}`,F={sessionId:t,timestamp:Date.now(),delta:k.delta,agent_type:g??`agent`,color_seed:s??t};try{S.transact(()=>{if(E.set(j,F),E.size>RING_BUFFER_LIMIT){let e=[...E.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,E.size-RING_BUFFER_LIMIT))E.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let s=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:s})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},O=()=>{e.unobserve(D)};e.observe(D),S.once(`destroy`,O)}function collectItemsInDeleteSet(e,t,s){iterateDeletedStructs(e,t,e=>{e instanceof Item&&s.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let s=[],g=[],S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=``,O=``,k=0,j=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,S=t.length,F=w.has(e),L=E.has(e);e.deleted?L&&(g.push({position:k,content:t,length:S}),D+=t,k+=S):(O+=t,F?s.push({position:j,content:t,length:S}):(D+=t,k+=S),j+=S)}return{insertions:s,deletions:g,before:D,after:O}}function synthesizeStackItemDiffText(e,t,s){let{before:g,after:S}=synthesizeStackItemDiff(e,t);return g===S?``:createPatch(s,g,S,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let s=t.doc,g=new Set,S=new Set;s&&s.transact(t=>{collectItemsInDeleteSet(t,e.insertions,g),collectItemsInDeleteSet(t,e.deletions,S)});let w=0,E=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&g.has(e)&&(w+=t),S.has(e)&&(E+=t)}return{additions:w,deletions:E}}function listAgentActivity(e,t){let s=[],g=null,S=!1;for(let w of e.sessionsForConnection(t)){if(S=!0,!g){let e=w.origin.context,s=typeof e?.agent_type==`string`?e.agent_type:void 0,S=typeof e?.color_seed==`string`?e.color_seed:t,E=iconFromClientName(s),D=AGENT_ICON_COLORS[E]??colorFromSeed(S);g={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:D,icon:E,connectionId:t}}let e=w.docName,E=w.um,D=w.dc.document.getText(`source`),O=[];for(let e=0;e<E.undoStack.length;e++){let t=E.undoStack[e],s=getBurstTs(t),{additions:g,deletions:S}=countStackItemChanges(t,D);O.push({stackIndex:e,ts:s,additions:g,deletions:S})}if(O.length===0)continue;O.sort((e,t)=>t.stackIndex-e.stackIndex);let k=O.reduce((e,t)=>e+t.additions,0),j=O.reduce((e,t)=>e+t.deletions,0),F=Math.max(...O.map(e=>e.ts));s.push({docName:e,additionsTotal:k,deletionsTotal:j,lastTs:F,bursts:O})}return S?(s.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:g,files:s}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const HocuspocusAuthTokenSchema=object$1({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional(),expectedDocLineageEpoch:string().optional(),clientProtocolVersion:number().optional(),clientRuntimeVersion:string().optional(),clientKind:string().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),s=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(s))return{kind:null,payload:void 0};if(t===-1)return{kind:s,payload:void 0};let g=e.slice(t+1);return{kind:s,payload:g.length>0?g:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,s){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof s==`string`&&s.length>0?s:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let s=HocuspocusAuthTokenSchema.safeParse(t);return s.success?s.data:void 0}const counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let s=getCounters(e);s.lastUserTxGen=++globalCounter,s.lastUserTxAtMs=Date.now()},s=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,s),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,s)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let s=counters.get(e);return s?s.settledGen>s.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let s=counters.get(e);return!s||s.lastUserTxAtMs===null?null:Math.max(0,t-s.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map,lastSplitBrainEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,s=Date.now()){let g=rateKey(e,t),S=lastEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)s-t>=w&&lastEmitMs.delete(e);return lastEmitMs.set(g,s),!0}function shouldEmitBridgeToleranceApplied(e,t,s=Date.now()){let g=toleranceRateKey(e,t),S=lastToleranceEmitMs.get(g),w=readDebounceMs();return S!==void 0&&s-S<w?!1:(lastToleranceEmitMs.set(g,s),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let s=e??`__nodoc__`,g=lastPathBEmitMs.get(s),S=readDebounceMs();if(g!==void 0&&t-g<S)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,s]of lastPathBEmitMs)t-s>=S&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(s,t),!0}function emitObserverAPathBFired(e,t){let s=shouldEmitObserverAPathBFired(e,t);return s||incrementObserverAPathBFiresSuppressed(),s}function shouldEmitBridgeSplitBrainRederive(e,t,s=Date.now()){let g=`${e}::${t??`__nodoc__`}`,S=lastSplitBrainEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastSplitBrainEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastSplitBrainEmitMs)s-t>=w&&lastSplitBrainEmitMs.delete(e);return lastSplitBrainEmitMs.set(g,s),!0}function emitBridgeSplitBrainRederive(e,t,s){let g=shouldEmitBridgeSplitBrainRederive(e,t,s);return g||incrementBridgeSplitBrainRederivesSuppressed(),g}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,s){let g=normalizeBridge(e),S=normalizeBridge(t);if(g===S){if(e!==t){let g=detectAppliedToleranceClasses(e,t),S=g.filter(e=>shouldEmitBridgeToleranceApplied(s.site,e,s.nowMs));g.length>0&&emitToleranceFire(g,e,t,s.docName);for(let e of S)incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:s.site,class:e}))}return!0}let w={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${g.slice(0,300)}\n frag: ${S.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(w);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let E=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(w,{verbose:E}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,s){let g={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return s&&Object.assign(g,s),g}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,s){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,s)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,s){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,s)})}function tracedAppendFileSync(e,t,s){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,s)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,s){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,s)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
771
771
  `);for(let e=0;e<t.length;e++){let s=t[e]??``;if(s.length!==0&&/^\s+$/.test(s))return{ok:!1,error:{code:`OKIGNORE_INVALID`,detail:`Whitespace-only pattern is not allowed.`,lineNumber:e+1}}}return{ok:!0}}function validateConfigContent(e,t){return e===`__config__/okignore`?validateOkignore(t):validateConfigYaml(t)}function defaultLkgFor(e){return e===`__config__/okignore`?``:serializedDefaults()}function validateConfigYaml(e){let t=(0,import_dist$1.parseDocument)(e);if(t.errors.length>0)return{ok:!1,error:{code:`YAML_PARSE`,detail:t.errors.map(e=>e.message).join(`; `)}};let s=t.toJSON()??{},g=ConfigSchema$1.safeParse(s);return g.success?{ok:!0}:{ok:!1,error:{code:`SCHEMA_INVALID`,issues:g.error.issues.map(e=>({path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}))}}}function loadConfigDoc(e,t,s){let g=e.getText(`source`);if(g.length>0)return;let S=configDocAbsPath(t,s),w=``;if(existsSync(S))try{w=readFileSync(S,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[config] Could not read ${S}: ${t}. Seeding with empty content.`),w=``}let E=validateConfigContent(t,w);!E.ok&&w.length>0&&getLogger(`config-persistence`).warn({docName:t,path:S},`[config-persistence] loadConfigDoc seeding invalid content for ${t} into Y.Text — first mutation will revert to LKG`),e.transact(()=>{w.length>0&&g.insert(0,w)},CONFIG_VALIDATION_REVERT_ORIGIN),E.ok&&w.length>0?s.lkgCache.set(t,w):s.lkgCache.set(t,defaultLkgFor(t))}async function atomicWriteConfig(e,t){await tracedMkdir(dirname(e),{recursive:!0});let s=`${e}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(s,t,`utf-8`),await tracedRename(s,e)}catch(e){try{tracedUnlinkSync(s)}catch{}throw e}}async function storeConfigDoc(e,t,s,g){return withConfigSpan(`config.persist`,{"config.scope":configScopeAttr(t),"config.transport":`fs`},async S=>{let w=await storeConfigDocInner(e,t,s,g);return S.setAttribute(`config.outcome`,persistOutcomeAttr(w)),w})}function persistOutcomeAttr(e){return e===`reverted`?`reverted`:e===`write-failed`?`rejected`:`success`}async function storeConfigDocInner(e,t,s,g){if(g.ephemeral&&t===`__config__/okignore`||s===CONFIG_VALIDATION_REVERT_ORIGIN)return`no-op`;let S=e.getText(`source`),w=S.toString(),E=g.lkgCache.get(t);if(w.length===0&&(t!==`__config__/okignore`||E===void 0||E===``)||E!==void 0&&w===E)return`no-op`;let D=configScopeAttr(t),O=withConfigSpanSync(`config.validate`,{"config.scope":D,"config.validation.layer":`L3`},e=>{let s=validateConfigContent(t,w);return e.setAttribute(`config.outcome`,s.ok?`success`:`rejected`),s.ok||emitSchemaInvalidIssueEvents(s.error),s});if(!O.ok)return await withConfigSpan(`config.revert`,{"config.scope":D,"config.outcome":`reverted`},async()=>{let s=E??defaultLkgFor(t);e.transact(()=>{S.length>0&&S.delete(0,S.length),S.insert(0,s)},CONFIG_VALIDATION_REVERT_ORIGIN),E===void 0&&g.lkgCache.set(t,s),t===`__config__/okignore`&&isKnownConfigError(O.error)&&okignoreRejectionCounter().add(1,{"error.code":O.error.code}),g.onConfigRejected?.(t,O.error)}),`reverted`;let k=configDocAbsPath(t,g);try{await tracedMkdir(dirname(k),{recursive:!0})}catch(e){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] could not create parent dir for ${k}: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not create parent directory for ${k}: ${s}`}),`write-failed`}try{return await withFileLock(`${k}.lock`,async()=>{let s=null;try{s=readFileSync(k,`utf-8`)}catch(e){if(e.code!==`ENOENT`){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] could not read config for reconciliation: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not read config for reconciliation at ${k}: ${s}`}),`write-failed`}}if(s!==null&&E!==void 0&&s!==E){if(validateConfigContent(t,s).ok)return e.transact(()=>{S.length>0&&S.delete(0,S.length),S.insert(0,s)},CONFIG_FILE_WATCHER_ORIGIN),g.lkgCache.set(t,s),getLogger(`config-persistence`).info({docName:t,path:k},`[config-persistence] reconciled: external writer landed; imported disk into Y.Text`),`reconciled`;getLogger(`config-persistence`).warn({docName:t,path:k},`[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write`)}try{await atomicWriteConfig(k,w)}catch(e){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] write-failed at ${k}: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Failed to persist config at ${k}: ${s}`}),`write-failed`}return g.lkgCache.set(t,w),`persisted`},{onWarn:(e,t)=>{getLogger(`config-persistence`).warn(t,`[config-persistence] ${e}`)}})}catch(e){if(e instanceof FileLockTimeoutError)return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] lock timeout at ${k}: ${e.message}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:e.message}),`write-failed`;throw e}}function applyExternalConfigChange(e,t,s,g){if(!e)return`no-op`;let S=g.lkgCache.get(t);if(S!==void 0&&S===s)return`no-op`;let w=configScopeAttr(t),E=withConfigSpanSync(`config.validate`,{"config.scope":w,"config.validation.layer":`L3`},e=>{let g=validateConfigContent(t,s);return e.setAttribute(`config.outcome`,g.ok?`success`:`rejected`),g.ok||emitSchemaInvalidIssueEvents(g.error),g});if(!E.ok)return t===`__config__/okignore`&&isKnownConfigError(E.error)&&okignoreRejectionCounter().add(1,{"error.code":E.error.code}),g.onConfigRejected?.(t,E.error),`rejected`;let D=e.getText(`source`);return e.transact(()=>{D.length>0&&D.delete(0,D.length),D.insert(0,s)},CONFIG_FILE_WATCHER_ORIGIN),g.lkgCache.set(t,s),`applied`}let pendingContributors=new Map;function recordContributor(e,t,s,g,S,w,E,D){let O=pendingContributors.get(t);if(O||(O={writerId:t,displayName:s,colorSeed:g??s,docs:new Set,subjectOverride:S,actor:w,summaries:[],previousPaths:[]},pendingContributors.set(t,O)),O.docs.add(e),S!==void 0&&(O.subjectOverride=S),w!==void 0){let e=O.actor??{};w.principalId!==void 0&&(e.principalId=w.principalId),w.agentType!==void 0&&(e.agentType=w.agentType),w.clientName!==void 0&&(e.clientName=w.clientName),w.clientVersion!==void 0&&(e.clientVersion=w.clientVersion),w.label!==void 0&&(e.label=w.label),O.actor=e}if(typeof E==`string`&&E.length>0&&O.summaries.push(E),D&&D.length>0)for(let e of D)O.previousPaths.push(e)}function swapContributors(){let e=pendingContributors;return pendingContributors=new Map,e}function restoreContributors(e){for(let[t,s]of e){let e=pendingContributors.get(t);e||(e={writerId:t,displayName:s.displayName,colorSeed:s.colorSeed,docs:new Set,actor:s.actor,summaries:[],previousPaths:[]},pendingContributors.set(t,e));for(let t of s.docs)e.docs.add(t);s.summaries.length>0&&(e.summaries=[...s.summaries,...e.summaries]),s.previousPaths.length>0&&(e.previousPaths=[...s.previousPaths,...e.previousPaths])}}function formatContributorsFrom(e){if(e.size===0)return``;let t=[``];for(let s of e.values()){let e={v:1,id:s.writerId,name:s.displayName,colorSeed:s.colorSeed,docs:[...s.docs]};s.summaries.length>0&&(e.summaries=[...s.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
772
772
  `)}function formatContributors(){return formatContributorsFrom(pendingContributors)}function restoreContributorEntry(e,t){let s=pendingContributors.get(e);s||(s={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[],previousPaths:[]},pendingContributors.set(e,s));for(let e of t.docs)s.docs.add(e);t.summaries.length>0&&(s.summaries=[...t.summaries,...s.summaries]),t.previousPaths.length>0&&(s.previousPaths=[...t.previousPaths,...s.previousPaths])}function clearContributors(){pendingContributors.clear()}function contributorCount(){return pendingContributors.size}function hasContributor(e){return pendingContributors.has(e)}const CONFLICT_MARKER_RE=/^(<{7} |={7}$|>{7} |\|{7} )/m;function containsConflictMarkers(e){return CONFLICT_MARKER_RE.test(e)}function splitMarkdownBlocks(e){let t=e.replace(/\n+$/,``);if(!t)return[];let s=t.split(`
773
773
  `),g=[],S=[],w=null;for(let e of s){let t=e.match(/^(`{3,}|~{3,})/);if(t){let e=t[1][0];w?e===w&&(w=null):w=e}w===null&&e.trim()===``&&S.length>0?(g.push(S.join(`
@@ -1711,7 +1711,7 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
1711
1711
  `);function register$16(e,t){e.registerTool(`checkpoint`,{description:DESCRIPTION$16,inputSchema:{summary:summaryArgSchema.describe(`Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({version:string().describe(VERSION_FIELD_DESCRIBE),previewUrl:previewUrlOutputField.describe(`Always null — a checkpoint is project-wide, not scoped to one doc.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=t.identityRef?.current,w=await httpPost(g,`/api/save-version`,{...e.summary===void 0?{}:{summary:e.summary},...S?{writers:[{id:`agent-${S.connectionId}`,name:S.displayName,email:`agent-${S.connectionId}@openknowledge.local`}]}:{}});if(!w.ok)return textResult(`Error: ${w.error}`,!0);let E=typeof w.checkpointRef==`string`?w.checkpointRef:``,D=E.split(`/`).pop()??``;return/^[0-9a-f]{40}$/i.test(D)?textPlusStructured(`Checkpoint saved. Version: ${D}`,{version:D,previewUrl:null}):textResult(`Error: checkpoint committed but the server returned no usable version ref ("${E}"). Find the latest checkpoint via \`history\`.`,!0)})}const DESCRIPTION$15=[`[Operates on disk; no running OK server required] Read the effective merged Open Knowledge config (defaults → user → project).`,``,`Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.`,``,"Read returns the FULL merged config or a sub-tree when `key` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, and `github.*` config sub-trees, plus `preview.baseUrl` and `preview.scriptSrc`, were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or, for the preview iframe, a fixed open network policy). Reading those keys returns `exists: false`. (`appearance.preview.autoOpen` is still a live key.)",``,`**Parameters:**`,'- `key` (optional) — Dotted config key. `"content"` returns the content sub-tree; `"appearance.theme"` returns just that leaf. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
1712
1712
  `),InputSchema$3={key:string().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$5=outputSchemaWithText({value:unknown().describe(`Resolved config value at the requested path (or full config).`),exists:boolean().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:string().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)});function readConfigPath(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s)return;s=s[e]}return s}function register$15(e,t){e.registerTool(`config`,{description:DESCRIPTION$15,inputSchema:InputSchema$3,outputSchema:OutputSchema$5,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=e.key?e.key.split(`.`).filter(e=>e.length>0):[],S=g.length>0?readConfigPath(s.config,g):s.config;return g.length>0&&S===void 0?textPlusStructured(`(no value at ${e.key})`,{value:null,exists:!1,...e.key?{key:e.key}:{}}):textPlusStructured(JSON.stringify(S,null,2),{value:S,exists:!0,...e.key?{key:e.key}:{}})})}const DESCRIPTION$14=["[Requires: Hocuspocus server] Read GitHub-sync merge conflicts. Dispatches on `kind`:",``,'- `kind: "list"` — enumerate every doc currently tracked in a merge-conflict state. Returns `{ list: [{ file, detectedAt, ... }] }` (empty when none). The entry point to the resolve flow.','- `kind: "content"` — fetch the three merge stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, lifecycleStatus } }`. `ours` reflects the live Y.Text (what the human sees) when the doc is loaded server-side.',``,`**Parameters:**`,"- `kind` — `list` | `content`.",'- `file` — Required for `kind: "content"`. Relative path WITH the `.md`/`.mdx` extension (e.g. `notes/sso.md`) — git stages key on the exact path, so do NOT strip the extension.',``,"The `shape` field discriminates the conflict: `both-modified` (both sides edited), `delete-modify` (you deleted, they edited — `ours` empty), or `modify-delete` (you edited, they deleted — `theirs` empty). Use it to pick the `resolve_conflict` strategy."].join(`
1713
1713
  `);function register$14(e,t){e.registerTool(`conflicts`,{description:DESCRIPTION$14,inputSchema:{kind:_enum([`list`,`content`]).describe("`list` enumerates tracked conflicts; `content` fetches one file's stages."),file:string().min(1).optional().describe('Required when `kind: "content"`. Conflicted file WITH extension (e.g. `notes/sso.md`) — git stages key on the exact path, so keep the extension (DD2).'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({list:looseObjectArray.optional().describe('`kind: "list"` — every tracked conflict (`{ file, detectedAt, ... }`).'),content:object$1({file:string().describe(`The conflicted file.`),base:string().describe(`Merge-base stage content.`),ours:string().describe(`Our stage (live Y.Text when loaded server-side).`),theirs:string().describe(`Their stage content.`),shape:_enum([`both-modified`,`delete-modify`,`modify-delete`]).describe("Conflict shape — pick the `resolve_conflict` strategy from it."),lifecycleStatus:string().nullable().describe(`The doc's lifecycle status, or null.`)}).optional().describe('`kind: "content"` — the three merge stages + shape + lifecycle.')}),annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.kind===`content`){if(!e.file)return textResult('Error: `kind: "content"` requires `file` — the conflicted file WITH extension, e.g. conflicts({ kind: "content", file: "notes/sso.md" }).',!0);let t=await httpGet(g,`/api/sync/conflict-content${`?file=${encodeURIComponent(e.file)}&source=ytext`}`);if(!t.ok){let e=t.error,s=typeof t.detail==`string`?t.detail:void 0;return textResult(`Error: ${s?`${e} — ${s}`:e}`,!0)}let s=t,S=typeof s.file==`string`?s.file:e.file,w=typeof s.base==`string`?s.base:``,E=typeof s.ours==`string`?s.ours:``,D=typeof s.theirs==`string`?s.theirs:``,O=s.kind===`delete-modify`||s.kind===`modify-delete`?s.kind:`both-modified`,k=typeof s.lifecycleStatus==`string`?s.lifecycleStatus:null;return textPlusStructured(`Conflict stages for ${S} (shape: ${O})${k?` (lifecycle: ${k})`:``}:\n--- base ---\n${w}\n--- ours ---\n${E}\n--- theirs ---\n${D}`,{content:{file:S,base:w,ours:E,theirs:D,shape:O,lifecycleStatus:k}})}let S=await httpGet(g,`/api/sync/conflicts`);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let w=S.conflicts,E=Array.isArray(w)?w:[];return textPlusStructured(E.length===0?`No conflicts tracked.`:`Tracked conflicts (${E.length}):\n${E.map(e=>`- ${e&&typeof e==`object`&&`file`in e?String(e.file??``):``}`).join(`
1714
- `)}`,{list:E})})}const PREVIEW_URL_SOURCES=[`lock`];function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function encodeFolderRoute(e){let t=e.replace(/^\/+|\/+$/g,``);return t?`${encodeDocName(t)}/`:``}const START_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',ATTACH_PREVIEW_ONCE_MESSAGE="No browser is attached to the preview. Open it in your host's surface: `preview_start` (Claude Code Desktop pane), or `preview_url` then navigate your in-app browser to the url (Cursor's `Navigate` / Codex desktop `@Browser`); on the Claude Code CLI, `ok open <doc>`.";function buildPreviewAttachWarning(e,t){return e?{action:`attach-preview-once`,previewUrl:e.url,message:ATTACH_PREVIEW_ONCE_MESSAGE,autoOpen:t}:{action:`start-ui`,previewUrl:null,message:START_UI_MESSAGE,autoOpen:t}}const START_UI_TEXT_HINT=START_UI_MESSAGE;async function resolvePreviewUrlForTool(e,t,s){return resolvePreviewUrl(e,{lockDir:resolveLockDir(s??await t.resolveCwd())})}function resolveUiInfo(e){try{let t=readUiLock(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while resolving ui info: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null}}async function awaitUiBaseUrl(e,t){let s=Date.now()+t.timeoutMs;for(;;){let{baseUrl:g}=resolveUiInfo(e);if(g!==null)return g;if(Date.now()>=s)return null;await new Promise(e=>setTimeout(e,t.pollIntervalMs))}}async function buildListResolver(e,t){let s={lockDir:resolveLockDir(t??await e.resolveCwd())};return{resolve:e=>resolvePreviewUrl(e,s)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let s=`/#/${encodeDocName(e)}`;try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:s,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const FrontmatterPatchValue=union([FrontmatterValueSchema,_null()]),FrontmatterArg=record(string(),FrontmatterPatchValue).describe(`Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a top-level key to null to delete it; keys you omit are unchanged. A nested object REPLACES the existing subtree at that key (send the full subtree you want). Example: { title: "Q3 Planning", tags: ["planning"], metadata: { version: "1.0", author: "Inkeep" } }.`),PositionArg=_enum([`append`,`prepend`,`replace`]).describe(`Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). append / prepend = add to the end / start.`);function splitTargetPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),s=t.lastIndexOf(`/`);return s===-1?{folder:``,name:t}:{folder:t.slice(0,s),name:t.slice(s+1)}}const TEMPLATE_NAME_REGEX=/^[A-Za-z0-9_-]+$/,TEMPLATE_PATH_DESCRIBE='Template path = `<folder>/<name>` (e.g. "fishing-log/trip-log"). The slashes are the folder it belongs to; the final segment is the template name (letters, digits, `_`, `-` only — no dots/spaces). Stored at `<folder>/.ok/templates/<name>.md`.',TEMPLATE_CONTENT_DESCRIBE="Template Markdown body. Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time.";function resolveTemplatePath(e){let{folder:t,name:s}=splitTargetPath(e);return TEMPLATE_NAME_REGEX.test(s)?{ok:!0,folder:t,name:s}:{ok:!1,error:`the final segment of a template path is its name — "${s}" must be letters, digits, \`_\`, \`-\` only (no dots/spaces). e.g. { template: { path: "fishing-log/trip-log" } }.`}}function exactlyOneTargetError(e,t){let s=t.filter(t=>e[t]!==void 0);if(s.length===1)return null;let g=t.map(e=>`\`${e}\``).join(`, `);return s.length===0?`Name exactly one of ${g} — the one thing you are addressing. Nest that target's fields under its key (e.g. \`{ document: { path, … } }\`); see this tool's parameter docs for which fields each target takes.`:`You named ${s.map(e=>`\`${e}\``).join(` and `)} — name exactly ONE target.`}const DESCRIPTION$13=["Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, or `asset`.",``,"- `document` — Doc path(s) to delete (a single path or an array). Inbound links become redlinks. Irreversible. [Requires: Hocuspocus server]","- `folder` — Folder path to delete (recursive). [Requires: Hocuspocus server]",'- `template` — `{ path: "<folder>/<name>" }` — a template to delete (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]','- `asset` — `{ path: "<folder>/<file.ext>" }` — a binary asset to delete. [Requires: Hocuspocus server]',``,'Call `links({ kind: "backlinks", document })` BEFORE deleting a doc to see what links here.'].join(`
1714
+ `)}`,{list:E})})}const PREVIEW_URL_SOURCES=[`lock`];function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function encodeFolderRoute(e){let t=e.replace(/^\/+|\/+$/g,``);return t?`${encodeDocName(t)}/`:``}const START_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',ATTACH_PREVIEW_ONCE_MESSAGE="No browser is attached to the preview. Open it in your host's surface: `preview_start` (Claude Code Desktop pane), or `preview_url` then navigate your in-app browser to the url (Cursor's `Navigate` / Codex desktop `@Browser`); on the Claude Code CLI, `ok open <doc>`.";function buildPreviewAttachWarning(e,t){return e?{action:`attach-preview-once`,previewUrl:e.url,message:ATTACH_PREVIEW_ONCE_MESSAGE,autoOpen:t}:{action:`start-ui`,previewUrl:null,message:START_UI_MESSAGE,autoOpen:t}}const START_UI_TEXT_HINT=START_UI_MESSAGE;async function resolvePreviewUrlForTool(e,t,s){return resolvePreviewUrl(e,{lockDir:resolveLockDir(s??await t.resolveCwd())})}function resolveUiInfo(e){try{let t=readUiLock(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while resolving ui info: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null}}async function awaitUiBaseUrl(e,t){let s=Date.now()+t.timeoutMs;for(;;){let{baseUrl:g}=resolveUiInfo(e);if(g!==null)return g;if(Date.now()>=s)return null;await new Promise(e=>setTimeout(e,t.pollIntervalMs))}}async function buildListResolver(e,t){let s={lockDir:resolveLockDir(t??await e.resolveCwd())};return{resolve:e=>resolvePreviewUrl(e,s)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let s=`/#/${encodeDocName(e)}`;try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:s,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const FrontmatterPatchValue=union([FrontmatterValueSchema,_null()]),FrontmatterArg=record(string(),FrontmatterPatchValue).describe(`Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a top-level key to null to delete it; keys you omit are unchanged. A nested object REPLACES the existing subtree at that key (send the full subtree you want). Example: { title: "Q3 Planning", tags: ["planning"], metadata: { version: "1.0", author: "Inkeep" } }.`),PositionArg=_enum([`append`,`prepend`,`replace`]).describe(`Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). append / prepend = add to the end / start.`),DocExtensionArg=_enum(SUPPORTED_DOC_EXTENSIONS).describe("File format for a NEW doc: `.md` (default) or `.mdx` (Markdown + JSX components). Honored only on create — an existing doc keeps its on-disk extension. Takes precedence over an extension typed into `path`.");function splitTargetPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),s=t.lastIndexOf(`/`);return s===-1?{folder:``,name:t}:{folder:t.slice(0,s),name:t.slice(s+1)}}const TEMPLATE_NAME_REGEX=/^[A-Za-z0-9_-]+$/,TEMPLATE_PATH_DESCRIBE='Template path = `<folder>/<name>` (e.g. "fishing-log/trip-log"). The slashes are the folder it belongs to; the final segment is the template name (letters, digits, `_`, `-` only — no dots/spaces). Stored at `<folder>/.ok/templates/<name>.md`.',TEMPLATE_CONTENT_DESCRIBE="Template Markdown body. Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time.";function resolveTemplatePath(e){let{folder:t,name:s}=splitTargetPath(e);return TEMPLATE_NAME_REGEX.test(s)?{ok:!0,folder:t,name:s}:{ok:!1,error:`the final segment of a template path is its name — "${s}" must be letters, digits, \`_\`, \`-\` only (no dots/spaces). e.g. { template: { path: "fishing-log/trip-log" } }.`}}function exactlyOneTargetError(e,t){let s=t.filter(t=>e[t]!==void 0);if(s.length===1)return null;let g=t.map(e=>`\`${e}\``).join(`, `);return s.length===0?`Name exactly one of ${g} — the one thing you are addressing. Nest that target's fields under its key (e.g. \`{ document: { path, … } }\`); see this tool's parameter docs for which fields each target takes.`:`You named ${s.map(e=>`\`${e}\``).join(` and `)} — name exactly ONE target.`}const DESCRIPTION$13=["Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, or `asset`.",``,"- `document` — Doc path(s) to delete (a single path or an array). Inbound links become redlinks. Irreversible. [Requires: Hocuspocus server]","- `folder` — Folder path to delete (recursive). [Requires: Hocuspocus server]",'- `template` — `{ path: "<folder>/<name>" }` — a template to delete (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]','- `asset` — `{ path: "<folder>/<file.ext>" }` — a binary asset to delete. [Requires: Hocuspocus server]',``,'Call `links({ kind: "backlinks", document })` BEFORE deleting a doc to see what links here.'].join(`
1715
1715
  `);function parseDeletedDocNames(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}async function deleteOneDoc(e,t,s,g){let S=normalizeDocName(e);if(!S.ok)return{docName:e,ok:!1,error:S.error.replace(/^Error:\s*/,``)};let w=await httpPost(t,`/api/delete-path`,{kind:`file`,path:S.docName,...agentIdentityFields(g.identityRef?.current)});if(!w.ok)return{docName:S.docName,ok:!1,error:w.error};let E=parseDeletedDocNames(w.deletedDocNames),D=await resolvePreviewUrlForTool(S.docName,{config:g.config,resolveCwd:g.resolveCwd},s);return{docName:S.docName,ok:!0,deletedDocNames:E.length>0?E:[S.docName],...D?{previousPreviewUrl:D.url}:{}}}function register$13(e,t){e.registerTool(`delete`,{description:DESCRIPTION$13,inputSchema:{document:union([string(),array(string()).min(1),object$1({path:union([string(),array(string()).min(1)])})]).optional().describe("Doc path(s) to delete — a string, an array, or `{ path }`. Inbound links become redlinks. Irreversible."),folder:union([string(),object$1({path:string()})]).optional().describe("Folder path to delete (recursive) — a string or `{ path }`."),template:object$1({path:string().describe("Template path = `<folder>/<name>`.")}).optional().describe(`A template to delete.`),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are its folder. Example: "images/diagram.png".`)}).optional().describe(`A binary asset to delete.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({ok:boolean(),deletedDocNames:array(string()).optional().describe(`The single docName removed (a document delete never cascades to descendants).`),error:string().optional().describe("Present when `ok` is false.")}).optional().describe(`Single-document delete result.`),folder:object$1({ok:boolean(),deletedDocNames:array(string())}).optional().describe(`Folder delete result (docNames removed).`),template:object$1({ok:boolean(),existed:boolean()}).optional().describe(`Template delete result.`),asset:object$1({ok:boolean(),path:string()}).optional().describe(`Asset delete result.`),documents:looseObjectArray.optional().describe(`Batch doc delete: per-doc result records.`),previousPreviewUrl:previousPreviewUrlField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s,w=typeof e.folder==`object`?e.folder.path:e.folder,E=e.document&&typeof e.document==`object`&&!Array.isArray(e.document)?e.document.path:e.document,D=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`]);if(D)return textResult(`Error: ${D}`,!0);if(e.template!==void 0){let s=resolveTemplatePath(e.template.path);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{folder:g,name:w}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=new URLSearchParams({folder:g,name:w});for(let[e,s]of Object.entries(agentIdentityFields(t.identityRef?.current)))typeof s==`string`&&s.length>0&&E.set(e,s);let D=await httpDelete(S,`/api/template?${E.toString()}`);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.existed===!0;return textPlusStructured(O?`Deleted template "${w}" from ${g||`(root)`}.`:`Template "${w}" did not exist in ${g||`(root)`} — nothing to delete.`,{template:{ok:!0,existed:O}})}if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.folder!==void 0){let e=await httpPost(S,`/api/delete-path`,{kind:`folder`,path:w,...agentIdentityFields(t.identityRef?.current)});if(!e.ok)return textResult(`Error: ${e.error}`,!0);let s=parseDeletedDocNames(e.deletedDocNames);return textPlusStructured(`Deleted folder ${w}${s.length?` (${s.length} doc(s))`:``}.`,{folder:{ok:!0,deletedDocNames:s}})}if(e.asset!==void 0){let s=e.asset.path.replace(/^\/+/,``).replace(/\/+$/,``),g=await httpPost(S,`/api/delete-path`,{kind:`asset`,path:s,...agentIdentityFields(t.identityRef?.current)});return g.ok?textPlusStructured(`Deleted asset ${s}.`,{asset:{ok:!0,path:s}}):textResult(`Error: ${g.error}`,!0)}let O=E;if(Array.isArray(O)){let e=await Promise.all(O.map(e=>deleteOneDoc(e,S,g,t))),s=e.filter(e=>e.ok).length,w=s===e.length,E=e.map(e=>e.ok?`Deleted ${e.docName}.`:`Failed ${e.docName}: ${e.error}`);return textPlusStructured(`${s}/${e.length} deleted.\n${E.join(`
1716
1716
  `)}`,{documents:e},!w)}let k=await deleteOneDoc(O,S,g,t);if(!k.ok)return textPlusStructured(`Error: ${k.error??`unknown error`}`,{document:{ok:!1,error:k.error}},!0);let j=k.deletedDocNames??[k.docName];return textPlusStructured(j.length===1?`Deleted ${j[0]}.`:`Deleted ${j.length} documents: ${j.join(`, `)}.`,{document:{ok:!0,deletedDocNames:j},...k.previousPreviewUrl?{previousPreviewUrl:k.previousPreviewUrl}:{}})})}function parseAdvisoryWarnings(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>{let t=AdvisoryWarningSchema.safeParse(e);return t.success?[t.data]:[]});return t.length>0?t:void 0}function integrityEntries(e){return e.filter(e=>e.kind===`content-divergence`||e.kind===`disk-edit-reconciled`)}function renderEntries(e){return e.filter(e=>e.kind===`mermaid-parse-error`)}function formatAdvisoryLines(e){let t=integrityEntries(e).map(formatIntegrityLine),s=renderEntries(e);return s.length>0&&t.push(formatRenderWarningsLine(s)),t}function formatAdvisoryBriefs(e){let t=integrityEntries(e).map(formatIntegrityBrief),s=renderEntries(e);return s.length>0&&t.push(formatRenderWarningsBrief(s)),t}function formatIntegrityLine(e){return e.kind===`content-divergence`?`⚠ Content divergence: ${e.actualBytes} actual bytes vs ${e.intendedBytes} intended (byteDelta=${e.byteDelta}). ${e.hint??`currentState carries the converged content (re-read only if it is truncated).`}`:`⚠ ${e.hint??`An out-of-band edit was reconciled into this document before your edit landed on top — re-read for the combined result.`}`}function formatIntegrityBrief(e){return e.kind===`content-divergence`?`⚠ Content divergence: ${e.actualBytes} actual vs ${e.intendedBytes} intended (byteDelta=${e.byteDelta}).`:`⚠ Out-of-band disk edit reconciled before this write — re-read for the combined result.`}function formatRenderWarningsLine(e){let t=e[0];if(e.length===1&&t){let e=t.line===void 0?``:` (line ${t.line})`,s=t.fenceFirstLine===``?`(empty fence)`:`("${t.fenceFirstLine}")`;return`⚠ Mermaid fence ${t.fenceIndex} ${s} will not render${e}: ${firstMessageLine(t.message)} Fix the fence and re-edit.`}return`⚠ ${e.length>=10?`10+`:String(e.length)} mermaid fences will not render — see structuredContent.document.warnings (kind "mermaid-parse-error") for per-fence errors. Fix the fences and re-edit.`}function formatRenderWarningsBrief(e){return`⚠ ${e.length>=10?`10+`:String(e.length)} mermaid fence${e.length===1?``:`s`} will not render (see warnings).`}function firstMessageLine(e){let t=e.split(`
1717
1717
  `,1)[0]?.trim()??``;return t.endsWith(`.`)||t.endsWith(`:`)?t:`${t}.`}const DESCRIPTION$12=`${["Edit one thing in place. Pass EXACTLY ONE of `document`, `folder`, or `template`. Within each: a body edit (`find` + `replace`) OR a `frontmatter` merge-patch — not both in one call.",``,"- `document` — Edit a doc [Requires: Hocuspocus server]. Body: `{ path, find, replace, occurrence? }` (occurrence = which match, 1 = first). Metadata: `{ path, frontmatter }` (merge-patch; `null` deletes a key). Body find/replace is body-only; frontmatter-intersecting finds are rejected.","- `folder` — Edit a folder (folders have no body): `{ path, frontmatter }` (merge-patch).",'- `template` — Edit a template: `{ path: "<folder>/<name>", ... }`; body `find`/`replace`/`occurrence?` or metadata `frontmatter`.',"- `summary` — Optional one-line user-outcome (≤80 chars) recorded in the timeline for any `document`, `folder`, or `template` edit. Avoid secrets or PII — persisted to git history.",``,'Responses may include `structuredContent.document.warnings` — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc with `exec("cat <path>")`) and `mermaid-parse-error` (the edit landed but that fence will not render — fix it and re-edit).'].join(`
@@ -1730,7 +1730,7 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
1730
1730
  `),UI_BIND_WAIT_TIMEOUT_MS=3e3,UI_BIND_WAIT_POLL_MS=100,InputSchema$2={document:string().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),folder:string().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),armPaneTarget:boolean().optional().describe("When true with a `document` or `folder`, arm that target so a subsequent Claude-pane base-open (`preview_start`) lands there instead of the presence-driven default. TTL-bounded (~30s) so a stale arm cannot hijack a later open."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$4=outputSchemaWithText({url:string().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:string().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:boolean().describe(`Whether a UI is running for the project.`),autoOpen:boolean().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`.")}),NO_UI_SERVER_RUNNING_MESSAGE='The OK server is running but no UI has bound for this project yet. Retry in a few seconds, or start one: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',NO_SERVER_MESSAGE='No Open Knowledge server is running for this project. Start it with `ok start` (also starts the preview UI), use `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',AUTOSTART_DISABLED_NOTE=` Auto-start is disabled (OK_MCP_AUTOSTART=0).`;function isServerLive(e){try{let t=readServerLock(e);return t!==null&&t.port>0&&isProcessAlive(t.pid)}catch(t){return process.stderr.write(`[preview-url] readServerLock failed at ${e} while checking server liveness: ${t instanceof Error?t.message:String(t)}\n`),!1}}function register$10(e,t){e.registerTool(`preview_url`,{description:DESCRIPTION$10,inputSchema:InputSchema$2,outputSchema:OutputSchema$4,annotations:{readOnlyHint:!1,idempotentHint:!0}},async e=>{if(e.document&&e.folder)return{isError:!0,content:[{type:`text`,text:`Error: document and folder are mutually exclusive — pass exactly one.`}]};let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=resolveLockDir(s.cwd),S={lockDir:g},w=s.config.appearance.preview.autoOpen,E=e.document?`#/${encodeDocName(e.document)}`:e.folder?`#/${encodeFolderRoute(e.folder)}`:null;if(e.armPaneTarget&&E)try{armPaneTarget(g,E)}catch{}let D=e.armPaneTarget&&!E?` (note: armPaneTarget was set but no document/folder was given, so nothing was armed)`:``,O=isServerLive(g),k=!1;if(t.serverUrl!==void 0)try{await resolveServerUrl(t.serverUrl,s.cwd)}catch(e){if(e instanceof AutoStartDisabledError)k=!0;else return{isError:!0,content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}]}}let{baseUrl:j}=resolveUiInfo(S);if(j===null&&!O&&isServerLive(g)&&(j=await awaitUiBaseUrl(S,{timeoutMs:t.uiBindWait?.timeoutMs??UI_BIND_WAIT_TIMEOUT_MS,pollIntervalMs:t.uiBindWait?.pollIntervalMs??UI_BIND_WAIT_POLL_MS})),j===null)return textPlusStructured(`${isServerLive(g)?NO_UI_SERVER_RUNNING_MESSAGE:`${NO_SERVER_MESSAGE}${k?AUTOSTART_DISABLED_NOTE:``}`}${D}`,{url:null,baseUrl:null,running:!1,autoOpen:w});let F=E?`${j}/${E}`:j;return textPlusStructured(`Preview URL: ${F}${D}`,{url:F,baseUrl:j,running:!0,autoOpen:w})})}const HistoryEntryOutputSchema=object$1({version:string().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:string().describe(`ISO timestamp of the entry.`),author:string().describe(`Author display name.`),authorEmail:string().describe(`Author email.`),kind:_enum([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:string().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:looseObjectArray.describe(`Per-contributor records parsed from the commit (writer id, name, docs, summaries).`),checkpoint:unknown().nullable().describe(`Checkpoint metadata when this entry is a checkpoint, else null.`)}),DESCRIPTION$9=[`[Requires: Hocuspocus server] List version history for a document, or the activity timeline for a folder.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.",``,"**Parameters (pass EXACTLY ONE of `document` / `folder`):**","- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",'- `folder` — Folder path for the FOLDER timeline: attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter) — who created / edited / renamed / moved / deleted them, when. `""` = project root.',"- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `kind` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
1731
1731
  `);function register$9(e,t){e.registerTool(`history`,{description:DESCRIPTION$9,inputSchema:{document:string().optional().describe("Document name to query history for. Mutually exclusive with `folder`."),folder:string().optional().describe('Folder path to query the FOLDER timeline for — attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter): created / edited / renamed / moved / deleted, by whom, when. Mutually exclusive with `document`. Use `""` for the project root.'),branch:string().optional().describe(`Branch name (default: current branch)`),limit:number().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:number().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),kind:_enum([`checkpoint`,`upstream`,`wip`]).optional().describe("Filter by entry type (`checkpoint` / `upstream` / `wip`)."),author:string().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:string().optional().describe(`Exclude entries by this author name or email`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({entries:array(HistoryEntryOutputSchema).describe("Timeline entries, newest first. Each carries a `version` for `restore_version`."),total:number().int().optional().describe(`Total entries available (pre-pagination).`),truncated:boolean().optional().describe(`Whether more entries exist beyond this returned page (the result was limit-capped).`),previewUrl:previewUrlOutputField,previewUrlSource:previewUrlSourceField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=e.folder!==void 0;if(w===(e.document!==void 0))return textResult("Error: pass EXACTLY ONE of `document` or `folder`.",!0);let E=new URLSearchParams,D=null;if(w)E.set(`folder`,e.folder??``);else{let t=normalizeDocName(e.document);if(!t.ok)return textResult(t.error,!0);E.set(`docName`,t.docName),D=t.docName}e.branch&&E.set(`branch`,e.branch),e.limit!=null&&E.set(`limit`,String(e.limit)),e.offset!=null&&E.set(`offset`,String(e.offset)),e.kind&&E.set(`type`,e.kind),e.author&&E.set(`author`,e.author),e.excludeAuthor&&E.set(`excludeAuthor`,e.excludeAuthor);let O=await httpGet(S,`/api/history?${E.toString()}`);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let{ok:k,...j}=O,F=(Array.isArray(j.entries)?j.entries:[]).map(e=>{let t=e;return{version:t.sha,timestamp:t.timestamp,author:t.author,authorEmail:t.authorEmail,kind:t.type,message:t.message,contributors:t.contributors,checkpoint:t.checkpoint??null}}),L=j.total,B=j.hasMore,H=D?await resolvePreviewUrlForTool(D,{config:t.config,resolveCwd:t.resolveCwd},g):null,q={entries:F,...typeof L==`number`?{total:L}:{},...typeof B==`boolean`?{truncated:B}:{}};return textPlusStructured(JSON.stringify(q,null,2),{...q,previewUrl:H?.url??null,...H?{previewUrlSource:H.source}:{}})})}const LINK_KINDS=[`backlinks`,`forward`,`dead`,`orphans`,`hubs`,`suggest`],DESCRIPTION$8=["[Requires: Hocuspocus server] Read the wiki-link graph. `kind` takes one value, or an array for a one-call audit — results merge into a single payload; any per-kind failure lands in an `errors` map.",``,'- `backlinks` / `forward` / `suggest` — operate on one page; require `document`. `suggest` finds prose mentions of the page not yet wrapped in link syntax. Each mention returns an `excerpt` (a normalized, `…`-trimmed snippet for context — NOT an edit-ready literal) plus an `offset`. To wrap one: re-read the doc (`exec("cat …")`), find the real mention text, and `edit` it into a `[[wiki-link]]`.',"- `dead` — missing internal link targets corpus-wide; optional `sourceDocuments` filter (OR semantics).","- `orphans` — disconnected pages; optional `mode`: `incoming` | `outgoing` | `both`.","- `hubs` — most-linked pages; optional `limit` (default 20)."].join(`
1732
1732
  `);function register$8(e,t){e.registerTool(`links`,{description:DESCRIPTION$8,inputSchema:{kind:union([_enum(LINK_KINDS),array(_enum(LINK_KINDS)).min(1)]).describe(`Link-graph view(s) to return — one kind, or an array to fetch several in one call (e.g. ["dead","orphans","hubs"] for a graph audit).`),document:string().optional().describe(`Target page (path, extension-less). Required for kind=backlinks|forward|suggest.`),sourceDocuments:array(string()).optional().describe(`Referring source docs to narrow the audit with OR semantics. Used by kind=dead.`),mode:_enum(ORPHAN_MODES).optional().describe(`Filter which type of graph disconnection to surface. Used by kind=orphans.`),limit:number().int().positive().max(100).optional().describe(`Maximum number of hubs to return (default 20, max 100). Used by kind=hubs.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({backlinks:looseObjectArray.optional().describe(`kind=backlinks: pages that link TO the target.`),forwardLinks:looseObjectArray.optional().describe(`kind=forward: links FROM the target (doc + external).`),deadLinks:looseObjectArray.optional().describe(`kind=dead: internal links whose target does not exist.`),orphans:looseObjectArray.optional().describe(`kind=orphans: disconnected pages.`),hubs:looseObjectArray.optional().describe(`kind=hubs: the most-linked pages.`),suggest:record(string(),unknown()).optional().describe("kind=suggest: `{ mentions: [{ source, excerpt, offset }], previewUrl }` — `excerpt` is a `…`-trimmed context snippet (re-read the doc for the real text before `edit`)."),errors:record(string(),string()).optional().describe("Per-kind failures on a multi-kind call: `{ kind: message }`."),cwd:string().describe(`Absolute directory the read ran against.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=Array.isArray(e.kind)?[...new Set(e.kind)]:[e.kind],{resolve:E}=await buildListResolver(t,g),D=await Promise.all(w.map(s=>runKind(s,e,S,g,t,E))),O={},k={};if(w.forEach((e,t)=>{let s=D[t];s.ok?Object.assign(O,s.data):k[e]=s.error}),Object.keys(O).length===0){let e=w.length===1?k[w[0]]:`All requested link kinds failed: ${JSON.stringify(k)}`;return textResult(e.startsWith(`Error`)?e:`Error: ${e}`,!0)}let j={...O,...Object.keys(k).length>0?{errors:k}:{},cwd:g};return textPlusStructured(JSON.stringify(j,null,2),j)})}function runKind(e,t,s,g,S,w){switch(e){case`backlinks`:return runBacklinks(t,s,w);case`forward`:return runForwardLinks(t,s,w);case`dead`:return runDeadLinks(t,s,w);case`orphans`:return runOrphans(t,s,w);case`hubs`:return runHubs(t,s,w);case`suggest`:return runSuggest(t,s,g,S)}}async function runBacklinks(e,t,s){if(!e.document)return{ok:!1,error:"kind=backlinks requires `document`."};let g=normalizeDocName(e.document);if(!g.ok)return{ok:!1,error:g.error};let S=await httpGet(t,`/api/backlinks?docName=${encodeURIComponent(g.docName)}`);if(!S.ok)return{ok:!1,error:String(S.error)};let{ok:w,...E}=S;return{ok:!0,data:{backlinks:(E.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runForwardLinks(e,t,s){if(!e.document)return{ok:!1,error:"kind=forward requires `document`."};let g=normalizeDocName(e.document);if(!g.ok)return{ok:!1,error:g.error};let S=await httpGet(t,`/api/forward-links?docName=${encodeURIComponent(g.docName)}`);if(!S.ok)return{ok:!1,error:String(S.error)};let{ok:w,...E}=S;return{ok:!0,data:{forwardLinks:(E.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runDeadLinks(e,t,s){let g=new URLSearchParams;for(let t of e.sourceDocuments??[]){let e=normalizeDocName(t);if(!e.ok)return{ok:!1,error:e.error};g.append(`sourceDocName`,e.docName)}let S=g.toString(),w=await httpGet(t,`/api/dead-links${S?`?${S}`:``}`);if(!w.ok)return{ok:!1,error:String(w.error)};let{ok:E,...D}=w;return{ok:!0,data:{deadLinks:(D.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,g=t?s(t):null,S=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}});return{...e,sources:S,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runOrphans(e,t,s){let g=await httpGet(t,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!g.ok)return{ok:!1,error:String(g.error)};let{ok:S,...w}=g;return{ok:!0,data:{orphans:(w.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runHubs(e,t,s){let g=await httpGet(t,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!g.ok)return{ok:!1,error:String(g.error)};let{ok:S,...w}=g;return{ok:!0,data:{hubs:(w.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runSuggest(e,t,s,g){if(!e.document)return{ok:!1,error:"kind=suggest requires `document`."};let S=normalizeDocName(e.document);if(!S.ok)return{ok:!1,error:S.error};let w=await httpGet(t,`/api/suggest-links?docName=${encodeURIComponent(S.docName)}`);if(!w.ok)return{ok:!1,error:String(w.error)};let{ok:E,...D}=w,O=await resolvePreviewUrlForTool(S.docName,{config:g.config,resolveCwd:g.resolveCwd},s);return{ok:!0,data:{suggest:{...D,previewUrl:O?.url??null,...O?{previewUrlSource:O.source}:{}}}}}const DESCRIPTION$7=["[Requires: Hocuspocus server] Move or rename a document, folder, or asset through the managed flow at `POST /api/rename-path`. Works for all three — the tool probes the content directory to decide. Inbound wiki-links plus supported inline Markdown links are rewritten across affected docs; renamed assets are reported.",``,`**Parameters:**`,"- `from` — Current path. Doc: docName (trailing `.md`/`.mdx` stripped). Folder: relative path, no leading/trailing slash. Asset: the file path incl. extension.","- `to` — New path. Same shape as `from`.",'- `template` — Move/rename a TEMPLATE instead of a doc/folder/asset: `{ from: "<folder>/<name>", to: "<folder>/<name>" }` (nested — a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc). Mutually exclusive with flat `from`/`to`. Inherited templates are not moved (move the local copy / the owning folder); templates carry no inbound links, so nothing is rewritten.','- `summary` — Optional one-line user-outcome (≤80 chars). If omitted, defaults to "Renamed X → Y". Avoid secrets or PII — persisted to git history.',``,"**Errors:** 400 — invalid path / excluded by `.gitignore`/`.okignore`; 404 — source does not exist; 409 — destination already exists (`colliding[]` returned)."].join(`
1733
- `);function parseRenameMappings(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromDocName:t,toDocName:s}]:[]}):[]}function parseRewrittenDocs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:s}=e;return typeof t==`string`&&typeof s==`number`?[{docName:t,rewrites:s}]:[]}):[]}function parseRenamedAssets(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromPath:t,toPath:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromPath:t,toPath:s}]:[]}):[]}function isValidFolderPath(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`..`))}function pluralize(e,t,s=`${t}s`){return e===1?t:s}function resolveMoveKind(e,t){let s=resolveWithinRoot(e,t);if(!s.ok)return null;let g=s.abs;if(existsSync(g))try{let e=statSync(g);if(e.isDirectory())return`folder`;if(e.isFile())return g.endsWith(`.md`)||g.endsWith(`.mdx`)?`file`:`asset`}catch(e){let t=e.code;if(t===`EACCES`||t===`EPERM`)return`file`}for(let e of[`.md`,`.mdx`])if(existsSync(`${g}${e}`))return`file`;return null}function register$7(e,t){e.registerTool(`move`,{description:DESCRIPTION$7,inputSchema:{from:string().optional().describe(`Current path of a document, folder, or asset (auto-detected).`),to:string().optional().describe(`New path. All inbound wiki-links + inline links are rewritten automatically.`),template:object$1({from:string(),to:string()}).optional().describe('Move/rename a TEMPLATE instead: `{ from: "<folder>/<name>", to: "<folder>/<name>" }`. Nested because a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc. Mutually exclusive with flat `from`/`to`.'),summary:summaryArgSchema.describe(`Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({ok:boolean().describe(`Whether the move succeeded.`),kind:_enum([`file`,`folder`,`asset`,`template`]).optional().describe("What was moved (`file`/`folder`/`asset` auto-detected from `from`; `template` when the `template` target was used)."),committed:boolean().optional().describe("Template move only: `true` = tracked `git mv` (history preserved), `false` = plain disk rename (untracked / local-only `.ok/`)."),renamed:array(object$1({fromDocName:string(),toDocName:string()})).optional().describe(`docName remappings performed.`),rewrittenDocs:looseObjectArray.optional().describe(`Docs whose inbound links were rewritten.`),renamedAssets:looseObjectArray.optional().describe(`Referenced assets that were moved alongside.`),previewUrls:record(string(),string()).optional().describe(`Route-only preview URL per new docName.`),previewUrlSource:previewUrlSourceField,previousPreviewUrl:previousPreviewUrlField,summary:summaryOutputSchema.optional(),error:string().optional().describe("Present when `ok` is false."),colliding:looseObjectArray.optional().describe(`On a 409 collision: the conflicting from→to pairs.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.template!==void 0){if(e.from!==void 0||e.to!==void 0)return textResult("Error: pass EITHER flat `from`/`to` (document/folder/asset) OR `template: { from, to }` — not both.",!0);let s=resolveTemplatePath(e.template.from);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let g=resolveTemplatePath(e.template.to);if(!g.ok)return textResult(`Error: ${g.error}`,!0);let S=await httpPost(w,`/api/template`,{fromFolder:s.folder,fromName:s.name,toFolder:g.folder,toName:g.name,...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(t.identityRef?.current)});if(!S.ok){let e=typeof S.error==`string`?S.error:`Template move failed`;return textPlusStructured(`Error: ${e}`,{ok:!1,kind:`template`,error:e},!0)}let E=S.committed===!0,D=typeof S.from==`string`?S.from:e.template.from,O=typeof S.to==`string`?S.to:e.template.to;return textPlusStructured(`${E?`Renamed`:`Moved`} template ${D} → ${O}.${E?``:" (Untracked `.ok/` — moved on disk without git history.)"}`,{ok:!0,kind:`template`,committed:E})}if(e.from===void 0||e.to===void 0)return textResult("Error: provide both `from` and `to` (or use `template: { from, to }` to move a template).",!0);let E=join(g,S.content.dir),D=resolveMoveKind(E,e.from);if(D===null){let t=resolveTemplatePath(e.from);return t.ok&&existsSync(join(E,t.folder,`.ok`,`templates`,`${t.name}.md`))?textResult(`Error: \`${e.from}\` is a template, not a doc/folder/asset. Move it with \`move({ template: { from: "${e.from}", to: "<folder>/<newName>" } })\`.`,!0):textResult(`Error: \`${e.from}\` does not exist as a doc, folder, or asset under the content directory.`,!0)}let O=e.from,k=e.to;if(D===`file`){let t=normalizeDocName(e.from);if(!t.ok)return textResult(t.error,!0);let s=normalizeDocName(e.to);if(!s.ok)return textResult(s.error,!0);O=t.docName,k=s.docName}else if(D===`folder`&&(!isValidFolderPath(e.from)||!isValidFolderPath(e.to)))return textResult("Error: folder `from`/`to` must be relative paths with no leading/trailing slash.",!0);let j=await httpPost(w,`/api/rename-path`,{kind:D,fromPath:O,toPath:k,...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(t.identityRef?.current)});if(!j.ok){let e=j.error,t=parseRenameCollidingPairs(j.colliding),s={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return textPlusStructured(`Error: ${e}`,s,!0)}let F=parseRenameMappings(j.renamed),L=parseRewrittenDocs(j.rewrittenDocs),B=parseRenamedAssets(j.renamedAssets),H={config:t.config,resolveCwd:t.resolveCwd},q={},ee,J;if(D===`file`){let e=await resolvePreviewUrlForTool(k,H,g),t=await resolvePreviewUrlForTool(O,H,g);e&&(q[k]=e.url,ee=e.source),t&&(J=t.url)}else if(D===`folder`)for(let{toDocName:e}of F){let t=await resolvePreviewUrlForTool(e,H,g);t&&(q[e]=t.url,ee??=t.source)}let Y=j.summary&&typeof j.summary==`object`?j.summary:void 0,te=typeof Y?.hint==`string`?Y.hint:void 0,ne=[];if(D===`asset`)ne.push(`Moved asset ${O} → ${k}.`);else if(D===`folder`)ne.push(F.length===0?`No managed docs under ${e.from}/ — nothing to rename. Empty folders are not tracked.`:`Renamed folder ${e.from}/ → ${e.to}/ (${F.length} doc${F.length===1?``:`s`}, ${L.length} rewrite${L.length===1?``:`s`}).`);else{let e=F.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${O} -> ${k}`,t=L.length===0?`No inbound links required updates.`:`Rewrote ${L.length} ${pluralize(L.length,`document`)}.`;ne.push(`Renamed ${e}. ${t}`)}return B.length>0&&ne.push(`Moved ${B.length} referenced ${pluralize(B.length,`asset`)}.`),te&&ne.push(te),textPlusStructured(ne.join(`
1733
+ `);function parseRenameMappings(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromDocName:t,toDocName:s}]:[]}):[]}function parseRewrittenDocs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:s}=e;return typeof t==`string`&&typeof s==`number`?[{docName:t,rewrites:s}]:[]}):[]}function parseRenamedAssets(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromPath:t,toPath:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromPath:t,toPath:s}]:[]}):[]}function isValidFolderPath(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`..`))}function pluralize(e,t,s=`${t}s`){return e===1?t:s}function resolveMoveKind(e,t){let s=resolveWithinRoot(e,t);if(!s.ok)return null;let g=s.abs;if(existsSync(g))try{let e=statSync(g);if(e.isDirectory())return`folder`;if(e.isFile())return g.endsWith(`.md`)||g.endsWith(`.mdx`)?`file`:`asset`}catch(e){let t=e.code;if(t===`EACCES`||t===`EPERM`)return`file`}for(let e of SUPPORTED_DOC_EXTENSIONS)if(existsSync(`${g}${e}`))return`file`;return null}function register$7(e,t){e.registerTool(`move`,{description:DESCRIPTION$7,inputSchema:{from:string().optional().describe(`Current path of a document, folder, or asset (auto-detected).`),to:string().optional().describe(`New path. All inbound wiki-links + inline links are rewritten automatically.`),template:object$1({from:string(),to:string()}).optional().describe('Move/rename a TEMPLATE instead: `{ from: "<folder>/<name>", to: "<folder>/<name>" }`. Nested because a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc. Mutually exclusive with flat `from`/`to`.'),summary:summaryArgSchema.describe(`Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({ok:boolean().describe(`Whether the move succeeded.`),kind:_enum([`file`,`folder`,`asset`,`template`]).optional().describe("What was moved (`file`/`folder`/`asset` auto-detected from `from`; `template` when the `template` target was used)."),committed:boolean().optional().describe("Template move only: `true` = tracked `git mv` (history preserved), `false` = plain disk rename (untracked / local-only `.ok/`)."),renamed:array(object$1({fromDocName:string(),toDocName:string()})).optional().describe(`docName remappings performed.`),rewrittenDocs:looseObjectArray.optional().describe(`Docs whose inbound links were rewritten.`),renamedAssets:looseObjectArray.optional().describe(`Referenced assets that were moved alongside.`),previewUrls:record(string(),string()).optional().describe(`Route-only preview URL per new docName.`),previewUrlSource:previewUrlSourceField,previousPreviewUrl:previousPreviewUrlField,summary:summaryOutputSchema.optional(),error:string().optional().describe("Present when `ok` is false."),colliding:looseObjectArray.optional().describe(`On a 409 collision: the conflicting from→to pairs.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.template!==void 0){if(e.from!==void 0||e.to!==void 0)return textResult("Error: pass EITHER flat `from`/`to` (document/folder/asset) OR `template: { from, to }` — not both.",!0);let s=resolveTemplatePath(e.template.from);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let g=resolveTemplatePath(e.template.to);if(!g.ok)return textResult(`Error: ${g.error}`,!0);let S=await httpPost(w,`/api/template`,{fromFolder:s.folder,fromName:s.name,toFolder:g.folder,toName:g.name,...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(t.identityRef?.current)});if(!S.ok){let e=typeof S.error==`string`?S.error:`Template move failed`;return textPlusStructured(`Error: ${e}`,{ok:!1,kind:`template`,error:e},!0)}let E=S.committed===!0,D=typeof S.from==`string`?S.from:e.template.from,O=typeof S.to==`string`?S.to:e.template.to;return textPlusStructured(`${E?`Renamed`:`Moved`} template ${D} → ${O}.${E?``:" (Untracked `.ok/` — moved on disk without git history.)"}`,{ok:!0,kind:`template`,committed:E})}if(e.from===void 0||e.to===void 0)return textResult("Error: provide both `from` and `to` (or use `template: { from, to }` to move a template).",!0);let E=join(g,S.content.dir),D=resolveMoveKind(E,e.from);if(D===null){let t=resolveTemplatePath(e.from);return t.ok&&existsSync(join(E,t.folder,`.ok`,`templates`,`${t.name}.md`))?textResult(`Error: \`${e.from}\` is a template, not a doc/folder/asset. Move it with \`move({ template: { from: "${e.from}", to: "<folder>/<newName>" } })\`.`,!0):textResult(`Error: \`${e.from}\` does not exist as a doc, folder, or asset under the content directory.`,!0)}let O=e.from,k=e.to;if(D===`file`){let t=normalizeDocName(e.from);if(!t.ok)return textResult(t.error,!0);let s=normalizeDocName(e.to);if(!s.ok)return textResult(s.error,!0);O=t.docName,k=s.docName}else if(D===`folder`&&(!isValidFolderPath(e.from)||!isValidFolderPath(e.to)))return textResult("Error: folder `from`/`to` must be relative paths with no leading/trailing slash.",!0);let j=await httpPost(w,`/api/rename-path`,{kind:D,fromPath:O,toPath:k,...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(t.identityRef?.current)});if(!j.ok){let e=j.error,t=parseRenameCollidingPairs(j.colliding),s={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return textPlusStructured(`Error: ${e}`,s,!0)}let F=parseRenameMappings(j.renamed),L=parseRewrittenDocs(j.rewrittenDocs),B=parseRenamedAssets(j.renamedAssets),H={config:t.config,resolveCwd:t.resolveCwd},q={},ee,J;if(D===`file`){let e=await resolvePreviewUrlForTool(k,H,g),t=await resolvePreviewUrlForTool(O,H,g);e&&(q[k]=e.url,ee=e.source),t&&(J=t.url)}else if(D===`folder`)for(let{toDocName:e}of F){let t=await resolvePreviewUrlForTool(e,H,g);t&&(q[e]=t.url,ee??=t.source)}let Y=j.summary&&typeof j.summary==`object`?j.summary:void 0,te=typeof Y?.hint==`string`?Y.hint:void 0,ne=[];if(D===`asset`)ne.push(`Moved asset ${O} → ${k}.`);else if(D===`folder`)ne.push(F.length===0?`No managed docs under ${e.from}/ — nothing to rename. Empty folders are not tracked.`:`Renamed folder ${e.from}/ → ${e.to}/ (${F.length} doc${F.length===1?``:`s`}, ${L.length} rewrite${L.length===1?``:`s`}).`);else{let e=F.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${O} -> ${k}`,t=L.length===0?`No inbound links required updates.`:`Rewrote ${L.length} ${pluralize(L.length,`document`)}.`;ne.push(`Renamed ${e}. ${t}`)}return B.length>0&&ne.push(`Moved ${B.length} referenced ${pluralize(B.length,`asset`)}.`),te&&ne.push(te),textPlusStructured(ne.join(`
1734
1734
  `),{ok:!0,kind:D,renamed:F,rewrittenDocs:L,...B.length>0?{renamedAssets:B}:{},...Object.keys(q).length>0?{previewUrls:q}:{},...ee?{previewUrlSource:ee}:{},...J?{previousPreviewUrl:J}:{},...Y?{summary:Y}:{}})})}const DESCRIPTION$6=[`[Operates on registry data; no running OK server required] Return the OK authoring palette so a generated document reads as one coherent, themed artifact.`,``,`Three sections:`,"- `components` — the **markdown-native forms** OK auto-promotes into themed canonical components at parse time. Write `> [!NOTE]` (not `<Callout>`), `<details>` (not `<Accordion>`), ` ```mermaid `, `$x$`. Each entry carries a copy-ready `example` + `guidance`.","- `embedPatterns` — copy-ready ` ```html preview ` starters (chart, stat cards, custom SVG, interactive control) already wired to the theme tokens, so an embed tracks light/dark with no hand-picked colors.",'- `tokens` — the CSS custom properties injected into every preview iframe; reference them as `var(--chart-1)`, `var(--foreground)`, … inside an `html preview` embed. **Inside SVG, route theme tokens through `style="..."` rather than presentation attributes** — `<circle style="fill: var(--chart-1)">` works; `<circle fill="var(--chart-1)">` silently falls back to black in Safari / older Chromium because CSS `var()` is not a valid SVG `<paint>` value per the W3C spec.',``,"External resources load directly: the preview iframe has open network access, so an embed can load external stylesheets, `fetch` live data, or pull map tiles / remote images / web fonts over `https:`. The iframe is a sandboxed null-origin frame — an embed can reach the network but never the knowledge base, cookies, or auth.",``,'Pass `components: [ids]` to ALSO get the full JSX-form prop schema for specific canonicals (e.g. `palette({ components: ["Callout", "Tabs"] })`) — merged from the former `get_components`.',``,`**Parameters:**`,"- `components` (optional) — Canonical ids to expand to full JSX-form detail (max 32). Case-sensitive (`Callout` not `callout`). Returns `componentDetails` + `notFound`.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
1735
1735
  `),InputSchema$1={components:array(string().min(1)).max(32).optional().describe("Canonical ids to expand to full JSX-form detail (max 32, case-sensitive). Returns `componentDetails` + `notFound`."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$3=outputSchemaWithText({version:literal(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:array(object$1({id:string(),displayName:string(),description:string(),authoring:_enum([`markdown`,`jsx`]).describe("`markdown` — write the markdown-native form OK auto-promotes; `jsx` — write the JSX tag directly (no markdown-native form exists)."),example:string().describe(`Copy-ready source for the authoring form.`),guidance:string().describe(`One line on when / how to use this construct.`)})).describe(`Canonical authoring constructs, keyed by the form an agent should write.`),embedPatterns:array(object$1({id:string(),title:string(),description:string(),snippet:string().describe("A complete, theme-wired ```html preview fenced block.")})).describe("Copy-ready themed `html preview` starters."),tokens:array(object$1({name:string().describe("CSS custom-property name, e.g. `--chart-1`."),light:string(),dark:string()})).describe("Theme tokens injected into every preview iframe — reference with `var(--name)`."),componentDetails:array(record(string(),unknown())).optional().describe("Full JSX-form prop schema for the requested `components` ids (when provided)."),notFound:array(string()).optional().describe("Requested `components` ids that did not match any canonical.")}),AUTHORING_FORMS=[{id:`Callout`,registryName:`Callout`,fallbackDisplayName:`Callout`,description:`Alert / admonition box in one of 15 themed type variants.`,authoring:`markdown`,example:`> [!NOTE]
1736
1736
  > Body text. Swap NOTE for TIP, IMPORTANT, WARNING, CAUTION, …`,guidance:"Write the GFM alert form — OK auto-promotes it to a themed Callout. 15 types; append `+` / `-` (e.g. `> [!NOTE]+`) to make it foldable."},{id:`Accordion`,registryName:`Accordion`,fallbackDisplayName:`Accordion`,description:`Collapsible section with a clickable summary.`,authoring:`markdown`,example:`<details>
@@ -1755,7 +1755,7 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
1755
1755
  `),{document:E,version:e.version,previewUrl:J?.url??null,...J?{previewUrlSource:J.source}:{},...j?{summary:j}:{},...L?{warnings:L}:{}})})}const DESCRIPTION$3=["[Requires: Hocuspocus server] Ranked retrieval across ALL non-ignored files (markdown by title/body, other file types by name/path, plus folders) — pair with `exec` `grep` for exhaustive content search. The cmd-K engine (title boost + body BM25 + recency).",``,"NAMES/paths are indexed for all files; BODY content for markdown only. Two-tier agent model: run this fast indexed `search` (all files by name/path + markdown content) IN PARALLEL with `exec` (`grep`) for exhaustive literal-string content search across every file — instant ranked hits plus full content coverage. Reach for `exec` grep when you need to match content inside code/config/data files.",``,"When semantic search is enabled for the workspace (an opt-in setting with an API key), an embeddings signal is additionally fused into `full_text` ranking, surfacing conceptually-related pages that share no keywords. This tool opts in by default; the `semantic` block in the response reports coverage. Note: with semantic enabled, the query and matching page content are sent to the configured embeddings provider (content egress). Set `semantic: false` to force pure-lexical ranking for a call.",``,"Returns scored `page`, `folder`, and name-only `file` hits, each with a `signals` breakdown (lexical / fullText / recency / vector); markdown `page` hits also carry a body snippet (`file` hits never do — name-only). `exec`-grep covers every content occurrence and needs no server.",``,`**Parameters:**`,"- `query` — Free-form; tokenized across title, name, path segments, and (with `full_text`) body.","- `intent` (optional) — `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.","- `scopes` (optional) — Result scope: `page` | `folder` | `file` | `content`. Defaults derive from `intent`.","- `limit` (optional) — Max rows; default 20, max 100.","- `semantic` (optional) — Set `false` to force pure-lexical ranking even when semantic search is enabled. Omit to use semantic when available.",``,'If the server is down, the tool returns a recovery hint — use `exec("grep ...")` as the server-free fallback.'].join(`
1756
1756
  `),InputSchema={query:string().describe(`Search query — title, path, or body terms.`),intent:_enum([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),scopes:array(_enum([`page`,`folder`,`content`,`file`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'file', 'content'. Defaults derive from intent.`),limit:number().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),semantic:boolean().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},SearchResultRowSchema=object$1({kind:_enum([`page`,`folder`,`file`]),path:string(),docName:string(),title:string().nullable(),score:number(),signals:object$1({lexical:number(),fullText:number(),recency:number(),vector:number().optional()}),snippet:string().optional(),previewUrl:string().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),SearchSemanticStatusSchema=object$1({capable:boolean(),applied:boolean(),coverage:object$1({embedded:number().int(),total:number().int()})}),OutputSchema$1=outputSchemaWithText({cwd:string(),query:string(),intent:string(),resultCount:number().int(),results:array(SearchResultRowSchema),elapsedMs:number().nullable(),semantic:SearchSemanticStatusSchema.optional()});function isSearchKind(e){return e===`page`||e===`folder`||e===`file`}function normalizeSignals(e){return{lexical:typeof e?.lexical==`number`?e.lexical:0,fullText:typeof e?.fullText==`number`?e.fullText:0,recency:typeof e?.recency==`number`?e.recency:0,...typeof e?.vector==`number`?{vector:e.vector}:{}}}function normalizeSemanticStatus(e){if(!(!e||typeof e.capable!=`boolean`))return{capable:e.capable,applied:e.applied===!0,coverage:{embedded:typeof e.coverage?.embedded==`number`?e.coverage.embedded:0,total:typeof e.coverage?.total==`number`?e.coverage.total:0}}}function formatSemanticNote(e){if(!e)return``;if(!e.capable)return`> Semantic: enabled but not ready (no API key, or warming up) — lexical ranking only.`;let{embedded:t,total:s}=e.coverage;return e.applied?`> Semantic: on — vector signal contributed (${t}/${s} pages embedded).`:t<s?`> Semantic: on — indexing ${t}/${s} pages; vectors are still filling in, re-run for fuller coverage.`:`> Semantic: on — no page cleared the similarity threshold for this query.`}function formatResultsBlock(e){if(e.length===0)return``;let t=[];for(let s of e){let e=s.title?.trim()||s.path;t.push(`### ${e} (${s.path})`),t.push(`Score ${s.score.toFixed(2)} — kind: ${s.kind}`),s.snippet&&t.push(s.snippet),t.push(``)}return t.join(`
1757
1757
  `)}function register$3(e,t){e.registerTool(`search`,{description:DESCRIPTION$3,inputSchema:InputSchema,outputSchema:OutputSchema$1,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(`${HOCUSPOCUS_NOT_RUNNING_ERROR}\nFor server-free literal-string search, use \`exec("grep ...")\` instead — it walks the filesystem and does not need Hocuspocus.`,!0);let E=e.intent??`full_text`,D=e.limit??20,O={query:e.query,intent:E,limit:D,semantic:e.semantic??!0,source:`mcp`};e.scopes&&(O.scopes=e.scopes);let k=await httpPost(w,`/api/search`,O);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let{resolve:j}=await buildListResolver({config:S,resolveCwd:async()=>g},g),F=(k.results??[]).flatMap(e=>{if(!isSearchKind(e.kind)||typeof e.path!=`string`)return[];let t=docNameFromPath(e.path),s=j(t);return[{kind:e.kind,path:e.path,docName:t,title:e.title??null,score:typeof e.score==`number`?e.score:0,signals:normalizeSignals(e.signals),...e.snippet?{snippet:e.snippet}:{},previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}]}),L=normalizeSemanticStatus(k.semantic),B={cwd:g,query:e.query,intent:E,resultCount:F.length,results:F,elapsedMs:typeof k.elapsedMs==`number`?k.elapsedMs:null,...L?{semantic:L}:{}},H=`## Search results for "${e.query}" (${F.length} hit${F.length===1?``:`s`}, intent: ${E})`,q=formatSemanticNote(L),ee=F.length===0?`No matches for "${e.query}".`:`${H}\n\n${formatResultsBlock(F)}`;return textPlusStructured(q?`${ee}\n${q}`:ee,B)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const DESCRIPTION$2=["[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",``,`Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own Open Knowledge install.`,``,"**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.",``,`**Parameters:**`,'- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.","- `cwd` (optional) — Project root (see `cwd` description below).",``,"**Preconditions:** project on a named branch (not detached HEAD); origin set to a `github.com` remote; the branch already pushed to origin."].join(`
1758
- `);function messageForShareError(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is not a `github.com` remote. Share links are GitHub-only in v1.";case`invalid-path`:return"The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.";default:return`Unknown share-construct-url error: ${String(e)}`}}function isExistingDirectory(e){try{return statSync(e).isDirectory()}catch{return!1}}function resolveExistingDocPath(e,t){for(let s of[`.mdx`,`.md`]){let g=`${t}${s}`;if(existsSync(g)){let t=resolveWithinRoot(e,g);return t.ok?t.rel:null}}return null}function resolveShareTarget(e,t,s,g){if(s===``)return g===`folder`?{ok:!0,kind:`folder`,sharePath:``}:{ok:!1,code:`invalid-path`};let S=resolveWithinRoot(t,s);if(!S.ok)return{ok:!1,code:`target-not-found`};let w=resolveExistingDocPath(e,S.abs.replace(/\.(mdx|md)$/i,``)),E=isExistingDirectory(S.abs);if(g===`doc`)return w===null?E?{ok:!1,code:`kind-mismatch`}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:w};if(g===`folder`){if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return w===null?{ok:!1,code:`target-not-found`}:{ok:!1,code:`kind-mismatch`}}if(w!==null)return{ok:!0,kind:`doc`,sharePath:w};if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return{ok:!1,code:`target-not-found`}}const OutputSchema=outputSchemaWithText({ok:boolean().describe(`Success discriminator.`),shareUrl:string().optional().describe(`Marketing share URL (success only).`),sharedUrl:string().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:string().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:_enum([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),error:_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:string().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:string().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:string().optional().describe(`Internal: preview-URL provenance.`)});function register$2(e,t){e.registerTool(`share_link`,{description:DESCRIPTION$2,inputSchema:{path:string().describe('Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).'),kind:_enum([`doc`,`folder`]).optional().describe("Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveShareTarget(g,join(g,S.content.dir),e.path,e.kind);if(!E.ok){let t;if(E.code===`kind-mismatch`){let s=e.kind===`folder`?`folder`:`doc`;t=`\`${e.path}\` exists, but not as a ${s}. Pass \`kind: '${s===`doc`?`folder`:`doc`}'\` to share it as the other kind.`}else t=E.code===`invalid-path`?'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.':`Target \`${e.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;let s={ok:!1,error:E.code,message:t};return textPlusStructured(`Error: ${t}`,s,!0)}let D=E.kind===`doc`?{kind:`doc`,docPath:E.sharePath}:{kind:`folder`,folderPath:E.sharePath},O;try{O=await fetch(`${w}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(D),signal:AbortSignal.timeout(3e4)})}catch(e){let t=`Server unreachable: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let k;try{k=await O.json()}catch(e){let t=`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!O.ok){let e;if(k&&typeof k==`object`){let t=k,s=typeof t.title==`string`?t.title:void 0,g=typeof t.detail==`string`?t.detail:void 0;e=s&&g?`${s}: ${g}`:s||g||`HTTP ${O.status}`}else e=`HTTP ${O.status}`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let j=ShareConstructUrlResponseSchema.safeParse(k);if(!j.success){let e=`Server returned an unexpected share-construct-url response shape.`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let F=j.data;if(!F.ok){let e=messageForShareError(F.error,F.branch),t={ok:!1,error:F.error,message:e,...F.branch?{branch:F.branch}:{}};return textPlusStructured(`Error: ${e}`,t,!0)}let{shareUrl:L,sharedUrl:B,branch:H}=F,q={ok:!0,shareUrl:L,sharedUrl:B,branch:H,resolvedKind:E.kind},ee={config:t.config,resolveCwd:t.resolveCwd},J=await resolvePreviewUrlForTool(E.sharePath.replace(/\.(mdx|md)$/i,``),ee,g);if(J&&E.kind===`folder`){let e=E.sharePath.replace(/^\/+|\/+$/g,``),t=e===``?`/#/`:`/#/${encodeDocName(e)}/`;J={...J,url:t}}let Y=e.path===``?`(content root)`:e.path;return textPlusStructured(`Share link for ${E.kind} \`${Y}\` on branch \`${H}\`:\n${L}`,{...q,previewUrl:J?.url??null,...J?{previewUrlSource:J.source}:{}})})}function buildConsolidateBody(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
1758
+ `);function messageForShareError(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is not a `github.com` remote. Share links are GitHub-only in v1.";case`invalid-path`:return"The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.";default:return`Unknown share-construct-url error: ${String(e)}`}}function isExistingDirectory(e){try{return statSync(e).isDirectory()}catch{return!1}}function resolveExistingDocPath(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=`${t}${s}`;if(existsSync(g)){let t=resolveWithinRoot(e,g);return t.ok?t.rel:null}}return null}function resolveShareTarget(e,t,s,g){if(s===``)return g===`folder`?{ok:!0,kind:`folder`,sharePath:``}:{ok:!1,code:`invalid-path`};let S=resolveWithinRoot(t,s);if(!S.ok)return{ok:!1,code:`target-not-found`};let w=resolveExistingDocPath(e,S.abs.replace(/\.(mdx|md)$/i,``)),E=isExistingDirectory(S.abs);if(g===`doc`)return w===null?E?{ok:!1,code:`kind-mismatch`}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:w};if(g===`folder`){if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return w===null?{ok:!1,code:`target-not-found`}:{ok:!1,code:`kind-mismatch`}}if(w!==null)return{ok:!0,kind:`doc`,sharePath:w};if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return{ok:!1,code:`target-not-found`}}const OutputSchema=outputSchemaWithText({ok:boolean().describe(`Success discriminator.`),shareUrl:string().optional().describe(`Marketing share URL (success only).`),sharedUrl:string().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:string().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:_enum([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),error:_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:string().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:string().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:string().optional().describe(`Internal: preview-URL provenance.`)});function register$2(e,t){e.registerTool(`share_link`,{description:DESCRIPTION$2,inputSchema:{path:string().describe('Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).'),kind:_enum([`doc`,`folder`]).optional().describe("Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveShareTarget(g,join(g,S.content.dir),e.path,e.kind);if(!E.ok){let t;if(E.code===`kind-mismatch`){let s=e.kind===`folder`?`folder`:`doc`;t=`\`${e.path}\` exists, but not as a ${s}. Pass \`kind: '${s===`doc`?`folder`:`doc`}'\` to share it as the other kind.`}else t=E.code===`invalid-path`?'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.':`Target \`${e.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;let s={ok:!1,error:E.code,message:t};return textPlusStructured(`Error: ${t}`,s,!0)}let D=E.kind===`doc`?{kind:`doc`,docPath:E.sharePath}:{kind:`folder`,folderPath:E.sharePath},O;try{O=await fetch(`${w}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(D),signal:AbortSignal.timeout(3e4)})}catch(e){let t=`Server unreachable: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let k;try{k=await O.json()}catch(e){let t=`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!O.ok){let e;if(k&&typeof k==`object`){let t=k,s=typeof t.title==`string`?t.title:void 0,g=typeof t.detail==`string`?t.detail:void 0;e=s&&g?`${s}: ${g}`:s||g||`HTTP ${O.status}`}else e=`HTTP ${O.status}`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let j=ShareConstructUrlResponseSchema.safeParse(k);if(!j.success){let e=`Server returned an unexpected share-construct-url response shape.`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let F=j.data;if(!F.ok){let e=messageForShareError(F.error,F.branch),t={ok:!1,error:F.error,message:e,...F.branch?{branch:F.branch}:{}};return textPlusStructured(`Error: ${e}`,t,!0)}let{shareUrl:L,sharedUrl:B,branch:H}=F,q={ok:!0,shareUrl:L,sharedUrl:B,branch:H,resolvedKind:E.kind},ee={config:t.config,resolveCwd:t.resolveCwd},J=await resolvePreviewUrlForTool(E.sharePath.replace(/\.(mdx|md)$/i,``),ee,g);if(J&&E.kind===`folder`){let e=E.sharePath.replace(/^\/+|\/+$/g,``),t=e===``?`/#/`:`/#/${encodeDocName(e)}/`;J={...J,url:t}}let Y=e.path===``?`(content root)`:e.path;return textPlusStructured(`Share link for ${E.kind} \`${Y}\` on branch \`${H}\`:\n${L}`,{...q,previewUrl:J?.url??null,...J?{previewUrlSource:J.source}:{}})})}function buildConsolidateBody(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
1759
1759
 
1760
1760
  Topic: ${e}
1761
1761
 
@@ -2820,11 +2820,11 @@ In headless mode, write the recap into the research article's "Further reading"
2820
2820
  - **Don't overwrite existing research silently.** If the topic was researched before, either iterate (Path C) or create a clearly-named successor (\`crdt-alternatives-2.md\`) and mark the old one as superseded.
2821
2821
  `}const DESCRIPTION$1=["Procedural guides for the three-layer wiki workflow + brownfield onboarding. Returns a numbered plan (instructional text, not data) — you execute it. Dispatches on `kind`:",``,'- `kind: "ingest"` — capture an external source (URL or local file) into the KB as raw, verbatim reference material (no analysis). Requires `source`.','- `kind: "research"` — gather sources and write provisional findings for a question. Requires `topic`.','- `kind: "consolidate"` — fold provisional material into a canonical article. Requires `topic`.','- `kind: "discover"` — extract conventions from an existing repo (folder frontmatter + templates + link graph). No payload.',``,`**Parameters:**`,"- `kind` — `ingest` | `research` | `consolidate` | `discover`.","- `source` — Required for `ingest`: the URL / file path / identifier to capture.","- `topic` — Required for `research` / `consolidate`: the topic, question, or anchor URL.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
2822
2822
  `);function register$1(e,t){let s=buildWorkflowHandler(`ingest`,t,`source`,buildIngestBody),g=buildWorkflowHandler(`research`,t,`topic`,buildResearchBody),S=buildWorkflowHandler(`consolidate`,t,`topic`,buildConsolidateBody);e.registerTool(`workflow`,{description:DESCRIPTION$1,inputSchema:{kind:_enum([`ingest`,`research`,`consolidate`,`discover`]).describe(`Which workflow guide to return.`),source:string().optional().describe('Required for `kind: "ingest"` — the URL / file / identifier to capture.'),topic:string().optional().describe('Required for `kind: "research"` / `"consolidate"` — the topic / question / anchor URL.'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({previewUrl:previewUrlOutputField.describe(`Always null — a workflow guide is prose, not a previewable document.`)})},async e=>{switch(e.kind){case`ingest`:return e.source?s(e):textResult('Error: workflow({ kind: "ingest" }) requires `source` — the URL / file / identifier to capture. e.g. workflow({ kind: "ingest", source: "https://example.com/spec" }).',!0);case`research`:return e.topic?g(e):textResult('Error: workflow({ kind: "research" }) requires `topic` — the question or topic to investigate. e.g. workflow({ kind: "research", topic: "rate-limit strategies" }).',!0);case`consolidate`:return e.topic?S(e):textResult('Error: workflow({ kind: "consolidate" }) requires `topic` — the topic to fold into a canonical article. e.g. workflow({ kind: "consolidate", topic: "rate-limit strategies" }).',!0);case`discover`:{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return s.ok?textPlusStructured(buildDiscoverBody(s.config.content.dir),{previewUrl:null}):textResult(`Error: ${s.error}`,!0)}default:return textResult(`Error: unknown workflow kind.`,!0)}})}const DESCRIPTION=`${["Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, or `asset` (or `documents` for a batch of docs).",``,'- `document` — Create or overwrite a doc via the CRDT layer [Requires: Hocuspocus server]. `{ path, content }`, or `{ path, template }` to instantiate from a folder template (mutually exclusive with `content`). Optional `frontmatter` (its own YAML) and `position` (`replace` default for a new doc; required for an existing one) — note supplying `frontmatter` alongside literal `content` forces `position: replace` (the only position that persists a YAML block), overriding an explicit `append`/`prepend`. Example: `{ document: { path: "meetings/standup", content: "# Standup\\n..." } }`.','- `folder` — Create a NEW folder (optionally with its own properties) [Requires: Hocuspocus server]. `{ path, frontmatter? }`. To change an EXISTING folder use `edit`. Example: `{ folder: { path: "ideas" } }`.','- `template` — Create a reusable starting shape for new docs in a folder. `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.','- `asset` — Upload a binary (image/file) via the media route [Requires: Hocuspocus server]. `{ path: "<folder>/<file.ext>", content(base64) | source(local path) }`.',"- `documents` — Batch: `[{ path, content?|template?, frontmatter?, position?, summary? }, ...]` written in order; the response reports each.","- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, for a single `document`/`folder`/`template`/`asset` write. For a `documents` batch, give each entry its own `summary` instead (a top-level `summary` is ignored on the batch path). Avoid secrets or PII — persisted to git history.",``,"Responses may include `structuredContent.document.warnings` (batch: per-entry under `documents[]`) — advisory entries discriminated by `kind`: `content-divergence` / `disk-edit-reconciled` (write-integrity — re-read the doc) and `mermaid-parse-error` (the write landed but that fence will not render — fix it and re-edit)."].join(`
2823
- `)}\n${renderInventoryFooter()}`;function frontmatterIgnoredNote(e,t){return e!==`prepend`&&e!==`append`||!t||stripFrontmatter(t).frontmatter.trim()===``?null:`Note: a \`---\` frontmatter block in this \`${e}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit({ document: { path, frontmatter } })\` (patch) or \`write({ document: { path, content, position: "replace" } })\` (full rewrite).`}function emptyAppendNoOpNote(e,t){return e!==`prepend`&&e!==`append`||t===void 0||stripFrontmatter(t).body!==``?null:`No content to ${e} — document unchanged. To clear a document, use \`position: "replace"\` with empty \`content\`.`}function docExtensionOnDisk(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=resolveWithinRoot(e,`${t}${s}`);if(g.ok&&existsSync(g.abs))return s}return null}function requestedDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}function extensionIgnoredNote(e,t,s){return e===null||t===null||e===t?null:`Note: "${s}" already exists as \`${s}${t}\`, so the requested \`${e}\` extension was not applied — the write went to \`${s}${t}\`. Changing a doc's on-disk extension in place isn't available via the MCP today.`}function composeWithFrontmatter(e,t){let{frontmatter:s,body:g}=stripFrontmatter(t),S={};if(s!==``){let e=parseFrontmatterYaml(unwrapFrontmatterFences(s));if(e.map===null)return{ok:!1,error:`EMBEDDED_FRONTMATTER_MALFORMED — \`content\` opens with a \`---\` block whose YAML failed to parse (${e.parseError}), so it can't be merged with the \`frontmatter\` param. Fix the embedded YAML, or supply the frontmatter only via the \`frontmatter\` param (not also inline in \`content\`).`};S=e.map}let w=serializeFrontmatterMap(mergePatch(S,e));return w===``?{ok:!0,markdown:g}:{ok:!0,markdown:withFences(w)+g}}async function writeOneDoc(e,t,s,g,S){let w=normalizeDocName(e.path);if(!w.ok)return{docName:e.path,ok:!1,error:w.error};let E=w.docName,D=S.identityRef?.current;if(e.template===void 0&&e.content===void 0)return{docName:E,ok:!1,error:"either `content` or `template` must be provided — omitting both would write empty content."};if(e.template!==void 0&&e.content!==void 0)return{docName:E,ok:!1,error:"TEMPLATE_AND_CONTENT_BOTH_SET — `template` and `content` are mutually exclusive. Pass one; fill placeholders via subsequent `edit` calls."};let O=e.content??``,k=e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0,j=docExtensionOnDisk(s,E),F=j!==null,L=requestedDocExtension(e.path),B;if(e.position!==void 0)B=e.position;else if(F)return{docName:E,ok:!1,error:`"${E}" already exists — pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit\` for a targeted change.`};else B=`replace`;if(e.template!==void 0){let s=parentFolderOf(E),g=resolveTemplatesAvailable(t,s,{depth:1}),S=g.find(t=>t.name===e.template);if(!S)return{docName:E,ok:!1,error:`template "${e.template}" not found for folder "${s||`.`}". Available: ${g.length===0?`(none)`:g.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`};let w;try{w=readFileSync(resolve(t,S.path),`utf-8`)}catch(e){return{docName:E,ok:!1,error:`failed to read template at ${S.path}: ${e.message}`}}let{body:k}=stripFrontmatter(w);O=applySubstitution(k,{date:todayIsoUtc(),user:D?.displayName??``}),B=`replace`}else if(k){let t=composeWithFrontmatter(e.frontmatter,O);if(!t.ok)return{docName:E,ok:!1,error:t.error};O=t.markdown,B=`replace`}if(!F&&normalizeBridge(O)===``)return{docName:E,ok:!1,error:`"${E}" does not exist and the content is empty — provide non-empty content to create the document.`};let H=await httpPost(g,`/api/agent-write-md`,{docName:E,markdown:O,position:B,...L!==null&&!F?{extension:L}:{},...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(D)});if(!H.ok){let e=typeof H.detail==`string`&&H.detail.length>0?H.detail:``;return{docName:E,ok:!1,error:e?`${String(H.error)} (${e})`:String(H.error)}}if(e.template!==void 0&&k){let t=await httpPost(g,`/api/frontmatter-patch`,{docName:E,patch:e.frontmatter,...agentIdentityFields(D)});if(!t.ok)return{docName:E,ok:!1,error:`document created from template but frontmatter failed: ${String(t.error)}`}}let q=extensionIgnoredNote(L,j,E);return{docName:E,ok:!0,position:B,...e.template===void 0?{}:{fromTemplate:e.template},...q?{extensionNote:q}:{},raw:H}}async function handleFolder(e,t,s,g){if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=g.identityRef?.current,w=await httpPost(s,`/api/create-folder`,{path:e.path,...t===void 0?{}:{summary:t},...agentIdentityFields(S)});if(!w.ok){let e=typeof w.detail==`string`&&w.detail.length>0?w.detail:``;return textResult(e?`Error: ${w.error} (${e})`:`Error: ${w.error}`,!0)}let E=[`Created folder ${e.path}.`];if(e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0){let g=await httpPut(s,`/api/folder-config`,{path:e.path,frontmatter:e.frontmatter,...t===void 0?{}:{summary:t},...agentIdentityFields(S)});if(!g.ok)return textPlusStructured(`Created folder ${e.path}, but writing its properties failed: ${g.error}. Use edit({ folder: { path: "${e.path}", frontmatter } }) to retry the properties.`,{folder:{ok:!0,path:e.path,frontmatterError:String(g.error)}});E.push(`Set folder properties (${e.path}/.ok/frontmatter.yml).`)}return textPlusStructured(E.join(`
2823
+ `)}\n${renderInventoryFooter()}`;function frontmatterIgnoredNote(e,t){return e!==`prepend`&&e!==`append`||!t||stripFrontmatter(t).frontmatter.trim()===``?null:`Note: a \`---\` frontmatter block in this \`${e}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit({ document: { path, frontmatter } })\` (patch) or \`write({ document: { path, content, position: "replace" } })\` (full rewrite).`}function emptyAppendNoOpNote(e,t){return e!==`prepend`&&e!==`append`||t===void 0||stripFrontmatter(t).body!==``?null:`No content to ${e} — document unchanged. To clear a document, use \`position: "replace"\` with empty \`content\`.`}function docExtensionOnDisk(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=resolveWithinRoot(e,`${t}${s}`);if(g.ok&&existsSync(g.abs))return s}return null}function requestedDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}function extensionIgnoredNote(e,t,s){return e===null||t===null||e===t?null:`Note: "${s}" already exists as \`${s}${t}\`, so the requested \`${e}\` extension was not applied — the write went to \`${s}${t}\`. Changing a doc's on-disk extension in place isn't available via the MCP today.`}function composeWithFrontmatter(e,t){let{frontmatter:s,body:g}=stripFrontmatter(t),S={};if(s!==``){let e=parseFrontmatterYaml(unwrapFrontmatterFences(s));if(e.map===null)return{ok:!1,error:`EMBEDDED_FRONTMATTER_MALFORMED — \`content\` opens with a \`---\` block whose YAML failed to parse (${e.parseError}), so it can't be merged with the \`frontmatter\` param. Fix the embedded YAML, or supply the frontmatter only via the \`frontmatter\` param (not also inline in \`content\`).`};S=e.map}let w=serializeFrontmatterMap(mergePatch(S,e));return w===``?{ok:!0,markdown:g}:{ok:!0,markdown:withFences(w)+g}}async function writeOneDoc(e,t,s,g,S){let w=normalizeDocName(e.path);if(!w.ok)return{docName:e.path,ok:!1,error:w.error};let E=w.docName,D=S.identityRef?.current;if(e.template===void 0&&e.content===void 0)return{docName:E,ok:!1,error:"either `content` or `template` must be provided — omitting both would write empty content."};if(e.template!==void 0&&e.content!==void 0)return{docName:E,ok:!1,error:"TEMPLATE_AND_CONTENT_BOTH_SET — `template` and `content` are mutually exclusive. Pass one; fill placeholders via subsequent `edit` calls."};let O=e.content??``,k=e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0,j=docExtensionOnDisk(s,E),F=j!==null,L=e.extension??requestedDocExtension(e.path),B;if(e.position!==void 0)B=e.position;else if(F)return{docName:E,ok:!1,error:`"${E}" already exists — pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit\` for a targeted change.`};else B=`replace`;if(e.template!==void 0){let s=parentFolderOf(E),g=resolveTemplatesAvailable(t,s,{depth:1}),S=g.find(t=>t.name===e.template);if(!S)return{docName:E,ok:!1,error:`template "${e.template}" not found for folder "${s||`.`}". Available: ${g.length===0?`(none)`:g.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`};let w;try{w=readFileSync(resolve(t,S.path),`utf-8`)}catch(e){return{docName:E,ok:!1,error:`failed to read template at ${S.path}: ${e.message}`}}let{body:k}=stripFrontmatter(w);O=applySubstitution(k,{date:todayIsoUtc(),user:D?.displayName??``}),B=`replace`}else if(k){let t=composeWithFrontmatter(e.frontmatter,O);if(!t.ok)return{docName:E,ok:!1,error:t.error};O=t.markdown,B=`replace`}if(!F&&normalizeBridge(O)===``)return{docName:E,ok:!1,error:`"${E}" does not exist and the content is empty — provide non-empty content to create the document.`};let H=await httpPost(g,`/api/agent-write-md`,{docName:E,markdown:O,position:B,...L!==null&&!F?{extension:L}:{},...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(D)});if(!H.ok){let e=typeof H.detail==`string`&&H.detail.length>0?H.detail:``;return{docName:E,ok:!1,error:e?`${String(H.error)} (${e})`:String(H.error)}}if(e.template!==void 0&&k){let t=await httpPost(g,`/api/frontmatter-patch`,{docName:E,patch:e.frontmatter,...agentIdentityFields(D)});if(!t.ok)return{docName:E,ok:!1,error:`document created from template but frontmatter failed: ${String(t.error)}`}}let q=extensionIgnoredNote(L,j,E);return{docName:E,ok:!0,position:B,...e.template===void 0?{}:{fromTemplate:e.template},...q?{extensionNote:q}:{},raw:H}}async function handleFolder(e,t,s,g){if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=g.identityRef?.current,w=await httpPost(s,`/api/create-folder`,{path:e.path,...t===void 0?{}:{summary:t},...agentIdentityFields(S)});if(!w.ok){let e=typeof w.detail==`string`&&w.detail.length>0?w.detail:``;return textResult(e?`Error: ${w.error} (${e})`:`Error: ${w.error}`,!0)}let E=[`Created folder ${e.path}.`];if(e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0){let g=await httpPut(s,`/api/folder-config`,{path:e.path,frontmatter:e.frontmatter,...t===void 0?{}:{summary:t},...agentIdentityFields(S)});if(!g.ok)return textPlusStructured(`Created folder ${e.path}, but writing its properties failed: ${g.error}. Use edit({ folder: { path: "${e.path}", frontmatter } }) to retry the properties.`,{folder:{ok:!0,path:e.path,frontmatterError:String(g.error)}});E.push(`Set folder properties (${e.path}/.ok/frontmatter.yml).`)}return textPlusStructured(E.join(`
2824
2824
  `),{folder:{ok:!0,path:e.path}})}async function handleTemplate(e,t,s,g){let S=resolveTemplatePath(e.path);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{folder:w,name:E}=S;if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=await httpPut(s,`/api/template`,{folder:w,name:E,body:e.content,frontmatter:{title:e.frontmatter.title,...typeof e.frontmatter.description==`string`?{description:e.frontmatter.description}:{},...Array.isArray(e.frontmatter.tags)?{tags:e.frontmatter.tags}:{}},...t===void 0?{}:{summary:t},...agentIdentityFields(g.identityRef?.current)});if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.created===!0,k=typeof D.path==`string`?D.path:void 0;return textPlusStructured(`${O?`Created`:`Updated`} template "${E}" in ${w||`(root)`}${k?` (${k})`:``}.`,{template:{ok:!0,path:k,created:O}})}async function handleAsset(e,t,s,g){if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.content===void 0==(e.source===void 0))return textResult("Error: provide exactly one of `content` (base64) or `source` (local file path) for an asset.",!0);let S;try{S=e.content===void 0?readFileSync(resolve(t,e.source)):Buffer.from(e.content,`base64`)}catch(e){return textResult(`Error: could not read asset bytes: ${e.message}`,!0)}if(S.byteLength===0)return textResult(`Error: asset is empty (0 bytes).`,!0);let{folder:w,name:E}=splitTargetPath(e.path),D=w?`${w}/${E}`:E,O=g.identityRef?.current,k=new URLSearchParams;O?.connectionId&&k.set(`agentId`,O.connectionId),O?.displayName&&k.set(`agentName`,O.displayName);let j=k.toString(),F=new FormData;F.append(`parentDocName`,D),F.append(`file`,new Blob([new Uint8Array(S)]),E);let L;try{let e=await fetch(`${s}/api/upload${j?`?${j}`:``}`,{method:`POST`,body:F}),t=await e.json().catch(()=>null);L=e.ok?{ok:!0,status:e.status,data:t??{}}:{ok:!1,status:e.status,error:t&&(typeof t.title==`string`?t.title:t.error)||`Upload failed (HTTP ${e.status}).`}}catch(e){return textResult(`Error: upload request failed: ${e.message}`,!0)}if(!L.ok)return textResult(`Error: ${L.error}`,!0);let B=typeof L.data?.src==`string`?L.data.src:void 0,H=typeof L.data?.path==`string`?L.data.path:void 0,q=L.data?.deduped===!0,ee=B??H??E;return textPlusStructured([`Uploaded asset to ${D}${q?` (deduplicated — identical bytes already present)`:``}.`,`Reference it in a doc with: ![${E}](${ee})`].join(`
2825
2825
  `),{asset:{ok:!0,...B?{src:B}:{},...H?{path:H}:{},...q?{deduped:q}:{}}})}async function handleBatch(e,t,s,g,S,w,E){let D=[];for(let w of e)D.push(await writeOneDoc(w,t,s,g,S));let O=D.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=resolvePreviewUrl(e.docName,{lockDir:w}),s=parseAdvisoryWarnings(e.raw.warnings);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...s?{warnings:s}:{}}}),k=O.filter(e=>e.ok).length,j=k===O.length,F=e.map((e,t)=>{let s=D[t];if(!s?.ok)return`Failed ${e.path}: ${s?.error??`unknown error`}`;if(emptyAppendNoOpNote(s.position,e.content))return`No change to ${e.path} — empty ${s.position}, document unchanged.`;let g=O[t],S=[`Wrote ${e.path} (${s.position}).`];return g?.ok&&g.warnings&&S.push(...formatAdvisoryBriefs(g.warnings)),S.join(` `)}),L=e.flatMap((e,t)=>{let s=D[t];if(!s?.ok)return[];let g=frontmatterIgnoredNote(s.position,e.content);return[...g?[g]:[],...s.extensionNote?[s.extensionNote]:[]].map(t=>`${e.path} — ${t}`)}),B=[`${k}/${O.length} written.`,...F,...L].join(`
2826
2826
  `),H={documents:O},q=D.find(e=>e.ok);return q&&q.raw.systemSubscriberCount===0&&(H.warning=buildPreviewAttachWarning(resolvePreviewUrl(q.docName,{lockDir:w}),E)),textPlusStructured(B,H,!j)}async function handleSingleDoc(e,t,s,g,S,w,E){let D=await writeOneDoc(e,t,s,g,S);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.raw,k=resolvePreviewUrl(D.docName,{lockDir:w}),j=typeof O.subscriberCount==`number`?O.subscriberCount:void 0,F=(typeof O.systemSubscriberCount==`number`?O.systemSubscriberCount:void 0)===0,L=j===0,B=Array.isArray(O.hints)?O.hints:void 0,H=O.summary&&typeof O.summary==`object`?O.summary:void 0,q=typeof H?.hint==`string`?H.hint:void 0,ee=parseAdvisoryWarnings(O.warnings),J=[emptyAppendNoOpNote(D.position,e.content)??(D.fromTemplate===void 0?`Written successfully (${D.position}).`:`Written successfully (instantiated from template "${D.fromTemplate}").`)],Y=frontmatterIgnoredNote(D.position,e.content);if(Y&&J.push(Y),D.extensionNote&&J.push(D.extensionNote),F&&!k&&J.push(START_UI_TEXT_HINT),q&&J.push(q),B)for(let e of B)e.message&&J.push(e.message);ee&&J.push(...formatAdvisoryLines(ee));let te=J.join(`
2827
- `);if(!k&&!F&&!L&&!B&&!H&&!ee)return textResult(te);let ne={};return B&&(ne.hints=B),H&&(ne.summary=H),ee&&(ne.warnings=ee),textPlusStructured(te,nestDocResult(k,F?buildPreviewAttachWarning(k,E):void 0,ne))}function register(e,t){let s={path:string().describe(`Document path, no extension. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup".`),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe(`Single-document write result (present when there is a doc-specific signal).`),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, error? }`."),previewUrl:previewUrlOutputField.optional(),previewUrlSource:previewUrlSourceField,warning:previewAttachWarningField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s,E=resolveLockDir(g),D=resolveContentDir(S,g),O=S.appearance.preview.autoOpen;if(e.documents!==void 0){let s=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`,`documents`]);return s?textResult(`Error: ${s}`,!0):w?handleBatch(e.documents,g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}let k=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`]);return k?textResult(`Error: ${k}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?handleAsset(e.asset,g,w,t):handleTemplate(e.template,e.summary,w,t):handleFolder(e.folder,e.summary,w,t):w?handleSingleDoc({...e.document,summary:e.summary},g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)})}function registerAllTools(e,t){let s=t.logger,g=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),S=e=>async g=>{try{let S=await t.resolveCwd(g);return(getCurrentMcpLogger()??s)?.debug(`tool cwd resolved`,{tool:e,cwd:S,...g?{explicit:g}:{}}),S}catch(t){throw(getCurrentMcpLogger()??s)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...g?{explicit:g}:{}}),t}};register$11(g,{resolveCwd:S(`exec`),serverUrl:t.serverUrl,config:t.config}),register$1(g,{config:t.config,resolveCwd:S(`workflow`)}),register$3(g,{resolveCwd:S(`search`),config:t.config,serverUrl:t.serverUrl}),register$8(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`links`)}),register(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`write`),identityRef:t.identityRef}),register$12(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit`),identityRef:t.identityRef}),register$13(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`delete`),identityRef:t.identityRef}),register$7(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`move`),identityRef:t.identityRef}),register$9(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`history`)}),register$16(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`checkpoint`),identityRef:t.identityRef}),register$4(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`restore_version`),identityRef:t.identityRef}),register$6(g,{resolveCwd:S(`palette`),config:t.config}),register$15(g,{config:t.config,resolveCwd:S(`config`)}),register$10(g,{config:t.config,resolveCwd:S(`preview_url`),serverUrl:t.serverUrl}),register$14(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`conflicts`)}),register$5(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,s){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(s))}function createSessionServer(e,t,s){let g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION});installPrettyZodErrors(S);let w=s??randomUUID$1(),E={current:{connectionId:w,displayName:w,colorSeed:w}};S.server.oninitialized=()=>{let e=S.server.getClientVersion(),t=sanitizeClientName(e?.name,w);E.current={connectionId:w,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let D=e.projectDir??e.contentDir;return registerAllTools(S,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return D;let t=resolveWithinRoot(D,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:g,identityRef:E}),{server:S,transport:t}}function createMcpHttpHandler(e){let t=new Map,s=e.sessionTtlMs??1800*1e3,g=e.maxSessions??100;async function S(s,g){let S=t.get(s);if(!S)return;t.delete(s),S.ttlTimer!==void 0&&clearTimeout(S.ttlTimer);let w=await Promise.allSettled([S.server.close(),S.transport.close()]);for(let t of w)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:s,reason:g},`MCP HTTP session close failed`);e.log?.info?.({sessionId:s,reason:g},`MCP HTTP session closed`)}function w(t,g){g.ttlTimer!==void 0&&clearTimeout(g.ttlTimer),g.ttlTimer=setTimeout(()=>{S(t,`ttl-expired`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},s),g.ttlTimer.unref?.()}return{async handle(s,E){let D=firstHeader(s.headers[`mcp-session-id`]);if(D){let e=t.get(D);if(!e){writePlain(E,404,`MCP session not found`);return}w(D,e),await e.transport.handleRequest(s,E);return}if(s.method!==`POST`){writePlain(E,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=g){e.log?.warn?.({activeSessions:t.size,maxSessions:g},`MCP HTTP session cap reached`),writePlain(E,503,`Too many active MCP sessions`);return}let O=firstHeader(s.headers[MCP_CONNECTION_ID_HEADER]),k=validateAgentId(O)??void 0;O!==void 0&&k===void 0&&e.log?.warn?.({headerLength:O.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let j=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID$1(),enableJsonResponse:!0,onsessioninitialized:async s=>{try{let g=createSessionServer(e,j,k);await g.server.connect(j),t.set(s,g),w(s,g),e.log?.info?.({sessionId:s},`MCP HTTP session initialized`)}catch(g){throw t.delete(s),e.log?.error?.({err:g,sessionId:s},`MCP HTTP session initialization failed`),g}}});j.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},j.onclose=()=>{let t=j.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}S(t,`transport-closed`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await j.handleRequest(s,E)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>S(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:s,mcpHttpHandler:g,log:S,sessionManager:w,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O,contentAssetMiddleware:k,reactShellMiddleware:j,ephemeral:F}=e,L=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,B=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});B.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let H=new Map,q=new Set,ee=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`));for(let[e,s]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,s);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(w?.startsWith(`/api/`)){s.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${w}`})}).catch(e=>{S.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},D=s=>{if(F===!0&&k!==void 0&&(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host))){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`content-asset`});return}E(k,`content-asset`,s)},O=e=>E(j,`react-shell`,e),L=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(j!==void 0&&w?.startsWith(`/assets/`)){O(()=>D(L));return}if(k!==void 0||j!==void 0){D(()=>O(L));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),B.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=H.get(s);e!==void 0&&(clearTimeout(e),H.delete(s),S.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&D){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),g=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);D.setPresence(toBroadcasterKey(s),{displayName:t.displayName,icon:e,color:g,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){S.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let g=setInterval(()=>{try{t.ping()}catch{}},3e4);g.unref?.();let k=s?setInterval(()=>{D?.bumpPresenceTs(toBroadcasterKey(s))},3e3):null;k?.unref?.(),t.on(`close`,()=>{if(clearInterval(g),k!==null&&clearInterval(k),!s)return;let e=setTimeout(()=>{if(H.delete(s),ee)return;let e=(async()=>{S.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await w?.closeAllForAgent(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{E?.clearFocus(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{D?.clearPresence(toBroadcasterKey(s))}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await O?.onSessionClose()}catch(e){S.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();q.add(e),e.finally(()=>q.delete(e))},L);e.unref?.(),H.set(s,e),S.info({connectionId:s,graceMs:L},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`Upgrade socket error`)}),B.handleUpgrade(e,t,g,t=>{let g=s.handleConnection(t,e),w=!1;t.on(`message`,e=>{if(w)return;let s=e.byteLength;if(s>MAX_COLLAB_MESSAGE_BYTES){w=!0,incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,bytes:s,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}g.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{g.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||S.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:B,shutdown:async()=>{if(!ee){ee=!0;for(let e of H.values())clearTimeout(e);H.clear(),q.size>0&&await Promise.allSettled(q)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),s=sanitizeIdentityField(t.searchParams.get(`displayName`)),g=sanitizeIdentityField(t.searchParams.get(`clientName`)),S=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return s===null||g===null||S===null?null:{displayName:s,clientName:g,colorSeed:S}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,s){super(MISSING_OK_CONFIG_MESSAGE,s),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-Bu9Rdqzq.mjs`),S=dirname(e);try{tracedMkdirSync(S,{recursive:!0})}catch(e){e.code!==`EEXIST`&&s.warn({err:e,watchDir:S},`failed to create watch directory; watcher may be inert`)}let w=g(S,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==S&&t!==e});await new Promise(e=>{w.once(`ready`,e)});let E=null;try{E=readFileSync(e,`utf-8`)}catch{}let D=(g,S=!0)=>{if(g!==e)return;let w;try{w=readFileSync(g,`utf-8`)}catch(e){if(e.code===`ENOENT`){S&&s.debug({path:g},`config file disappeared between event and read; dropping`);return}s.warn({err:e,path:g},`config file read failed; dropping event`);return}if(w!==E){E=w;try{t(w)}catch(e){s.warn({err:e,path:g},`config file change handler threw`)}}},O=e=>D(e);w.on(`add`,O),w.on(`change`,O),w.on(`unlink`,t=>{t===e&&s.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),w.on(`error`,t=>{s.warn({err:t,watchDir:S,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let k=0,j=setInterval(()=>{k++,D(e,!1),k>=20&&clearInterval(j)},500);j.unref?.();let F=!1;return async()=>{F||(F=!0,clearInterval(j),await w.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-Bu9Rdqzq.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&s.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&s.debug({path:e},`config file disappeared between event and read; dropping`);return}s.warn({err:t,path:e},`config file read failed; dropping event`);return}if(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=relative(g,join(s,e.file));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}const BUILTIN_SKIP_FILES=new Set([`.DS_Store`,`.localized`]);function isAlwaysSkipFile(e){return BUILTIN_SKIP_FILES.has(e.slice(e.lastIndexOf(`/`)+1))}const SECRET_BEARING_DIRS=new Set([`.ssh`,`.aws`,`.gnupg`,`.kube`,`.docker`]);function pathHasSecretBearingDirSegment(e){for(let t of e.split(`/`))if(SECRET_BEARING_DIRS.has(t.toLowerCase()))return!0;return!1}const SECRET_CREDENTIAL_BASENAMES=new Set([`credentials`,`.netrc`,`.npmrc`,`.pgpass`,`.git-credentials`]),SECRET_KEY_SUFFIXES=[`.pem`,`.key`,`.p12`,`.pfx`,`.keystore`,`.jks`,`.ppk`];function isSecretBearingFile(e){let t=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(t===`.env`||t.startsWith(`.env.`)||SECRET_CREDENTIAL_BASENAMES.has(t)||t.startsWith(`id_rsa`)||t.startsWith(`id_ed25519`)||t.startsWith(`id_ecdsa`)||t.startsWith(`id_dsa`))return!0;for(let e of SECRET_KEY_SUFFIXES)if(t.endsWith(e))return!0;return!1}function isSingleDocAncestorDir(e,t){return t===e||t.startsWith(`${e}/`)}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D,O,k,j=0,F=0,L=0;function B(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],S=0,B=0;for(let s of IGNORE_FILE_NAMES){let w=join(t,s);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);S+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${w}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);S+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,w));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:S};B+=loadNestedIgnoreFiles(s,t,e,H),S=H.value;let q=loadGitExcludeSources(t,H);S=H.value,q.length>0&&(g.push(...q),e.add(q));let ee=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return D=e,O=g,k=ee,j=g.length,F=B,L=S,{patternCount:j,nestedFileCount:F,bytes:L}}B();let H=new Map;function q(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}let ee=()=>{S===void 0&&populateDirCount(s,``,q,H)};ee();function J(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function Y(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:q(e)}return{isExcluded(e,t){if(J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((H.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e)||pathHasSecretBearingDirSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e)?!0:t?.bypassFilters?!1:Y(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;H.set(t,(H.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=H.get(t)??0;s<=1?H.delete(t):H.set(t,s-1)},rebuildDirCount(){let e=new Map(H);H.clear();try{ee()}catch(t){for(let[t,s]of e)H.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=k,w=j,E=F,q=L,J=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async Y=>{try{let t=B();H.clear(),ee();let s=Date.now()-J;if(Y.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s}}catch(g){D=t,O=s,k=S,j=w,F=E,L=q,H.clear();try{ee()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let B=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(B)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:B}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
2827
+ `);if(!k&&!F&&!L&&!B&&!H&&!ee)return textResult(te);let ne={};return B&&(ne.hints=B),H&&(ne.summary=H),ee&&(ne.warnings=ee),textPlusStructured(te,nestDocResult(k,F?buildPreviewAttachWarning(k,E):void 0,ne))}function register(e,t){let s={path:string().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),extension:DocExtensionArg.optional(),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe(`Single-document write result (present when there is a doc-specific signal).`),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, error? }`."),previewUrl:previewUrlOutputField.optional(),previewUrlSource:previewUrlSourceField,warning:previewAttachWarningField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s,E=resolveLockDir(g),D=resolveContentDir(S,g),O=S.appearance.preview.autoOpen;if(e.documents!==void 0){let s=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`,`documents`]);return s?textResult(`Error: ${s}`,!0):w?handleBatch(e.documents,g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}let k=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`]);return k?textResult(`Error: ${k}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?handleAsset(e.asset,g,w,t):handleTemplate(e.template,e.summary,w,t):handleFolder(e.folder,e.summary,w,t):w?handleSingleDoc({...e.document,summary:e.summary},g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)})}function registerAllTools(e,t){let s=t.logger,g=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),S=e=>async g=>{try{let S=await t.resolveCwd(g);return(getCurrentMcpLogger()??s)?.debug(`tool cwd resolved`,{tool:e,cwd:S,...g?{explicit:g}:{}}),S}catch(t){throw(getCurrentMcpLogger()??s)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...g?{explicit:g}:{}}),t}};register$11(g,{resolveCwd:S(`exec`),serverUrl:t.serverUrl,config:t.config}),register$1(g,{config:t.config,resolveCwd:S(`workflow`)}),register$3(g,{resolveCwd:S(`search`),config:t.config,serverUrl:t.serverUrl}),register$8(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`links`)}),register(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`write`),identityRef:t.identityRef}),register$12(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit`),identityRef:t.identityRef}),register$13(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`delete`),identityRef:t.identityRef}),register$7(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`move`),identityRef:t.identityRef}),register$9(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`history`)}),register$16(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`checkpoint`),identityRef:t.identityRef}),register$4(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`restore_version`),identityRef:t.identityRef}),register$6(g,{resolveCwd:S(`palette`),config:t.config}),register$15(g,{config:t.config,resolveCwd:S(`config`)}),register$10(g,{config:t.config,resolveCwd:S(`preview_url`),serverUrl:t.serverUrl}),register$14(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`conflicts`)}),register$5(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,s){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(s))}function createSessionServer(e,t,s){let g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION});installPrettyZodErrors(S);let w=s??randomUUID$1(),E={current:{connectionId:w,displayName:w,colorSeed:w}};S.server.oninitialized=()=>{let e=S.server.getClientVersion(),t=sanitizeClientName(e?.name,w);E.current={connectionId:w,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let D=e.projectDir??e.contentDir;return registerAllTools(S,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return D;let t=resolveWithinRoot(D,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:g,identityRef:E}),{server:S,transport:t}}function createMcpHttpHandler(e){let t=new Map,s=e.sessionTtlMs??1800*1e3,g=e.maxSessions??100;async function S(s,g){let S=t.get(s);if(!S)return;t.delete(s),S.ttlTimer!==void 0&&clearTimeout(S.ttlTimer);let w=await Promise.allSettled([S.server.close(),S.transport.close()]);for(let t of w)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:s,reason:g},`MCP HTTP session close failed`);e.log?.info?.({sessionId:s,reason:g},`MCP HTTP session closed`)}function w(t,g){g.ttlTimer!==void 0&&clearTimeout(g.ttlTimer),g.ttlTimer=setTimeout(()=>{S(t,`ttl-expired`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},s),g.ttlTimer.unref?.()}return{async handle(s,E){let D=firstHeader(s.headers[`mcp-session-id`]);if(D){let e=t.get(D);if(!e){writePlain(E,404,`MCP session not found`);return}w(D,e),await e.transport.handleRequest(s,E);return}if(s.method!==`POST`){writePlain(E,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=g){e.log?.warn?.({activeSessions:t.size,maxSessions:g},`MCP HTTP session cap reached`),writePlain(E,503,`Too many active MCP sessions`);return}let O=firstHeader(s.headers[MCP_CONNECTION_ID_HEADER]),k=validateAgentId(O)??void 0;O!==void 0&&k===void 0&&e.log?.warn?.({headerLength:O.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let j=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID$1(),enableJsonResponse:!0,onsessioninitialized:async s=>{try{let g=createSessionServer(e,j,k);await g.server.connect(j),t.set(s,g),w(s,g),e.log?.info?.({sessionId:s},`MCP HTTP session initialized`)}catch(g){throw t.delete(s),e.log?.error?.({err:g,sessionId:s},`MCP HTTP session initialization failed`),g}}});j.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},j.onclose=()=>{let t=j.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}S(t,`transport-closed`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await j.handleRequest(s,E)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>S(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:s,mcpHttpHandler:g,log:S,sessionManager:w,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O,contentAssetMiddleware:k,reactShellMiddleware:j,ephemeral:F}=e,L=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,B=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});B.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let H=new Map,q=new Set,ee=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`));for(let[e,s]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,s);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(w?.startsWith(`/api/`)){s.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${w}`})}).catch(e=>{S.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},D=s=>{if(F===!0&&k!==void 0&&(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host))){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`content-asset`});return}E(k,`content-asset`,s)},O=e=>E(j,`react-shell`,e),L=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(j!==void 0&&w?.startsWith(`/assets/`)){O(()=>D(L));return}if(k!==void 0||j!==void 0){D(()=>O(L));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),B.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=H.get(s);e!==void 0&&(clearTimeout(e),H.delete(s),S.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&D){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),g=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);D.setPresence(toBroadcasterKey(s),{displayName:t.displayName,icon:e,color:g,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){S.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let g=setInterval(()=>{try{t.ping()}catch{}},3e4);g.unref?.();let k=s?setInterval(()=>{D?.bumpPresenceTs(toBroadcasterKey(s))},3e3):null;k?.unref?.(),t.on(`close`,()=>{if(clearInterval(g),k!==null&&clearInterval(k),!s)return;let e=setTimeout(()=>{if(H.delete(s),ee)return;let e=(async()=>{S.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await w?.closeAllForAgent(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{E?.clearFocus(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{D?.clearPresence(toBroadcasterKey(s))}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await O?.onSessionClose()}catch(e){S.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();q.add(e),e.finally(()=>q.delete(e))},L);e.unref?.(),H.set(s,e),S.info({connectionId:s,graceMs:L},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`Upgrade socket error`)}),B.handleUpgrade(e,t,g,t=>{let g=s.handleConnection(t,e),w=!1;t.on(`message`,e=>{if(w)return;let s=e.byteLength;if(s>MAX_COLLAB_MESSAGE_BYTES){w=!0,incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,bytes:s,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}g.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{g.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||S.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:B,shutdown:async()=>{if(!ee){ee=!0;for(let e of H.values())clearTimeout(e);H.clear(),q.size>0&&await Promise.allSettled(q)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),s=sanitizeIdentityField(t.searchParams.get(`displayName`)),g=sanitizeIdentityField(t.searchParams.get(`clientName`)),S=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return s===null||g===null||S===null?null:{displayName:s,clientName:g,colorSeed:S}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,s){super(MISSING_OK_CONFIG_MESSAGE,s),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-Bu9Rdqzq.mjs`),S=dirname(e);try{tracedMkdirSync(S,{recursive:!0})}catch(e){e.code!==`EEXIST`&&s.warn({err:e,watchDir:S},`failed to create watch directory; watcher may be inert`)}let w=g(S,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==S&&t!==e});await new Promise(e=>{w.once(`ready`,e)});let E=null;try{E=readFileSync(e,`utf-8`)}catch{}let D=(g,S=!0)=>{if(g!==e)return;let w;try{w=readFileSync(g,`utf-8`)}catch(e){if(e.code===`ENOENT`){S&&s.debug({path:g},`config file disappeared between event and read; dropping`);return}s.warn({err:e,path:g},`config file read failed; dropping event`);return}if(w!==E){E=w;try{t(w)}catch(e){s.warn({err:e,path:g},`config file change handler threw`)}}},O=e=>D(e);w.on(`add`,O),w.on(`change`,O),w.on(`unlink`,t=>{t===e&&s.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),w.on(`error`,t=>{s.warn({err:t,watchDir:S,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let k=0,j=setInterval(()=>{k++,D(e,!1),k>=20&&clearInterval(j)},500);j.unref?.();let F=!1;return async()=>{F||(F=!0,clearInterval(j),await w.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-Bu9Rdqzq.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&s.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&s.debug({path:e},`config file disappeared between event and read; dropping`);return}s.warn({err:t,path:e},`config file read failed; dropping event`);return}if(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=relative(g,join(s,e.file));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}const BUILTIN_SKIP_FILES=new Set([`.DS_Store`,`.localized`]);function isAlwaysSkipFile(e){return BUILTIN_SKIP_FILES.has(e.slice(e.lastIndexOf(`/`)+1))}const SECRET_BEARING_DIRS=new Set([`.ssh`,`.aws`,`.gnupg`,`.kube`,`.docker`]);function pathHasSecretBearingDirSegment(e){for(let t of e.split(`/`))if(SECRET_BEARING_DIRS.has(t.toLowerCase()))return!0;return!1}const SECRET_CREDENTIAL_BASENAMES=new Set([`credentials`,`.netrc`,`.npmrc`,`.pgpass`,`.git-credentials`]),SECRET_KEY_SUFFIXES=[`.pem`,`.key`,`.p12`,`.pfx`,`.keystore`,`.jks`,`.ppk`];function isSecretBearingFile(e){let t=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(t===`.env`||t.startsWith(`.env.`)||SECRET_CREDENTIAL_BASENAMES.has(t)||t.startsWith(`id_rsa`)||t.startsWith(`id_ed25519`)||t.startsWith(`id_ecdsa`)||t.startsWith(`id_dsa`))return!0;for(let e of SECRET_KEY_SUFFIXES)if(t.endsWith(e))return!0;return!1}function isSingleDocAncestorDir(e,t){return t===e||t.startsWith(`${e}/`)}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D,O,k,j=0,F=0,L=0;function B(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],S=0,B=0;for(let s of IGNORE_FILE_NAMES){let w=join(t,s);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);S+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${w}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);S+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,w));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:S};B+=loadNestedIgnoreFiles(s,t,e,H),S=H.value;let q=loadGitExcludeSources(t,H);S=H.value,q.length>0&&(g.push(...q),e.add(q));let ee=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return D=e,O=g,k=ee,j=g.length,F=B,L=S,{patternCount:j,nestedFileCount:F,bytes:L}}B();let H=new Map;function q(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}let ee=()=>{S===void 0&&populateDirCount(s,``,q,H)};ee();function J(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function Y(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:q(e)}return{isExcluded(e,t){if(J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((H.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e)||pathHasSecretBearingDirSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e)?!0:t?.bypassFilters?!1:Y(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;H.set(t,(H.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=H.get(t)??0;s<=1?H.delete(t):H.set(t,s-1)},rebuildDirCount(){let e=new Map(H);H.clear();try{ee()}catch(t){for(let[t,s]of e)H.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=k,w=j,E=F,q=L,J=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async Y=>{try{let t=B();H.clear(),ee();let s=Date.now()-J;if(Y.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s}}catch(g){D=t,O=s,k=S,j=w,F=E,L=q,H.clear();try{ee()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let B=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(B)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:B}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
2828
2828
  `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){let s=e.startsWith(`!`),g=s?e.slice(1):e,S=g.startsWith(`/`)?g.slice(1):g,w=S.endsWith(`/`)?S.slice(0,-1):S,E=g.startsWith(`/`)||w.includes(`/`)?`${t}/${S}`:`${t}/**/${S}`;return s?`!${E}`:E}function loadNestedIgnoreFiles(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let w=0;for(let E of S){if(!E.isDirectory()||BUILTIN_SKIP_DIRS.has(E.name))continue;let S=join(e,E.name),D=relative(t,S);if(!D.startsWith(`..`)&&!(s.ignores(D)||s.ignores(`${D}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(S,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);g.value+=e.length;let S=parseIgnorePatterns(e).map(e=>prefixPattern(e,D));s.add(S),w++}catch(s){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,s)}}w+=loadNestedIgnoreFiles(S,t,s,g)}}return w}async function initContentDirStateAsync(e,t,s,g,S,w,E){let D;try{D=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let O of D){let D=t?`${t}/${O.name}`:O.name;if(O.isDirectory()){if(BUILTIN_SKIP_DIRS.has(O.name))continue;let t=join(e,O.name);if(!w){let e=relative(s,t);if(e.startsWith(`..`)||g.ignores(e)||g.ignores(`${e}/`))continue;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${s} at ${S}:`,e)}}}await initContentDirStateAsync(t,D,s,g,S,w,E)}else if(O.isFile()&&isSupportedDocFile(O.name)){if(!w){let e=S?`${S}/${D}`:D;if(g.ignores(e))continue}E.set(t,(E.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D=(0,import_ignore.default)(),O=[],k=new Map,j=()=>{S===void 0&&populateDirCount(s,``,F,k)};function F(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}function L(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function B(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:F(e)}async function H(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[];for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=parseIgnorePatterns(await readFile$1(g,`utf-8`));e.add(t.map(e=>prefixPattern(e,w)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let j=await loadGitExcludeSourcesAsync(t,{value:0});j.length>0&&(g.push(...j),e.add(j));let F=new Map;S===void 0&&await initContentDirStateAsync(s,``,t,e,w,E,F),D=e,O=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),k.clear();for(let[e,t]of F)k.set(e,t)}return await H(),{isExcluded(e,t){if(L(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(B(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((k.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e)||pathHasSecretBearingDirSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return L(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e)?!0:t?.bypassFilters?!1:B(e)},getWatcherIgnoreGlobs(){return O},incrementMdDir(e){let t=e===`.`?``:e;k.set(t,(k.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=k.get(t)??0;s<=1?k.delete(t):k.set(t,s-1)},rebuildDirCount(){let e=new Map(k);k.clear();try{j()}catch(t){for(let[t,s]of e)k.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=new Map(k),w=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async E=>{try{await H();let t=Date.now()-w;if(E.setAttributes({"ok.ignore.pattern_count":O.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:O.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(g){D=t,O=s,k.clear();for(let[e,t]of S)k.set(e,t);let w=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(w)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:w}}}})}}}function runDocLineageGuard(e,t,s){try{if(typeof t!=`string`||t.length===0||isSystemDoc(e)||isConfigDoc(e))return;let g=s.getLoadedDoc(e);if(g===void 0)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch: claim against unloaded ${e} is stale by construction`);let S=g.getMap(`lifecycle`).get(LINEAGE_EPOCH_KEY);if(typeof S!=`string`||S.length===0||S!==t)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch for ${e}: claimed epoch does not match the live lineage`)}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthDocLineageGuardError(),console.warn(JSON.stringify({event:`doc-lineage-guard-error`,documentName:e,errorName:t instanceof Error?t.name:typeof t,message:t instanceof Error?t.message:String(t)}))}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let s=resolve(e,t.slice(5));try{return readFileSync(s,`utf-8`).trim()}catch{try{let s=readFileSync(resolve(e,`packed-refs`),`utf-8`),g=t.slice(5),S=s.split(`
2829
2829
  `).find(e=>e.endsWith(` ${g}`));if(S)return S.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}function watchedGitFile(e){let t=e.split(`/`).pop()??``;return WATCHED_FILES.has(t)?t:null}async function tryStartParcelHeadWatcher(e,t){let s;try{s=await import(`@parcel/watcher`)}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher unavailable; falling back to chokidar`),null}try{let g=await s.subscribe(e,(e,s)=>{if(e){getLogger(`head-watcher`).warn({err:e},`[head-watcher] parcel subscription error`);return}for(let e of s)t(e.path)});return()=>g.unsubscribe()}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar`),null}}async function startChokidarHeadWatcher(e,t){let{watch:s}=await import(`./chokidar-Bu9Rdqzq.mjs`),g=s(e,{ignoreInitial:!0,depth:0,followSymlinks:!1});return g.on(`all`,(e,s)=>t(s)),g.on(`error`,e=>{getLogger(`head-watcher`).warn({err:e},`[head-watcher] chokidar watcher error`)}),()=>g.close()}async function startHeadWatcher(e,t,s,g={}){let S=resolveGitDir(e);if(!S)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let w=S,E=!1,D=null,O=null,k=null,j=null;async function F(e){if(B&&await B,!E)return;D&&=(clearTimeout(D),null),O&&=(clearTimeout(O),null);let t=readHeadSha(w),g=k!==t,S=readBranchFromHead(w),F;F=S?.startsWith(`detached-`)?`detached-head`:j===S?`within-branch`:`cross-branch`;let L=j;try{await s({headMoved:g,oldHead:k,newHead:t,timeout:e,batchKind:F,oldBranch:L,newBranch:S})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{E=!1,k=t,j=S}}function L(){D&&clearTimeout(D),D=setTimeout(()=>{D=null,F(!1)},QUIET_WINDOW_MS)}let B=null;async function H(e){if(!E){E=!0,k=readHeadSha(w);let s=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();B=s,await s,B=null,O=setTimeout(()=>{O=null,F(!0)},BATCH_TIMEOUT_MS)}L()}let q=e=>{let t=watchedGitFile(e);t!==null&&H(t)},ee=null,J=`chokidar`;if(g.forceBackend!==`chokidar`&&(ee=await tryStartParcelHeadWatcher(w,q),ee&&(J=`parcel`)),!ee){if(g.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable for HEAD watching (forced backend)`);ee=await startChokidarHeadWatcher(w,q),J=`chokidar`}let Y=ee;return k=readHeadSha(w),j=readBranchFromHead(w),getLogger(`head-watcher`).info({gitDir:w,backend:J},`watching for HEAD changes`),{unsubscribe:async()=>{E&&await F(!1),D&&clearTimeout(D),O&&clearTimeout(O),await Y()},getLastKnownBranch:()=>j}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:s,signalChannel:g,debounceMs:S=100}=e,w=new Map;function E(e){let t=w.get(e);t&&(clearTimeout(t),w.delete(e))}function D(e,D){E(e),w.set(e,setTimeout(()=>{w.delete(e);try{let S=serializeLiveDocument(D);t.updateDocumentFromMarkdown(e,S),g?.(`backlinks`),g?.(`graph`),s&&(s.updateDocumentFromMarkdown(e,S),g?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},S))}return{async onChange({documentName:e,document:t,transactionOrigin:s}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(s)&&s.context?.origin===`file-watcher`||D(e,t)},async beforeUnloadDocument({documentName:e}){E(e)},async onDestroy(){for(let e of w.values())clearTimeout(e);w.clear()}}}const log$4=getLogger(`shadow-gc`),GC_GRACE_PERIOD_MS=1440*60*1e3,SESSION_WRITER_TTL_MS=720*60*60*1e3;function extractBranchNames(e){let t=new Set;for(let s of e){let e=s.replace(/^refs\/wip\//,``),g=e.lastIndexOf(`/`);if(g<=0)continue;let S=e.slice(0,g);parseWriterId(e.slice(g+1)).classification!==`unknown`&&t.add(S)}return t}async function getProjectBranchSha(e,t){try{return(await esm_default().env({GIT_DIR:e}).raw(`rev-parse`,`refs/heads/${t}`)).trim()}catch{return null}}async function listProjectBranches(e){let t=new Set;try{let s=(await esm_default().env({GIT_DIR:e}).raw(`for-each-ref`,`refs/heads/`,`--format=%(refname:short)`)).trim();if(s)for(let e of s.split(`
2830
2830
  `))e&&t.add(e)}catch(e){log$4.warn({err:e},`[shadow-gc] listProjectBranches failed; treating as no project branches`)}return t}async function gcShadowBranches(e,t,s=DEFAULT_CHECKPOINT_RETENTION,g=`.`){let S={deletedBranches:[],renamedBranches:[],retainedBranches:[],checkpointGc:{},deletedStaleSessionRefs:0},w=shadowGit(e,{timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}),E;try{E=(await w.raw(`for-each-ref`,`refs/wip/`,`--format=%(refname)`)).trim()}catch{return S}if(!E)return S;let D=E.split(`
@@ -2843,7 +2843,7 @@ In headless mode, write the recap into the research article's "Further reading"
2843
2843
  `,`
2844
2844
  `).split(`
2845
2845
  `),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();initChain=Promise.resolve();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(){let e=this.initChain.then(()=>this.initOnce());return this.initChain=e.catch(e=>{console.warn(`[tag-index] init failed (chain cleared for next init):`,e)}),e}async initOnce(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=await this.listDocsWithPaths(),t=50;for(let t=0;t<e.length;t+=50){let s=e.slice(t,t+50),g=await Promise.all(s.map(async({docName:e,filePath:t})=>{try{return{docName:e,markdown:await readFile$1(t,`utf-8`)}}catch(t){return console.warn(`[tag-index] Failed to read ${e} during init:`,t),null}}));for(let e of g)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown)}catch(t){console.warn(`[tag-index] Failed to index ${e.docName} during init:`,t)}}}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))}async listDocsWithPaths(){let e=[];await 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))}async walkContentDir(e,t){let s;try{s=await readdir(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;await 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 buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}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,singleDocRelPath:ee,ephemeral:J=!1}=e,Y=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}function ne(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function ae(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}initTelemetry();let oe=randomUUID$1(),se=getLocalDir(s);if(acquireServerLock(se,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:se,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(se),e}let ce=createBasenameIndex(),ue=(e,t)=>ce.resolveEmbed(e,t),de=(e,s)=>{let g=ce.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}},fe,me,ge,_e,ve,ye,Ce,we,Te=null,De=null,je=null,Me=null,Pe=ne(),Ie=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ne();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Pe.enabled,providerFingerprint:ae(Pe)}),Re=null,ze=new Set,Be=!1,Ve,Ue,We,Ge=new Promise((e,t)=>{Ue=e,We=t});function Ke(e){Te?.signal(e)}let Xe=2e3,$e=null;function nt(){$e!==null&&clearTimeout($e),$e=setTimeout(()=>{$e=null,me.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let rt=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),it=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||rt.setRenamed(e,t)},at=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(rt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}rt.setDeleted(e)}},st=e=>{isSystemDoc(e)||isConfigDoc(e)||rt.delete(e)};try{fe=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{me.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ge.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild(Wt).then(({prunedFiles:e,prunedFolders:t})=>{let s=e+t;s>0?getLogger(`server-factory`).info({pruned:s,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),me=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:fe}),ge=new TagIndex({contentDir:t,contentFilter:fe}),ge.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),_e={current:F},ve=E?createMaintenanceCoordinator({getShadow:()=>_e.current??null,getCurrentBranch:()=>Kt?.getLastKnownBranch()??null,contentRoot:L??``,projectGitDir:resolveGitDir(s)??void 0,isWriterLive:e=>{if(!je&&!we)return getLogger(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(je?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of we?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,ye=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:_e,ephemeral:J,contentRoot:L,backlinkIndex:me,configHomedirOverride:k,getCurrentBranch:()=>Kt?.getLastKnownBranch()??null,resolveEmbed:ue,resolveSize:de,getPrincipal:()=>Re,onAgentCommit:()=>Te?.signal(`session-activity`),onFlushCommit:()=>ve?.noteFlushCommit(),onDiskFlush:(e,t,s,g)=>{Te?.emitDiskAck(e,t),!(isSystemDoc(e)||isConfigDoc(e))&&assetReferencesChanged(g,s)&&(Me?.(),Ke(`files`))},onConfigRejected:(e,t)=>Te?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),Ce=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[ye.extension]});let B=Ce.shouldUnloadDocument.bind(Ce);Ce.shouldUnloadDocument=e=>{if(ze.has(e)||Be&&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)},Ve=async e=>{ze.add(e);try{await Ce.unloadDocument(e)}finally{ze.delete(e)}},Te=new CC1Broadcaster(Ce),De=new AgentFocusBroadcaster(Ce),je=new AgentPresenceBroadcaster(Ce),we=new AgentSessionManager(Ce);let q=createLiveDerivedIndexExtension({backlinkIndex:me,tagIndex:ge,signalChannel:Ke});Ce.configuration.extensions.push(q),Ce.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!==oe)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${oe}`);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`&&(Re&&s.principalId===Re.id?E.principalId=Re.id:Re?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Re.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),Ce.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 Y=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(Y,`${e}${getDocExtension(e)}`);return!t.startsWith(`${Y}/`)&&t!==Y?null:t}Ce.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:rt,resolveFilePath:te,fileExists:existsSync})}}),Ce.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Ce.documents.get(e)})}}),Ce.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 ae=createApiExtension({hocuspocus:Ce,sessionManager:we,contentDir:t,contentFilter:fe,serverInstanceId:oe,getFileIndex:()=>Wt?Wt.getFileIndex():new Map,getAllFilesIndex:()=>Wt?Wt.getAllFilesIndex():new Map,getFileIndexGeneration:()=>Wt?.getFileIndexGeneration()??0,mutateFileIndex:e=>Wt?.mutateFileIndex(e),getFolderIndex:()=>Wt?Wt.getFolderIndex():new Map,getAliasMap:()=>Wt?Wt.getAliasMap():new Map,getFolderAliasIndex:()=>Wt?Wt.getFolderAliasIndex():new Map,rescanFiles:()=>Wt?.rescanFromDisk(),enableTestRoutes:j,shadowRef:_e,flushGitCommit:()=>ye.flushPendingGitCommit(),flushContributors:()=>ye.flushContributors(),takeStoreFailure:e=>ye.takeStoreFailure(e),takeStoreDivergence:e=>ye.takeStoreDivergence(e),markAgentWriteStore:e=>ye.markAgentWriteStore(e),getCurrentBranch:()=>Kt?.getLastKnownBranch()??null,getDiskAckSVs:()=>Te?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:me,tagIndex:ge,signalChannel:Ke,agentFocusBroadcaster:De,agentPresenceBroadcaster:je,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>$t,localOpCliArgs:H,projectDir:s,resolveEmbed:ue,getPrincipal:()=>Re,forceUnloadDocument:Ve,ready:Ge,recentlyRemovedDocs:rt,serializeDoc:jt,semanticSearch:Ie,getSemanticSimilarityFloor:()=>ne().similarityFloor,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Me=e}});Ce.configuration.extensions.push(ae),Ce.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:_e,contentRoot:L,getCurrentBranch:()=>Kt?.getLastKnownBranch()??null,resolveEmbed:ue,resolveSize:de})),Ce.configuration.extensions.push(createSyncHandshakeSpanExtension()),Ce.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>$t,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(se),e}let vt=null,Tt=new Map,Et=[];function Dt(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function jt(e){let t=Ce.documents.get(e);return t?serializeYDocSource(t):null}let Mt=(e,t)=>applyExternalChange(Ce,e,t,ue,de);function Ft(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let It=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of Ce.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=Ce.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,ue,s)},FILE_WATCHER_ORIGIN)}catch(t){Y.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},Lt=null,Rt=e=>{e&&(Lt===null&&(Lt=new Set,setImmediate(()=>{let e=Lt;if(Lt=null,e)try{for(let t of e)It(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Lt.add(e))};function zt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Bt(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),me.updateDocumentFromMarkdown(e.docName,e.content),nt(),ge.updateDocumentFromMarkdown(e.docName,e.content),Ke(`files`),Ke(`backlinks`),Ke(`graph`),Ke(`tags`),st(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=Ce.documents.get(t);if(!g){me.updateDocumentFromMarkdown(t,s),nt(),ge.updateDocumentFromMarkdown(t,s),Ke(`backlinks`),Ke(`graph`),Ke(`tags`);return}let S=getReconciledBase(t)??``,w=jt(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(Y.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`:Ft(g),me.updateDocumentFromMarkdown(t,s),nt(),ge.updateDocumentFromMarkdown(t,s),Ke(`backlinks`),Ke(`graph`),Ke(`tags`);break;case`clean`:try{Mt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Ft(g),me.updateDocumentFromMarkdown(t,s),nt(),ge.updateDocumentFromMarkdown(t,s),Ke(`backlinks`),Ke(`graph`),Ke(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Ft(g)}break;case`merged`:try{Mt(t,E.newContent),setReconciledBase(t,s),incrementReconcile(),Ft(g),me.updateDocumentFromMarkdown(t,s),nt(),ge.updateDocumentFromMarkdown(t,s),Ke(`backlinks`),Ke(`graph`),Ke(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Ft(g)}break;case`conflicts`:try{Mt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),me.updateDocumentFromMarkdown(t,s),nt(),ge.updateDocumentFromMarkdown(t,s),Ke(`backlinks`),Ke(`graph`),Ke(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}{let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}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=Ce.documents.get(t);if(!s){me.deleteDocument(t),nt(),ge.deleteDocument(t),Ke(`files`),Ke(`backlinks`),Ke(`graph`),Ke(`tags`),at(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=jt(t)??``,w=S!==g;if(w&&_e.current){let e=_e.current,s=Kt?.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(),Y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{Y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),me.deleteDocument(t),nt(),ge.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),Ce.closeConnections(t),await Ve(s),Ke(`files`),Ke(`backlinks`),Ke(`graph`),Ke(`tags`),at(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=Ce.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),me.renameDocument(t,s,g),nt(),ge.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}Y.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),Ke(`files`),Ke(`backlinks`),Ke(`graph`),Ke(`tags`),it(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=Ce.documents.get(t);if(!s)return;let g=jt(t);g===null?Y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,g);let S=s.getMap(`lifecycle`);S.set(`status`,`conflict`),S.set(`reason`,`conflict-markers`),Y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ce.add(e.relativePath),Ke(`files`),Rt(basename(e.relativePath));break;case`asset-delete`:ce.remove(e.relativePath),Ke(`files`),Rt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Ke(`files`);break;case`file-create`:case`file-update`:case`file-delete`:Ke(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=zt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Vt=[];async function Ht(e){if(isBatchInProgress()){Vt.push(e);return}await Bt(e)}async function Ut(){let e=Vt.splice(0,Vt.length);for(let t of e)await Bt(t)}let Wt=null,Kt=null,$t=null,en=null;async function jr(e){if(Ce.documents.size===0)return;let t=!1,s=new Promise(e=>{Ce.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(Ce.documents.keys());Ce.closeConnections(),Ce.flushPendingStores();for(let e of Ce.documents.values())e.getConnectionsCount()===0&&Ce.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(Ce.documents.keys()),S=[],E=[];if(_e.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=jt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Dt(_e.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:_e.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),Y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),Y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else Y.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 Mr(){return en||(en=(async()=>{let e=Date.now(),t=[];Be=!0,$e!==null&&(clearTimeout($e),$e=null);let g,S=await Promise.race([Ge.then(()=>`completed`,e=>(Y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&Y.warn({},`[server] init did not complete within 5s during shutdown`);let w=Ce.documents.size;ve?.destroy();try{try{try{Kt&&=(await Kt.unsubscribe(),null),Wt&&=(await Wt.unsubscribe(),null);for(let{docName:e,cleanup:t}of Et)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Et.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{Te?.destroy(),je?.destroy(),vt&&=(await vt.disconnect(),null);for(let[e,t]of Tt)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Tt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await we.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await jr(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ye.flushPendingGitCommit(),await ye.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)}),Y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{$t&&=(await $t.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(_e.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(_e.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(_e.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?Y.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):Y.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(se)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),Y.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)})}}})(),en)}let Fr=[];async function Ir(){try{Re=await loadPrincipal(s),Y.info({principalId:Re.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!_e.current)try{_e.current=await initShadowRepo(s),Y.info({gitDir:_e.current.gitDir},`[server] history repo initialized at ${_e.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Fr.push(`shadow-repo`)}if(_e.current){let e=null;try{e=loadRenameLogIndex(_e.current.gitDir),sweepLazyPopOrphans(_e.current.gitDir,e),setRenameLogIndex(_e.current.gitDir,e),Y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){Y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(_e.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){Y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await ve?.runBootMaintenance()}catch(e){Y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(_e.current)try{await shadowGit(_e.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`)){Y.warn({},`[server] history repo appears corrupted — reinitializing`);try{_e.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),_e.current=void 0,Fr.includes(`shadow-repo`)||Fr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(_e.current)try{let e=resolve(_e.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{}Y.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(_e.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){Y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else Y.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){Y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){Y.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;Y.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){Y.error({err:e},`[server] managed rename recovery failed`),Fr.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&Y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){Y.error({err:e},`[server] upload-tempfile sweep failed`),Fr.push(`upload-tempfile-sweep`)}try{vt=await Ce.openDirectConnection(SYSTEM_DOC_NAME),Te?.emitServerInfo(oe,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Fr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await Ce.openDirectConnection(e);Tt.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Fr.push(`config-doc:${e}`)}let S=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 e of g){let t=S.get(e);if(t)try{Y.info({docName:e,path:t},`[config-file-watcher] starting`);let s=await startConfigFileWatcher(t,t=>{let s=Ce.documents.get(e);Y.info({docName:e,hasDocument:s!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,e,t,ye.configPersistenceCtx);if(Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=te();$t?.setEnabled(e).catch(t=>{Y.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}let S=ne();Ie.applyConfig({enabled:S.enabled,providerFingerprint:ae(S)})});Et.push({docName:e,cleanup:s}),Y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(s){Y.warn({err:s,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Fr.push(`config-file-watcher:${e}`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:s,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(s,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(S=t)}}catch{}let w=S?[e,g,S]:[e,g],E=Y;E.info({okignorePath:e,gitignorePath:g,gitInfoExcludePath:S,ephemeral:J},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let D=J?null:await startMultiPathConfigFileWatcher(w,(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(Ce.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,ye.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let S=await fe.rebuildIgnorePatterns();if(S.ok)E.info({changedPath:relative(s,t),patternCount:S.patternCount,nestedFileCount:S.nestedFileCount,durationMs:S.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),Te?.signal(`files`);else{let e=relative(s,t)||`.`;E.warn({changedPath:e,error:S.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),Te?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Et.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`))}catch(e){Y.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Fr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),me.switchBranch(E);try{{let e=getActiveBranch();try{if(await me.loadFromDisk(e)){let t=await me.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await me.rebuildFromDisk(e);me.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){Y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Wt=await startWatcher(t,Ht,fe);try{await ge.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Fr.push(`tag-index`)}let e=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:fe,basenameIndex:ce,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during seed (${t}${s?` ${s}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:ce,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during single-file seed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Fr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Fr.push(`basename-index`)}}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Fr.push(`file-watcher`)}try{Kt=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),Ce.flushPendingStores(),await ye.flushPendingGitCommit(),setBatchInProgress(!0),_e.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of Ce.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=jt(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(_e.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),Y.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){Y.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Vt.length,g=e.newBranch??`main`;if(Y.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`){if(setBatchInProgress(!1),await Ut(),await ye.flushDeferredStores(`within-branch`),$t!==null)try{await $t.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Vt.splice(0,Vt.length),switchReconciledBaseScope(g),$e!==null&&(clearTimeout($e),$e=null),me.switchBranch(g),fe.rebuildDirCount();try{let e=0;ce.clear(),await seedBasenameIndex({contentDir:t,contentFilter:fe,basenameIndex:ce,onSkip:(t,s,S)=>{e++,Y.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.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`),Fr.includes(`basename-index-partial`)||Fr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of Ce.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=jt(e)??``;if(S!==t&&_e.current){let t=_e.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(),Y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{Y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Y.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);Mt(e,w),setReconciledBase(e,w),Y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){Y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}Y.info({branch:g,docCount:Ce.documents.size},`[branch-switch] loaded branch ${g} (${Ce.documents.size} docs)`);try{if(await me.loadFromDisk(g)){let e=await me.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await me.rebuildFromDisk(g);me.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){Y.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ge.init(),_e.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Ce.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(_e.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`:Mt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:Mt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=Ce.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){Y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&Y.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&_e.current)try{let t=shadowGit(_e.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
2846
- `))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ye.flushDeferredStores(`discard-stale`),Te?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&_e.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(_e.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Fr.push(`head-watcher`)}function D(e){for(let g of e)try{let e=relative(t,join(s,g));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Ce.documents.get(S);if(!w)continue;let E=jt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let O=buildSyncCredentialArgs(H);try{$t=new SyncEngine({projectDir:s,contentDir:t,contentFilter:fe,contentRoot:L,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:Te,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ye.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:D,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await $t.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),$t=null}Ke(`files`),Ke(`backlinks`),Ke(`graph`),Ke(`tags`)}return Ir().then(Ue,We),{hocuspocus:Ce,sessionManager:we,cc1Broadcaster:Te,agentFocusBroadcaster:De,agentPresenceBroadcaster:je,maintenanceCoordinator:ve,contentFilter:fe,basenameIndex:ce,serverInstanceId:oe,destroy:Mr,ready:Ge,degraded:Fr,lockDir:se,get syncEngine(){return $t}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-CyhBidkz-DXuuHDkK.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se}=H,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:S}),fe=D();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:q,mcpHttpHandler:de,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e,ephemeral:e.ephemeral}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;g!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);fe.once(`error`,g),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,g),t()})})}catch(e){if(ge)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let we=fe.address(),Te=typeof we==`object`&&we?we.port:e.port??0;if(ue=Te,O(te,Te),ge&&updateUiLockPort(te,Te),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let De=!1,je=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};return ye=async()=>{if(De)return;De=!0;let e=[],t=async(t,s)=>{try{await je(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),de!==void 0&&await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:ye,lockDir:te,contentDir:e.contentDir,port:Te,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
2846
+ `))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ye.flushDeferredStores(`discard-stale`),Te?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&_e.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(_e.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Fr.push(`head-watcher`)}function D(e){for(let g of e)try{let e=relative(t,join(s,g));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Ce.documents.get(S);if(!w)continue;let E=jt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let O=buildSyncCredentialArgs(H);try{$t=new SyncEngine({projectDir:s,contentDir:t,contentFilter:fe,contentRoot:L,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:Te,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ye.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:D,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await $t.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),$t=null}Ke(`files`),Ke(`backlinks`),Ke(`graph`),Ke(`tags`)}return Ir().then(Ue,We),{hocuspocus:Ce,sessionManager:we,cc1Broadcaster:Te,agentFocusBroadcaster:De,agentPresenceBroadcaster:je,maintenanceCoordinator:ve,contentFilter:fe,basenameIndex:ce,serverInstanceId:oe,destroy:Mr,ready:Ge,degraded:Fr,lockDir:se,get syncEngine(){return $t}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-CyhBidkz-DUTkjNDG.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se}=H,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:S}),fe=D();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:q,mcpHttpHandler:de,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e,ephemeral:e.ephemeral}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;g!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);fe.once(`error`,g),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,g),t()})})}catch(e){if(ge)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let we=fe.address(),Te=typeof we==`object`&&we?we.port:e.port??0;if(ue=Te,O(te,Te),ge&&updateUiLockPort(te,Te),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let De=!1,je=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};return ye=async()=>{if(De)return;De=!0;let e=[],t=async(t,s)=>{try{await je(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),de!==void 0&&await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:ye,lockDir:te,contentDir:e.contentDir,port:Te,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
2847
2847
  `).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){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};log.info({},`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?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`Open Knowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
2848
2848
  `,`utf-8`),t}export{STARTER_TEMPLATES as $,writeConfigPatch as $i,isSelfWrite as $n,runDeviceFlowSubprocess as $r,createOsProbe as $t,LIVE_DERIVED_INDEX_DEBOUNCE_MS as A,tracedWriteFile as Ai,getMetrics as An,reconcile as Ar,clearContributors as At,OBSERVER_SYNC_ORIGIN as B,writeStateManifest as Bi,initToleranceTelemetryWriter as Bn,resolveCursorBinaryDefault as Br,countShadowObjects as Bt,GIT_UPSTREAM_WRITER as C,tracedMkdir as Ci,gcCheckpointRefs as Cn,readProjectLocalSemanticConfig as Cr,buildExecResult as Ct,HocuspocusAuthRejection as D,tracedRmSync as Di,getLogger as Dn,readTargetRecordedAt as Dr,classifyEvents as Dt,HOCUSPOCUS_AUTH_REJECTION_REASONS as E,tracedRenameSync as Ei,getLogFilePath as En,readStateManifest as Er,buildWipTree as Et,MCP_SERVER_NAME as F,validateCloneInputs as Fi,incrementCollabSocketFilteredError as Fn,releaseUiLock as Fr,commitWipFromTree as Ft,ROLLBACK_ORIGIN as G,LATEST_PROTOCOL_VERSION as Gi,isAllowedWorkspaceHostHeader as Gn,resolveUiInfo as Gr,createContentFilter as Gt,PANE_TARGET_TTL_MS as H,writeTracker as Hi,installTestLoggers as Hn,resolveLockDir as Hr,countWipRefs as Ht,MIN_GIT_VERSION as I,validateSkillZip as Ii,incrementServerObserverFire as In,removeLastKnownHash as Ir,compareSemver as It,SKILL_INSTALL_EVENTS_FILE_REL as J,isJSONRPCResultResponse as Ji,isKnownPackId as Jn,rewriteMarkdownLinksForDocumentRename as Jr,createEphemeralProjectDir as Jt,ROOT_GITIGNORE_TEMPLATE as K,isInitializedNotification as Ki,isConfigDoc as Kn,restoreContributors as Kr,createContentFilterAsync as Kt,MISSING_OK_CONFIG_MESSAGE as L,withSpan as Li,initContent as Ln,resetMetrics as Lr,containsConflictMarkers as Lt,MANAGED_RENAME_ORIGIN as M,updateLastKnownHash as Mi,handleCollabSocketError as Mn,recordSkillInstallEvent as Mr,coercePackId as Mt,MAX_AGENT_SESSIONS as N,updateUiLockPort as Ni,handleSpawnCursor as Nn,registerAllTools as Nr,commitUpstreamImport as Nt,HocuspocusAuthTokenSchema as O,tracedRmdirSync as Oi,getLogsDir as On,readTargetVersion as Or,classifyFsPath as Ot,MCP_CONNECTION_ID_HEADER as P,validateAgentId as Pi,hasGcLogLatch as Pn,registerWrite as Pr,commitWip as Pt,STARTER_PACK_IDS as Q,withFileLockSync as Qi,isProjectRoot as Qn,runCloneSubprocess as Qr,createMcpHttpHandler as Qt,McpLogger as R,withSpanSync as Ri,initShadowRepo as Rn,resolveBundledSkillDir as Rr,contentHash as Rt,GIT_PREFLIGHT_FAIL_SPAN_NAME as S,tracedLinkSync as Si,formatContributorsFrom as Sn,readBranchFromHead as Sr,buildConfigYmlContent as St,GitTooOldError as T,tracedRename as Ti,getLocalDir as Tn,readSkillInstallStateSnapshot as Tr,buildStarterFolderFrontmatterYaml as Tt,PinoLogger as U,McpServer as Ui,installUserSkill as Un,resolvePack as Ur,createApiExtension as Ut,OK_OKIGNORE_TEMPLATE as V,writeTargetVersion as Vi,installPrettyZodErrors as Vn,resolveCursorSpawnInvocation as Vr,countStaleAgentWipRefs as Vt,ProjectGitInitError as W,JSONRPCMessageSchema as Wi,isAllowedApiOrigin as Wn,resolvePackageVersion as Wr,createAssetServeMiddleware as Wt,STARTER_FOLDER_FRONTMATTER_FILENAME as X,readConfigSafely as Xi,isPairedWriteOrigin as Xn,runAuthReposSubprocess as Xr,createFileLogger as Xt,STARTER_FOLDERS as Y,atomicWriteFileSync as Yi,isLoopbackAddress as Yn,rewriteWikiLinksForDocumentRename as Yr,createExternalChangeHandler as Yt,STARTER_PACKS as Z,resolveConfigPath as Zi,isPathWithinDir as Zn,runAuthStatusSubprocess as Zr,createLiveDerivedIndexExtension as Zt,DEFAULT_PACK_ID as _,streamingProblemEvent as _i,findEnclosingGitRoot as _n,pathToDocName as _r,assertGitAvailable as _t,AgentPresenceBroadcaster as a,saveInMemoryCheckpoint as ai,describeStoredEmbeddingsKey as an,loadPrincipal as ar,SingleFileNotMarkdownError as at,FILE_WATCHER_ORIGIN as b,toBroadcasterKey as bi,formatAuthRejectionWire as bn,readAllTargets as br,bootServer as bt,AutoStartDisabledError as c,serializeError as ci,detectProjectShape as cn,logsPreviousPath as cr,UiLockCollisionError as ct,CONFIG_FILENAME as d,shutdownTelemetry as di,encodeFolderRoute as dn,normalizeFsPath as dr,acquireUiLock as dt,GitDirAccessError as ea,runWithMcpLogger as ei,createPersistenceExtension as en,isSystemDoc as er,STATE_MANIFEST_FILENAME as et,CONFLICT_MARKER_RE as f,spansCurrentPath as fi,ensureProjectGit as fn,packageVersionMajorMinor as fr,applyAgentMarkdownWrite as ft,DEFAULT_EMBEDDINGS_DIMENSIONS as g,startWatcher as gi,fallbackPaths as gn,parseKeepaliveConnectionId as gr,assertCompatibleStateManifest as gt,DEFAULT_CHECKPOINT_RETENTION as h,splitMarkdownBlocks as hi,extractWikiLinksFromMarkdown as hn,parseHocuspocusAuthToken as hr,armPaneTarget as ht,AgentFocusBroadcaster as i,resolveShadowDir as ia,sanitizeClientName as ii,createTestLogger as in,listStarterPacks as ir,SingleFileNotFoundError as it,LOG_MD_TEMPLATE as j,tracedWriteFileSync as ji,getTracer as jn,recordContributor as jr,clearEmbeddingsKeyFromAllBackends as jt,INSTALLED_AGENTS_SCHEMES as k,tracedUnlinkSync as ki,getMeter as kn,readUiLock as kr,clearArmedPaneTarget as kt,BacklinkIndex as l,setActiveSpanAttributes as li,emitPreflightFailureSpan as ln,makeLazyEmbeddingsKeyStore as lr,__getShowAllWalkStatsForTesting as lt,ConfigSchema as m,spawnDetached as mi,evictStaleTrackerEntries as mn,parseGitVersion as mr,applySeed as mt,AGENT_ID_RE as n,parseCheckpoint as na,safeSubdir as ni,createServerObserverExtension as nn,lastKnownHash as nr,SeedRootDirError as nt,AgentSessionCapacityError as o,saveVersion as oi,detectClaudeDesktopPresence as on,loggerFactory as or,StateManifestError as ot,CURSOR_BUNDLE_PATHS_BY_PLATFORM as p,spansPreviousPath as pi,errorResponse as pn,parseAuthRejectionWire as pr,applyExternalChange as pt,SERVICE_WRITER as q,isJSONRPCRequest as qi,isHocuspocusAuthRejectionReason as qn,restoreLifecycleFromConflictsJson as qr,createEmbeddingsSecretStore as qt,AGENT_WRITE_ORIGIN as r,resolveGitDirDetailed as ra,safetyCheckpoint as ri,createStreamingErrorWriter as rn,listRescueCheckpoints as rr,SingleFileNotAFileError as rt,AgentSessionManager as s,seedBasenameIndex as si,detectGit as sn,logsCurrentPath as sr,TagIndex as st,AGENT_ID_MAX_LEN as t,MalformedGitPointerError as ta,safeContentPath as ti,createServer$1 as tn,isToleranceTelemetryEnabled as tr,SeedPrerequisiteError as tt,CC1Broadcaster as u,shadowGit as ui,encodeDocName as un,mountMcpAndApi as ur,__resetShowAllWalkStatsForTesting as ut,EMBEDDINGS_API_KEY_ENV as v,swapContributors as vi,findEnclosingProjectRoot as vn,planSeed as vr,assertNeverDiskEvent as vt,GitNotAvailableError as w,tracedMkdirSync as wi,getCurrentMcpLogger as wn,readServerPackageVersion as wr,buildSkillZip as wt,FileEmbeddingsBackend as x,tracedAppendFileSync as xi,formatContributors as xn,readArmedPaneTarget as xr,buildAndOpenSkill as xt,FILE_SYSTEM_WRITER as y,teardownToleranceTelemetryWriter as yi,flushFileLogger as yn,prepareSingleFileOpen as yr,attachIdleShutdown as yt,MissingOkConfigError as z,writeRootGitignoreForNewRepo as zi,initTelemetry as zn,resolveContentDir as zr,contributorCount as zt};
2849
- //# sourceMappingURL=dist-Bl_tym1Z.mjs.map
2849
+ //# sourceMappingURL=dist-CTSVLMDV.mjs.map