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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +1 -1
  3. package/dist/cli.mjs +17 -17
  4. package/dist/config-schema.json +17 -0
  5. package/dist/config.project-local.schema.json +17 -0
  6. package/dist/constants-Ba7kuv_h.mjs +2 -0
  7. package/dist/dist-BYM_jxPa.mjs +1 -0
  8. package/dist/{dist-DEBa6nkk.mjs → dist-Pe1Q8dMj.mjs} +24 -24
  9. package/dist/{gh-detect-Cm8hekXk.mjs → gh-detect-C6QZctcU.mjs} +2 -2
  10. package/dist/index.mjs +1 -1
  11. package/dist/init-CM8vkkIB.mjs +1 -0
  12. package/dist/{init-reB4XeLP.mjs → init-CWVdQeQP.mjs} +5 -5
  13. package/dist/{launch-json-removal-v_ZIEJ04.mjs → launch-json-removal-TcMw8bt1.mjs} +2 -2
  14. package/dist/{loader-C3crD0ZW.mjs → loader-B7V7uIES.mjs} +2 -2
  15. package/dist/loader-BktwkYhG.mjs +1 -0
  16. package/dist/{open-browser-B5KfPH4H.mjs → open-browser-CPSoIF8R.mjs} +2 -2
  17. package/dist/{preview-yptAXY9Q.mjs → preview-BBQwe-gv.mjs} +2 -2
  18. package/dist/preview-C317XX3v.mjs +1 -0
  19. package/dist/public/assets/{ActivityModeContent-DIN900Tw.js → ActivityModeContent-tdDE-61j.js} +1 -1
  20. package/dist/public/assets/{CodeMirrorPropInput-ZO7IAXY4.js → CodeMirrorPropInput-DNVWCpb0.js} +2 -2
  21. package/dist/public/assets/DocumentContext-Dc9Bp6oO.js +36 -0
  22. package/dist/public/assets/{EnableSyncConfirmDialog-CDm2rW8c.js → EnableSyncConfirmDialog-BRji_vuj.js} +1 -1
  23. package/dist/public/assets/{GraphPanel-BSBoTUuF.js → GraphPanel-cScfZ2Kh.js} +9 -9
  24. package/dist/public/assets/ManagedArtifactProperties-_bcR56Re.js +1 -0
  25. package/dist/public/assets/{McpConsentDialogBody-DZr8d0vu.js → McpConsentDialogBody-pimma18E.js} +1 -1
  26. package/dist/public/assets/{MermaidDocEditor-DqKOZzfV.js → MermaidDocEditor-Bm909VrA.js} +1 -1
  27. package/dist/public/assets/PropertyPanel-CvVf4BX_.js +2 -0
  28. package/dist/public/assets/{SettingsDialogBody-ILc_zuoi.js → SettingsDialogBody-DUbN9FMx.js} +3 -3
  29. package/dist/public/assets/{ShareBranchSwitchDialog-Dv66XosJ.js → ShareBranchSwitchDialog-nDcQbyjK.js} +1 -1
  30. package/dist/public/assets/{ShareReceiveDialog-DcJrhi3C.js → ShareReceiveDialog-Bi91UHeB.js} +1 -1
  31. package/dist/public/assets/{ShareReceiveMissDialog-8AKkkTF9.js → ShareReceiveMissDialog-Cr-lyfq3.js} +1 -1
  32. package/dist/public/assets/{SkillEditorActions-D7GmHyae.js → SkillEditorActions-COoshjEA.js} +1 -1
  33. package/dist/public/assets/{SourceEditor-F7MHMYDQ.js → SourceEditor-CmecCLss.js} +1 -1
  34. package/dist/public/assets/{TerminalPanel-Z0XhL8rx.js → TerminalPanel-C8Yoxppo.js} +3 -3
  35. package/dist/public/assets/{agent-presence-Bf_k8RmI.js → agent-presence-BgZw7jcH.js} +1 -1
  36. package/dist/public/assets/{auth-state-cache-Ck3G6jUi.js → auth-state-cache-DewLLWl7.js} +4 -4
  37. package/dist/public/assets/config-provider-CPU__wB0.js +4 -0
  38. package/dist/public/assets/{dist-LUHivJAB.js → dist-BJTNIx2m.js} +1 -1
  39. package/dist/public/assets/{dist-BmgoHUkm.js → dist-DwvfOBE4.js} +107 -107
  40. package/dist/public/assets/{doc-hash-W5LZeE0c.js → doc-hash-BtUMDwMU.js} +1 -1
  41. package/dist/public/assets/{documents-events-CijCy-Sc.js → documents-events-DrrEYmNa.js} +1 -1
  42. package/dist/public/assets/{file-tree-adapter-Bjoeiw_B.js → file-tree-adapter-BiXhoQNr.js} +1 -1
  43. package/dist/public/assets/{index-BpZF8EJT.js → index-BDOi3sKE.js} +94 -94
  44. package/dist/public/assets/index-Bai-YKSb.css +1 -0
  45. package/dist/public/assets/{keyboard-shortcuts-DDw4HRe3.js → keyboard-shortcuts-CH4qhzpw.js} +1 -1
  46. package/dist/public/assets/{navigation-targets-V0noaD6h.js → navigation-targets-C8x96muf.js} +1 -1
  47. package/dist/public/assets/{open-managed-artifact-tab-_d-k5W-o.js → open-managed-artifact-tab-C7sLBkCv.js} +1 -1
  48. package/dist/public/assets/{pending-receive-nav-store-Cqe-Gc-y.js → pending-receive-nav-store-D83rXcWH.js} +1 -1
  49. package/dist/public/assets/{prop-types-DK0zwiLA.js → prop-types-589M92VT.js} +1 -1
  50. package/dist/public/assets/{receive-store-DIQKaDkz.js → receive-store-DUmQ9Q7m.js} +1 -1
  51. package/dist/public/assets/{selection-context-D7Vmm-jV.js → selection-context-D_zj8y90.js} +1 -1
  52. package/dist/public/assets/skill-actions-DbGgyPDT.js +1 -0
  53. package/dist/public/assets/{skills-api-FVkz2ZvD.js → skills-api-DULTMJrv.js} +1 -1
  54. package/dist/public/assets/{src-BfQVXkAq.js → src-DReJgyBg.js} +1 -1
  55. package/dist/public/assets/{target-navigation-intent-BF4mAnMq.js → target-navigation-intent-BrbTHf_2.js} +1 -1
  56. package/dist/public/assets/{typing-burst-detector-D0BBhVWB.js → typing-burst-detector-BCt9a4xO.js} +1 -1
  57. package/dist/public/assets/{workspace-paths-B1R7zp-q.js → workspace-paths-AsbfFKxa.js} +1 -1
  58. package/dist/public/index.html +26 -26
  59. package/dist/{repair-launch-json-DJL0xXvL.mjs → repair-launch-json-Du0EU3Si.mjs} +2 -2
  60. package/dist/{repair-mcp-configs-DsGk5WD7.mjs → repair-mcp-configs-DCP-rfpP.mjs} +2 -2
  61. package/dist/repair-skills-BDe9l22O.mjs +1 -0
  62. package/dist/{repair-skills-wFFbPc3w.mjs → repair-skills-DuNm-kMp.mjs} +2 -2
  63. package/dist/schemas/v0/config.project-local.schema.json +17 -0
  64. package/dist/server-lock-GuuouVft-CO_sPVNi.mjs +1 -0
  65. package/dist/{server-lock-iLcBw_q0-CEih6ZHm.mjs → server-lock-iLcBw_q0-nWzkxbfg.mjs} +17 -17
  66. package/dist/{src-DHfQops5.mjs → src-B9TNCBdI.mjs} +2 -2
  67. package/dist/{start-r9b4OB7D.mjs → start-Dld0QqQ2.mjs} +2 -2
  68. package/dist/start-rypz41-s.mjs +1 -0
  69. package/dist/{write-project-skill-CAZzOEUh.mjs → write-project-skill-DyoxYjJB.mjs} +2 -2
  70. package/package.json +1 -1
  71. package/dist/constants-DK10Qbwz.mjs +0 -2
  72. package/dist/dist-D-bO1Mlq.mjs +0 -1
  73. package/dist/init-BGGQ3ing.mjs +0 -1
  74. package/dist/loader-pzsmJGfG.mjs +0 -1
  75. package/dist/preview-GYvJ1m2X.mjs +0 -1
  76. package/dist/public/assets/DocumentContext-yguu7wL1.js +0 -35
  77. package/dist/public/assets/ManagedArtifactProperties-DCr0fsi-.js +0 -1
  78. package/dist/public/assets/PropertyPanel-C_ExYapZ.js +0 -2
  79. package/dist/public/assets/config-provider-CQL47dca.js +0 -4
  80. package/dist/public/assets/index-A8hej5b5.css +0 -1
  81. package/dist/public/assets/skill-actions-C3jnKy6a.js +0 -1
  82. package/dist/repair-skills-UdFUgcgx.mjs +0 -1
  83. package/dist/server-lock-GuuouVft-CPaJpyJ7.mjs +0 -1
  84. package/dist/start-esyH-MiN.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 CLIENT_VERSION_HEADER,$a as detectRemovedKeys,$i as parseManagedArtifactName,$n as ShareTargetStatusResponseSchema,$r as TrashCleanupSuccessSchema,$t as LocalOpEmbeddingsMutationSuccessSchema,A as AgentWriteMdRequestSchema,Aa as PluginKey,Ai as extractFrontmatterTags,An as SKILL_STATE_TARGETS,Ao as unknown,Ar as SyncConflictContentSuccessSchema,At as FolderConfigPutRequestSchema,B as BrokenLinkSchema,Ba as DEFAULT_SPANS_MAX_BYTES,Bi as isHiddenDocName,Bn as SeedApplyRequestSchema,Bo as parseAsync,Br as TagsListSuccessSchema,Bt as INSTALLED_SKILLS_REL,C as AdvisoryWarningSchema,Ca as tagsMatchingPrefix,Ci as detectFmRegion,Cn as RenamePathSuccessSchema,Co as number,Cr as SkillUninstallSuccessSchema,Ct as DuplicatePathSuccessSchema,D as AgentPatchSuccessSchema,Da as validateDocName,Di as emptySkillState,Dn as SKILL_CONTENT_ROOT,Do as record,Dr as SpawnCursorSuccessSchema,Dt as EmbedDetectSuccessSchema,E as AgentPatchRequestSchema,Ea as unwrapFrontmatterFences,Ei as emptyInstalledSkills,En as RollbackSuccessSchema,Eo as preprocess,Er as SkillsListSuccessSchema,Et as EDITOR_PROJECT_SKILL_ROOT,F as BacklinkCountsSuccessSchema,Fa as ConfigSchema$1,Fi as getWikiLinkText,Fn as SYSTEM_DOC_NAME,Fo as describe$1,Fr as SyncTriggerRequestSchema,Ft as FrontmatterValueSchema,G as CC1DiskAckPayloadSchema,Ga as LOCAL_DIR,Gi as isValidBranchName,Gn as ServerInfoSuccessSchema,Go as defineLazy,Gr as TemplatePutRequestSchema,Gt as KNOWN_NON_GITHUB_GIT_HOSTS,H as CC1ConfigIgnoreNestedErrorPayloadSchema,Ha as EXECUTABLE_BLOCKLIST_EXTENSIONS,Hi as isManagedArtifactDocName,Hn as SeedListPacksSuccessSchema,Ho as safeParseAsync$1,Hr as TemplateGetSuccessSchema,Ht as InstallSkillSuccessSchema,I as BacklinksSuccessSchema,Ia as DEFAULT_DEDUP_MODE,Ii as iconFromClientName,In as SaveVersionRequestSchema,Io as meta$1,Ir as SyncTriggerSuccessSchema,J as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ja as SANDBOXED_HTML_CSP,Ji as normalizeBridge,Jn as SharePublishNameCheckResponseSchema,Jr as TestFlushGitSuccessSchema,Jt as LocalOpAuthEmptySuccessSchema,K as CC1ServerInfoPayloadSchema,Ka as OK_PROJECT_MARKER,Ki as managedArtifactDocNameFromContentTarget,Kn as ShareConstructUrlRequestSchema,Ko as normalizeParams,Kr as TemplatePutSuccessSchema,Kt as LINEAGE_EPOCH_KEY,L as BranchInfoResponseSchema,La as DEFAULT_EMBEDDINGS_BASE_URL,Li as instantiateDoc,Ln as SaveVersionSuccessSchema,Lo as $ZodObject,Lr as TEMPLATE_IDENTITY_KEY,Lt as HistorySuccessSchema,M as AgentWriteRequestSchema,Ma as fnv1aDigest,Mi as getAgentCanonicalDescriptors,Mn as SKILL_TARGETS_REL,Mo as datetime,Mr as SyncResolveConflictRequestSchema,Mt as ForwardLinksSuccessSchema,N as AgentWriteSuccessSchema,Na as ASSET_EXTENSIONS,Ni as getHeadingSlug,No as toJSONSchema,Nr as SyncResolveConflictSuccessSchema,Nt as FrontmatterPatchRequestSchema,O as AgentUndoRequestSchema,Oa as withFences,Oi as encodeShareUrl,On as SKILL_NAME_REGEX,Oo as string,Or as StreamingProblemEventSchema,Ot as EmptyRequestSchema,P as ApiConfigSuccessSchema,Pa as CONFIG_SCHEMA_MAJOR_PATH,Pi as getParseHealth,Pn as SUPPORTED_DOC_EXTENSIONS,Pr as SyncStatusSchema,Pt as FrontmatterPatchSuccessSchema,Q as CC1_CONTRACT_VERSION,Qa as checkEmbeddingsBaseUrl,Qi as parseInstalledSkills,Qn as ShareTargetStatusRequestSchema,Qr as TrashCleanupRequestSchema,Qt as LocalOpCloneRequestSchema,R as BridgeInvariantViolationError,Ra as DEFAULT_EMBEDDINGS_MODEL,Ri as isBranchNotFoundGitError,Rn as SearchRequestSchema,Ro as $ZodType,Rr as TEMPLATE_NAME_REGEX,Rt as HistoryVersionSuccessSchema,Sa as stripFrontmatter,Si as detectAppliedToleranceClasses,Sn as RenamePathRequestSchema,So as looseObject,Sr as SkillUninstallRequestSchema,St as DuplicatePathRequestSchema,T as AgentBurstDiffSuccessSchema,Ta as toWikiLinkSlug,Ti as emitToleranceFire,Tn as RollbackRequestSchema,To as optional,Tr as SkillUpdateSuccessSchema,Tt as EDITOR_PROJECT_CONFIG_PATH,U as CC1ConfigValidationRejectedPayloadSchema,Ua as INLINE_RENDERABLE_EXTENSIONS,Ui as isOrphanMode,Un as SeedPlanSuccessSchema,Uo as prettifyError,Ur as TemplateMoveRequestSchema,Ut as InstalledAgentsSuccessSchema,V as CC1BranchSwitchedPayloadSchema,Va as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,Vn as SeedApplySuccessSchema,Vo as safeParse$1,Vr as TemplateDeleteSuccessSchema,Vt as InstallSkillRequestSchema,W as CC1DerivedViewPayloadSchema,Wa as LINKABLE_ASSET_EXTENSIONS,Wi as isParseEquivalentBridge,Wn as SemanticIndexStatusSchema,Wo as clone,Wr as TemplateMoveSuccessSchema,Wt as InstalledSkillsSchema,X as CC1_CHANNEL_DISK_ACK,Xa as addConfigSpanEvent,Xi as parseFrontmatterYaml,Xn as SharePublishRequestSchema,Xr as TestRescanFilesSuccessSchema,Xt as LocalOpAuthSetIdentityRequestSchema,Y as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Ya as SANDBOXED_HTML_EXTENSIONS,Yi as overMultipliedBodyLines,Yn as SharePublishOwnersResponseSchema,Yo as require_dist$1,Yr as TestRescanBacklinksSuccessSchema,Yt as LocalOpAuthHostRequestSchema,Z as CC1_CHANNEL_SERVER_INFO,Za as applyPatchToDocument,Zi as parseGlobalSkillBundleDoc,Zn as SharePublishResponseSchema,Zr as TestResetSuccessSchema,Zt as LocalOpAuthStatusSuccessSchema,_ as releaseServerLock,_a as setToleranceTelemetryHook,_i as createCodeFenceTracker,_n as PROTOCOL_VERSION,_o as boolean,_r as SkillTargetEditorSchema,_t as DeadLinksSuccessSchema,a as acquireProcessLock,aa as projectFull,ai as applyIncrementalDiff,an as MANAGED_ARTIFACT_SCOPES,ao as mediaKindForSidebarAssetExtension,ar as SkillGetSuccessSchema,at as CheckoutRequestSchema,ba as skillLiveDocName,bi as createWorkspaceSearchDocument,bn as PrincipalSuccessSchema,bo as intersection,br as SkillTargetsPutSuccessSchema,bt as DocumentListSuccessSchema,c as isProcessAlive,ca as readFmMap,ci as classifyGitAuthError,cn as MetricsAgentPresenceSuccessSchema,co as validatePatchScopes,cr as SkillInstallSuccessSchema,ct as ClientLogsSuccessSchema,d as markProcessLockDraining,da as resolveAssetProjectPath,dn as ORPHAN_MODES,dr as SkillPutRequestSchema,dt as CreatePageRequestSchema,ea as parseProjectSkillBundleDoc,ei as UA_PATTERNS,en as LocalOpEmbeddingsSetKeyRequestSchema,eo as humanFormat,er as SkillDeleteSuccessSchema,et as CONFIG_DOC_NAMES,f as markServerLockDraining,fi as colorFromSeed,fn as OrphansSuccessSchema,fo as ZodOptional$1,fr as SkillPutSuccessSchema,ft as CreatePageSuccessSchema,g as releaseProcessLock,ga as serializeFrontmatterMap,gi as createBasenameIndex,gn as PROJECT_SKILL_EDITOR_IDS,go as array,gr as SkillStateSchema,gt as DOCUMENT_OPEN_BYTE_LIMIT,h as readServerLock,ha as searchWorkspaceCorpus,hi as containsXmlTag,hn as PREVIEW_THEME_TOKENS,hr as SkillScopeSchema,ia as previewEmbedFence,ii as applyFastDiff,in as MANAGED_ARTIFACT_PREFIX_TEMPLATE,io as locateIssue,ir as SkillFilePutSuccessSchema,it as CONFIG_DOC_NAME_USER,j as AgentWriteMdSuccessSchema,ja as Fragment,ji as formatFileSize,jn as SKILL_STATE_VERSION_RE,jr as SyncConflictsSuccessSchema,jt as FolderConfigPutSuccessSchema,k as AgentUndoSuccessSchema,ka as getSchema,ki as expandTagToHierarchy,kn as SKILL_STATE_REL,ko as union,kr as SuggestLinksSuccessSchema,kt as FolderConfigGetSuccessSchema,l as isValidLockPid,la as reattachLeadingDocBoundary,li as classifyMarkdownHref,ln as MetricsParseHealthSuccessSchema,lo as withConfigSpan,lr as SkillMoveRequestSchema,lt as CreateFolderRequestSchema,ma as resolveSkillBundleWikiTarget,mi as composeTemplateFile,mn as PREVIEW_EMBED_STARTERS,mo as _null,mr as SkillRestoreSuccessSchema,n as RUNTIME_VERSION,na as parseTemplateFile,ni as UploadRequestSchema,nn as LocalOpOkInitResponseSchema,no as isMermaidDocFile,nr as SkillFileGetSuccessSchema,nt as CONFIG_DOC_NAME_PROJECT,o as acquireServerLock,oa as projectMergeBoundarySpace,oi as applyPatchToFm,on as MCP_SERVER_NAME,oo as normalizeAttachmentFolderPath,or as SkillInstallRequestSchema,ot as CheckoutResponseSchema,p as readProcessLock,pa as resolveInternalHref,pi as comparePmStructural,pn as PARSE_EQUIVALENCE_TOLERANCE,po as _enum,pr as SkillRestoreRequestSchema,q as CC1_CHANNEL_BRANCH_SWITCHED,qi as mergeThreeWay,qn as ShareConstructUrlResponseSchema,qo as $constructor,qr as TemplatesListSuccessSchema,qt as LinkGraphSuccessSchema,ra as prependFrontmatter,ri as WorkspaceSuccessSchema,rn as MANAGED_ARTIFACT_PREFIX_SKILL,ro as isValidAttachmentFolderPath,rr as SkillFilePutRequestSchema,rt as CONFIG_DOC_NAME_PROJECT_LOCAL,sa as projectSkillContentDocName,si as assertNeverProblemType,sn as MarkdownManager,so as toConfigIssue,sr as SkillInstallStateSuccessSchema,st as ClientLogsRequestSchema,t as ProcessLockCollisionError,ta as parseSkillTargets,ti as UploadAssetSuccessSchema,tn as LocalOpOkInitRequestSchema,to as isKnownConfigError,tr as SkillFileDeleteSuccessSchema,tt as CONFIG_DOC_NAME_OKIGNORE,ua as renderInventoryFooter,ui as classifyWikiLinkTarget,un as MetricsReconciliationSuccessSchema,uo as withConfigSpanSync,ur as SkillMoveSuccessSchema,ut as CreateFolderSuccessSchema,v as updateProcessLockPort,va as sharedExtensions,vi as createTagInTextRegex,vn as PageHeadingsSuccessSchema,vo as custom,vr as SkillTargetsGetSuccessSchema,vt as DeletePathRequestSchema,w as AgentActivitySuccessSchema,wa as toBridgeInvariantLog,wi as displayNameFromClientName,wn as RescueListSuccessSchema,wo as object$1,wr as SkillUpdateRequestSchema,x as AGENT_ICON_COLORS,xa as splitLeadingDocBoundary,xi as defaultScheduler,xn as ProblemDetailsSchema,xo as literal,xr as SkillTargetsSchema,xt as DocumentReadSuccessSchema,yi as createWorkspaceSearchCorpus,yn as PagesSuccessSchema,yo as discriminatedUnion,yr as SkillTargetsPutRequestSchema,yt as DeletePathSuccessSchema,z as BridgeMergeContentLossError,za as DEFAULT_LOGS_MAX_BYTES,zi as isFrontmatterValueEmpty,zn as SearchSuccessSchema,zo as parse$1,zr as TagsForNameSuccessSchema,zt as HubsSuccessSchema}from"./server-lock-iLcBw_q0-CEih6ZHm.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-BQ4-CT8p.mjs";import{a as simpleGit,i as esm_default,n as createGitInstance,o as require_src$15,r as withParentLock,t as applyGitEnv}from"./git-handle-XXj9bu6B-B4fXubq8.mjs";import{t as createPatch}from"./libesm-_Wi8iuGI.mjs";import{n as mimes,t as build_default}from"./build-CCNlCFyu.mjs";import{t as require_yazl}from"./yazl-DgCFuIuD.mjs";import{t as I1}from"./chunk-B74TABJS-DlbqoTuk.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-DigWkxW2.mjs";import{A as gt$1,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi$1,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,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-BGSUD5R5-DQ0_iOyO.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-KX3P26DQ-Cli1PSKS.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-XKIhMSUi.mjs";import{r as o$1}from"./chunk-CWQS3NFK-DNm_iIwd.mjs";import{t as m$2}from"./chunk-DXB73IDG-Bx-Ikbnu.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-_0tQyQsf.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-Kbs3GRxW.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-LGuZyK6R.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-BoP5OA93.mjs";import{n as n$1}from"./chunk-3THT3N7L-CBWmNncQ.mjs";import{t as n$2}from"./chunk-44UOCSGV-B6GSHp1s.mjs";import{t as import_websocket_server$1}from"./wrapper-CGw3ogaz.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,delimiter,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{homedir,hostname,platform,tmpdir}from"node:os";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,symlinkSync,unlinkSync,writeFileSync}from"node:fs";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";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$2 from"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 GIT_AUTHOR_WRITER_PREFIX=`git-author-`;function gitAuthorWriterId(e){return`${GIT_AUTHOR_WRITER_PREFIX}${fnv1aDigest(e.trim().toLowerCase())}`}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|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 CLIENT_VERSION_HEADER,$a as addConfigSpanEvent,$i as parseFrontmatterYaml,$n as SharePublishRequestSchema,$r as TestRescanFilesSuccessSchema,$t as LocalOpAuthSetIdentityRequestSchema,A as AgentWriteMdRequestSchema,Aa as validateDocName,Ai as emptySkillState,An as SKILL_CONTENT_ROOT,Ao as record,Ar as SpawnCursorSuccessSchema,At as FolderConfigPutRequestSchema,B as BrokenLinkSchema,Ba as DEFAULT_EMBEDDINGS_BASE_URL,Bi as instantiateDoc,Bn as SaveVersionSuccessSchema,Bo as $ZodObject,Br as TEMPLATE_IDENTITY_KEY,Bt as INSTALLED_SKILLS_REL,C as AdvisoryWarningSchema,Ca as skillLiveDocName,Ci as createWorkspaceSearchDocument,Cn as PrincipalSuccessSchema,Co as intersection,Cr as SkillTargetsPutSuccessSchema,Ct as DuplicatePathSuccessSchema,D as AgentPatchSuccessSchema,Da as toBridgeInvariantLog,Di as displayNameFromClientName,Dn as RescueListSuccessSchema,Do as object$1,Dr as SkillUpdateRequestSchema,Dt as EmbedDetectSuccessSchema,E as AgentPatchRequestSchema,Ea as tagsMatchingPrefix,Ei as detectFmRegion,En as RenamePathSuccessSchema,Eo as number,Er as SkillUninstallSuccessSchema,Et as EDITOR_PROJECT_SKILL_ROOT,F as BacklinkCountsSuccessSchema,Fa as fnv1aDigest,Fi as getAgentCanonicalDescriptors,Fn as SKILL_TARGETS_REL,Fo as datetime,Fr as SyncResolveConflictRequestSchema,Ft as FrontmatterValueSchema,G as CC1DiskAckPayloadSchema,Ga as EXECUTABLE_BLOCKLIST_EXTENSIONS,Gi as isManagedArtifactDocName,Gn as SeedListPacksSuccessSchema,Go as safeParseAsync$1,Gr as TemplateGetSuccessSchema,Gt as KNOWN_NON_GITHUB_GIT_HOSTS,H as CC1ConfigIgnoreNestedErrorPayloadSchema,Ha as DEFAULT_LOGS_MAX_BYTES,Hi as isFrontmatterValueEmpty,Hn as SearchSuccessSchema,Ho as parse$1,Hr as TagsForNameSuccessSchema,Ht as InstallSkillSuccessSchema,I as BacklinksSuccessSchema,Ia as ASSET_EXTENSIONS,Ii as getHeadingSlug,Io as toJSONSchema,Ir as SyncResolveConflictSuccessSchema,J as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ja as LOCAL_DIR,Ji as isValidBranchName,Jn as ServerInfoSuccessSchema,Jo as defineLazy,Jr as TemplatePutRequestSchema,Jt as LinkPreviewMetadataSchema,K as CC1ServerInfoPayloadSchema,Ka as INLINE_RENDERABLE_EXTENSIONS,Ki as isOrphanMode,Kn as SeedPlanSuccessSchema,Ko as prettifyError,Kr as TemplateMoveRequestSchema,Kt as LINEAGE_EPOCH_KEY,L as BranchInfoResponseSchema,La as CONFIG_SCHEMA_MAJOR_PATH,Li as getParseHealth,Ln as SUPPORTED_DOC_EXTENSIONS,Lr as SyncStatusSchema,Lt as HistorySuccessSchema,M as AgentWriteRequestSchema,Ma as getSchema,Mi as expandTagToHierarchy,Mn as SKILL_STATE_REL,Mo as union,Mr as SuggestLinksSuccessSchema,Mt as ForwardLinksSuccessSchema,N as AgentWriteSuccessSchema,Na as PluginKey,Ni as extractFrontmatterTags,Nn as SKILL_STATE_TARGETS,No as unknown,Nr as SyncConflictContentSuccessSchema,Nt as FrontmatterPatchRequestSchema,O as AgentUndoRequestSchema,Oa as toWikiLinkSlug,Oi as emitToleranceFire,On as RollbackRequestSchema,Oo as optional,Or as SkillUpdateSuccessSchema,Ot as EmptyRequestSchema,P as ApiConfigSuccessSchema,Pa as Fragment,Pi as formatFileSize,Pn as SKILL_STATE_VERSION_RE,Pr as SyncConflictsSuccessSchema,Pt as FrontmatterPatchSuccessSchema,Q as CC1_CONTRACT_VERSION,Qa as SANDBOXED_HTML_EXTENSIONS,Qi as overMultipliedBodyLines,Qn as SharePublishOwnersResponseSchema,Qo as require_dist$1,Qr as TestRescanBacklinksSuccessSchema,Qt as LocalOpAuthHostRequestSchema,R as BridgeInvariantViolationError,Ra as ConfigSchema$1,Ri as getWikiLinkText,Rn as SYSTEM_DOC_NAME,Ro as describe$1,Rr as SyncTriggerRequestSchema,Rt as HistoryVersionSuccessSchema,Si as createWorkspaceSearchCorpus,Sn as PagesSuccessSchema,So as discriminatedUnion,Sr as SkillTargetsPutRequestSchema,St as DuplicatePathRequestSchema,T as AgentBurstDiffSuccessSchema,Ta as stripFrontmatter,Ti as detectAppliedToleranceClasses,Tn as RenamePathRequestSchema,To as looseObject,Tr as SkillUninstallRequestSchema,Tt as EDITOR_PROJECT_CONFIG_PATH,U as CC1ConfigValidationRejectedPayloadSchema,Ua as DEFAULT_SPANS_MAX_BYTES,Ui as isHiddenDocName,Un as SeedApplyRequestSchema,Uo as parseAsync,Ur as TagsListSuccessSchema,Ut as InstalledAgentsSuccessSchema,V as CC1BranchSwitchedPayloadSchema,Va as DEFAULT_EMBEDDINGS_MODEL,Vi as isBranchNotFoundGitError,Vn as SearchRequestSchema,Vo as $ZodType,Vr as TEMPLATE_NAME_REGEX,Vt as InstallSkillRequestSchema,W as CC1DerivedViewPayloadSchema,Wa as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,Wn as SeedApplySuccessSchema,Wo as safeParse$1,Wr as TemplateDeleteSuccessSchema,Wt as InstalledSkillsSchema,X as CC1_CHANNEL_DISK_ACK,Xi as mergeThreeWay,Xn as ShareConstructUrlResponseSchema,Xo as $constructor,Xr as TemplatesListSuccessSchema,Xt as LinkPreviewResponseSchema,Y as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Ya as OK_PROJECT_MARKER,Yi as managedArtifactDocNameFromContentTarget,Yn as ShareConstructUrlRequestSchema,Yo as normalizeParams,Yr as TemplatePutSuccessSchema,Yt as LinkPreviewRequestSchema,Z as CC1_CHANNEL_SERVER_INFO,Za as SANDBOXED_HTML_CSP,Zi as normalizeBridge,Zn as SharePublishNameCheckResponseSchema,Zr as TestFlushGitSuccessSchema,Zt as LocalOpAuthEmptySuccessSchema,_ as releaseServerLock,_a as resolveSkillBundleWikiTarget,_i as composeTemplateFile,_n as PREVIEW_EMBED_STARTERS,_o as _null,_r as SkillRestoreSuccessSchema,_t as DeadLinksSuccessSchema,a as acquireProcessLock,aa as parseTemplateFile,ai as UploadRequestSchema,an as LocalOpOkInitResponseSchema,ao as isMermaidDocFile,ar as SkillFileGetSuccessSchema,at as CheckoutRequestSchema,ba as setToleranceTelemetryHook,bi as createCodeFenceTracker,bn as PROTOCOL_VERSION,bo as boolean,br as SkillTargetEditorSchema,bt as DocumentListSuccessSchema,c as isProcessAlive,ca as projectFull,ci as applyIncrementalDiff,cn as MANAGED_ARTIFACT_SCOPES,co as mediaKindForSidebarAssetExtension,cr as SkillGetSuccessSchema,ct as ClientLogsSuccessSchema,d as markProcessLockDraining,da as readFmMap,di as classifyGitAuthError,dn as MetricsAgentPresenceSuccessSchema,do as validatePatchScopes,dr as SkillInstallSuccessSchema,dt as CreatePageRequestSchema,ea as parseGlobalSkillBundleDoc,ei as TestResetSuccessSchema,en as LocalOpAuthStatusSuccessSchema,eo as applyPatchToDocument,er as SharePublishResponseSchema,et as CONFIG_DOC_NAMES,f as markServerLockDraining,fa as reattachLeadingDocBoundary,fi as classifyMarkdownHref,fn as MetricsParseHealthSuccessSchema,fo as withConfigSpan,fr as SkillMoveRequestSchema,ft as CreatePageSuccessSchema,g as releaseProcessLock,ga as resolveInternalHref,gi as comparePmStructural,gn as PARSE_EQUIVALENCE_TOLERANCE,go as _enum,gr as SkillRestoreRequestSchema,gt as DOCUMENT_OPEN_BYTE_LIMIT,h as readServerLock,hi as colorFromSeed,hn as OrphansSuccessSchema,ho as ZodOptional$1,hr as SkillPutSuccessSchema,ia as parseSkillTargets,ii as UploadAssetSuccessSchema,in as LocalOpOkInitRequestSchema,io as isKnownConfigError,ir as SkillFileDeleteSuccessSchema,it as CONFIG_DOC_NAME_USER,j as AgentWriteMdSuccessSchema,ja as withFences,ji as encodeShareUrl,jn as SKILL_NAME_REGEX,jo as string,jr as StreamingProblemEventSchema,jt as FolderConfigPutSuccessSchema,k as AgentUndoSuccessSchema,ka as unwrapFrontmatterFences,ki as emptyInstalledSkills,kn as RollbackSuccessSchema,ko as preprocess,kr as SkillsListSuccessSchema,kt as FolderConfigGetSuccessSchema,l as isValidLockPid,la as projectMergeBoundarySpace,li as applyPatchToFm,ln as MCP_SERVER_NAME,lo as normalizeAttachmentFolderPath,lr as SkillInstallRequestSchema,lt as CreateFolderRequestSchema,ma as resolveAssetProjectPath,mn as ORPHAN_MODES,mr as SkillPutRequestSchema,n as RUNTIME_VERSION,na as parseManagedArtifactName,ni as TrashCleanupSuccessSchema,nn as LocalOpEmbeddingsMutationSuccessSchema,no as detectRemovedKeys,nr as ShareTargetStatusResponseSchema,nt as CONFIG_DOC_NAME_PROJECT,o as acquireServerLock,oa as prependFrontmatter,oi as WorkspaceSuccessSchema,on as MANAGED_ARTIFACT_PREFIX_SKILL,oo as isValidAttachmentFolderPath,or as SkillFilePutRequestSchema,ot as CheckoutResponseSchema,p as readProcessLock,pa as renderInventoryFooter,pi as classifyWikiLinkTarget,pn as MetricsReconciliationSuccessSchema,po as withConfigSpanSync,pr as SkillMoveSuccessSchema,q as CC1_CHANNEL_BRANCH_SWITCHED,qa as LINKABLE_ASSET_EXTENSIONS,qi as isParseEquivalentBridge,qn as SemanticIndexStatusSchema,qo as clone,qr as TemplateMoveSuccessSchema,qt as LinkGraphSuccessSchema,ra as parseProjectSkillBundleDoc,ri as UA_PATTERNS,rn as LocalOpEmbeddingsSetKeyRequestSchema,ro as humanFormat,rr as SkillDeleteSuccessSchema,rt as CONFIG_DOC_NAME_PROJECT_LOCAL,sa as previewEmbedFence,si as applyFastDiff,sn as MANAGED_ARTIFACT_PREFIX_TEMPLATE,so as locateIssue,sr as SkillFilePutSuccessSchema,st as ClientLogsRequestSchema,t as ProcessLockCollisionError,ta as parseInstalledSkills,ti as TrashCleanupRequestSchema,tn as LocalOpCloneRequestSchema,to as checkEmbeddingsBaseUrl,tr as ShareTargetStatusRequestSchema,tt as CONFIG_DOC_NAME_OKIGNORE,ua as projectSkillContentDocName,ui as assertNeverProblemType,un as MarkdownManager,uo as toConfigIssue,ur as SkillInstallStateSuccessSchema,ut as CreateFolderSuccessSchema,v as updateProcessLockPort,va as searchWorkspaceCorpus,vi as containsXmlTag,vn as PREVIEW_THEME_TOKENS,vr as SkillScopeSchema,vt as DeletePathRequestSchema,w as AgentActivitySuccessSchema,wa as splitLeadingDocBoundary,wi as defaultScheduler,wn as ProblemDetailsSchema,wo as literal,wr as SkillTargetsSchema,x as AGENT_ICON_COLORS,xa as sharedExtensions,xi as createTagInTextRegex,xn as PageHeadingsSuccessSchema,xo as custom,xr as SkillTargetsGetSuccessSchema,xt as DocumentReadSuccessSchema,ya as serializeFrontmatterMap,yi as createBasenameIndex,yn as PROJECT_SKILL_EDITOR_IDS,yo as array,yr as SkillStateSchema,yt as DeletePathSuccessSchema,z as BridgeMergeContentLossError,za as DEFAULT_DEDUP_MODE,zi as iconFromClientName,zn as SaveVersionRequestSchema,zo as meta$1,zr as SyncTriggerSuccessSchema,zt as HubsSuccessSchema}from"./server-lock-iLcBw_q0-nWzkxbfg.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-BQ4-CT8p.mjs";import{a as simpleGit,i as esm_default,n as createGitInstance,o as require_src$15,r as withParentLock,t as applyGitEnv}from"./git-handle-XXj9bu6B-B4fXubq8.mjs";import{t as createPatch}from"./libesm-_Wi8iuGI.mjs";import{n as mimes,t as build_default}from"./build-CCNlCFyu.mjs";import{t as require_yazl}from"./yazl-DgCFuIuD.mjs";import{t as I1}from"./chunk-B74TABJS-DlbqoTuk.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-DigWkxW2.mjs";import{A as gt$1,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi$1,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,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-BGSUD5R5-DQ0_iOyO.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-KX3P26DQ-Cli1PSKS.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-XKIhMSUi.mjs";import{r as o$1}from"./chunk-CWQS3NFK-DNm_iIwd.mjs";import{t as m$2}from"./chunk-DXB73IDG-Bx-Ikbnu.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-_0tQyQsf.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-Kbs3GRxW.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-LGuZyK6R.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-BoP5OA93.mjs";import{n as n$1}from"./chunk-3THT3N7L-CBWmNncQ.mjs";import{t as n$2}from"./chunk-44UOCSGV-B6GSHp1s.mjs";import{t as import_websocket_server$1}from"./wrapper-CGw3ogaz.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,delimiter,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{homedir,hostname,platform,tmpdir}from"node:os";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,symlinkSync,unlinkSync,writeFileSync}from"node:fs";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";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$2 from"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{lookup}from"node:dns/promises";import{createServer,request}from"node:http";import{request as request$1}from"node:https";import{createBrotliDecompress,createGunzip,createInflate}from"node:zlib";import{Http2ServerRequest,constants as constants$3}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup as lookup$1}from"node:dns";const GIT_AUTHOR_WRITER_PREFIX=`git-author-`;function gitAuthorWriterId(e){return`${GIT_AUTHOR_WRITER_PREFIX}${fnv1aDigest(e.trim().toLowerCase())}`}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|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===`producer-guard-loss`){let e=w;return typeof e.construct==`string`?{kind:`producer-guard-loss`,docName:E,size:D,metadata:{construct:e.construct}}:null}if(S===`observer-a-duplication`){let e=w;return typeof e.duplicatedLineCount==`number`&&Number.isFinite(e.duplicatedLineCount)?{kind:`observer-a-duplication`,docName:E,size:D,metadata:{duplicatedLineCount:e.duplicatedLineCount}}: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(`
@@ -38,7 +38,7 @@ To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.w
38
38
  `),F=Buffer.from(`\r`),L=Buffer.from(`-`);function B(){}let H=2e3,q=16*1024,ee=0,J=1,Y=2;var te=class{constructor(e){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0,this.cb=e}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0}push(e,t,s){let g=t;for(;t<s;)switch(this.state){case 0:{let S=!1;for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(fe[s]!==1){if(s!==58||(this.name+=e.latin1Slice(g,t),this.name.length===0))return-1;++t,S=!0,this.state=1;break}}if(!S){this.name+=e.latin1Slice(g,t);break}}case 1:{let S=!1;for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(s!==32&&s!==9){g=t,S=!0,this.state=2;break}}if(!S)break}case 2:switch(this.crlf){case 0:for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(me[s]!==1){if(s!==13)return-1;++this.crlf;break}}this.value+=e.latin1Slice(g,t++);break;case 1:if(this.byteCount===q||(++this.byteCount,e[t++]!==10))return-1;++this.crlf;break;case 2:{if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];s===32||s===9?(g=t,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),this.header[this.name]===void 0?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),s===13?(++this.crlf,++t):(g=t,this.crlf=0,this.state=0,this.name=``,this.value=``));break}case 3:{if(this.byteCount===q||(++this.byteCount,e[t++]!==10))return-1;let s=this.header;return this.reset(),this.cb(s),t}}break}return t}},ne=class extends s{constructor(e,t){super(e),this.truncated=!1,this._readcb=null,this.once(`end`,()=>{if(this._read(),--t._fileEndsLeft===0&&t._finalcb){let e=t._finalcb;t._finalcb=null,process.nextTick(e)}})}_read(e){let t=this._readcb;t&&(this._readcb=null,t())}};let ae={push:(e,t)=>{},destroy:()=>{}};function oe(e,t){let s=e._writecb;e._writecb=null,t?e.destroy(t):s&&s()}function se(e,t){return e}var ce=class extends g{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};if(super(t),!e.conType.params||typeof e.conType.params.boundary!=`string`)throw Error(`Multipart: Boundary not found`);let s=e.conType.params.boundary,g=typeof e.defParamCharset==`string`&&e.defParamCharset?D(e.defParamCharset):se,H=e.defCharset||`utf8`,q=e.preservePath,ee={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.fileHwm==`number`?e.fileHwm:void 0},J=e.limits,Y=J&&typeof J.fieldSize==`number`?J.fieldSize:1*1024*1024,oe=J&&typeof J.fileSize==`number`?J.fileSize:1/0,ce=J&&typeof J.files==`number`?J.files:1/0,ue=J&&typeof J.fields==`number`?J.fields:1/0,de=J&&typeof J.parts==`number`?J.parts:1/0,fe=-1,me=0,ge=0,_e=!1;this._fileEndsLeft=0,this._fileStream=void 0,this._complete=!1;let ve=0,ye,Ce=0,we,Te,De,je,Me=!1,Pe=!1,Ie=!1;this._hparser=null;let Re=new te(e=>{this._hparser=null,_e=!1,De=`text/plain`,we=H,Te=`7bit`,je=void 0,Me=!1;let t;if(!e[`content-disposition`]){_e=!0;return}let s=k(e[`content-disposition`][0],g);if(!s||s.type!==`form-data`){_e=!0;return}if(s.params&&(s.params.name&&(je=s.params.name),s.params[`filename*`]?t=s.params[`filename*`]:s.params.filename&&(t=s.params.filename),t!==void 0&&!q&&(t=w(t))),e[`content-type`]){let t=O(e[`content-type`][0]);t&&(De=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(we=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(Te=e[`content-transfer-encoding`][0].toLowerCase()),De===`application/octet-stream`||t!==void 0){if(ge===ce){Pe||(Pe=!0,this.emit(`filesLimit`)),_e=!0;return}if(++ge,this.listenerCount(`file`)===0){_e=!0;return}ve=0,this._fileStream=new ne(ee,this),++this._fileEndsLeft,this.emit(`file`,je,this._fileStream,{filename:t,encoding:Te,mimeType:De})}else{if(me===ue){Ie||(Ie=!0,this.emit(`fieldsLimit`)),_e=!0;return}if(++me,this.listenerCount(`field`)===0){_e=!0;return}ye=[],Ce=0}}),ze=0,Be=(e,t,s,g,S)=>{retrydata:for(;t;){if(this._hparser!==null){let e=this._hparser.push(t,s,g);if(e===-1){this._hparser=null,Re.reset(),this.emit(`error`,Error(`Malformed part header`));break}s=e}if(s===g)break;if(ze!==0){if(ze===1){switch(t[s]){case 45:ze=2,++s;break;case 13:ze=3,++s;break;default:ze=0}if(s===g)return}if(ze===2){if(ze=0,t[s]===45){this._complete=!0,this._bparser=ae;return}let e=this._writecb;this._writecb=B,Be(!1,L,0,1,!1),this._writecb=e}else if(ze===3)if(ze=0,t[s]===10){if(++s,fe>=de||(this._hparser=Re,s===g))break;continue retrydata}else{let e=this._writecb;this._writecb=B,Be(!1,F,0,1,!1),this._writecb=e}}if(!_e){if(this._fileStream){let e,w=Math.min(g-s,oe-ve);S?e=t.slice(s,s+w):(e=Buffer.allocUnsafe(w),t.copy(e,0,s,s+w)),ve+=e.length,ve===oe?(e.length>0&&this._fileStream.push(e),this._fileStream.emit(`limit`),this._fileStream.truncated=!0,_e=!0):this._fileStream.push(e)||(this._writecb&&(this._fileStream._readcb=this._writecb),this._writecb=null)}else if(ye!==void 0){let e,w=Math.min(g-s,Y-Ce);S?e=t.slice(s,s+w):(e=Buffer.allocUnsafe(w),t.copy(e,0,s,s+w)),Ce+=w,ye.push(e),Ce===Y&&(_e=!0,Me=!0)}}break}if(e){if(ze=1,this._fileStream)this._fileStream.push(null),this._fileStream=null;else if(ye!==void 0){let e;switch(ye.length){case 0:e=``;break;case 1:e=E(ye[0],we,0);break;default:e=E(Buffer.concat(ye,Ce),we,0)}ye=void 0,Ce=0,this.emit(`field`,je,e,{nameTruncated:!1,valueTruncated:Me,encoding:Te,mimeType:De})}++fe===de&&this.emit(`partsLimit`)}};this._bparser=new S(`\r\n--${s}`,Be),this._writecb=null,this._finalcb=null,this.write(j)}static detect(e){return e.type===`multipart`&&e.subtype===`form-data`}_write(e,t,s){this._writecb=s,this._bparser.push(e,0),this._writecb&&oe(this)}_destroy(e,t){this._hparser=null,this._bparser=ae,e||=de(this);let s=this._fileStream;s&&(this._fileStream=null,s.destroy(e)),t(e)}_final(e){if(this._bparser.destroy(),!this._complete)return e(Error(`Unexpected end of form`));this._fileEndsLeft?this._finalcb=ue.bind(null,this,e):ue(this,e)}};function ue(e,t,s){if(s)return t(s);s=de(e),t(s)}function de(e){if(e._hparser)return Error(`Malformed part header`);let t=e._fileStream;if(t&&(e._fileStream=null,t.destroy(Error(`Unexpected end of file`))),!e._complete)return Error(`Unexpected end of form`)}let fe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],me=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];t.exports=ce})),require_urlencoded=__commonJSMin$2(((e,t)=>{let{Writable:s}=__require$2(`stream`),{getDecoder:g}=require_utils$2();var S=class extends s{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};super(t);let s=e.defCharset||`utf8`;e.conType.params&&typeof e.conType.params.charset==`string`&&(s=e.conType.params.charset),this.charset=s;let S=e.limits;this.fieldSizeLimit=S&&typeof S.fieldSize==`number`?S.fieldSize:1*1024*1024,this.fieldsLimit=S&&typeof S.fields==`number`?S.fields:1/0,this.fieldNameSizeLimit=S&&typeof S.fieldNameSize==`number`?S.fieldNameSize:100,this._inKey=!0,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,this._fields=0,this._key=``,this._val=``,this._byte=-2,this._lastPos=0,this._encode=0,this._decoder=g(s)}static detect(e){return e.type===`application`&&e.subtype===`x-www-form-urlencoded`}_write(e,t,s){if(this._fields>=this.fieldsLimit)return s();let g=0,S=e.length;if(this._lastPos=0,this._byte!==-2){if(g=w(this,e,g,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();this._inKey?++this._bytesKey:++this._bytesVal}main:for(;g<S;)if(this._inKey){for(g=E(this,e,g,S);g<S;){switch(e[g]){case 61:this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._key=this._decoder(this._key,this._encode),this._encode=0,this._inKey=!1;continue main;case 38:if(this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._key=this._decoder(this._key,this._encode),this._encode=0,this._bytesKey>0&&this.emit(`field`,this._key,``,{nameTruncated:this._keyTrunc,valueTruncated:!1,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),s();continue;case 43:this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._key+=` `,this._lastPos=g+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=g+1,this._byte=-1,g=w(this,e,g+1,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();++this._bytesKey,g=E(this,e,g,S);continue}++g,++this._bytesKey,g=E(this,e,g,S)}this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g))}else{for(g=D(this,e,g,S);g<S;){switch(e[g]){case 38:if(this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._inKey=!0,this._val=this._decoder(this._val,this._encode),this._encode=0,(this._bytesKey>0||this._bytesVal>0)&&this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),s();continue main;case 43:this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._val+=` `,this._lastPos=g+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._lastPos=g+1,this._byte=-1,g=w(this,e,g+1,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();++this._bytesVal,g=D(this,e,g,S);continue}++g,++this._bytesVal,g=D(this,e,g,S)}this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g))}s()}_final(e){if(this._byte!==-2)return e(Error(`Malformed urlencoded form`));(!this._inKey||this._bytesKey>0||this._bytesVal>0)&&(this._inKey?this._key=this._decoder(this._key,this._encode):this._val=this._decoder(this._val,this._encode),this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`})),e()}};function w(e,t,s,g){if(s>=g)return g;if(e._byte===-1){let S=O[t[s++]];if(S===-1)return-1;if(S>=8&&(e._encode=2),s<g){let g=O[t[s++]];if(g===-1)return-1;e._inKey?e._key+=String.fromCharCode((S<<4)+g):e._val+=String.fromCharCode((S<<4)+g),e._byte=-2,e._lastPos=s}else e._byte=S}else{let g=O[t[s++]];if(g===-1)return-1;e._inKey?e._key+=String.fromCharCode((e._byte<<4)+g):e._val+=String.fromCharCode((e._byte<<4)+g),e._byte=-2,e._lastPos=s}return s}function E(e,t,s,g){if(e._bytesKey>e.fieldNameSizeLimit){for(e._keyTrunc||e._lastPos<s&&(e._key+=t.latin1Slice(e._lastPos,s-1)),e._keyTrunc=!0;s<g;++s){let g=t[s];if(g===61||g===38)break;++e._bytesKey}e._lastPos=s}return s}function D(e,t,s,g){if(e._bytesVal>e.fieldSizeLimit){for(e._valTrunc||e._lastPos<s&&(e._val+=t.latin1Slice(e._lastPos,s-1)),e._valTrunc=!0;s<g&&t[s]!==38;++s)++e._bytesVal;e._lastPos=s}return s}let O=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports=S})),require_lib=__commonJSMin$2(((e,t)=>{let{parseContentType:s}=require_utils$2();function g(e){let t=e.headers,g=s(t[`content-type`]);if(!g)throw Error(`Malformed content type`);for(let s of S){if(!s.detect(g))continue;let S={limits:e.limits,headers:t,conType:g,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return e.highWaterMark&&(S.highWaterMark=e.highWaterMark),e.fileHwm&&(S.fileHwm=e.fileHwm),S.defCharset=e.defCharset,S.defParamCharset=e.defParamCharset,S.preservePath=e.preservePath,new s(S)}throw Error(`Unsupported content type: ${t[`content-type`]}`)}let S=[require_multipart(),require_urlencoded()].filter(function(e){return typeof e.detect==`function`});t.exports=e=>{if((typeof e!=`object`||!e)&&(e={}),typeof e.headers!=`object`||e.headers===null||typeof e.headers[`content-type`]!=`string`)throw Error(`Missing Content-Type`);return g(e)}}));const WINDOWS_1252_EXTRA={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},WINDOWS_1252_REVERSE={};for(let[e,t]of Object.entries(WINDOWS_1252_EXTRA))WINDOWS_1252_REVERSE[t]=Number.parseInt(e,10);let _utf8Decoder;function utf8Decoder(){if(globalThis.TextDecoder!==void 0)return _utf8Decoder??=new globalThis.TextDecoder(`utf-8`)}const CHUNK=32*1024,REPLACEMENT=65533;function textDecode(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=utf8Decoder();return t?t.decode(e):decodeUTF8(e)}case`utf-16le`:return decodeUTF16LE(e);case`us-ascii`:case`ascii`:return decodeASCII(e);case`latin1`:case`iso-8859-1`:return decodeLatin1(e);case`windows-1252`:return decodeWindows1252(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function flushChunk(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function pushCodeUnit(e,t,s){t.push(s),t.length>=CHUNK&&flushChunk(e,t)}function pushCodePoint(e,t,s){if(s<=65535){pushCodeUnit(e,t,s);return}s-=65536,pushCodeUnit(e,t,55296+(s>>10)),pushCodeUnit(e,t,56320+(s&1023))}function decodeUTF8(e){let t=[],s=[],g=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(g=3);g<e.length;){let S=e[g];if(S<=127){pushCodeUnit(t,s,S),g++;continue}if(S<194||S>244){pushCodeUnit(t,s,REPLACEMENT),g++;continue}if(S<=223){if(g+1>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1];if((w&192)!=128){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodeUnit(t,s,(S&31)<<6|w&63),g+=2;continue}if(S<=239){if(g+2>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1],E=e[g+2];if(!((w&192)==128&&(E&192)==128&&!(S===224&&w<160)&&!(S===237&&w>=160))){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodeUnit(t,s,(S&15)<<12|(w&63)<<6|E&63),g+=3;continue}if(g+3>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1],E=e[g+2],D=e[g+3];if(!((w&192)==128&&(E&192)==128&&(D&192)==128&&!(S===240&&w<144)&&!(S===244&&w>143))){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodePoint(t,s,(S&7)<<18|(w&63)<<12|(E&63)<<6|D&63),g+=4}return flushChunk(t,s),t.join(``)}function decodeUTF16LE(e){let t=[],s=[],g=e.length,S=0;for(;S+1<g;){let w=e[S]|e[S+1]<<8;if(S+=2,w>=55296&&w<=56319){if(S+1<g){let g=e[S]|e[S+1]<<8;g>=56320&&g<=57343?(pushCodeUnit(t,s,w),pushCodeUnit(t,s,g),S+=2):pushCodeUnit(t,s,REPLACEMENT)}else pushCodeUnit(t,s,REPLACEMENT);continue}if(w>=56320&&w<=57343){pushCodeUnit(t,s,REPLACEMENT);continue}pushCodeUnit(t,s,w)}return S<g&&pushCodeUnit(t,s,REPLACEMENT),flushChunk(t,s),t.join(``)}function decodeASCII(e){let t=[];for(let s=0;s<e.length;s+=CHUNK){let g=Math.min(e.length,s+CHUNK),S=Array(g-s);for(let t=s,w=0;t<g;t++,w++)S[w]=e[t]&127;t.push(String.fromCharCode.apply(null,S))}return t.join(``)}function decodeLatin1(e){let t=[];for(let s=0;s<e.length;s+=CHUNK){let g=Math.min(e.length,s+CHUNK),S=Array(g-s);for(let t=s,w=0;t<g;t++,w++)S[w]=e[t];t.push(String.fromCharCode.apply(null,S))}return t.join(``)}function decodeWindows1252(e){let t=[],s=``;for(let g=0;g<e.length;g++){let S=e[g],w=S>=128&&S<=159?WINDOWS_1252_EXTRA[S]:void 0;s+=w??String.fromCharCode(S),s.length>=CHUNK&&(t.push(s),s=``)}return s&&t.push(s),t.join(``)}function dv(e){return new DataView(e.buffer,e.byteOffset)}const UINT8={len:1,get(e,t){return dv(e).getUint8(t)},put(e,t,s){return dv(e).setUint8(t,s),t+1}},UINT16_LE={len:2,get(e,t){return dv(e).getUint16(t,!0)},put(e,t,s){return dv(e).setUint16(t,s,!0),t+2}},UINT16_BE={len:2,get(e,t){return dv(e).getUint16(t)},put(e,t,s){return dv(e).setUint16(t,s),t+2}},UINT32_LE={len:4,get(e,t){return dv(e).getUint32(t,!0)},put(e,t,s){return dv(e).setUint32(t,s,!0),t+4}},UINT32_BE={len:4,get(e,t){return dv(e).getUint32(t)},put(e,t,s){return dv(e).setUint32(t,s),t+4}},INT32_BE={len:4,get(e,t){return dv(e).getInt32(t)},put(e,t,s){return dv(e).setInt32(t,s),t+4}},UINT64_LE={len:8,get(e,t){return dv(e).getBigUint64(t,!0)},put(e,t,s){return dv(e).setBigUint64(t,s,!0),t+8}};var StringType=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return textDecode(e.subarray(t,t+this.len),this.encoding)}};const defaultMessages=`End-Of-Stream`;var EndOfStreamError=class extends Error{constructor(){super(defaultMessages),this.name=`EndOfStreamError`}},AbortError=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},AbstractStreamReader=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let s=await this.read(e,t);return this.peekQueue.push(e.subarray(0,s)),s}async read(e,t=!1){if(e.length===0)return 0;let s=this.readFromPeekBuffer(e);if(this.endOfStream||(s+=await this.readRemainderFromStream(e.subarray(s),t)),s===0&&!t)throw new EndOfStreamError;return s}readFromPeekBuffer(e){let t=e.length,s=0;for(;this.peekQueue.length>0&&t>0;){let g=this.peekQueue.pop();if(!g)throw Error(`peekData should be defined`);let S=Math.min(g.length,t);e.set(g.subarray(0,S),s),s+=S,t-=S,S<g.length&&this.peekQueue.push(g.subarray(S))}return s}async readRemainderFromStream(e,t){let s=0;for(;s<e.length&&!this.endOfStream;){if(this.interrupted)throw new AbortError;let g=await this.readFromStream(e.subarray(s),t);if(g===0)break;s+=g}if(!t&&s<e.length)throw new EndOfStreamError;return s}},WebStreamReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},WebStreamByobReader=class extends WebStreamReader{async readFromStream(e,t){if(e.length===0)return 0;let s=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return s.done&&(this.endOfStream=s.done),s.value?(e.set(s.value),s.value.length):0}},WebStreamDefaultReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let s=Math.min(t.length,e.length);return e.set(t.subarray(0,s)),s<t.length?this.buffer=t.subarray(s):this.buffer=null,s}async readFromStream(e,t){if(e.length===0)return 0;let s=0;for(this.buffer&&(s+=this.writeChunk(e,this.buffer));s<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(s+=this.writeChunk(e.subarray(s),t.value))}if(!t&&s===0&&this.endOfStream)throw new EndOfStreamError;return s}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function makeWebStreamReader(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new WebStreamDefaultReader(t):new WebStreamByobReader(t)}catch(t){if(t instanceof TypeError)return new WebStreamDefaultReader(e.getReader());throw t}}var AbstractTokenizer=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let s=new Uint8Array(e.len);if(await this.readBuffer(s,{position:t})<e.len)throw new EndOfStreamError;return e.get(s,0)}async peekToken(e,t=this.position){let s=new Uint8Array(e.len);if(await this.peekBuffer(s,{position:t})<e.len)throw new EndOfStreamError;return e.get(s,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};const maxBufferSize=256e3;var ReadStreamTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let s=this.normalizeOptions(e,t),g=s.position-this.position;if(g>0)return await this.ignore(g),this.readBuffer(e,t);if(g<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(s.length===0)return 0;let S=await this.streamReader.read(e.subarray(0,s.length),s.mayBeLess);if(this.position+=S,(!t||!t.mayBeLess)&&S<s.length)throw new EndOfStreamError;return S}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=0;if(s.position){let t=s.position-this.position;if(t>0){let S=new Uint8Array(s.length+t);return g=await this.peekBuffer(S,{mayBeLess:s.mayBeLess}),e.set(S.subarray(t)),g-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(s.length>0){try{g=await this.streamReader.peek(e.subarray(0,s.length),s.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof EndOfStreamError)return 0;throw e}if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError}return g}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(maxBufferSize,e),s=new Uint8Array(t),g=0;for(;g<e;){let S=e-g,w=await this.readBuffer(s,{length:Math.min(t,S)});if(w<0)return w;g+=w}return g}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},BufferTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let s=await this.peekBuffer(e,t);return this.position+=s,s}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=Math.min(this.uint8Array.length-s.position,s.length);if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError;return e.set(this.uint8Array.subarray(s.position,s.position+g)),g}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},BlobTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let s=await this.peekBuffer(e,t);return this.position+=s,s}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=Math.min(this.blob.size-s.position,s.length);if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError;let S=await this.blob.slice(s.position,s.position+g).arrayBuffer();return e.set(new Uint8Array(S)),g}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function fromWebStream(e,t){let s=makeWebStreamReader(e),g=t??{},S=g.onClose;return g.onClose=async()=>{if(await s.close(),S)return S()},new ReadStreamTokenizer(s,g)}function fromBuffer(e,t){return new BufferTokenizer(e,t)}function fromBlob(e,t){return new BlobTokenizer(e,t)}const Signature={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},DataDescriptor={get(e){return{signature:UINT32_LE.get(e,0),compressedSize:UINT32_LE.get(e,8),uncompressedSize:UINT32_LE.get(e,12)}},len:16},LocalFileHeaderToken={get(e){let t=UINT16_LE.get(e,6);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,4),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,8),compressedSize:UINT32_LE.get(e,18),uncompressedSize:UINT32_LE.get(e,22),filenameLength:UINT16_LE.get(e,26),extraFieldLength:UINT16_LE.get(e,28),filename:null}},len:30},EndOfCentralDirectoryRecordToken={get(e){return{signature:UINT32_LE.get(e,0),nrOfThisDisk:UINT16_LE.get(e,4),nrOfThisDiskWithTheStart:UINT16_LE.get(e,6),nrOfEntriesOnThisDisk:UINT16_LE.get(e,8),nrOfEntriesOfSize:UINT16_LE.get(e,10),sizeOfCd:UINT32_LE.get(e,12),offsetOfStartOfCd:UINT32_LE.get(e,16),zipFileCommentLength:UINT16_LE.get(e,20)}},len:22},FileHeader={get(e){let t=UINT16_LE.get(e,8);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,6),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,10),compressedSize:UINT32_LE.get(e,20),uncompressedSize:UINT32_LE.get(e,24),filenameLength:UINT16_LE.get(e,28),extraFieldLength:UINT16_LE.get(e,30),fileCommentLength:UINT16_LE.get(e,32),relativeOffsetOfLocalHeader:UINT32_LE.get(e,42),filename:null}},len:46};var import_src$8=__toESM$2(require_src$15(),1);function signatureToArray(e){let t=new Uint8Array(UINT32_LE.len);return UINT32_LE.put(t,0,e),t}const debug=(0,import_src$8.default)(`tokenizer:inflate`),syncBufferSize=256*1024,ddSignatureArray=signatureToArray(Signature.DataDescriptor),eocdSignatureBytes=signatureToArray(Signature.EndOfCentralDirectory);var ZipHandler=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(syncBufferSize)}async isZip(){return await this.peekSignature()===Signature.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(UINT32_LE)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),s=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(s,{position:e.fileInfo.size-t});for(let g=s.length-4;g>=0;g--)if(s[g]===eocdSignatureBytes[0]&&s[g+1]===eocdSignatureBytes[1]&&s[g+2]===eocdSignatureBytes[2]&&s[g+3]===eocdSignatureBytes[3])return e.fileInfo.size-t+g;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){debug(`Cannot reading central-directory without random-read support`);return}debug(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){debug(`Central-directory 32-bit signature found`);let s=await this.tokenizer.readToken(EndOfCentralDirectoryRecordToken,t),g=[];this.tokenizer.setPosition(s.offsetOfStartOfCd);for(let e=0;e<s.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(FileHeader);if(t.signature!==Signature.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new StringType(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),g.push(t),debug(`Add central-directory file-entry: n=${e+1}/${g.length}: filename=${g[e].filename}`)}return this.tokenizer.setPosition(e),g}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let s=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let g=e(t);s=!!g.stop;let S;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],s=syncBufferSize;debug(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let S=-1;for(;S<0&&s===syncBufferSize;){s=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),S=indexOf(this.syncBuffer.subarray(0,s),ddSignatureArray);let t=S>=0?S:s;if(g.handler){let s=new Uint8Array(t);await this.tokenizer.readBuffer(s),e.push(s)}else await this.tokenizer.ignore(t)}debug(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),g.handler&&await this.inflate(t,mergeArrays(e),g.handler)}else g.handler?(debug(`Reading compressed-file-data: ${t.compressedSize} bytes`),S=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(S),await this.inflate(t,S,g.handler)):(debug(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(debug(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(DataDescriptor)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-DataDescriptor.len}`)}while(!s)}async iterateOverCentralDirectory(e,t){for(let s of e){let e=t(s);if(e.handler){this.tokenizer.setPosition(s.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let g=new Uint8Array(s.compressedSize);await this.tokenizer.readBuffer(g),await this.inflate(t,g,e.handler)}}if(e.stop)break}}async inflate(t,s,g){if(t.compressedMethod===0)return g(s);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return debug(`Decompress filename=${t.filename}, compressed-size=${s.length}`),g(await e.decompressDeflateRaw(s))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),s=new DecompressionStream(`deflate-raw`),g=t.pipeThrough(s);try{let e=await new Response(g).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(UINT32_LE);if(e===Signature.LocalFileHeader){let e=await this.tokenizer.readToken(LocalFileHeaderToken);return e.filename=await this.tokenizer.readToken(new StringType(e.filenameLength,`utf-8`)),e}if(e===Signature.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function indexOf(e,t){let s=e.length,g=t.length;if(g>s)return-1;for(let S=0;S<=s-g;S++){let s=!0;for(let w=0;w<g;w++)if(e[S+w]!==t[w]){s=!1;break}if(s)return S}return-1}function mergeArrays(e){let t=e.reduce((e,t)=>e+t.length,0),s=new Uint8Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return s}var GzipHandler=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let s=new Uint8Array(1024),g=await e.readBuffer(s,{mayBeLess:!0});if(g===0){t.close();return}t.enqueue(s.subarray(0,g))}}).pipeThrough(new DecompressionStream(`gzip`))}};const objectToString=Object.prototype.toString,uint8ArrayStringified=`[object Uint8Array]`;function isType(e,t,s){return e?e.constructor===t?!0:objectToString.call(e)===s:!1}function isUint8Array(e){return isType(e,Uint8Array,uint8ArrayStringified)}function assertUint8Array(e){if(!isUint8Array(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function concatUint8Arrays(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let s=new Uint8Array(t),g=0;for(let t of e)assertUint8Array(t),s.set(t,g),g+=t.length;return s}const cachedDecoders={utf8:new globalThis.TextDecoder(`utf8`)},cachedEncoder=new globalThis.TextEncoder,byteToHexLookupTable=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function getUintBE(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function stringToBytes(e,t){if(t===`utf-16le`){let t=[];for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);t.push(g&255,g>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);t.push(g>>8&255,g&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function tarHeaderChecksumMatches(e,t=0){let s=Number.parseInt(new StringType(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(s))return!1;let g=256;for(let s=t;s<t+148;s++)g+=e[s];for(let s=t+156;s<t+512;s++)g+=e[s];return s===g}const uint32SyncSafeToken={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},extensions=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),mimeTypes=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),maximumUntrustedSkipSizeInBytes=16*1024*1024;var ParserHardLimitError=class extends Error{};function getSafeBound(e,t,s){if(!Number.isFinite(e)||e<0||e>t)throw new ParserHardLimitError(`${s} has invalid size ${e} (maximum ${t} bytes)`);return e}async function safeIgnore(e,t,{maximumLength:s=maximumUntrustedSkipSizeInBytes,reason:g=`skip`}={}){let S=getSafeBound(t,s,g);await e.ignore(S)}async function safeReadBuffer(e,t,s,{maximumLength:g=t.length,reason:S=`read`}={}){let w=getSafeBound(s?.length??t.length,g,S);return e.readBuffer(t,{...s,length:w})}function checkBytes(e,t,s){s={offset:0,...s};for(let[g,S]of t.entries())if(s.mask){if(S!==(s.mask[g]&e[g+s.offset]))return!1}else if(S!==e[g+s.offset])return!1;return!0}function hasUnknownFileSize(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function hasExceededUnknownSizeScanBudget(e,t,s){return hasUnknownFileSize(e)&&e.position-t>s}const maximumZipEntrySizeInBytes=1024*1024,maximumZipEntryCount=1024,maximumZipBufferedReadSizeInBytes=2**31-1,maximumZipTextEntrySizeInBytes=maximumZipEntrySizeInBytes,recoverableZipErrorMessages=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),recoverableZipErrorMessagePrefixes=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],recoverableZipErrorCodes=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function decompressDeflateRawWithLimit(e,{maximumLength:t=maximumZipEntrySizeInBytes}={}){let s=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),g=[],S=0;try{for(;;){let{done:e,value:w}=await s.read();if(e)break;if(S+=w.length,S>t)throw await s.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);g.push(w)}}finally{s.releaseLock()}let w=new Uint8Array(S),E=0;for(let e of g)w.set(e,E),E+=e.length;return w}function mergeByteChunks(e,t){let s=new Uint8Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return s}function getMaximumZipBufferedReadLength(e){let t=e.fileInfo.size,s=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(s,maximumZipBufferedReadSizeInBytes)}function isRecoverableZipError(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return!0;if(!(e instanceof Error))return!1;if(recoverableZipErrorMessages.has(e.message)||recoverableZipErrorCodes.has(e.code))return!0;for(let t of recoverableZipErrorMessagePrefixes)if(e.message.startsWith(t))return!0;return!1}function canReadZipEntryForDetection(e,t=maximumZipEntrySizeInBytes){let s=[e.compressedSize,e.uncompressedSize];for(let e of s)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function createIWorkZipDetectionState(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function updateIWorkZipDetectionStateFromFilename(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function getIWorkFileTypeFromZipEntries(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function getFileTypeFromMimeType(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function createOpenXmlZipDetectionState(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function updateOpenXmlZipDetectionStateFromFilename(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function getOpenXmlFileTypeFromDirectoryNames(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function getOpenXmlFileTypeFromZipEntries(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return getOpenXmlFileTypeFromDirectoryNames(e)}function getOpenXmlMimeTypeFromContentTypesXml(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let s=e.slice(0,t),g=s.lastIndexOf(`"`);return s.slice(g+1)}const zipDataDescriptorSignature=134695760,zipDataDescriptorLengthInBytes=16,zipDataDescriptorOverlapLengthInBytes=zipDataDescriptorLengthInBytes-1;function findZipDataDescriptorOffset(e,t){if(e.length<zipDataDescriptorLengthInBytes)return-1;let s=e.length-zipDataDescriptorLengthInBytes;for(let g=0;g<=s;g++)if(UINT32_LE.get(e,g)===zipDataDescriptorSignature&&UINT32_LE.get(e,g+8)===t+g)return g;return-1}async function readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:t,maximumLength:s=maximumZipEntrySizeInBytes}={}){let{syncBuffer:g}=e,{length:S}=g,w=[],E=0;for(;;){let D=await e.tokenizer.peekBuffer(g,{mayBeLess:!0}),O=findZipDataDescriptorOffset(g.subarray(0,D),E),k=O>=0?0:D===S?Math.min(zipDataDescriptorOverlapLengthInBytes,D-1):0,j=O>=0?O:D-k;if(j===0)break;if(E+=j,E>s)throw Error(`ZIP entry compressed data exceeds ${s} bytes`);if(t){let t=new Uint8Array(j);await e.tokenizer.readBuffer(t),w.push(t)}else await e.tokenizer.ignore(j);if(O>=0)break}if(hasUnknownFileSize(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=E),t)return mergeByteChunks(w,E)}function getRemainingZipScanBudget(e,t){return hasUnknownFileSize(e.tokenizer)?Math.max(0,maximumUntrustedSkipSizeInBytes-(e.tokenizer.position-t)):Math.max(0,maximumZipEntrySizeInBytes-e.knownSizeDescriptorScannedBytes)}async function readZipEntryData(e,t,{shouldBuffer:s,maximumDescriptorLength:g=maximumZipEntrySizeInBytes}={}){if(t.dataDescriptor&&t.compressedSize===0)return readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:s,maximumLength:g});if(!s){await safeIgnore(e.tokenizer,t.compressedSize,{maximumLength:hasUnknownFileSize(e.tokenizer)?maximumZipEntrySizeInBytes:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let S=getMaximumZipBufferedReadLength(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>S)throw Error(`ZIP entry compressed data exceeds ${S} bytes`);let w=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(w),w}ZipHandler.prototype.inflate=async function(e,t,s){if(e.compressedMethod===0)return s(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return s(await decompressDeflateRawWithLimit(t,{maximumLength:maximumZipEntrySizeInBytes}))},ZipHandler.prototype.unzip=async function(e){let t=!1,s=0,g=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(hasExceededUnknownSizeScanBudget(this.tokenizer,g,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`);let S=await this.readLocalFileHeader();if(!S)break;if(s++,s>maximumZipEntryCount)throw Error(`ZIP entry count exceeds ${maximumZipEntryCount}`);let w=e(S);t=!!w.stop,await this.tokenizer.ignore(S.extraFieldLength);let E=await readZipEntryData(this,S,{shouldBuffer:!!w.handler,maximumDescriptorLength:Math.min(maximumZipEntrySizeInBytes,getRemainingZipScanBudget(this,g))});if(w.handler&&await this.inflate(S,E,w.handler),S.dataDescriptor){let e=new Uint8Array(zipDataDescriptorLengthInBytes);if(await this.tokenizer.readBuffer(e),UINT32_LE.get(e,0)!==zipDataDescriptorSignature)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(hasExceededUnknownSizeScanBudget(this.tokenizer,g,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`)}while(!t)};async function detectZip(e){let t,s=createOpenXmlZipDetectionState(),g=createIWorkZipDetectionState();try{await new ZipHandler(e).unzip(e=>{if(updateOpenXmlZipDetectionStateFromFilename(s,e.filename),updateIWorkZipDetectionStateFromFilename(g,e.filename),g.hasDocumentEntry&&(g.hasMasterSlideEntry||g.hasTablesEntry))return t=getIWorkFileTypeFromZipEntries(g),{stop:!0};let S=e.filename===`[Content_Types].xml`,w=getOpenXmlFileTypeFromZipEntries(s);if(!S&&w)return t=w,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?{async handler(e){t=getFileTypeFromMimeType(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return s.hasContentTypesEntry=!0,canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?(s.isParsingContentTypes=!0,{async handler(e){let g=getOpenXmlMimeTypeFromContentTypesXml(new TextDecoder(`utf-8`).decode(e));g&&(t=getFileTypeFromMimeType(g)),s.hasParsedContentTypesEntry=!0,s.isParsingContentTypes=!1},stop:!0}):(s.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!isRecoverableZipError(e))throw e;s.isParsingContentTypes&&(s.isParsingContentTypes=!1,s.hasUnparseableContentTypes=!0),!t&&e instanceof EndOfStreamError&&!s.hasContentTypesEntry&&(t=getOpenXmlFileTypeFromDirectoryNames(s))}let S=hasUnknownFileSize(e)&&g.hasDocumentEntry&&!g.hasMasterSlideEntry&&!g.hasTablesEntry&&!g.hasCalculationEngineEntry?void 0:getIWorkFileTypeFromZipEntries(g);return t??getOpenXmlFileTypeFromZipEntries(s)??S??{ext:`zip`,mime:`application/zip`}}const maximumEbmlDocumentTypeSizeInBytes=64,maximumEbmlElementPayloadSizeInBytes=1024*1024,maximumEbmlElementCount=256;async function detectEbml(e){async function t(){let t=await e.peekNumber(UINT8),s=128,g=0;for(;(t&s)===0&&s!==0;)++g,s>>=1;let S=new Uint8Array(g+1);return await safeReadBuffer(e,S,void 0,{maximumLength:S.length,reason:`EBML field`}),S}async function s(){let e=await t(),s=await t();s[0]^=128>>s.length-1;let g=Math.min(6,s.length),S=new DataView(e.buffer),w=new DataView(s.buffer,s.length-g,g);return{id:getUintBE(S),len:getUintBE(w)}}async function g(t){let g=0;for(;t>0;){if(g++,g>maximumEbmlElementCount||hasExceededUnknownSizeScanBudget(e,w,16777216))return;let S=e.position,E=await s();if(E.id===17026){if(E.len>maximumEbmlDocumentTypeSizeInBytes)return;let t=getSafeBound(E.len,maximumEbmlDocumentTypeSizeInBytes,`EBML DocType`);return(await e.readToken(new StringType(t))).replaceAll(/\0.*$/gv,``)}if(hasUnknownFileSize(e)&&(!Number.isFinite(E.len)||E.len<0||E.len>maximumEbmlElementPayloadSizeInBytes)||(await safeIgnore(e,E.len,{maximumLength:hasUnknownFileSize(e)?maximumEbmlElementPayloadSizeInBytes:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=S))return}}let S=await s(),w=e.position;switch(await g(S.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const maximumPngChunkCount=512,maximumPngStreamScanBudgetInBytes=16*1024*1024,maximumPngChunkSizeInBytes=1024*1024;function isPngAncillaryChunk(e){return(e.codePointAt(0)&32)!=0}async function detectPng(e){let t={ext:`png`,mime:`image/png`},s={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function g(){return{length:await e.readToken(INT32_BE),type:await e.readToken(new StringType(4,`latin1`))}}let S=hasUnknownFileSize(e),w=e.position,E=0,D=!1;do{if(E++,E>maximumPngChunkCount||hasExceededUnknownSizeScanBudget(e,w,maximumPngStreamScanBudgetInBytes))break;let O=e.position,k=await g();if(k.length<0)return;if(k.type===`IHDR`){if(k.length!==13)return;D=!0}switch(k.type){case`IDAT`:return t;case`acTL`:return s;default:if(!D&&k.type!==`CgBI`)return;if(S&&k.length>maximumPngChunkSizeInBytes)return D&&isPngAncillaryChunk(k.type)?t:void 0;try{await safeIgnore(e,k.length+4,{maximumLength:S?maximumPngChunkSizeInBytes+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!S&&(e instanceof ParserHardLimitError||e instanceof EndOfStreamError))return t;throw e}}if(e.position<=O)break}while(e.position+8<e.fileInfo.size);return t}const maximumAsfHeaderObjectCount=512,maximumAsfHeaderPayloadSizeInBytes=1024*1024;async function detectAsf(e){let t=!1;try{async function s(){let t=new Uint8Array(16);return await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(UINT64_LE))}}await safeIgnore(e,30,{maximumLength:30,reason:`ASF header prelude`});let g=hasUnknownFileSize(e),S=e.position,w=0;for(;e.position+24<e.fileInfo.size&&(w++,!(w>maximumAsfHeaderObjectCount||hasExceededUnknownSizeScanBudget(e,S,16777216)));){let S=e.position,w=await s(),E=w.size-24;if(!Number.isFinite(E)||E<0){t=!0;break}if(checkBytes(w.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(E-=await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),checkBytes(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(checkBytes(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(g&&E>maximumAsfHeaderPayloadSizeInBytes){t=!0;break}if(await safeIgnore(e,E,{maximumLength:g?maximumAsfHeaderPayloadSizeInBytes:e.fileInfo.size,reason:`ASF header payload`}),e.position<=S){t=!0;break}}}catch(s){if(s instanceof EndOfStreamError||s instanceof ParserHardLimitError)hasUnknownFileSize(e)&&(t=!0);else throw s}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const reasonableDetectionSizeInBytes=4100,maximumMpegOffsetTolerance=reasonableDetectionSizeInBytes-2,maximumNestedGzipDetectionSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumNestedGzipProbeDepth=1,unknownSizeGzipProbeTimeoutInMilliseconds=100,maximumId3HeaderSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumTiffTagCount=512,maximumDetectionReentryCount=256,maximumTiffStreamIfdOffsetInBytes=1024*1024,maximumTiffIfdOffsetInBytes=maximumUntrustedSkipSizeInBytes;function normalizeSampleSize(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):reasonableDetectionSizeInBytes}function normalizeMpegOffsetTolerance(e){return Number.isFinite(e)?Math.max(0,Math.min(maximumMpegOffsetTolerance,Math.trunc(e))):0}function getKnownFileSizeOrMaximum(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function importAtRuntime(e){return import(e)}function toDefaultStream(e){return e.pipeThrough(new TransformStream)}function readWithSignal(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((s,g)=>{t.addEventListener(`abort`,()=>{g(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function createByteLimitedReadableStream(e,t){let s=e.getReader(),g=0,S=!1,w=!1,E=async e=>{S||w||(w=!0,await s.cancel(e))};return new ReadableStream({async pull(e){if(g>=t){e.close(),await E();return}let{done:w,value:D}=await s.read();if(w||!D){S=!0,e.close();return}let O=t-g;if(D.length>O){e.enqueue(D.subarray(0,O)),g+=O,e.close(),await E();return}e.enqueue(D),g+=D.length},async cancel(e){await E(e)}})}async function fileTypeFromBuffer(e,t){return new FileTypeParser(t).fromBuffer(e)}var FileTypeParser=class e{constructor(e){let t=normalizeMpegOffsetTolerance(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return fromWebStream(toDefaultStream(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let s=e.position;for(let t of this.detectors){let g;try{g=await t.detect(e)}catch(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return;throw e}if(g)return g;if(s!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(fromBuffer(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=fromBlob(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:s}]=await Promise.all([importAtRuntime(`node:fs/promises`),importAtRuntime(`strtok3`)]),g=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),S=await g.stat();if(!S.isFile()){await g.close();return}let w=new s(g,{...this.getTokenizerOptions(),fileInfo:{path:e,size:S.size}});return this.fromTokenizer(w)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let s=normalizeSampleSize(t?.sampleSize??4100),g,S=!1,w=e.getReader(),E=[],D=0;try{for(;D<s;){let{value:e,done:t}=await readWithSignal(w,this.options.signal);if(t||!e){S=!0;break}E.push(e),D+=e.length}if(!S&&D===s){let{value:e,done:t}=await readWithSignal(w,this.options.signal);t||!e?S=!0:(E.push(e),D+=e.length)}}finally{w.releaseLock()}if(D>0){let e=E.length===1?E[0]:concatUint8Arrays(E);try{g=await this.fromBuffer(e.subarray(0,s))}catch(e){if(!(e instanceof EndOfStreamError))throw e;g=void 0}!S&&g?.ext===`pages`&&(g={ext:`zip`,mime:`application/zip`})}let O=new TransformStream({start(e){for(let t of E)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),k=e.pipeThrough(O);return k.fileType=g,k}async detectGzip(t){if(this.gzipProbeDepth>=maximumNestedGzipProbeDepth)return{ext:`gz`,mime:`application/gzip`};let s=createByteLimitedReadableStream(new GzipHandler(t).inflate(),maximumNestedGzipDetectionSizeInBytes),g=hasUnknownFileSize(t),S,w,E,D;if(g){let t=new AbortController;S=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after ${unknownSizeGzipProbeTimeoutInMilliseconds} ms`,`TimeoutError`))},unknownSizeGzipProbeTimeoutInMilliseconds),w=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),E=new e({...this.options,signal:w}),E.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{D=await(E??this).fromStream(s)}catch(e){if(e?.name===`AbortError`&&w?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(S),g||this.gzipProbeDepth--}return D?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return checkBytes(this.buffer,e,t)}checkString(e,t){return this.check(stringToBytes(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(reasonableDetectionSizeInBytes),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,hasUnknownFileSize(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await safeIgnore(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(uint32SyncSafeToken),s=hasUnknownFileSize(e);if(!Number.isFinite(t)||t<0||s&&(t>maximumId3HeaderSizeInBytes||e.position+t>maximumId3HeaderSizeInBytes))return;if(e.position+t>e.fileInfo.size)return s?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await safeIgnore(e,t,{maximumLength:s?maximumId3HeaderSizeInBytes:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return detectZip(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),checkBytes(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:checkBytes(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:checkBytes(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:checkBytes(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:checkBytes(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:checkBytes(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return detectEbml(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=UINT32_BE.get(this.buffer,4),t=UINT16_BE.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new StringType(4,`latin1`).get(this.buffer,2);if(/^\d+$/v.test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new StringType(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
39
39
  `,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10]))return detectPng(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new StringType(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.checkString(`REGEDIT4\r
40
40
  `))return{ext:`reg`,mime:`application/x-ms-regedit`};if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217]))return detectAsf(e);if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new StringType(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.checkString(`<?xml `,{offset:2,encoding:`utf-16be`})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x-ms-shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x-ft-apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x-ft-fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:`jmp`,mime:`application/x-jmp-data`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&tarHeaderChecksumMatches(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254])){let e=`utf-16le`;return this.checkString(`<?xml `,{offset:2,encoding:e})?{ext:`xml`,mime:`application/xml`}:this.check([255,14],{offset:2})&&this.checkString(`SketchUp Model`,{offset:4,encoding:e})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:this.checkString(`Windows Registry Editor Version 5.00\r
41
- `,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(reasonableDetectionSizeInBytes);let t=getKnownFileSizeOrMaximum(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);if(!(t>maximumTiffTagCount)&&!(hasUnknownFileSize(this.tokenizer)&&2+t*12>maximumTiffIfdOffsetInBytes))for(let s=0;s<t;++s){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},s=(e?UINT16_BE:UINT16_LE).get(this.buffer,2),g=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(s===42){if(g>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(g>=8){let t=(e?UINT16_BE:UINT16_LE).get(this.buffer,8),s=(e?UINT16_BE:UINT16_LE).get(this.buffer,10);if(t===28&&s===254||t===31&&s===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(hasUnknownFileSize(this.tokenizer)&&g>maximumTiffStreamIfdOffsetInBytes)return t;let s=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,g,{maximumLength:s,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let S;try{S=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return S??t}if(s===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};const supportedExtensions=new Set(extensions),supportedMimeTypes=new Set(mimeTypes);var util;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function s(e){throw Error()}e.assertNever=s,e.arrayToEnum=e=>{let t={};for(let s of e)t[s]=s;return t},e.getValidEnumValues=t=>{let s=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),g={};for(let e of s)g[e]=t[e];return e.objectValues(g)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},e.find=(e,t)=>{for(let s of e)if(t(s))return s},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function g(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=g,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(util||={});var objectUtil;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||={});const ZodParsedType=util.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),getParsedType=e=>{switch(typeof e){case`undefined`:return ZodParsedType.undefined;case`string`:return ZodParsedType.string;case`number`:return Number.isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case`boolean`:return ZodParsedType.boolean;case`function`:return ZodParsedType.function;case`bigint`:return ZodParsedType.bigint;case`symbol`:return ZodParsedType.symbol;case`object`:return Array.isArray(e)?ZodParsedType.array:e===null?ZodParsedType.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?ZodParsedType.promise:typeof Map<`u`&&e instanceof Map?ZodParsedType.map:typeof Set<`u`&&e instanceof Set?ZodParsedType.set:typeof Date<`u`&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var ZodError=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},s={_errors:[]},g=e=>{for(let S of e.issues)if(S.code===`invalid_union`)S.unionErrors.map(g);else if(S.code===`invalid_return_type`)g(S.returnTypeError);else if(S.code===`invalid_arguments`)g(S.argumentsError);else if(S.path.length===0)s._errors.push(t(S));else{let e=s,g=0;for(;g<S.path.length;){let s=S.path[g];g===S.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(S))):e[s]=e[s]||{_errors:[]},e=e[s],g++}}};return g(this),s}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),s=[];for(let g of this.issues)if(g.path.length>0){let s=g.path[0];t[s]=t[s]||[],t[s].push(e(g))}else s.push(e(g));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};ZodError.create=e=>new ZodError(e);const errorMap=(e,t)=>{let s;switch(e.code){case ZodIssueCode.invalid_type:s=e.received===ZodParsedType.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:s=`Unrecognized key(s) in object: ${util.joinValues(e.keys,`, `)}`;break;case ZodIssueCode.invalid_union:s=`Invalid input`;break;case ZodIssueCode.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${util.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:s=`Invalid enum value. Expected ${util.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode.invalid_arguments:s=`Invalid function arguments`;break;case ZodIssueCode.invalid_return_type:s=`Invalid function return type`;break;case ZodIssueCode.invalid_date:s=`Invalid date`;break;case ZodIssueCode.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:util.assertNever(e.validation):s=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case ZodIssueCode.too_small:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case ZodIssueCode.too_big:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case ZodIssueCode.custom:s=`Invalid input`;break;case ZodIssueCode.invalid_intersection_types:s=`Intersection results could not be merged`;break;case ZodIssueCode.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode.not_finite:s=`Number must be finite`;break;default:s=t.defaultError,util.assertNever(e)}return{message:s}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{let{data:t,path:s,errorMaps:g,issueData:S}=e,w=[...s,...S.path||[]],E={...S,path:w};if(S.message!==void 0)return{...S,path:w,message:S.message};let D=``,O=g.filter(e=>!!e).slice().reverse();for(let e of O)D=e(E,{data:t,defaultError:D}).message;return{...S,path:w,message:D}};function addIssueToContext(e,t){let s=getErrorMap(),g=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===errorMap?void 0:errorMap].filter(e=>!!e)});e.common.issues.push(g)}var ParseStatus=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let s=[];for(let g of t){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&e.dirty(),s.push(g.value)}return{status:e.value,value:s}}static async mergeObjectAsync(t,s){let g=[];for(let e of s){let t=await e.key,s=await e.value;g.push({key:t,value:s})}return e.mergeObjectSync(t,g)}static mergeObjectSync(e,t){let s={};for(let g of t){let{key:t,value:S}=g;if(t.status===`aborted`||S.status===`aborted`)return INVALID;t.status===`dirty`&&e.dirty(),S.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(S.value!==void 0||g.alwaysSet)&&(s[t.value]=S.value)}return{status:e.value,value:s}}};const INVALID=Object.freeze({status:`aborted`}),DIRTY=e=>({status:`dirty`,value:e}),OK=e=>({status:`valid`,value:e}),isAborted=e=>e.status===`aborted`,isDirty=e=>e.status===`dirty`,isValid=e=>e.status===`valid`,isAsync=e=>typeof Promise<`u`&&e instanceof Promise;var errorUtil;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(errorUtil||={});var ParseInputLazyPath=class{constructor(e,t,s,g){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=g}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new ZodError(e.common.issues),this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:s,required_error:g,description:S}=e;if(t&&(s||g))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:S}:{errorMap:(t,S)=>{let{message:w}=e;return t.code===`invalid_enum_value`?{message:w??S.defaultError}:S.data===void 0?{message:w??g??S.defaultError}:t.code===`invalid_type`?{message:w??s??S.defaultError}:{message:S.defaultError}},description:S}}var ZodType=class{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(isAsync(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};return handleResult(s,this._parseSync({data:e,path:s.path,parent:s}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this[`~standard`].async)try{let s=this._parseSync({data:e,path:[],parent:t});return isValid(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>isValid(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},g=this._parse({data:e,path:s.path,parent:s});return handleResult(s,await(isAsync(g)?g:Promise.resolve(g)))}refine(e,t){let s=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,g)=>{let S=e(t),w=()=>g.addIssue({code:ZodIssueCode.custom,...s(t)});return typeof Promise<`u`&&S instanceof Promise?S.then(e=>e?!0:(w(),!1)):S?!0:(w(),!1)})}refinement(e,t){return this._refinement((s,g)=>e(s)?!0:(g.addIssue(typeof t==`function`?t(s,g):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;let emojiRegex$1;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,dateRegex=RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let s=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`,s=[];return s.push(e.local?`Z?`:`Z`),e.offset&&s.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${s.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!!((t===`v4`||!t)&&ipv4Regex.test(e)||(t===`v6`||!t)&&ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{let[s]=e.split(`.`);if(!s)return!1;let g=s.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(s.length+(4-s.length%4)%4,`=`),S=JSON.parse(atob(g));return!(typeof S!=`object`||!S||`typ`in S&&S?.typ!==`JWT`||!S.alg||t&&S.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!!((t===`v4`||!t)&&ipv4CidrRegex.test(e)||(t===`v6`||!t)&&ipv6CidrRegex.test(e))}var ZodString=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}let t=new ParseStatus,s;for(let g of this._def.checks)if(g.kind===`min`)e.data.length<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`max`)e.data.length>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`length`){let S=e.data.length>g.value,w=e.data.length<g.value;(S||w)&&(s=this._getOrReturnCtx(e,s),S?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}):w&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}),t.dirty())}else if(g.kind===`email`)emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`email`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`emoji`)emojiRegex$1||=new RegExp(_emojiRegex,`u`),emojiRegex$1.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`emoji`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`uuid`)uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`nanoid`)nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid`)cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid2`)cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`ulid`)ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`url`)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()}else g.kind===`regex`?(g.regex.lastIndex=0,g.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`regex`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty())):g.kind===`trim`?e.data=e.data.trim():g.kind===`includes`?e.data.includes(g.value,g.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:g.value,position:g.position},message:g.message}),t.dirty()):g.kind===`toLowerCase`?e.data=e.data.toLowerCase():g.kind===`toUpperCase`?e.data=e.data.toUpperCase():g.kind===`startsWith`?e.data.startsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:g.value},message:g.message}),t.dirty()):g.kind===`endsWith`?e.data.endsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:g.value},message:g.message}),t.dirty()):g.kind===`datetime`?datetimeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:g.message}),t.dirty()):g.kind===`date`?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`date`,message:g.message}),t.dirty()):g.kind===`time`?timeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`time`,message:g.message}),t.dirty()):g.kind===`duration`?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`duration`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`ip`?isValidIP(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ip`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`jwt`?isValidJWT(e.data,g.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`cidr`?isValidCidr(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64`?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64url`?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):util.assertNever(g);return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...errorUtil.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let s=(e.toString().split(`.`)[1]||``).length,g=(t.toString().split(`.`)[1]||``).length,S=s>g?s:g;return Number.parseInt(e.toFixed(S).replace(`.`,``))%Number.parseInt(t.toFixed(S).replace(`.`,``))/10**S}var ZodNumber=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`int`?util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:g.message}),s.dirty()):g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`multipleOf`?floatSafeRemainder(e.data,g.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):g.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:errorUtil.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks)if(s.kind===`finite`||s.kind===`int`||s.kind===`multipleOf`)return!0;else s.kind===`min`?(t===null||s.value>t)&&(t=s.value):s.kind===`max`&&(e===null||s.value<e)&&(e=s.value);return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodBigInt=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:`bigint`,minimum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:`bigint`,maximum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`multipleOf`?e.data%g.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodBigInt.create=e=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams(e)});var ZodBoolean=class extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodDate=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(Number.isNaN(e.data.getTime()))return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID;let t=new ParseStatus,s;for(let g of this._def.checks)g.kind===`min`?e.data.getTime()<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:g.message,inclusive:!0,exact:!1,minimum:g.value,type:`date`}),t.dirty()):g.kind===`max`?e.data.getTime()>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:g.message,inclusive:!0,exact:!1,maximum:g.value,type:`date`}),t.dirty()):util.assertNever(g);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ZodDate.create=e=>new ZodDate({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}};ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}};ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}};ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}};ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}};ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});var ZodArray=class e extends ZodType{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),g=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(g.exactLength!==null){let e=t.data.length>g.exactLength.value,S=t.data.length<g.exactLength.value;(e||S)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:S?g.exactLength.value:void 0,maximum:e?g.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:g.exactLength.message}),s.dirty())}if(g.minLength!==null&&t.data.length<g.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.minLength.value,type:`array`,inclusive:!0,exact:!1,message:g.minLength.message}),s.dirty()),g.maxLength!==null&&t.data.length>g.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:g.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((e,s)=>g.type._parseAsync(new ParseInputLazyPath(t,e,t.path,s)))).then(e=>ParseStatus.mergeArray(s,e));let S=[...t.data].map((e,s)=>g.type._parseSync(new ParseInputLazyPath(t,e,t.path,s)));return ParseStatus.mergeArray(s,S)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:errorUtil.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:errorUtil.toString(s)}})}nonempty(e){return this.min(1,e)}};ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof ZodObject){let t={};for(let s in e.shape){let g=e.shape[s];t[s]=ZodOptional.create(deepPartialify(g))}return new ZodObject({...e._def,shape:()=>t})}else if(e instanceof ZodArray)return new ZodArray({...e._def,type:deepPartialify(e.element)});else if(e instanceof ZodOptional)return ZodOptional.create(deepPartialify(e.unwrap()));else if(e instanceof ZodNullable)return ZodNullable.create(deepPartialify(e.unwrap()));else if(e instanceof ZodTuple)return ZodTuple.create(e.items.map(e=>deepPartialify(e)));else return e}var ZodObject=class e extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:util.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}let{status:t,ctx:s}=this._processInputParams(e),{shape:g,keys:S}=this._getCached(),w=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in s.data)S.includes(e)||w.push(e);let E=[];for(let e of S){let t=g[e],S=s.data[e];E.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(s,S,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of w)E.push({key:{status:`valid`,value:e},value:{status:`valid`,value:s.data[e]}});else if(e===`strict`)w.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:w}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of w){let g=s.data[t];E.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(s,g,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of E){let s=await t.key,g=await t.value;e.push({key:s,value:g,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(t,e)):ParseStatus.mergeObjectSync(t,E)}get shape(){return this._def.shape()}strict(t){return errorUtil.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,s)=>{let g=this._def.errorMap?.(e,s).message??s.defaultError;return e.code===`unrecognized_keys`?{message:errorUtil.errToObj(t).message??g}:{message:g}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let s={};for(let e of util.objectKeys(t))t[e]&&this.shape[e]&&(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}omit(t){let s={};for(let e of util.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return deepPartialify(this)}partial(t){let s={};for(let e of util.objectKeys(this.shape)){let g=this.shape[e];t&&!t[e]?s[e]=g:s[e]=g.optional()}return new e({...this._def,shape:()=>s})}required(t){let s={};for(let e of util.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ZodOptional;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function g(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let s of e)if(s.result.status===`dirty`)return t.common.issues.push(...s.ctx.common.issues),s.result;let s=e.map(e=>new ZodError(e.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}if(t.common.async)return Promise.all(s.map(async e=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(g);{let e,g=[];for(let S of s){let s={...t,common:{...t.common,issues:[]},parent:null},w=S._parseSync({data:t.data,path:t.path,parent:s});if(w.status===`valid`)return w;w.status===`dirty`&&!e&&(e={result:w,ctx:s}),s.common.issues.length&&g.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let S=g.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:S}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];var ZodDiscriminatedUnion=class e extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;let s=this.discriminator,g=t.data[s],S=this.optionsMap.get(g);return S?t.common.async?S._parseAsync({data:t.data,path:t.path,parent:t}):S._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,g){let S=new Map;for(let e of s){let s=getDiscriminator(e.shape[t]);if(!s.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let g of s){if(S.has(g))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(g)}`);S.set(g,e)}}return new e({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:S,...processCreateParams(g)})}};function mergeValues(e,t){let s=getParsedType(e),g=getParsedType(t);if(e===t)return{valid:!0,data:e};if(s===ZodParsedType.object&&g===ZodParsedType.object){let s=util.objectKeys(t),g=util.objectKeys(e).filter(e=>s.indexOf(e)!==-1),S={...e,...t};for(let s of g){let g=mergeValues(e[s],t[s]);if(!g.valid)return{valid:!1};S[s]=g.data}return{valid:!0,data:S}}else if(s===ZodParsedType.array&&g===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let g=0;g<e.length;g++){let S=e[g],w=t[g],E=mergeValues(S,w);if(!E.valid)return{valid:!1};s.push(E.data)}return{valid:!0,data:s}}else if(s===ZodParsedType.date&&g===ZodParsedType.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=(e,g)=>{if(isAborted(e)||isAborted(g))return INVALID;let S=mergeValues(e.value,g.value);return S.valid?((isDirty(e)||isDirty(g))&&t.dirty(),{status:t.value,value:S.data}):(addIssueToContext(s,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,t])=>g(e,t)):g(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};ZodIntersection.create=(e,t,s)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(s)});var ZodTuple=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.array)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:s.parsedType}),INVALID;if(s.data.length<this._def.items.length)return addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),INVALID;!this._def.rest&&s.data.length>this._def.items.length&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let g=[...s.data].map((e,t)=>{let g=this._def.items[t]||this._def.rest;return g?g._parse(new ParseInputLazyPath(s,e,s.path,t)):null}).filter(e=>!!e);return s.common.async?Promise.all(g).then(e=>ParseStatus.mergeArray(t,e)):ParseStatus.mergeArray(t,g)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};var ZodRecord=class e extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.object)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:s.parsedType}),INVALID;let g=[],S=this._def.keyType,w=this._def.valueType;for(let e in s.data)g.push({key:S._parse(new ParseInputLazyPath(s,e,s.path,e)),value:w._parse(new ParseInputLazyPath(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?ParseStatus.mergeObjectAsync(t,g):ParseStatus.mergeObjectSync(t,g)}get element(){return this._def.valueType}static create(t,s,g){return s instanceof ZodType?new e({keyType:t,valueType:s,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(g)}):new e({keyType:ZodString.create(),valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(s)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.map)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:s.parsedType}),INVALID;let g=this._def.keyType,S=this._def.valueType,w=[...s.data.entries()].map(([e,t],w)=>({key:g._parse(new ParseInputLazyPath(s,e,s.path,[w,`key`])),value:S._parse(new ParseInputLazyPath(s,t,s.path,[w,`value`]))}));if(s.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let s of w){let g=await s.key,S=await s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let s of w){let g=s.key,S=s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}}}};ZodMap.create=(e,t,s)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(s)});var ZodSet=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.set)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:s.parsedType}),INVALID;let g=this._def;g.minSize!==null&&s.data.size<g.minSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.minSize.value,type:`set`,inclusive:!0,exact:!1,message:g.minSize.message}),t.dirty()),g.maxSize!==null&&s.data.size>g.maxSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:g.maxSize.message}),t.dirty());let S=this._def.valueType;function w(e){let s=new Set;for(let g of e){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&t.dirty(),s.add(g.value)}return{status:t.value,value:s}}let E=[...s.data.values()].map((e,t)=>S._parse(new ParseInputLazyPath(s,e,s.path,t)));return s.common.async?Promise.all(E).then(e=>w(e)):w(E)}min(t,s){return new e({...this._def,minSize:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:errorUtil.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});var ZodFunction=class e extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function s(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:s}})}function g(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:s}})}let S={errorMap:t.common.contextualErrorMap},w=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let E=new ZodError([]),D=await e._def.args.parseAsync(t,S).catch(e=>{throw E.addIssue(s(t,e)),E}),O=await Reflect.apply(w,this,D);return await e._def.returns._def.type.parseAsync(O,S).catch(e=>{throw E.addIssue(g(O,e)),E})})}else{let e=this;return OK(function(...t){let E=e._def.args.safeParse(t,S);if(!E.success)throw new ZodError([s(t,E.error)]);let D=Reflect.apply(w,this,E.data),O=e._def.returns.safeParse(D,S);if(!O.success)throw new ZodError([g(D,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ZodTuple.create(t).rest(ZodUnknown.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,s,g){return new e({args:t||ZodTuple.create([]).rest(ZodUnknown.create()),returns:s||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(g)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});var ZodLiteral=class extends ZodType{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}var ZodEnum=class e extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{expected:util.joinValues(s),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,s=this._def){return e.create(t,{...this._def,...s})}exclude(t,s=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...s})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(e){let t=util.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==ZodParsedType.string&&s.parsedType!==ZodParsedType.number){let e=util.objectValues(t);return addIssueToContext(s,{expected:util.joinValues(e),received:s.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(util.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=util.objectValues(t);return addIssueToContext(s,{received:s.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==ZodParsedType.promise&&t.common.async===!1?(addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID):OK((t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=this._def.effect||null,S={addIssue:e=>{addIssueToContext(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(S.addIssue=S.addIssue.bind(S),g.type===`preprocess`){let e=g.transform(s.data,S);if(s.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let g=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g});{if(t.value===`aborted`)return INVALID;let g=this._def.schema._parseSync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g}}if(g.type===`refinement`){let e=e=>{let t=g.refinement(e,S);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(s.common.async===!1){let g=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return g.status===`aborted`?INVALID:(g.status===`dirty`&&t.dirty(),e(g.value),{status:t.value,value:g.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(s=>s.status===`aborted`?INVALID:(s.status===`dirty`&&t.dirty(),e(s.value).then(()=>({status:t.value,value:s.value}))))}if(g.type===`transform`)if(s.common.async===!1){let e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!isValid(e))return INVALID;let w=g.transform(e.value,S);if(w instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:w}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>isValid(e)?Promise.resolve(g.transform(e.value,S)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(g)}};ZodEffects.create=(e,t,s)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(s)}),ZodEffects.createWithPreprocess=(e,t,s)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(s)});var ZodOptional=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===ZodParsedType.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...processCreateParams(t)});var ZodCatch=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},g=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return isAsync(g)?g.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})})):{status:`valid`,value:g.status===`valid`?g.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:`valid`,value:e.data}}};ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});var ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},ZodPipeline=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})();{let e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(t,s){return new e({in:t,out:s,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),s=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>s(e)):s(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(ZodFirstPartyTypeKind||={});const stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ZodMiniType=$constructor(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,s)=>parse$1(e,t,s,{callee:e.parse}),e.safeParse=(t,s)=>safeParse$1(e,t,s),e.parseAsync=async(t,s)=>parseAsync(e,t,s,{callee:e.parseAsync}),e.safeParseAsync=async(t,s)=>safeParseAsync$1(e,t,s),e.check=(...s)=>e.clone({...t,checks:[...t.checks??[],...s.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,s)=>clone(e,t,s),e.brand=()=>e,e.register=((t,s)=>(t.add(e,s),e)),e.apply=t=>t(e)}),ZodMiniObject=$constructor(`ZodMiniObject`,(e,t)=>{$ZodObject.init(e,t),ZodMiniType.init(e,t),defineLazy(e,`shape`,()=>t.shape)});function object(e,t){return new ZodMiniObject({type:`object`,shape:e??{},...normalizeParams(t)})}const describe=describe$1,meta=meta$1;function isZ4Schema(e){return!!e._zod}function objectFromShape(e){let t=Object.values(e);if(t.length===0)return object({});let s=t.every(isZ4Schema),g=t.every(e=>!isZ4Schema(e));if(s)return object(e);if(g)return objectType(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?safeParse$1(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await safeParseAsync$1(e,t):await e.safeParseAsync(t)}function getObjectShape(e){if(!e)return;let t;if(t=isZ4Schema(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function normalizeObjectSchema(e){if(e){if(typeof e==`object`){let t=e,s=e;if(!t._def&&!s._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return objectFromShape(e)}}if(isZ4Schema(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function getParseErrorMessage(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function getSchemaDescription(e){return e.description}function isSchemaOptional(e){if(isZ4Schema(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function getLiteralValue(e){if(isZ4Schema(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let s=e.value;if(s!==void 0)return s}const LATEST_PROTOCOL_VERSION=`2025-11-25`,DEFAULT_NEGOTIATED_PROTOCOL_VERSION=`2025-03-26`,SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],RELATED_TASK_META_KEY=`io.modelcontextprotocol/related-task`,JSONRPC_VERSION=`2.0`,AssertObjectSchema=custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),ProgressTokenSchema=union([string(),number().int()]),CursorSchema=string(),TaskCreationParamsSchema=looseObject({ttl:number().optional(),pollInterval:number().optional()}),TaskMetadataSchema=object$1({ttl:number().optional()}),RelatedTaskMetadataSchema=object$1({taskId:string()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=e=>TaskAugmentedRequestParamsSchema.safeParse(e).success,RequestSchema=object$1({method:string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),NotificationSchema=object$1({method:string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string(),number().int()]),JSONRPCRequestSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=e=>JSONRPCRequestSchema.safeParse(e).success,JSONRPCNotificationSchema=object$1({jsonrpc:literal(`2.0`),...NotificationSchema.shape}).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema.safeParse(e).success,JSONRPCResultResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=e=>JSONRPCResultResponseSchema.safeParse(e).success;var ErrorCode;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(ErrorCode||={});const JSONRPCErrorResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema.optional(),error:object$1({code:number().int(),message:string(),data:unknown().optional()})}).strict(),isJSONRPCErrorResponse=e=>JSONRPCErrorResponseSchema.safeParse(e).success,JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal(`notifications/cancelled`),params:CancelledNotificationParamsSchema}),IconSchema=object$1({src:string(),mimeType:string().optional(),sizes:array(string()).optional(),theme:_enum([`light`,`dark`]).optional()}),IconsSchema=object$1({icons:array(IconSchema).optional()}),BaseMetadataSchema=object$1({name:string(),title:string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string(),websiteUrl:string().optional(),description:string().optional()}),FormElicitationCapabilitySchema=intersection(object$1({applyDefaults:boolean().optional()}),record(string(),unknown())),ElicitationCapabilitySchema=preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,intersection(object$1({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string(),unknown()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),sampling:object$1({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object$1({listChanged:boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal(`initialize`),params:InitializeRequestParamsSchema}),isInitializeRequest=e=>InitializeRequestSchema.safeParse(e).success,ServerCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object$1({listChanged:boolean().optional()}).optional(),resources:object$1({subscribe:boolean().optional(),listChanged:boolean().optional()}).optional(),tools:object$1({listChanged:boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/initialized`),params:NotificationsParamsSchema.optional()}),isInitializedNotification=e=>InitializedNotificationSchema.safeParse(e).success,PingRequestSchema=RequestSchema.extend({method:literal(`ping`),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object$1({progress:number(),total:optional(number()),message:optional(string())}),ProgressNotificationParamsSchema=object$1({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal(`notifications/progress`),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),TaskSchema=object$1({taskId:string(),status:TaskStatusSchema,ttl:union([number(),_null()]),createdAt:string(),lastUpdatedAt:string(),pollInterval:optional(number()),statusMessage:optional(string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tasks/status`),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/get`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal(`tasks/result`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal(`tasks/list`)}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/cancel`),params:BaseRequestParamsSchema.extend({taskId:string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object$1({uri:string(),mimeType:optional(string()),_meta:record(string(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string()}),Base64Schema=string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum([`user`,`assistant`]),AnnotationsSchema=object$1({audience:array(RoleSchema).optional(),priority:number().min(0).max(1).optional(),lastModified:datetime({offset:!0}).optional()}),ResourceSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string(),description:optional(string()),mimeType:optional(string()),size:optional(number()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string(),description:optional(string()),mimeType:optional(string()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/list`)}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/templates/list`)}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal(`resources/read`),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/list_changed`),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/subscribe`),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/unsubscribe`),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/updated`),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object$1({name:string(),description:optional(string()),required:optional(boolean())}),PromptSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal(`prompts/list`)}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string(),arguments:record(string(),string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal(`prompts/get`),params:GetPromptRequestParamsSchema}),TextContentSchema=object$1({type:literal(`text`),text:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ImageContentSchema=object$1({type:literal(`image`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),AudioContentSchema=object$1({type:literal(`audio`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ToolUseContentSchema=object$1({type:literal(`tool_use`),name:string(),id:string(),input:record(string(),unknown()),_meta:record(string(),unknown()).optional()}),EmbeddedResourceSchema=object$1({type:literal(`resource`),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal(`resource_link`)}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object$1({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/prompts/list_changed`),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object$1({title:string().optional(),readOnlyHint:boolean().optional(),destructiveHint:boolean().optional(),idempotentHint:boolean().optional(),openWorldHint:boolean().optional()}),ToolExecutionSchema=object$1({taskSupport:_enum([`required`,`optional`,`forbidden`]).optional()}),ToolSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string().optional(),inputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()),outputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal(`tools/list`)}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string(),unknown()).optional(),isError:boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string(),arguments:record(string(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal(`tools/call`),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tools/list_changed`),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object$1({autoRefresh:boolean().default(!0),debounceMs:number().int().nonnegative().default(300)}),LoggingLevelSchema=_enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal(`logging/setLevel`),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal(`notifications/message`),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object$1({name:string().optional()}),ModelPreferencesSchema=object$1({hints:array(ModelHintSchema).optional(),costPriority:number().min(0).max(1).optional(),speedPriority:number().min(0).max(1).optional(),intelligencePriority:number().min(0).max(1).optional()}),ToolChoiceSchema=object$1({mode:_enum([`auto`,`required`,`none`]).optional()}),ToolResultContentSchema=object$1({type:literal(`tool_result`),toolUseId:string().describe(`The unique identifier for the corresponding tool call.`),content:array(ContentBlockSchema).default([]),structuredContent:object$1({}).loose().optional(),isError:boolean().optional(),_meta:record(string(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object$1({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string().optional(),includeContext:_enum([`none`,`thisServer`,`allServers`]).optional(),temperature:number().optional(),maxTokens:number().int(),stopSequences:array(string()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal(`sampling/createMessage`),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`]).or(string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(string())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object$1({type:literal(`boolean`),title:string().optional(),description:string().optional(),default:boolean().optional()}),StringSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),minLength:number().optional(),maxLength:number().optional(),format:_enum([`email`,`uri`,`date`,`date-time`]).optional(),default:string().optional()}),NumberSchemaSchema=object$1({type:_enum([`number`,`integer`]),title:string().optional(),description:string().optional(),minimum:number().optional(),maximum:number().optional(),default:number().optional()}),UntitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),default:string().optional()}),TitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),oneOf:array(object$1({const:string(),title:string()})),default:string().optional()}),LegacyTitledEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),enumNames:array(string()).optional(),default:string().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({type:literal(`string`),enum:array(string())}),default:array(string()).optional()}),TitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({anyOf:array(object$1({const:string(),title:string()}))}),default:array(string()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`form`).optional(),message:string(),requestedSchema:object$1({type:literal(`object`),properties:record(string(),PrimitiveSchemaDefinitionSchema),required:array(string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`url`),message:string(),elicitationId:string(),url:string().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal(`elicitation/create`),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal(`notifications/elicitation/complete`),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum([`accept`,`decline`,`cancel`]),content:preprocess(e=>e===null?void 0:e,record(string(),union([string(),number(),boolean(),array(string())])).optional())}),ResourceTemplateReferenceSchema=object$1({type:literal(`ref/resource`),uri:string()}),PromptReferenceSchema=object$1({type:literal(`ref/prompt`),name:string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object$1({name:string(),value:string()}),context:object$1({arguments:record(string(),string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal(`completion/complete`),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function assertCompleteRequestResourceTemplate(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string()).max(100),total:optional(number().int()),hasMore:optional(boolean())})}),RootSchema=object$1({uri:string().startsWith(`file://`),name:string().optional(),_meta:record(string(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal(`roots/list`),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/roots/list_changed`),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);var McpError=class e extends Error{constructor(e,t,s){super(`MCP error ${e}: ${t}`),this.code=e,this.data=s,this.name=`McpError`}static fromError(t,s,g){if(t===ErrorCode.UrlElicitationRequired&&g){let e=g;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,s)}return new e(t,s,g)}},UrlElicitationRequiredError=class extends McpError{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(ErrorCode.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}const ignoreOverride=Symbol(`Let zodToJsonSchema decide on which parser to use`),defaultOptions={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},getDefaultOptions=e=>typeof e==`string`?{...defaultOptions,name:e}:{...defaultOptions,...e},getRefs=e=>{let t=getDefaultOptions(e),s=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:s,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage(e,t,s,g){g?.errorMessages&&s&&(e.errorMessage={...e.errorMessage,[t]:s})}function setResponseValueAndErrors(e,t,s,g,S){e[t]=s,addErrorMessage(e,t,g,S)}const getRelativePath=(e,t)=>{let s=0;for(;s<e.length&&s<t.length&&e[s]===t[s];s++);return[(e.length-s).toString(),...t.slice(s)].join(`/`)};function parseAnyDef(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?getRelativePath(t,e.currentPath):t.join(`/`)}}function parseArrayDef(e,t){let s={type:`array`};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(s.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&setResponseValueAndErrors(s,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(s,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(s,`minItems`,e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(s,`maxItems`,e.exactLength.value,e.exactLength.message,t)),s}function parseBigintDef(e,t){let s={type:`integer`,format:`int64`};if(!e.checks)return s;for(let g of e.checks)switch(g.kind){case`min`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`minimum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMinimum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMinimum=!0),setResponseValueAndErrors(s,`minimum`,g.value,g.message,t));break;case`max`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`maximum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMaximum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMaximum=!0),setResponseValueAndErrors(s,`maximum`,g.value,g.message,t));break;case`multipleOf`:setResponseValueAndErrors(s,`multipleOf`,g.value,g.message,t);break}return s}function parseBooleanDef(){return{type:`boolean`}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}const parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,s){let g=s??t.dateStrategy;if(Array.isArray(g))return{anyOf:g.map((s,g)=>parseDateDef(e,t,s))};switch(g){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return integerDateParser(e,t)}}const integerDateParser=(e,t)=>{let s={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return s;for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minimum`,g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maximum`,g.value,g.message,t);break}return s};function parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return t.effectStrategy===`input`?parseDef(e.schema._def,t):parseAnyDef(t)}function parseEnumDef(e){return{type:`string`,enum:Array.from(e.values)}}const isJsonSchema7AllOfType=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function parseIntersectionDef(e,t){let s=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),g=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,S=[];return s.forEach(e=>{if(isJsonSchema7AllOfType(e))S.push(...e.allOf),e.unevaluatedProperties===void 0&&(g=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:s,...g}=e;t=g}else g=void 0;S.push(t)}}),S.length?{allOf:S,...g}:void 0}function parseLiteralDef(e,t){let s=typeof e.value;return s!==`bigint`&&s!==`number`&&s!==`boolean`&&s!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:s===`bigint`?`integer`:s,enum:[e.value]}:{type:s===`bigint`?`integer`:s,const:e.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),emojiRegex),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(e,t){let s={type:`string`};if(e.checks)for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(s,`email`,g.message,t);break;case`format:idn-email`:addFormat(s,`idn-email`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.email,g.message,t);break}break;case`url`:addFormat(s,`uri`,g.message,t);break;case`uuid`:addFormat(s,`uuid`,g.message,t);break;case`regex`:addPattern(s,g.regex,g.message,t);break;case`cuid`:addPattern(s,zodPatterns.cuid,g.message,t);break;case`cuid2`:addPattern(s,zodPatterns.cuid2,g.message,t);break;case`startsWith`:addPattern(s,RegExp(`^${escapeLiteralCheckValue(g.value,t)}`),g.message,t);break;case`endsWith`:addPattern(s,RegExp(`${escapeLiteralCheckValue(g.value,t)}$`),g.message,t);break;case`datetime`:addFormat(s,`date-time`,g.message,t);break;case`date`:addFormat(s,`date`,g.message,t);break;case`time`:addFormat(s,`time`,g.message,t);break;case`duration`:addFormat(s,`duration`,g.message,t);break;case`length`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t),setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`includes`:addPattern(s,RegExp(escapeLiteralCheckValue(g.value,t)),g.message,t);break;case`ip`:g.version!==`v6`&&addFormat(s,`ipv4`,g.message,t),g.version!==`v4`&&addFormat(s,`ipv6`,g.message,t);break;case`base64url`:addPattern(s,zodPatterns.base64url,g.message,t);break;case`jwt`:addPattern(s,zodPatterns.jwt,g.message,t);break;case`cidr`:g.version!==`v6`&&addPattern(s,zodPatterns.ipv4Cidr,g.message,t),g.version!==`v4`&&addPattern(s,zodPatterns.ipv6Cidr,g.message,t);break;case`emoji`:addPattern(s,zodPatterns.emoji(),g.message,t);break;case`ulid`:addPattern(s,zodPatterns.ulid,g.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(s,`binary`,g.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(s,`contentEncoding`,`base64`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.base64,g.message,t);break}break;case`nanoid`:addPattern(s,zodPatterns.nanoid,g.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(g)}return s}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const ALPHA_NUMERIC=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let s=0;s<e.length;s++)ALPHA_NUMERIC.has(e[s])||(t+=`\\`),t+=e[s];return t}function addFormat(e,t,s,g){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&g.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...s&&g.errorMessages&&{errorMessage:{format:s}}})):setResponseValueAndErrors(e,`format`,t,s,g)}function addPattern(e,t,s,g){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&g.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags(t,g),...s&&g.errorMessages&&{errorMessage:{pattern:s}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,g),s,g)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let s={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},g=s.i?e.source.toLowerCase():e.source,S=``,w=!1,E=!1,D=!1;for(let e=0;e<g.length;e++){if(w){S+=g[e],w=!1;continue}if(s.i){if(E){if(g[e].match(/[a-z]/)){D?(S+=g[e],S+=`${g[e-2]}-${g[e]}`.toUpperCase(),D=!1):g[e+1]===`-`&&g[e+2]?.match(/[a-z]/)?(S+=g[e],D=!0):S+=`${g[e]}${g[e].toUpperCase()}`;continue}}else if(g[e].match(/[a-z]/)){S+=`[${g[e]}${g[e].toUpperCase()}]`;continue}}if(s.m){if(g[e]===`^`){S+=`(^|(?<=[\r
41
+ `,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(reasonableDetectionSizeInBytes);let t=getKnownFileSizeOrMaximum(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);if(!(t>maximumTiffTagCount)&&!(hasUnknownFileSize(this.tokenizer)&&2+t*12>maximumTiffIfdOffsetInBytes))for(let s=0;s<t;++s){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},s=(e?UINT16_BE:UINT16_LE).get(this.buffer,2),g=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(s===42){if(g>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(g>=8){let t=(e?UINT16_BE:UINT16_LE).get(this.buffer,8),s=(e?UINT16_BE:UINT16_LE).get(this.buffer,10);if(t===28&&s===254||t===31&&s===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(hasUnknownFileSize(this.tokenizer)&&g>maximumTiffStreamIfdOffsetInBytes)return t;let s=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,g,{maximumLength:s,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let S;try{S=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return S??t}if(s===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};const supportedExtensions=new Set(extensions),supportedMimeTypes=new Set(mimeTypes);var require_ipaddr=__commonJSMin$2(((e,t)=>{(function(e){let s=`(0?\\d+|0x[a-f0-9]+)`,g={fourOctet:RegExp(`^${s}\\.${s}\\.${s}\\.${s}$`,`i`),threeOctet:RegExp(`^${s}\\.${s}\\.${s}$`,`i`),twoOctet:RegExp(`^${s}\\.${s}$`,`i`),longValue:RegExp(`^${s}$`,`i`)},S=RegExp(`^0[0-7]+$`,`i`),w=RegExp(`^0x[a-f0-9]+$`,`i`),E=`%[0-9a-z]{1,}`,D=`(?:[0-9a-f]+::?)+`,O={zoneIndex:new RegExp(E,`i`),native:RegExp(`^(::)?(${D})?([0-9a-f]+)?(::)?(${E})?$`,`i`),deprecatedTransitional:RegExp(`^(?:::)(${s}\\.${s}\\.${s}\\.${s}(${E})?)$`,`i`),transitional:RegExp(`^((?:${D})|(?:::)(?:${D})?)${s}\\.${s}\\.${s}\\.${s}(${E})?$`,`i`)};function k(e,t){if(e.indexOf(`::`)!==e.lastIndexOf(`::`))return null;let s=0,g=-1,S=(e.match(O.zoneIndex)||[])[0],w,E;for(S&&(S=S.substring(1),e=e.replace(/%.+$/,``));(g=e.indexOf(`:`,g+1))>=0;)s++;if(e.substr(0,2)===`::`&&s--,e.substr(-2,2)===`::`&&s--,s>t)return null;for(E=t-s,w=`:`;E--;)w+=`0:`;return e=e.replace(`::`,w),e[0]===`:`&&(e=e.slice(1)),e[e.length-1]===`:`&&(e=e.slice(0,-1)),t=(function(){let t=e.split(`:`),s=[];for(let e=0;e<t.length;e++)s.push(parseInt(t[e],16));return s})(),{parts:t,zoneId:S}}function j(e,t,s,g){if(e.length!==t.length)throw Error(`ipaddr: cannot match CIDR for objects with different lengths`);let S=0,w;for(;g>0;){if(w=s-g,w<0&&(w=0),e[S]>>w!==t[S]>>w)return!1;g-=s,S+=1}return!0}function F(e){if(w.test(e))return parseInt(e,16);if(e[0]===`0`&&!isNaN(parseInt(e[1],10))){if(S.test(e))return parseInt(e,8);throw Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function L(e,t){for(;e.length<t;)e=`0${e}`;return e}let B={};B.IPv4=(function(){function e(e){if(e.length!==4)throw Error(`ipaddr: ipv4 octet count should be 4`);let t,s;for(t=0;t<e.length;t++)if(s=e[t],!(0<=s&&s<=255))throw Error(`ipaddr: ipv4 octet should fit in 8 bits`);this.octets=e}return e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,18,0,0]),15],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]],as112:[[new e([192,175,48,0]),24],[new e([192,31,196,0]),24]],amt:[[new e([192,52,193,0]),24]]},e.prototype.kind=function(){return`ipv4`},e.prototype.match=function(e,t){let s;if(t===void 0&&(s=e,e=s[0],t=s[1]),e.kind()!==`ipv4`)throw Error(`ipaddr: cannot match ipv4 address with non-ipv4 one`);return j(this.octets,e.octets,8,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,s={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},g,S,w;for(g=3;g>=0;--g)if(S=this.octets[g],S in s){if(w=s[S],t&&w!==0)return null;w!==8&&(t=!0),e+=w}else return null;return 32-e},e.prototype.range=function(){return B.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return B.IPv6.parse(`::ffff:${this.toString()}`)},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(`.`)},e})(),B.IPv4.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),s=t[0].toByteArray(),g=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),S=[],w=0;for(;w<4;)S.push(parseInt(s[w],10)|parseInt(g[w],10)^255),w++;return new this(S)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},B.IPv4.isIPv4=function(e){return this.parser(e)!==null},B.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch{return!1}},B.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch{return!1}},B.IPv4.isValidFourPartDecimal=function(e){return!!(B.IPv4.isValid(e)&&e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},B.IPv4.isValidCIDRFourPartDecimal=function(e){let t=e.match(/^(.+)\/(\d+)$/);return!B.IPv4.isValidCIDR(e)||!t?!1:B.IPv4.isValidFourPartDecimal(t[1])},B.IPv4.networkAddressFromCIDR=function(e){let t,s,g,S,w;try{for(t=this.parseCIDR(e),g=t[0].toByteArray(),w=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),S=[],s=0;s<4;)S.push(parseInt(g[s],10)&parseInt(w[s],10)),s++;return new this(S)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},B.IPv4.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv4 Address`);return new this(t)},B.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){let e=parseInt(t[2]);if(e>=0&&e<=32){let s=[this.parse(t[1]),e];return Object.defineProperty(s,`toString`,{value:function(){return this.join(`/`)}}),s}}throw Error(`ipaddr: string is not formatted like an IPv4 CIDR range`)},B.IPv4.parser=function(e){let t,s,S;if(t=e.match(g.fourOctet))return(function(){let e=t.slice(1,6),g=[];for(let t=0;t<e.length;t++)s=e[t],g.push(F(s));return g})();if(t=e.match(g.longValue)){if(S=F(t[1]),S>4294967295||S<0)throw Error(`ipaddr: address outside defined range`);return(function(){let e=[],t;for(t=0;t<=24;t+=8)e.push(S>>t&255);return e})().reverse()}else if(t=e.match(g.twoOctet))return(function(){let e=t.slice(1,4),s=[];if(S=F(e[1]),S>16777215||S<0)throw Error(`ipaddr: address outside defined range`);return s.push(F(e[0])),s.push(S>>16&255),s.push(S>>8&255),s.push(S&255),s})();else if(t=e.match(g.threeOctet))return(function(){let e=t.slice(1,5),s=[];if(S=F(e[2]),S>65535||S<0)throw Error(`ipaddr: address outside defined range`);return s.push(F(e[0])),s.push(F(e[1])),s.push(S>>8&255),s.push(S&255),s})();else return null},B.IPv4.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>32)throw Error(`ipaddr: invalid IPv4 prefix length`);let t=[0,0,0,0],s=0,g=Math.floor(e/8);for(;s<g;)t[s]=255,s++;return g<4&&(t[g]=2**(e%8)-1<<8-e%8),new this(t)},B.IPv6=(function(){function e(e,t){let s,g;if(e.length===16)for(this.parts=[],s=0;s<=14;s+=2)this.parts.push(e[s]<<8|e[s+1]);else if(e.length===8)this.parts=e;else throw Error(`ipaddr: ipv6 part count should be 8 or 16`);for(s=0;s<this.parts.length;s++)if(g=this.parts[s],!(0<=g&&g<=65535))throw Error(`ipaddr: ipv6 part should fit in 16 bits`);t&&(this.zoneId=t)}return e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new e([65216,0,0,0,0,0,0,0]),10],discard:[new e([256,0,0,0,0,0,0,0]),64],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new e([100,65435,0,0,0,0,0,0]),96],[new e([100,65435,1,0,0,0,0,0]),48]],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],benchmarking:[new e([8193,2,0,0,0,0,0,0]),48],amt:[new e([8193,3,0,0,0,0,0,0]),32],as112v6:[[new e([8193,4,274,0,0,0,0,0]),48],[new e([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new e([8193,16,0,0,0,0,0,0]),28],orchid2:[new e([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new e([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new e([24320,0,0,0,0,0,0,0]),16],reserved:[[new e([8193,0,0,0,0,0,0,0]),23],[new e([8193,3512,0,0,0,0,0,0]),32],[new e([16383,0,0,0,0,0,0,0]),20]]},e.prototype.isIPv4MappedAddress=function(){return this.range()===`ipv4Mapped`},e.prototype.kind=function(){return`ipv6`},e.prototype.match=function(e,t){let s;if(t===void 0&&(s=e,e=s[0],t=s[1]),e.kind()!==`ipv6`)throw Error(`ipaddr: cannot match ipv6 address with non-ipv6 one`);return j(this.parts,e.parts,16,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,s={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},g,S;for(let w=7;w>=0;--w)if(g=this.parts[w],g in s){if(S=s[g],t&&S!==0)return null;S!==16&&(t=!0),e+=S}else return null;return 128-e},e.prototype.range=function(){return B.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e,t=[],s=this.parts;for(let g=0;g<s.length;g++)e=s[g],t.push(e>>8),t.push(e&255);return t},e.prototype.toFixedLengthString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(L(this.parts[t].toString(16),4));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error(`ipaddr: trying to convert a generic ipv6 address to ipv4`);let e=this.parts.slice(-2),t=e[0],s=e[1];return new B.IPv4([t>>8,t&255,s>>8,s&255])},e.prototype.toNormalizedString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toRFC5952String=function(){let e=/((^|:)(0(:|$)){2,})/g,t=this.toNormalizedString(),s=0,g=-1,S;for(;S=e.exec(t);)S[0].length>g&&(s=S.index,g=S[0].length);return g<0?t:`${t.substring(0,s)}::${t.substring(s+g)}`},e.prototype.toString=function(){return this.toRFC5952String()},e})(),B.IPv6.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),s=t[0].toByteArray(),g=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),S=[],w=0;for(;w<16;)S.push(parseInt(s[w],10)|parseInt(g[w],10)^255),w++;return new this(S)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},B.IPv6.isIPv6=function(e){return this.parser(e)!==null},B.IPv6.isValid=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{let t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch{return!1}},B.IPv6.isValidCIDR=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{return this.parseCIDR(e),!0}catch{return!1}},B.IPv6.networkAddressFromCIDR=function(e){let t,s,g,S,w;try{for(t=this.parseCIDR(e),g=t[0].toByteArray(),w=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),S=[],s=0;s<16;)S.push(parseInt(g[s],10)&parseInt(w[s],10)),s++;return new this(S)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},B.IPv6.parse=function(e){let t=this.parser(e);if(t.parts===null)throw Error(`ipaddr: string is not formatted like an IPv6 Address`);return new this(t.parts,t.zoneId)},B.IPv6.parseCIDR=function(e){let t,s,g;if((s=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(s[2]),t>=0&&t<=128))return g=[this.parse(s[1]),t],Object.defineProperty(g,`toString`,{value:function(){return this.join(`/`)}}),g;throw Error(`ipaddr: string is not formatted like an IPv6 CIDR range`)},B.IPv6.parser=function(e){let t,s,g,S,w,E;if(g=e.match(O.deprecatedTransitional))return this.parser(`::ffff:${g[1]}`);if(O.native.test(e))return k(e,8);if((g=e.match(O.transitional))&&(E=g[6]||``,t=g[1],g[1].endsWith(`::`)||(t=t.slice(0,-1)),t=k(t+E,6),t.parts)){for(w=[parseInt(g[2]),parseInt(g[3]),parseInt(g[4]),parseInt(g[5])],s=0;s<w.length;s++)if(S=w[s],!(0<=S&&S<=255))return null;return t.parts.push(w[0]<<8|w[1]),t.parts.push(w[2]<<8|w[3]),{parts:t.parts,zoneId:t.zoneId}}return null},B.IPv6.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>128)throw Error(`ipaddr: invalid IPv6 prefix length`);let t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],s=0,g=Math.floor(e/8);for(;s<g;)t[s]=255,s++;return g<16&&(t[g]=2**(e%8)-1<<8-e%8),new this(t)},B.fromByteArray=function(e){let t=e.length;if(t===4)return new B.IPv4(e);if(t===16)return new B.IPv6(e);throw Error(`ipaddr: the binary input is neither an IPv6 nor IPv4 address`)},B.isValid=function(e){return B.IPv6.isValid(e)||B.IPv4.isValid(e)},B.isValidCIDR=function(e){return B.IPv6.isValidCIDR(e)||B.IPv4.isValidCIDR(e)},B.parse=function(e){if(B.IPv6.isValid(e))return B.IPv6.parse(e);if(B.IPv4.isValid(e))return B.IPv4.parse(e);throw Error(`ipaddr: the address has neither IPv6 nor IPv4 format`)},B.parseCIDR=function(e){try{return B.IPv6.parseCIDR(e)}catch{try{return B.IPv4.parseCIDR(e)}catch{throw Error(`ipaddr: the address has neither IPv6 nor IPv4 CIDR format`)}}},B.process=function(e){let t=this.parse(e);return t.kind()===`ipv6`&&t.isIPv4MappedAddress()?t.toIPv4Address():t},B.subnetMatch=function(e,t,s){let g,S,w,E;for(S in s??=`unicast`,t)if(Object.prototype.hasOwnProperty.call(t,S)){for(w=t[S],w[0]&&!(w[0]instanceof Array)&&(w=[w]),g=0;g<w.length;g++)if(E=w[g],e.kind()===E[0].kind()&&e.match.apply(e,E))return S}return s},t!==void 0&&t.exports?t.exports=B:e.ipaddr=B})(e)})),util;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function s(e){throw Error()}e.assertNever=s,e.arrayToEnum=e=>{let t={};for(let s of e)t[s]=s;return t},e.getValidEnumValues=t=>{let s=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),g={};for(let e of s)g[e]=t[e];return e.objectValues(g)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},e.find=(e,t)=>{for(let s of e)if(t(s))return s},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function g(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=g,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(util||={});var objectUtil;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||={});const ZodParsedType=util.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),getParsedType=e=>{switch(typeof e){case`undefined`:return ZodParsedType.undefined;case`string`:return ZodParsedType.string;case`number`:return Number.isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case`boolean`:return ZodParsedType.boolean;case`function`:return ZodParsedType.function;case`bigint`:return ZodParsedType.bigint;case`symbol`:return ZodParsedType.symbol;case`object`:return Array.isArray(e)?ZodParsedType.array:e===null?ZodParsedType.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?ZodParsedType.promise:typeof Map<`u`&&e instanceof Map?ZodParsedType.map:typeof Set<`u`&&e instanceof Set?ZodParsedType.set:typeof Date<`u`&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var ZodError=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},s={_errors:[]},g=e=>{for(let S of e.issues)if(S.code===`invalid_union`)S.unionErrors.map(g);else if(S.code===`invalid_return_type`)g(S.returnTypeError);else if(S.code===`invalid_arguments`)g(S.argumentsError);else if(S.path.length===0)s._errors.push(t(S));else{let e=s,g=0;for(;g<S.path.length;){let s=S.path[g];g===S.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(S))):e[s]=e[s]||{_errors:[]},e=e[s],g++}}};return g(this),s}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),s=[];for(let g of this.issues)if(g.path.length>0){let s=g.path[0];t[s]=t[s]||[],t[s].push(e(g))}else s.push(e(g));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};ZodError.create=e=>new ZodError(e);const errorMap=(e,t)=>{let s;switch(e.code){case ZodIssueCode.invalid_type:s=e.received===ZodParsedType.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:s=`Unrecognized key(s) in object: ${util.joinValues(e.keys,`, `)}`;break;case ZodIssueCode.invalid_union:s=`Invalid input`;break;case ZodIssueCode.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${util.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:s=`Invalid enum value. Expected ${util.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode.invalid_arguments:s=`Invalid function arguments`;break;case ZodIssueCode.invalid_return_type:s=`Invalid function return type`;break;case ZodIssueCode.invalid_date:s=`Invalid date`;break;case ZodIssueCode.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:util.assertNever(e.validation):s=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case ZodIssueCode.too_small:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case ZodIssueCode.too_big:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case ZodIssueCode.custom:s=`Invalid input`;break;case ZodIssueCode.invalid_intersection_types:s=`Intersection results could not be merged`;break;case ZodIssueCode.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode.not_finite:s=`Number must be finite`;break;default:s=t.defaultError,util.assertNever(e)}return{message:s}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{let{data:t,path:s,errorMaps:g,issueData:S}=e,w=[...s,...S.path||[]],E={...S,path:w};if(S.message!==void 0)return{...S,path:w,message:S.message};let D=``,O=g.filter(e=>!!e).slice().reverse();for(let e of O)D=e(E,{data:t,defaultError:D}).message;return{...S,path:w,message:D}};function addIssueToContext(e,t){let s=getErrorMap(),g=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===errorMap?void 0:errorMap].filter(e=>!!e)});e.common.issues.push(g)}var ParseStatus=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let s=[];for(let g of t){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&e.dirty(),s.push(g.value)}return{status:e.value,value:s}}static async mergeObjectAsync(t,s){let g=[];for(let e of s){let t=await e.key,s=await e.value;g.push({key:t,value:s})}return e.mergeObjectSync(t,g)}static mergeObjectSync(e,t){let s={};for(let g of t){let{key:t,value:S}=g;if(t.status===`aborted`||S.status===`aborted`)return INVALID;t.status===`dirty`&&e.dirty(),S.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(S.value!==void 0||g.alwaysSet)&&(s[t.value]=S.value)}return{status:e.value,value:s}}};const INVALID=Object.freeze({status:`aborted`}),DIRTY=e=>({status:`dirty`,value:e}),OK=e=>({status:`valid`,value:e}),isAborted=e=>e.status===`aborted`,isDirty=e=>e.status===`dirty`,isValid=e=>e.status===`valid`,isAsync=e=>typeof Promise<`u`&&e instanceof Promise;var errorUtil;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(errorUtil||={});var ParseInputLazyPath=class{constructor(e,t,s,g){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=g}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new ZodError(e.common.issues),this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:s,required_error:g,description:S}=e;if(t&&(s||g))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:S}:{errorMap:(t,S)=>{let{message:w}=e;return t.code===`invalid_enum_value`?{message:w??S.defaultError}:S.data===void 0?{message:w??g??S.defaultError}:t.code===`invalid_type`?{message:w??s??S.defaultError}:{message:S.defaultError}},description:S}}var ZodType=class{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(isAsync(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};return handleResult(s,this._parseSync({data:e,path:s.path,parent:s}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this[`~standard`].async)try{let s=this._parseSync({data:e,path:[],parent:t});return isValid(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>isValid(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},g=this._parse({data:e,path:s.path,parent:s});return handleResult(s,await(isAsync(g)?g:Promise.resolve(g)))}refine(e,t){let s=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,g)=>{let S=e(t),w=()=>g.addIssue({code:ZodIssueCode.custom,...s(t)});return typeof Promise<`u`&&S instanceof Promise?S.then(e=>e?!0:(w(),!1)):S?!0:(w(),!1)})}refinement(e,t){return this._refinement((s,g)=>e(s)?!0:(g.addIssue(typeof t==`function`?t(s,g):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;let emojiRegex$1;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,dateRegex=RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let s=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`,s=[];return s.push(e.local?`Z?`:`Z`),e.offset&&s.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${s.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!!((t===`v4`||!t)&&ipv4Regex.test(e)||(t===`v6`||!t)&&ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{let[s]=e.split(`.`);if(!s)return!1;let g=s.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(s.length+(4-s.length%4)%4,`=`),S=JSON.parse(atob(g));return!(typeof S!=`object`||!S||`typ`in S&&S?.typ!==`JWT`||!S.alg||t&&S.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!!((t===`v4`||!t)&&ipv4CidrRegex.test(e)||(t===`v6`||!t)&&ipv6CidrRegex.test(e))}var ZodString=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}let t=new ParseStatus,s;for(let g of this._def.checks)if(g.kind===`min`)e.data.length<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`max`)e.data.length>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`length`){let S=e.data.length>g.value,w=e.data.length<g.value;(S||w)&&(s=this._getOrReturnCtx(e,s),S?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}):w&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}),t.dirty())}else if(g.kind===`email`)emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`email`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`emoji`)emojiRegex$1||=new RegExp(_emojiRegex,`u`),emojiRegex$1.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`emoji`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`uuid`)uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`nanoid`)nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid`)cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid2`)cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`ulid`)ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`url`)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()}else g.kind===`regex`?(g.regex.lastIndex=0,g.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`regex`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty())):g.kind===`trim`?e.data=e.data.trim():g.kind===`includes`?e.data.includes(g.value,g.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:g.value,position:g.position},message:g.message}),t.dirty()):g.kind===`toLowerCase`?e.data=e.data.toLowerCase():g.kind===`toUpperCase`?e.data=e.data.toUpperCase():g.kind===`startsWith`?e.data.startsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:g.value},message:g.message}),t.dirty()):g.kind===`endsWith`?e.data.endsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:g.value},message:g.message}),t.dirty()):g.kind===`datetime`?datetimeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:g.message}),t.dirty()):g.kind===`date`?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`date`,message:g.message}),t.dirty()):g.kind===`time`?timeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`time`,message:g.message}),t.dirty()):g.kind===`duration`?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`duration`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`ip`?isValidIP(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ip`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`jwt`?isValidJWT(e.data,g.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`cidr`?isValidCidr(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64`?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64url`?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):util.assertNever(g);return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...errorUtil.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let s=(e.toString().split(`.`)[1]||``).length,g=(t.toString().split(`.`)[1]||``).length,S=s>g?s:g;return Number.parseInt(e.toFixed(S).replace(`.`,``))%Number.parseInt(t.toFixed(S).replace(`.`,``))/10**S}var ZodNumber=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`int`?util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:g.message}),s.dirty()):g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`multipleOf`?floatSafeRemainder(e.data,g.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):g.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:errorUtil.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks)if(s.kind===`finite`||s.kind===`int`||s.kind===`multipleOf`)return!0;else s.kind===`min`?(t===null||s.value>t)&&(t=s.value):s.kind===`max`&&(e===null||s.value<e)&&(e=s.value);return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodBigInt=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:`bigint`,minimum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:`bigint`,maximum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`multipleOf`?e.data%g.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodBigInt.create=e=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams(e)});var ZodBoolean=class extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodDate=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(Number.isNaN(e.data.getTime()))return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID;let t=new ParseStatus,s;for(let g of this._def.checks)g.kind===`min`?e.data.getTime()<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:g.message,inclusive:!0,exact:!1,minimum:g.value,type:`date`}),t.dirty()):g.kind===`max`?e.data.getTime()>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:g.message,inclusive:!0,exact:!1,maximum:g.value,type:`date`}),t.dirty()):util.assertNever(g);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ZodDate.create=e=>new ZodDate({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}};ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}};ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}};ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}};ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}};ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});var ZodArray=class e extends ZodType{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),g=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(g.exactLength!==null){let e=t.data.length>g.exactLength.value,S=t.data.length<g.exactLength.value;(e||S)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:S?g.exactLength.value:void 0,maximum:e?g.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:g.exactLength.message}),s.dirty())}if(g.minLength!==null&&t.data.length<g.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.minLength.value,type:`array`,inclusive:!0,exact:!1,message:g.minLength.message}),s.dirty()),g.maxLength!==null&&t.data.length>g.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:g.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((e,s)=>g.type._parseAsync(new ParseInputLazyPath(t,e,t.path,s)))).then(e=>ParseStatus.mergeArray(s,e));let S=[...t.data].map((e,s)=>g.type._parseSync(new ParseInputLazyPath(t,e,t.path,s)));return ParseStatus.mergeArray(s,S)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:errorUtil.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:errorUtil.toString(s)}})}nonempty(e){return this.min(1,e)}};ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof ZodObject){let t={};for(let s in e.shape){let g=e.shape[s];t[s]=ZodOptional.create(deepPartialify(g))}return new ZodObject({...e._def,shape:()=>t})}else if(e instanceof ZodArray)return new ZodArray({...e._def,type:deepPartialify(e.element)});else if(e instanceof ZodOptional)return ZodOptional.create(deepPartialify(e.unwrap()));else if(e instanceof ZodNullable)return ZodNullable.create(deepPartialify(e.unwrap()));else if(e instanceof ZodTuple)return ZodTuple.create(e.items.map(e=>deepPartialify(e)));else return e}var ZodObject=class e extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:util.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}let{status:t,ctx:s}=this._processInputParams(e),{shape:g,keys:S}=this._getCached(),w=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in s.data)S.includes(e)||w.push(e);let E=[];for(let e of S){let t=g[e],S=s.data[e];E.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(s,S,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of w)E.push({key:{status:`valid`,value:e},value:{status:`valid`,value:s.data[e]}});else if(e===`strict`)w.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:w}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of w){let g=s.data[t];E.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(s,g,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of E){let s=await t.key,g=await t.value;e.push({key:s,value:g,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(t,e)):ParseStatus.mergeObjectSync(t,E)}get shape(){return this._def.shape()}strict(t){return errorUtil.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,s)=>{let g=this._def.errorMap?.(e,s).message??s.defaultError;return e.code===`unrecognized_keys`?{message:errorUtil.errToObj(t).message??g}:{message:g}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let s={};for(let e of util.objectKeys(t))t[e]&&this.shape[e]&&(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}omit(t){let s={};for(let e of util.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return deepPartialify(this)}partial(t){let s={};for(let e of util.objectKeys(this.shape)){let g=this.shape[e];t&&!t[e]?s[e]=g:s[e]=g.optional()}return new e({...this._def,shape:()=>s})}required(t){let s={};for(let e of util.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ZodOptional;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function g(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let s of e)if(s.result.status===`dirty`)return t.common.issues.push(...s.ctx.common.issues),s.result;let s=e.map(e=>new ZodError(e.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}if(t.common.async)return Promise.all(s.map(async e=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(g);{let e,g=[];for(let S of s){let s={...t,common:{...t.common,issues:[]},parent:null},w=S._parseSync({data:t.data,path:t.path,parent:s});if(w.status===`valid`)return w;w.status===`dirty`&&!e&&(e={result:w,ctx:s}),s.common.issues.length&&g.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let S=g.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:S}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];var ZodDiscriminatedUnion=class e extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;let s=this.discriminator,g=t.data[s],S=this.optionsMap.get(g);return S?t.common.async?S._parseAsync({data:t.data,path:t.path,parent:t}):S._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,g){let S=new Map;for(let e of s){let s=getDiscriminator(e.shape[t]);if(!s.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let g of s){if(S.has(g))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(g)}`);S.set(g,e)}}return new e({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:S,...processCreateParams(g)})}};function mergeValues(e,t){let s=getParsedType(e),g=getParsedType(t);if(e===t)return{valid:!0,data:e};if(s===ZodParsedType.object&&g===ZodParsedType.object){let s=util.objectKeys(t),g=util.objectKeys(e).filter(e=>s.indexOf(e)!==-1),S={...e,...t};for(let s of g){let g=mergeValues(e[s],t[s]);if(!g.valid)return{valid:!1};S[s]=g.data}return{valid:!0,data:S}}else if(s===ZodParsedType.array&&g===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let g=0;g<e.length;g++){let S=e[g],w=t[g],E=mergeValues(S,w);if(!E.valid)return{valid:!1};s.push(E.data)}return{valid:!0,data:s}}else if(s===ZodParsedType.date&&g===ZodParsedType.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=(e,g)=>{if(isAborted(e)||isAborted(g))return INVALID;let S=mergeValues(e.value,g.value);return S.valid?((isDirty(e)||isDirty(g))&&t.dirty(),{status:t.value,value:S.data}):(addIssueToContext(s,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,t])=>g(e,t)):g(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};ZodIntersection.create=(e,t,s)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(s)});var ZodTuple=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.array)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:s.parsedType}),INVALID;if(s.data.length<this._def.items.length)return addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),INVALID;!this._def.rest&&s.data.length>this._def.items.length&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let g=[...s.data].map((e,t)=>{let g=this._def.items[t]||this._def.rest;return g?g._parse(new ParseInputLazyPath(s,e,s.path,t)):null}).filter(e=>!!e);return s.common.async?Promise.all(g).then(e=>ParseStatus.mergeArray(t,e)):ParseStatus.mergeArray(t,g)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};var ZodRecord=class e extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.object)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:s.parsedType}),INVALID;let g=[],S=this._def.keyType,w=this._def.valueType;for(let e in s.data)g.push({key:S._parse(new ParseInputLazyPath(s,e,s.path,e)),value:w._parse(new ParseInputLazyPath(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?ParseStatus.mergeObjectAsync(t,g):ParseStatus.mergeObjectSync(t,g)}get element(){return this._def.valueType}static create(t,s,g){return s instanceof ZodType?new e({keyType:t,valueType:s,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(g)}):new e({keyType:ZodString.create(),valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(s)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.map)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:s.parsedType}),INVALID;let g=this._def.keyType,S=this._def.valueType,w=[...s.data.entries()].map(([e,t],w)=>({key:g._parse(new ParseInputLazyPath(s,e,s.path,[w,`key`])),value:S._parse(new ParseInputLazyPath(s,t,s.path,[w,`value`]))}));if(s.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let s of w){let g=await s.key,S=await s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let s of w){let g=s.key,S=s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}}}};ZodMap.create=(e,t,s)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(s)});var ZodSet=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.set)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:s.parsedType}),INVALID;let g=this._def;g.minSize!==null&&s.data.size<g.minSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.minSize.value,type:`set`,inclusive:!0,exact:!1,message:g.minSize.message}),t.dirty()),g.maxSize!==null&&s.data.size>g.maxSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:g.maxSize.message}),t.dirty());let S=this._def.valueType;function w(e){let s=new Set;for(let g of e){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&t.dirty(),s.add(g.value)}return{status:t.value,value:s}}let E=[...s.data.values()].map((e,t)=>S._parse(new ParseInputLazyPath(s,e,s.path,t)));return s.common.async?Promise.all(E).then(e=>w(e)):w(E)}min(t,s){return new e({...this._def,minSize:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:errorUtil.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});var ZodFunction=class e extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function s(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:s}})}function g(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:s}})}let S={errorMap:t.common.contextualErrorMap},w=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let E=new ZodError([]),D=await e._def.args.parseAsync(t,S).catch(e=>{throw E.addIssue(s(t,e)),E}),O=await Reflect.apply(w,this,D);return await e._def.returns._def.type.parseAsync(O,S).catch(e=>{throw E.addIssue(g(O,e)),E})})}else{let e=this;return OK(function(...t){let E=e._def.args.safeParse(t,S);if(!E.success)throw new ZodError([s(t,E.error)]);let D=Reflect.apply(w,this,E.data),O=e._def.returns.safeParse(D,S);if(!O.success)throw new ZodError([g(D,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ZodTuple.create(t).rest(ZodUnknown.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,s,g){return new e({args:t||ZodTuple.create([]).rest(ZodUnknown.create()),returns:s||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(g)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});var ZodLiteral=class extends ZodType{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}var ZodEnum=class e extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{expected:util.joinValues(s),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,s=this._def){return e.create(t,{...this._def,...s})}exclude(t,s=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...s})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(e){let t=util.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==ZodParsedType.string&&s.parsedType!==ZodParsedType.number){let e=util.objectValues(t);return addIssueToContext(s,{expected:util.joinValues(e),received:s.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(util.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=util.objectValues(t);return addIssueToContext(s,{received:s.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==ZodParsedType.promise&&t.common.async===!1?(addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID):OK((t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=this._def.effect||null,S={addIssue:e=>{addIssueToContext(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(S.addIssue=S.addIssue.bind(S),g.type===`preprocess`){let e=g.transform(s.data,S);if(s.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let g=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g});{if(t.value===`aborted`)return INVALID;let g=this._def.schema._parseSync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g}}if(g.type===`refinement`){let e=e=>{let t=g.refinement(e,S);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(s.common.async===!1){let g=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return g.status===`aborted`?INVALID:(g.status===`dirty`&&t.dirty(),e(g.value),{status:t.value,value:g.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(s=>s.status===`aborted`?INVALID:(s.status===`dirty`&&t.dirty(),e(s.value).then(()=>({status:t.value,value:s.value}))))}if(g.type===`transform`)if(s.common.async===!1){let e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!isValid(e))return INVALID;let w=g.transform(e.value,S);if(w instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:w}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>isValid(e)?Promise.resolve(g.transform(e.value,S)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(g)}};ZodEffects.create=(e,t,s)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(s)}),ZodEffects.createWithPreprocess=(e,t,s)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(s)});var ZodOptional=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===ZodParsedType.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...processCreateParams(t)});var ZodCatch=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},g=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return isAsync(g)?g.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})})):{status:`valid`,value:g.status===`valid`?g.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:`valid`,value:e.data}}};ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});var ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},ZodPipeline=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})();{let e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(t,s){return new e({in:t,out:s,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),s=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>s(e)):s(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(ZodFirstPartyTypeKind||={});const stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ZodMiniType=$constructor(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,s)=>parse$1(e,t,s,{callee:e.parse}),e.safeParse=(t,s)=>safeParse$1(e,t,s),e.parseAsync=async(t,s)=>parseAsync(e,t,s,{callee:e.parseAsync}),e.safeParseAsync=async(t,s)=>safeParseAsync$1(e,t,s),e.check=(...s)=>e.clone({...t,checks:[...t.checks??[],...s.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,s)=>clone(e,t,s),e.brand=()=>e,e.register=((t,s)=>(t.add(e,s),e)),e.apply=t=>t(e)}),ZodMiniObject=$constructor(`ZodMiniObject`,(e,t)=>{$ZodObject.init(e,t),ZodMiniType.init(e,t),defineLazy(e,`shape`,()=>t.shape)});function object(e,t){return new ZodMiniObject({type:`object`,shape:e??{},...normalizeParams(t)})}const describe=describe$1,meta=meta$1;function isZ4Schema(e){return!!e._zod}function objectFromShape(e){let t=Object.values(e);if(t.length===0)return object({});let s=t.every(isZ4Schema),g=t.every(e=>!isZ4Schema(e));if(s)return object(e);if(g)return objectType(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?safeParse$1(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await safeParseAsync$1(e,t):await e.safeParseAsync(t)}function getObjectShape(e){if(!e)return;let t;if(t=isZ4Schema(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function normalizeObjectSchema(e){if(e){if(typeof e==`object`){let t=e,s=e;if(!t._def&&!s._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return objectFromShape(e)}}if(isZ4Schema(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function getParseErrorMessage(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function getSchemaDescription(e){return e.description}function isSchemaOptional(e){if(isZ4Schema(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function getLiteralValue(e){if(isZ4Schema(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let s=e.value;if(s!==void 0)return s}const LATEST_PROTOCOL_VERSION=`2025-11-25`,DEFAULT_NEGOTIATED_PROTOCOL_VERSION=`2025-03-26`,SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],RELATED_TASK_META_KEY=`io.modelcontextprotocol/related-task`,JSONRPC_VERSION=`2.0`,AssertObjectSchema=custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),ProgressTokenSchema=union([string(),number().int()]),CursorSchema=string(),TaskCreationParamsSchema=looseObject({ttl:number().optional(),pollInterval:number().optional()}),TaskMetadataSchema=object$1({ttl:number().optional()}),RelatedTaskMetadataSchema=object$1({taskId:string()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=e=>TaskAugmentedRequestParamsSchema.safeParse(e).success,RequestSchema=object$1({method:string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),NotificationSchema=object$1({method:string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string(),number().int()]),JSONRPCRequestSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=e=>JSONRPCRequestSchema.safeParse(e).success,JSONRPCNotificationSchema=object$1({jsonrpc:literal(`2.0`),...NotificationSchema.shape}).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema.safeParse(e).success,JSONRPCResultResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=e=>JSONRPCResultResponseSchema.safeParse(e).success;var ErrorCode;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(ErrorCode||={});const JSONRPCErrorResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema.optional(),error:object$1({code:number().int(),message:string(),data:unknown().optional()})}).strict(),isJSONRPCErrorResponse=e=>JSONRPCErrorResponseSchema.safeParse(e).success,JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal(`notifications/cancelled`),params:CancelledNotificationParamsSchema}),IconSchema=object$1({src:string(),mimeType:string().optional(),sizes:array(string()).optional(),theme:_enum([`light`,`dark`]).optional()}),IconsSchema=object$1({icons:array(IconSchema).optional()}),BaseMetadataSchema=object$1({name:string(),title:string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string(),websiteUrl:string().optional(),description:string().optional()}),FormElicitationCapabilitySchema=intersection(object$1({applyDefaults:boolean().optional()}),record(string(),unknown())),ElicitationCapabilitySchema=preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,intersection(object$1({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string(),unknown()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),sampling:object$1({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object$1({listChanged:boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal(`initialize`),params:InitializeRequestParamsSchema}),isInitializeRequest=e=>InitializeRequestSchema.safeParse(e).success,ServerCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object$1({listChanged:boolean().optional()}).optional(),resources:object$1({subscribe:boolean().optional(),listChanged:boolean().optional()}).optional(),tools:object$1({listChanged:boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/initialized`),params:NotificationsParamsSchema.optional()}),isInitializedNotification=e=>InitializedNotificationSchema.safeParse(e).success,PingRequestSchema=RequestSchema.extend({method:literal(`ping`),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object$1({progress:number(),total:optional(number()),message:optional(string())}),ProgressNotificationParamsSchema=object$1({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal(`notifications/progress`),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),TaskSchema=object$1({taskId:string(),status:TaskStatusSchema,ttl:union([number(),_null()]),createdAt:string(),lastUpdatedAt:string(),pollInterval:optional(number()),statusMessage:optional(string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tasks/status`),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/get`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal(`tasks/result`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal(`tasks/list`)}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/cancel`),params:BaseRequestParamsSchema.extend({taskId:string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object$1({uri:string(),mimeType:optional(string()),_meta:record(string(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string()}),Base64Schema=string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum([`user`,`assistant`]),AnnotationsSchema=object$1({audience:array(RoleSchema).optional(),priority:number().min(0).max(1).optional(),lastModified:datetime({offset:!0}).optional()}),ResourceSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string(),description:optional(string()),mimeType:optional(string()),size:optional(number()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string(),description:optional(string()),mimeType:optional(string()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/list`)}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/templates/list`)}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal(`resources/read`),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/list_changed`),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/subscribe`),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/unsubscribe`),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/updated`),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object$1({name:string(),description:optional(string()),required:optional(boolean())}),PromptSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal(`prompts/list`)}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string(),arguments:record(string(),string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal(`prompts/get`),params:GetPromptRequestParamsSchema}),TextContentSchema=object$1({type:literal(`text`),text:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ImageContentSchema=object$1({type:literal(`image`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),AudioContentSchema=object$1({type:literal(`audio`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ToolUseContentSchema=object$1({type:literal(`tool_use`),name:string(),id:string(),input:record(string(),unknown()),_meta:record(string(),unknown()).optional()}),EmbeddedResourceSchema=object$1({type:literal(`resource`),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal(`resource_link`)}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object$1({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/prompts/list_changed`),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object$1({title:string().optional(),readOnlyHint:boolean().optional(),destructiveHint:boolean().optional(),idempotentHint:boolean().optional(),openWorldHint:boolean().optional()}),ToolExecutionSchema=object$1({taskSupport:_enum([`required`,`optional`,`forbidden`]).optional()}),ToolSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string().optional(),inputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()),outputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal(`tools/list`)}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string(),unknown()).optional(),isError:boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string(),arguments:record(string(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal(`tools/call`),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tools/list_changed`),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object$1({autoRefresh:boolean().default(!0),debounceMs:number().int().nonnegative().default(300)}),LoggingLevelSchema=_enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal(`logging/setLevel`),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal(`notifications/message`),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object$1({name:string().optional()}),ModelPreferencesSchema=object$1({hints:array(ModelHintSchema).optional(),costPriority:number().min(0).max(1).optional(),speedPriority:number().min(0).max(1).optional(),intelligencePriority:number().min(0).max(1).optional()}),ToolChoiceSchema=object$1({mode:_enum([`auto`,`required`,`none`]).optional()}),ToolResultContentSchema=object$1({type:literal(`tool_result`),toolUseId:string().describe(`The unique identifier for the corresponding tool call.`),content:array(ContentBlockSchema).default([]),structuredContent:object$1({}).loose().optional(),isError:boolean().optional(),_meta:record(string(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object$1({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string().optional(),includeContext:_enum([`none`,`thisServer`,`allServers`]).optional(),temperature:number().optional(),maxTokens:number().int(),stopSequences:array(string()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal(`sampling/createMessage`),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`]).or(string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(string())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object$1({type:literal(`boolean`),title:string().optional(),description:string().optional(),default:boolean().optional()}),StringSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),minLength:number().optional(),maxLength:number().optional(),format:_enum([`email`,`uri`,`date`,`date-time`]).optional(),default:string().optional()}),NumberSchemaSchema=object$1({type:_enum([`number`,`integer`]),title:string().optional(),description:string().optional(),minimum:number().optional(),maximum:number().optional(),default:number().optional()}),UntitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),default:string().optional()}),TitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),oneOf:array(object$1({const:string(),title:string()})),default:string().optional()}),LegacyTitledEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),enumNames:array(string()).optional(),default:string().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({type:literal(`string`),enum:array(string())}),default:array(string()).optional()}),TitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({anyOf:array(object$1({const:string(),title:string()}))}),default:array(string()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`form`).optional(),message:string(),requestedSchema:object$1({type:literal(`object`),properties:record(string(),PrimitiveSchemaDefinitionSchema),required:array(string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`url`),message:string(),elicitationId:string(),url:string().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal(`elicitation/create`),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal(`notifications/elicitation/complete`),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum([`accept`,`decline`,`cancel`]),content:preprocess(e=>e===null?void 0:e,record(string(),union([string(),number(),boolean(),array(string())])).optional())}),ResourceTemplateReferenceSchema=object$1({type:literal(`ref/resource`),uri:string()}),PromptReferenceSchema=object$1({type:literal(`ref/prompt`),name:string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object$1({name:string(),value:string()}),context:object$1({arguments:record(string(),string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal(`completion/complete`),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function assertCompleteRequestResourceTemplate(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string()).max(100),total:optional(number().int()),hasMore:optional(boolean())})}),RootSchema=object$1({uri:string().startsWith(`file://`),name:string().optional(),_meta:record(string(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal(`roots/list`),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/roots/list_changed`),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);var McpError=class e extends Error{constructor(e,t,s){super(`MCP error ${e}: ${t}`),this.code=e,this.data=s,this.name=`McpError`}static fromError(t,s,g){if(t===ErrorCode.UrlElicitationRequired&&g){let e=g;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,s)}return new e(t,s,g)}},UrlElicitationRequiredError=class extends McpError{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(ErrorCode.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}const ignoreOverride=Symbol(`Let zodToJsonSchema decide on which parser to use`),defaultOptions={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},getDefaultOptions=e=>typeof e==`string`?{...defaultOptions,name:e}:{...defaultOptions,...e},getRefs=e=>{let t=getDefaultOptions(e),s=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:s,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage(e,t,s,g){g?.errorMessages&&s&&(e.errorMessage={...e.errorMessage,[t]:s})}function setResponseValueAndErrors(e,t,s,g,S){e[t]=s,addErrorMessage(e,t,g,S)}const getRelativePath=(e,t)=>{let s=0;for(;s<e.length&&s<t.length&&e[s]===t[s];s++);return[(e.length-s).toString(),...t.slice(s)].join(`/`)};function parseAnyDef(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?getRelativePath(t,e.currentPath):t.join(`/`)}}function parseArrayDef(e,t){let s={type:`array`};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(s.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&setResponseValueAndErrors(s,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(s,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(s,`minItems`,e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(s,`maxItems`,e.exactLength.value,e.exactLength.message,t)),s}function parseBigintDef(e,t){let s={type:`integer`,format:`int64`};if(!e.checks)return s;for(let g of e.checks)switch(g.kind){case`min`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`minimum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMinimum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMinimum=!0),setResponseValueAndErrors(s,`minimum`,g.value,g.message,t));break;case`max`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`maximum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMaximum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMaximum=!0),setResponseValueAndErrors(s,`maximum`,g.value,g.message,t));break;case`multipleOf`:setResponseValueAndErrors(s,`multipleOf`,g.value,g.message,t);break}return s}function parseBooleanDef(){return{type:`boolean`}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}const parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,s){let g=s??t.dateStrategy;if(Array.isArray(g))return{anyOf:g.map((s,g)=>parseDateDef(e,t,s))};switch(g){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return integerDateParser(e,t)}}const integerDateParser=(e,t)=>{let s={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return s;for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minimum`,g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maximum`,g.value,g.message,t);break}return s};function parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return t.effectStrategy===`input`?parseDef(e.schema._def,t):parseAnyDef(t)}function parseEnumDef(e){return{type:`string`,enum:Array.from(e.values)}}const isJsonSchema7AllOfType=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function parseIntersectionDef(e,t){let s=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),g=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,S=[];return s.forEach(e=>{if(isJsonSchema7AllOfType(e))S.push(...e.allOf),e.unevaluatedProperties===void 0&&(g=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:s,...g}=e;t=g}else g=void 0;S.push(t)}}),S.length?{allOf:S,...g}:void 0}function parseLiteralDef(e,t){let s=typeof e.value;return s!==`bigint`&&s!==`number`&&s!==`boolean`&&s!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:s===`bigint`?`integer`:s,enum:[e.value]}:{type:s===`bigint`?`integer`:s,const:e.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),emojiRegex),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(e,t){let s={type:`string`};if(e.checks)for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(s,`email`,g.message,t);break;case`format:idn-email`:addFormat(s,`idn-email`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.email,g.message,t);break}break;case`url`:addFormat(s,`uri`,g.message,t);break;case`uuid`:addFormat(s,`uuid`,g.message,t);break;case`regex`:addPattern(s,g.regex,g.message,t);break;case`cuid`:addPattern(s,zodPatterns.cuid,g.message,t);break;case`cuid2`:addPattern(s,zodPatterns.cuid2,g.message,t);break;case`startsWith`:addPattern(s,RegExp(`^${escapeLiteralCheckValue(g.value,t)}`),g.message,t);break;case`endsWith`:addPattern(s,RegExp(`${escapeLiteralCheckValue(g.value,t)}$`),g.message,t);break;case`datetime`:addFormat(s,`date-time`,g.message,t);break;case`date`:addFormat(s,`date`,g.message,t);break;case`time`:addFormat(s,`time`,g.message,t);break;case`duration`:addFormat(s,`duration`,g.message,t);break;case`length`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t),setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`includes`:addPattern(s,RegExp(escapeLiteralCheckValue(g.value,t)),g.message,t);break;case`ip`:g.version!==`v6`&&addFormat(s,`ipv4`,g.message,t),g.version!==`v4`&&addFormat(s,`ipv6`,g.message,t);break;case`base64url`:addPattern(s,zodPatterns.base64url,g.message,t);break;case`jwt`:addPattern(s,zodPatterns.jwt,g.message,t);break;case`cidr`:g.version!==`v6`&&addPattern(s,zodPatterns.ipv4Cidr,g.message,t),g.version!==`v4`&&addPattern(s,zodPatterns.ipv6Cidr,g.message,t);break;case`emoji`:addPattern(s,zodPatterns.emoji(),g.message,t);break;case`ulid`:addPattern(s,zodPatterns.ulid,g.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(s,`binary`,g.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(s,`contentEncoding`,`base64`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.base64,g.message,t);break}break;case`nanoid`:addPattern(s,zodPatterns.nanoid,g.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(g)}return s}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const ALPHA_NUMERIC=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let s=0;s<e.length;s++)ALPHA_NUMERIC.has(e[s])||(t+=`\\`),t+=e[s];return t}function addFormat(e,t,s,g){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&g.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...s&&g.errorMessages&&{errorMessage:{format:s}}})):setResponseValueAndErrors(e,`format`,t,s,g)}function addPattern(e,t,s,g){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&g.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags(t,g),...s&&g.errorMessages&&{errorMessage:{pattern:s}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,g),s,g)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let s={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},g=s.i?e.source.toLowerCase():e.source,S=``,w=!1,E=!1,D=!1;for(let e=0;e<g.length;e++){if(w){S+=g[e],w=!1;continue}if(s.i){if(E){if(g[e].match(/[a-z]/)){D?(S+=g[e],S+=`${g[e-2]}-${g[e]}`.toUpperCase(),D=!1):g[e+1]===`-`&&g[e+2]?.match(/[a-z]/)?(S+=g[e],D=!0):S+=`${g[e]}${g[e].toUpperCase()}`;continue}}else if(g[e].match(/[a-z]/)){S+=`[${g[e]}${g[e].toUpperCase()}]`;continue}}if(s.m){if(g[e]===`^`){S+=`(^|(?<=[\r
42
42
  ]))`;continue}else if(g[e]===`$`){S+=`($|(?=[\r
43
43
  ]))`;continue}}if(s.s&&g[e]===`.`){S+=E?`${g[e]}\r\n`:`[${g[e]}\r\n]`;continue}S+=g[e],g[e]===`\\`?w=!0:E&&g[e]===`]`?E=!1:!E&&g[e]===`[`&&(E=!0)}try{new RegExp(S)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return S}function parseRecordDef(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((s,g)=>({...s,[g]:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,g]})??parseAnyDef(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let s={type:`object`,additionalProperties:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return s;if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){let{type:g,...S}=parseStringDef(e.keyType._def,t);return{...s,propertyNames:S}}else if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...s,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){let{type:g,...S}=parseBrandedDef(e.keyType._def,t);return{...s,propertyNames:S}}return s}function parseMapDef(e,t){return t.mapStrategy===`record`?parseRecordDef(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[parseDef(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||parseAnyDef(t),parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||parseAnyDef(t)],minItems:2,maxItems:2}}}function parseNativeEnumDef(e){let t=e.values,s=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),g=Array.from(new Set(s.map(e=>typeof e)));return{type:g.length===1?g[0]===`string`?`string`:`number`:[`string`,`number`],enum:s}}function parseNeverDef(e){return e.target===`openAi`?void 0:{not:parseAnyDef({...e,currentPath:[...e.currentPath,`not`]})}}function parseNullDef(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const primitiveMappings={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function parseUnionDef(e,t){if(t.target===`openApi3`)return asAnyOf(e,t);let s=e.options instanceof Map?Array.from(e.options.values()):e.options;if(s.every(e=>e._def.typeName in primitiveMappings&&(!e._def.checks||!e._def.checks.length))){let e=s.reduce((e,t)=>{let s=primitiveMappings[t._def.typeName];return s&&!e.includes(s)?[...e,s]:e},[]);return{type:e.length>1?e:e[0]}}else if(s.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=s.reduce((e,t)=>{let s=typeof t._def.value;switch(s){case`string`:case`number`:case`boolean`:return[...e,s];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===s.length){let t=e.filter((e,t,s)=>s.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:s.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(s.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:s.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return asAnyOf(e,t)}const asAnyOf=(e,t)=>{let s=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,s)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${s}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return s.length?{anyOf:s}:void 0};function parseNullableDef(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:primitiveMappings[e.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let s=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath]});return s&&`$ref`in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}let s=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return s&&{anyOf:[s,{type:`null`}]}}function parseNumberDef(e,t){let s={type:`number`};if(!e.checks)return s;for(let g of e.checks)switch(g.kind){case`int`:s.type=`integer`,addErrorMessage(s,`type`,g.message,t);break;case`min`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`minimum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMinimum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMinimum=!0),setResponseValueAndErrors(s,`minimum`,g.value,g.message,t));break;case`max`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`maximum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMaximum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMaximum=!0),setResponseValueAndErrors(s,`maximum`,g.value,g.message,t));break;case`multipleOf`:setResponseValueAndErrors(s,`multipleOf`,g.value,g.message,t);break}return s}function parseObjectDef(e,t){let s=t.target===`openAi`,g={type:`object`,properties:{}},S=[],w=e.shape();for(let e in w){let E=w[e];if(E===void 0||E._def===void 0)continue;let D=safeIsOptional(E);D&&s&&(E._def.typeName===`ZodOptional`&&(E=E._def.innerType),E.isNullable()||(E=E.nullable()),D=!1);let O=parseDef(E._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});O!==void 0&&(g.properties[e]=O,D||S.push(e))}S.length&&(g.required=S);let E=decideAdditionalProperties(e,t);return E!==void 0&&(g.additionalProperties=E),g}function decideAdditionalProperties(e,t){if(e.catchall._def.typeName!==`ZodNever`)return parseDef(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function safeIsOptional(e){try{return e.isOptional()}catch{return!0}}const parseOptionalDef=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return parseDef(e.innerType._def,t);let s=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return s?{anyOf:[{not:parseAnyDef(t)},s]}:parseAnyDef(t)},parsePipelineDef=(e,t)=>{if(t.pipeStrategy===`input`)return parseDef(e.in._def,t);if(t.pipeStrategy===`output`)return parseDef(e.out._def,t);let s=parseDef(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[s,parseDef(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,s?`1`:`0`]})].filter(e=>e!==void 0)}};function parsePromiseDef(e,t){return parseDef(e.type._def,t)}function parseSetDef(e,t){let s={type:`array`,uniqueItems:!0,items:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&setResponseValueAndErrors(s,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&setResponseValueAndErrors(s,`maxItems`,e.maxSize.value,e.maxSize.message,t),s}function parseTupleDef(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,s)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${s}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:parseDef(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,s)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${s}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function parseUndefinedDef(e){return{not:parseAnyDef(e)}}function parseUnknownDef(e){return parseAnyDef(e)}const parseReadonlyDef=(e,t)=>parseDef(e.innerType._def,t),selectParser=(e,t,s)=>{switch(t){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(e,s);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(e,s);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(e,s);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(e,s);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(e,s);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(s);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(s);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(e,s);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(e,s);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(e,s);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(e,s);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(e,s);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(e,s);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(e);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(e);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(e,s);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(e,s);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(e,s);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(e,s);case ZodFirstPartyTypeKind.ZodLazy:return()=>e.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(e,s);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(s);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(e,s);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(s);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(s);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(e,s);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(e,s);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(e,s);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(e,s);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(e,s);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(e=>void 0)(t)}};function parseDef(e,t,s=!1){let g=t.seen.get(e);if(t.override){let S=t.override?.(e,t,g,s);if(S!==ignoreOverride)return S}if(g&&!s){let e=get$ref(g,t);if(e!==void 0)return e}let S={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,S);let w=selectParser(e,e.typeName,t),E=typeof w==`function`?parseDef(w(),t):w;if(E&&addMeta(e,t,E),t.postProcess){let s=t.postProcess(E,e,t);return S.jsonSchema=E,s}return S.jsonSchema=E,E}const get$ref=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:getRelativePath(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,s)=>t.currentPath[s]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),parseAnyDef(t)):t.$refStrategy===`seen`?parseAnyDef(t):void 0}},addMeta=(e,t,s)=>(e.description&&(s.description=e.description,t.markdownDescription&&(s.markdownDescription=e.description)),s),zodToJsonSchema=(e,t)=>{let s=getRefs(t),g=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,g])=>({...e,[t]:parseDef(g._def,{...s,currentPath:[...s.basePath,s.definitionPath,t]},!0)??parseAnyDef(s)}),{}):void 0,S=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,w=parseDef(e._def,S===void 0?s:{...s,currentPath:[...s.basePath,s.definitionPath,S]},!1)??parseAnyDef(s),E=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;E!==void 0&&(w.title=E),s.flags.hasReferencedOpenAiAnyType&&(g||={},g[s.openAiAnyTypeName]||(g[s.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:s.$refStrategy===`relative`?`1`:[...s.basePath,s.definitionPath,s.openAiAnyTypeName].join(`/`)}}));let D=S===void 0?g?{...w,[s.definitionPath]:g}:w:{$ref:[...s.$refStrategy===`relative`?[]:s.basePath,s.definitionPath,S].join(`/`),[s.definitionPath]:{...g,[S]:w}};return s.target===`jsonSchema7`?D.$schema=`http://json-schema.org/draft-07/schema#`:(s.target===`jsonSchema2019-09`||s.target===`openAi`)&&(D.$schema=`https://json-schema.org/draft/2019-09/schema#`),s.target===`openAi`&&(`anyOf`in D||`oneOf`in D||`allOf`in D||`type`in D&&Array.isArray(D.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),D};function mapMiniTarget(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function toJsonSchemaCompat(e,t){return isZ4Schema(e)?toJSONSchema(e,{target:mapMiniTarget(t?.target),io:t?.pipeStrategy??`input`}):zodToJsonSchema(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function getMethodLiteral(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let s=getLiteralValue(t);if(typeof s!=`string`)throw Error(`Schema method literal must be a string`);return s}function parseWithCompat(e,t){let s=safeParse(e,t);if(!s.success)throw s.error;return s.data}const DEFAULT_REQUEST_TIMEOUT_MSEC=6e4;var Protocol=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(CancelledNotificationSchema,e=>{this._oncancel(e)}),this.setNotificationHandler(ProgressNotificationSchema,e=>{this._onprogress(e)}),this.setRequestHandler(PingRequestSchema,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(e,t)=>{let s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new McpError(ErrorCode.InvalidParams,`Failed to retrieve task: Task not found`);return{...s}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(e,t)=>{let s=async()=>{let g=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(g,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,s=t.id,g=this._requestResolvers.get(s);if(g)if(this._requestResolvers.delete(s),e.type===`response`)g(t);else{let e=t;g(new McpError(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${s}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let S=await this._taskStore.getTask(g,t.sessionId);if(!S)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${g}`);if(!isTerminal(S.status))return await this._waitForTaskUpdate(g,t.signal),await s();if(isTerminal(S.status)){let e=await this._taskStore.getTaskResult(g,t.sessionId);return this._clearTaskQueue(g),{...e,_meta:{...e._meta,[RELATED_TASK_META_KEY]:{taskId:g}}}}return await s()};return await s()}),this.setRequestHandler(ListTasksRequestSchema,async(e,t)=>{try{let{tasks:s,nextCursor:g}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:s,nextCursor:g,_meta:{}}}catch(e){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(e,t)=>{try{let s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${e.params.taskId}`);if(isTerminal(s.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let g=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!g)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...g}}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,s,g,S=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(g,t),startTime:Date.now(),timeout:t,maxTotalTimeout:s,resetTimeoutOnProgress:S,onTimeout:g})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let s=Date.now()-t.startTime;if(t.maxTotalTimeout&&s>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),McpError.fromError(ErrorCode.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:s});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let s=this.transport?.onerror;this._transport.onerror=e=>{s?.(e),this._onerror(e)};let g=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{g?.(e,t),isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)?this._onresponse(e):isJSONRPCRequest(e)?this._onrequest(e,t):isJSONRPCNotification(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=McpError.fromError(ErrorCode.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let s of e.values())s(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let s=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,g=this._transport,S=e.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(s===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:ErrorCode.MethodNotFound,message:`Method not found`}};S&&this._taskMessageQueue?this._enqueueTaskMessage(S,{type:`error`,message:t,timestamp:Date.now()},g?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):g?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let w=new AbortController;this._requestHandlerAbortControllers.set(e.id,w);let E=isTaskAugmentedRequestParams(e.params)?e.params.task:void 0,D=this._taskStore?this.requestTaskStore(e,g?.sessionId):void 0,O={signal:w.signal,sessionId:g?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(w.signal.aborted)return;let s={relatedRequestId:e.id};S&&(s.relatedTask={taskId:S}),await this.notification(t,s)},sendRequest:async(t,s,g)=>{if(w.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,`Request was cancelled`);let E={...g,relatedRequestId:e.id};S&&!E.relatedTask&&(E.relatedTask={taskId:S});let O=E.relatedTask?.taskId??S;return O&&D&&await D.updateTaskStatus(O,`input_required`),await this.request(t,s,E)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:S,taskStore:D,taskRequestedTtl:E?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{E&&this.assertTaskHandlerCapability(e.method)}).then(()=>s(e,O)).then(async t=>{if(w.signal.aborted)return;let s={result:t,jsonrpc:`2.0`,id:e.id};S&&this._taskMessageQueue?await this._enqueueTaskMessage(S,{type:`response`,message:s,timestamp:Date.now()},g?.sessionId):await g?.send(s)},async t=>{if(w.signal.aborted)return;let s={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:ErrorCode.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};S&&this._taskMessageQueue?await this._enqueueTaskMessage(S,{type:`error`,message:s,timestamp:Date.now()},g?.sessionId):await g?.send(s)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===w&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...s}=e.params,g=Number(t),S=this._progressHandlers.get(g);if(!S){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let w=this._responseHandlers.get(g),E=this._timeoutInfo.get(g);if(E&&w&&E.resetTimeoutOnProgress)try{this._resetTimeout(g)}catch(e){this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),w(e);return}S(s)}_onresponse(e){let t=Number(e.id),s=this._requestResolvers.get(t);if(s){this._requestResolvers.delete(t),isJSONRPCResultResponse(e)?s(e):s(new McpError(e.error.code,e.error.message,e.error.data));return}let g=this._responseHandlers.get(t);if(g===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let S=!1;if(isJSONRPCResultResponse(e)&&e.result&&typeof e.result==`object`){let s=e.result;if(s.task&&typeof s.task==`object`){let e=s.task;typeof e.taskId==`string`&&(S=!0,this._taskProgressTokens.set(e.taskId,t))}}S||this._progressHandlers.delete(t),isJSONRPCResultResponse(e)?g(e):g(McpError.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,s){let{task:g}=s??{};if(!g){try{yield{type:`result`,result:await this.request(e,t,s)}}catch(e){yield{type:`error`,error:e instanceof McpError?e:new McpError(ErrorCode.InternalError,String(e))}}return}let S;try{let g=await this.request(e,CreateTaskResultSchema,s);if(g.task)S=g.task.taskId,yield{type:`taskCreated`,task:g.task};else throw new McpError(ErrorCode.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:S},s);if(yield{type:`taskStatus`,task:e},isTerminal(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:S},t,s)}:e.status===`failed`?yield{type:`error`,error:new McpError(ErrorCode.InternalError,`Task ${S} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new McpError(ErrorCode.InternalError,`Task ${S} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:S},t,s)};return}let g=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,g)),s?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof McpError?e:new McpError(ErrorCode.InternalError,String(e))}}}request(e,t,s){let{relatedRequestId:g,resumptionToken:S,onresumptiontoken:w,task:E,relatedTask:D}=s??{};return new Promise((O,k)=>{let j=e=>{k(e)};if(!this._transport){j(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),E&&this.assertTaskCapability(e.method)}catch(e){j(e);return}s?.signal?.throwIfAborted();let F=this._requestMessageId++,L={...e,jsonrpc:`2.0`,id:F};s?.onprogress&&(this._progressHandlers.set(F,s.onprogress),L.params={...e.params,_meta:{...e.params?._meta||{},progressToken:F}}),E&&(L.params={...L.params,task:E}),D&&(L.params={...L.params,_meta:{...L.params?._meta||{},[RELATED_TASK_META_KEY]:D}});let B=e=>{this._responseHandlers.delete(F),this._progressHandlers.delete(F),this._cleanupTimeout(F),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:F,reason:String(e)}},{relatedRequestId:g,resumptionToken:S,onresumptiontoken:w}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),k(e instanceof McpError?e:new McpError(ErrorCode.RequestTimeout,String(e)))};this._responseHandlers.set(F,e=>{if(!s?.signal?.aborted){if(e instanceof Error)return k(e);try{let s=safeParse(t,e.result);s.success?O(s.data):k(s.error)}catch(e){k(e)}}}),s?.signal?.addEventListener(`abort`,()=>{B(s?.signal?.reason)});let H=s?.timeout??6e4;this._setupTimeout(F,H,s?.maxTotalTimeout,()=>B(McpError.fromError(ErrorCode.RequestTimeout,`Request timed out`,{timeout:H})),s?.resetTimeoutOnProgress??!1);let q=D?.taskId;q?(this._requestResolvers.set(F,e=>{let t=this._responseHandlers.get(F);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${F}`))}),this._enqueueTaskMessage(q,{type:`request`,message:L,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(F),k(e)})):this._transport.send(L,{relatedRequestId:g,resumptionToken:S,onresumptiontoken:w}).catch(e=>{this._cleanupTimeout(F),k(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},GetTaskResultSchema,t)}async getTaskResult(e,t,s){return this.request({method:`tasks/result`,params:e},t,s)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},ListTasksResultSchema,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},CancelTaskResultSchema,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let s=t?.relatedTask?.taskId;if(s){let g={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}};await this._enqueueTaskMessage(s,{type:`notification`,message:g,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:`2.0`};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}}),this._transport?.send(s,t).catch(e=>this._onerror(e))});return}let g={...e,jsonrpc:`2.0`};t?.relatedTask&&(g={...g,params:{...g.params,_meta:{...g.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}}),await this._transport.send(g,t)}setRequestHandler(e,t){let s=getMethodLiteral(e);this.assertRequestHandlerCapability(s),this._requestHandlers.set(s,(s,g)=>{let S=parseWithCompat(e,s);return Promise.resolve(t(S,g))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let s=getMethodLiteral(e);this._notificationHandlers.set(s,s=>{let g=parseWithCompat(e,s);return Promise.resolve(t(g))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,s){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let g=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,s,g)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let s=await this._taskMessageQueue.dequeueAll(e,t);for(let t of s)if(t.type===`request`&&isJSONRPCRequest(t.message)){let s=t.message.id,g=this._requestResolvers.get(s);g?(g(new McpError(ErrorCode.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(s)):this._onerror(Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let s=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(s=t.pollInterval)}catch{}return new Promise((e,g)=>{if(t.aborted){g(new McpError(ErrorCode.InvalidRequest,`Request cancelled`));return}let S=setTimeout(e,s);t.addEventListener(`abort`,()=>{clearTimeout(S),g(new McpError(ErrorCode.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let s=this._taskStore;if(!s)throw Error(`No task store configured`);return{createTask:async g=>{if(!e)throw Error(`No request provided`);return await s.createTask(g,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let g=await s.getTask(e,t);if(!g)throw new McpError(ErrorCode.InvalidParams,`Failed to retrieve task: Task not found`);return g},storeTaskResult:async(e,g,S)=>{await s.storeTaskResult(e,g,S,t);let w=await s.getTask(e,t);if(w){let t=TaskStatusNotificationSchema.parse({method:`notifications/tasks/status`,params:w});await this.notification(t),isTerminal(w.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>s.getTaskResult(e,t),updateTaskStatus:async(e,g,S)=>{let w=await s.getTask(e,t);if(!w)throw new McpError(ErrorCode.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(isTerminal(w.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${e}" from terminal status "${w.status}" to "${g}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await s.updateTaskStatus(e,g,S,t);let E=await s.getTask(e,t);if(E){let t=TaskStatusNotificationSchema.parse({method:`notifications/tasks/status`,params:E});await this.notification(t),isTerminal(E.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>s.listTasks(e,t)}}};function isPlainObject$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mergeCapabilities(e,t){let s={...e};for(let e in t){let g=e,S=t[g];if(S===void 0)continue;let w=s[g];isPlainObject$1(w)&&isPlainObject$1(S)?s[g]={...w,...S}:s[g]=S}return s}var require_code$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var s=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=s;var g=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){var e;return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){var e;return this._names??=this._items.reduce((e,t)=>(t instanceof s&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=g,e.nil=new g(``);function S(e,...t){let s=[e[0]],S=0;for(;S<t.length;)D(s,t[S]),s.push(e[++S]);return new g(s)}e._=S;let w=new g(`+`);function E(e,...t){let s=[B(e[0])],S=0;for(;S<t.length;)s.push(w),D(s,t[S]),s.push(w,B(e[++S]));return O(s),new g(s)}e.str=E;function D(e,t){t instanceof g?e.push(...t._items):t instanceof s?e.push(t):e.push(F(t))}e.addCodeArg=D;function O(e){let t=1;for(;t<e.length-1;){if(e[t]===w){let s=k(e[t-1],e[t+1]);if(s!==void 0){e.splice(t-1,3,s);continue}e[t++]=`+`}t++}}function k(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof s||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof s))return`"${e}${t.slice(1)}`}function j(e,t){return t.emptyStr()?e:e.emptyStr()?t:E`${e}${t}`}e.strConcat=j;function F(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:B(Array.isArray(e)?e.join(`,`):e)}function L(e){return new g(B(e))}e.stringify=L;function B(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=B;function H(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new g(`.${t}`):S`[${t}]`}e.getProperty=H;function q(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new g(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=q;function ee(e){return new g(e.toString())}e.regexpCode=ee})),require_scope=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=require_code$1();var s=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},g;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(g||(e.UsedValueState=g={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var S=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,s;if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=S;var w=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:s,itemIndex:g}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(s)}[${g}]`}};e.ValueScopeName=w;let E=(0,t._)`\n`;e.ValueScope=class extends S{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?E:t.nil}}get(){return this._scope}name(e){return new w(e,this._newName(e))}value(e,t){var s;if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let g=this.toName(e),{prefix:S}=g,w=t.key??t.ref,E=this._values[S];if(E){let e=E.get(w);if(e)return e}else E=this._values[S]=new Map;E.set(w,g);let D=this._scope[S]||(this._scope[S]=[]),O=D.length;return D[O]=t.ref,g.setValue(t,{property:S,itemIndex:O}),g}getValue(e,t){let s=this._values[e];if(s)return s.get(t)}scopeRefs(e,s=this._values){return this._reduceValues(s,s=>{if(s.scopePath===void 0)throw Error(`CodeGen: name "${s}" has no value`);return(0,t._)`${e}${s.scopePath}`})}scopeCode(e=this._values,t,s){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,s)}_reduceValues(S,w,E={},D){let O=t.nil;for(let k in S){let j=S[k];if(!j)continue;let F=E[k]=E[k]||new Map;j.forEach(S=>{if(F.has(S))return;F.set(S,g.Started);let E=w(S);if(E){let s=this.opts.es5?e.varKinds.var:e.varKinds.const;O=(0,t._)`${O}${s} ${S} = ${E};${this.opts._n}`}else if(E=D?.(S))O=(0,t._)`${O}${E}${this.opts._n}`;else throw new s(S);F.set(S,g.Completed)})}return O}}})),require_codegen=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=require_code$1(),s=require_scope();var g=require_code$1();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return g._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return g.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return g.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return g.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return g.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return g.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return g.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return g.Name}});var S=require_scope();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return S.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return S.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return S.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return S.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var w=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},E=class extends w{constructor(e,t,s){super(),this.varKind=e,this.name=t,this.rhs=s}render({es5:e,_n:t}){let g=e?s.varKinds.var:this.varKind,S=this.rhs===void 0?``:` = ${this.rhs}`;return`${g} ${this.name}${S};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ge(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},D=class extends w{constructor(e,t,s){super(),this.lhs=e,this.rhs=t,this.sideEffects=s}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,s){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ge(this.rhs,e,s),this}get names(){return me(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},O=class extends D{constructor(e,t,s,g){super(e,s,g),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},k=class extends w{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},j=class extends w{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},F=class extends w{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},L=class extends w{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ge(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},B=class extends w{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,s)=>t+s.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let s=e[t].optimizeNodes();Array.isArray(s)?e.splice(t,1,...s):s?e[t]=s:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:s}=this,g=s.length;for(;g--;){let S=s[g];S.optimizeNames(e,t)||(_e(e,S.names),s.splice(g,1))}return s.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>fe(e,t.names),{})}},H=class extends B{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},q=class extends B{},ee=class extends H{};ee.kind=`else`;var J=class e extends H{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let s=this.else;if(s){let e=s.optimizeNodes();s=this.else=Array.isArray(e)?new ee(e):e}if(s)return t===!1?s instanceof e?s:s.nodes:this.nodes.length?this:new e(ve(t),s instanceof e?[s]:s.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){var s;if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ge(this.condition,e,t),this}get names(){let e=super.names;return me(e,this.condition),this.else&&fe(e,this.else.names),e}};J.kind=`if`;var Y=class extends H{};Y.kind=`for`;var te=class extends Y{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ge(this.iteration,e,t),this}get names(){return fe(super.names,this.iteration.names)}},ne=class extends Y{constructor(e,t,s,g){super(),this.varKind=e,this.name=t,this.from=s,this.to=g}render(e){let t=e.es5?s.varKinds.var:this.varKind,{name:g,from:S,to:w}=this;return`for(${t} ${g}=${S}; ${g}<${w}; ${g}++)`+super.render(e)}get names(){return me(me(super.names,this.from),this.to)}},ae=class extends Y{constructor(e,t,s,g){super(),this.loop=e,this.varKind=t,this.name=s,this.iterable=g}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ge(this.iterable,e,t),this}get names(){return fe(super.names,this.iterable.names)}},oe=class extends H{constructor(e,t,s){super(),this.name=e,this.args=t,this.async=s}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};oe.kind=`func`;var se=class extends B{render(e){return`return `+super.render(e)}};se.kind=`return`;var ce=class extends H{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var s,g;return super.optimizeNames(e,t),(s=this.catch)==null||s.optimizeNames(e,t),(g=this.finally)==null||g.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&fe(e,this.catch.names),this.finally&&fe(e,this.finally.names),e}},ue=class extends H{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ue.kind=`catch`;var de=class extends H{render(e){return`finally`+super.render(e)}};de.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
44
44
  `:``},this._extScope=e,this._scope=new s.Scope({parent:e}),this._nodes=[new q]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let s=this._extScope.value(e,t);return(this._values[s.prefix]||(this._values[s.prefix]=new Set)).add(s),s}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,s,g){let S=this._scope.toName(t);return s!==void 0&&g&&(this._constants[S.str]=s),this._leafNode(new E(e,S,s)),S}const(e,t,g){return this._def(s.varKinds.const,e,t,g)}let(e,t,g){return this._def(s.varKinds.let,e,t,g)}var(e,t,g){return this._def(s.varKinds.var,e,t,g)}assign(e,t,s){return this._leafNode(new D(e,t,s))}add(t,s){return this._leafNode(new O(t,e.operators.ADD,s))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new L(e)),this}object(...e){let s=[`{`];for(let[g,S]of e)s.length>1&&s.push(`,`),s.push(g),(g!==S||this.opts.es5)&&(s.push(`:`),(0,t.addCodeArg)(s,S));return s.push(`}`),new t._Code(s)}if(e,t,s){if(this._blockNode(new J(e)),t&&s)this.code(t).else().code(s).endIf();else if(t)this.code(t).endIf();else if(s)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new J(e))}else(){return this._elseNode(new ee)}endIf(){return this._endBlockNode(J,ee)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new te(e),t)}forRange(e,t,g,S,w=this.opts.es5?s.varKinds.var:s.varKinds.let){let E=this._scope.toName(e);return this._for(new ne(w,E,t,g),()=>S(E))}forOf(e,g,S,w=s.varKinds.const){let E=this._scope.toName(e);if(this.opts.es5){let e=g instanceof t.Name?g:this.var(`_arr`,g);return this.forRange(`_i`,0,(0,t._)`${e}.length`,s=>{this.var(E,(0,t._)`${e}[${s}]`),S(E)})}return this._for(new ae(`of`,w,E,g),()=>S(E))}forIn(e,g,S,w=this.opts.es5?s.varKinds.var:s.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${g})`,S);let E=this._scope.toName(e);return this._for(new ae(`in`,w,E,g),()=>S(E))}endFor(){return this._endBlockNode(Y)}label(e){return this._leafNode(new k(e))}break(e){return this._leafNode(new j(e))}return(e){let t=new se;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(se)}try(e,t,s){if(!t&&!s)throw Error(`CodeGen: "try" without "catch" and "finally"`);let g=new ce;if(this._blockNode(g),this.code(e),t){let e=this.name(`e`);this._currNode=g.catch=new ue(e),t(e)}return s&&(this._currNode=g.finally=new de,this.code(s)),this._endBlockNode(ue,de)}throw(e){return this._leafNode(new F(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let s=this._nodes.length-t;if(s<0||e!==void 0&&s!==e)throw Error(`CodeGen: wrong number of nodes: ${s} vs ${e} expected`);return this._nodes.length=t,this}func(e,s=t.nil,g,S){return this._blockNode(new oe(e,s,g)),S&&this.code(S).endFunc(),this}endFunc(){return this._endBlockNode(oe)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let s=this._currNode;if(s instanceof e||t&&s instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof J))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function fe(e,t){for(let s in t)e[s]=(e[s]||0)+(t[s]||0);return e}function me(e,s){return s instanceof t._CodeOrName?fe(e,s.names):e}function ge(e,s,g){if(e instanceof t.Name)return S(e);if(!w(e))return e;return new t._Code(e._items.reduce((e,s)=>(s instanceof t.Name&&(s=S(s)),s instanceof t._Code?e.push(...s._items):e.push(s),e),[]));function S(e){let t=g[e.str];return t===void 0||s[e.str]!==1?e:(delete s[e.str],t)}function w(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&s[e.str]===1&&g[e.str]!==void 0)}}function _e(e,t){for(let s in t)e[s]=(e[s]||0)-(t[s]||0)}function ve(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${je(e)}`}e.not=ve;let ye=De(e.operators.AND);function Ce(...e){return e.reduce(ye)}e.and=Ce;let we=De(e.operators.OR);function Te(...e){return e.reduce(we)}e.or=Te;function De(e){return(s,g)=>s===t.nil?g:g===t.nil?s:(0,t._)`${je(s)} ${e} ${je(g)}`}function je(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),require_util=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=require_codegen(),s=require_code$1();function g(e){let t={};for(let s of e)t[s]=!0;return t}e.toHash=g;function S(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(w(e,t),!E(t,e.self.RULES.all))}e.alwaysValidSchema=S;function w(e,t=e.schema){let{opts:s,self:g}=e;if(!s.strictSchema||typeof t==`boolean`)return;let S=g.RULES.keywords;for(let s in t)S[s]||ae(e,`unknown keyword: "${s}"`)}e.checkUnknownRules=w;function E(e,t){if(typeof e==`boolean`)return!e;for(let s in e)if(t[s])return!0;return!1}e.schemaHasRules=E;function D(e,t){if(typeof e==`boolean`)return!e;for(let s in e)if(s!==`$ref`&&t.all[s])return!0;return!1}e.schemaHasRulesButRef=D;function O({topSchemaRef:e,schemaPath:s},g,S,w){if(!w){if(typeof g==`number`||typeof g==`boolean`)return g;if(typeof g==`string`)return(0,t._)`${g}`}return(0,t._)`${e}${s}${(0,t.getProperty)(S)}`}e.schemaRefOrVal=O;function k(e){return L(decodeURIComponent(e))}e.unescapeFragment=k;function j(e){return encodeURIComponent(F(e))}e.escapeFragment=j;function F(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=F;function L(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=L;function B(e,t){if(Array.isArray(e))for(let s of e)t(s);else t(e)}e.eachItem=B;function H({mergeNames:e,mergeToName:s,mergeValues:g,resultToName:S}){return(w,E,D,O)=>{let k=D===void 0?E:D instanceof t.Name?(E instanceof t.Name?e(w,E,D):s(w,E,D),D):E instanceof t.Name?(s(w,D,E),E):g(E,D);return O===t.Name&&!(k instanceof t.Name)?S(w,k):k}}e.mergeEvaluated={props:H({mergeNames:(e,s,g)=>e.if((0,t._)`${g} !== true && ${s} !== undefined`,()=>{e.if((0,t._)`${s} === true`,()=>e.assign(g,!0),()=>e.assign(g,(0,t._)`${g} || {}`).code((0,t._)`Object.assign(${g}, ${s})`))}),mergeToName:(e,s,g)=>e.if((0,t._)`${g} !== true`,()=>{s===!0?e.assign(g,!0):(e.assign(g,(0,t._)`${g} || {}`),ee(e,g,s))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:q}),items:H({mergeNames:(e,s,g)=>e.if((0,t._)`${g} !== true && ${s} !== undefined`,()=>e.assign(g,(0,t._)`${s} === true ? true : ${g} > ${s} ? ${g} : ${s}`)),mergeToName:(e,s,g)=>e.if((0,t._)`${g} !== true`,()=>e.assign(g,s===!0?!0:(0,t._)`${g} > ${s} ? ${g} : ${s}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function q(e,s){if(s===!0)return e.var(`props`,!0);let g=e.var(`props`,(0,t._)`{}`);return s!==void 0&&ee(e,g,s),g}e.evaluatedPropsToName=q;function ee(e,s,g){Object.keys(g).forEach(g=>e.assign((0,t._)`${s}${(0,t.getProperty)(g)}`,!0))}e.setEvaluated=ee;let J={};function Y(e,t){return e.scopeValue(`func`,{ref:t,code:J[t.code]||(J[t.code]=new s._Code(t.code))})}e.useFunc=Y;var te;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(te||(e.Type=te={}));function ne(e,s,g){if(e instanceof t.Name){let S=s===te.Num;return g?S?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:S?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return g?(0,t.getProperty)(e).toString():`/`+F(e)}e.getErrorPath=ne;function ae(e,t,s=e.opts.strictSchema){if(s){if(t=`strict mode: ${t}`,s===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=ae})),require_names=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),require_errors=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=require_codegen(),s=require_util(),g=require_names();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:s})=>s?(0,t.str)`"${e}" keyword must be ${s} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function S(s,g=e.keywordError,S,w){let{it:E}=s,{gen:D,compositeRule:j,allErrors:L}=E,B=F(s,g,S);w??(j||L)?O(D,B):k(E,(0,t._)`[${B}]`)}e.reportError=S;function w(t,s=e.keywordError,S){let{it:w}=t,{gen:E,compositeRule:D,allErrors:j}=w;O(E,F(t,s,S)),D||j||k(w,g.default.vErrors)}e.reportExtraError=w;function E(e,s){e.assign(g.default.errors,s),e.if((0,t._)`${g.default.vErrors} !== null`,()=>e.if(s,()=>e.assign((0,t._)`${g.default.vErrors}.length`,s),()=>e.assign(g.default.vErrors,null)))}e.resetErrorsCount=E;function D({gen:e,keyword:s,schemaValue:S,data:w,errsCount:E,it:D}){if(E===void 0)throw Error(`ajv implementation error`);let O=e.name(`err`);e.forRange(`i`,E,g.default.errors,E=>{e.const(O,(0,t._)`${g.default.vErrors}[${E}]`),e.if((0,t._)`${O}.instancePath === undefined`,()=>e.assign((0,t._)`${O}.instancePath`,(0,t.strConcat)(g.default.instancePath,D.errorPath))),e.assign((0,t._)`${O}.schemaPath`,(0,t.str)`${D.errSchemaPath}/${s}`),D.opts.verbose&&(e.assign((0,t._)`${O}.schema`,S),e.assign((0,t._)`${O}.data`,w))})}e.extendErrors=D;function O(e,s){let S=e.const(`err`,s);e.if((0,t._)`${g.default.vErrors} === null`,()=>e.assign(g.default.vErrors,(0,t._)`[${S}]`),(0,t._)`${g.default.vErrors}.push(${S})`),e.code((0,t._)`${g.default.errors}++`)}function k(e,s){let{gen:g,validateName:S,schemaEnv:w}=e;w.$async?g.throw((0,t._)`new ${e.ValidationError}(${s})`):(g.assign((0,t._)`${S}.errors`,s),g.return(!1))}let j={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function F(e,s,g){let{createErrors:S}=e.it;return S===!1?(0,t._)`{}`:L(e,s,g)}function L(e,t,s={}){let{gen:g,it:S}=e,w=[B(S,s),H(e,s)];return q(e,t,w),g.object(...w)}function B({errorPath:e},{instancePath:S}){let w=S?(0,t.str)`${e}${(0,s.getErrorPath)(S,s.Type.Str)}`:e;return[g.default.instancePath,(0,t.strConcat)(g.default.instancePath,w)]}function H({keyword:e,it:{errSchemaPath:g}},{schemaPath:S,parentSchema:w}){let E=w?g:(0,t.str)`${g}/${e}`;return S&&(E=(0,t.str)`${E}${(0,s.getErrorPath)(S,s.Type.Str)}`),[j.schemaPath,E]}function q(e,{params:s,message:S},w){let{keyword:E,data:D,schemaValue:O,it:k}=e,{opts:F,propertyName:L,topSchemaRef:B,schemaPath:H}=k;w.push([j.keyword,E],[j.params,typeof s==`function`?s(e):s||(0,t._)`{}`]),F.messages&&w.push([j.message,typeof S==`function`?S(e):S]),F.verbose&&w.push([j.schema,O],[j.parentSchema,(0,t._)`${B}${H}`],[g.default.data,D]),L&&w.push([j.propertyName,L])}})),require_boolSchema=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=require_errors(),s=require_codegen(),g=require_names(),S={message:`boolean schema is false`};function w(e){let{gen:t,schema:S,validateName:w}=e;S===!1?D(e,!1):typeof S==`object`&&S.$async===!0?t.return(g.default.data):(t.assign((0,s._)`${w}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=w;function E(e,t){let{gen:s,schema:g}=e;g===!1?(s.var(t,!1),D(e)):s.var(t,!0)}e.boolOrEmptySchema=E;function D(e,s){let{gen:g,data:w}=e,E={gen:g,keyword:`false schema`,data:w,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(E,S,void 0,s)}})),require_rules=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function s(e){return typeof e==`string`&&t.has(e)}e.isJSONType=s;function g(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=g})),require_applicability=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},g){let S=t.RULES.types[g];return S&&S!==!0&&s(e,S)}e.schemaHasRulesForType=t;function s(e,t){return t.rules.some(t=>g(e,t))}e.shouldUseGroup=s;function g(e,t){var s;return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=g})),require_dataType=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=require_rules(),s=require_applicability(),g=require_errors(),S=require_codegen(),w=require_util();var E;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(E||(e.DataType=E={}));function D(e){let t=O(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=D;function O(e){let s=Array.isArray(e)?e:e?[e]:[];if(s.every(t.isJSONType))return s;throw Error(`type must be JSONType or JSONType[]: `+s.join(`,`))}e.getJSONTypes=O;function k(e,t){let{gen:g,data:S,opts:w}=e,D=F(t,w.coerceTypes),O=t.length>0&&!(D.length===0&&t.length===1&&(0,s.schemaHasRulesForType)(e,t[0]));if(O){let s=q(t,S,w.strictNumbers,E.Wrong);g.if(s,()=>{D.length?L(e,t,D):J(e)})}return O}e.coerceAndCheckDataType=k;let j=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function F(e,t){return t?e.filter(e=>j.has(e)||t===`array`&&e===`array`):[]}function L(e,t,s){let{gen:g,data:w,opts:E}=e,D=g.let(`dataType`,(0,S._)`typeof ${w}`),O=g.let(`coerced`,(0,S._)`undefined`);E.coerceTypes===`array`&&g.if((0,S._)`${D} == 'object' && Array.isArray(${w}) && ${w}.length == 1`,()=>g.assign(w,(0,S._)`${w}[0]`).assign(D,(0,S._)`typeof ${w}`).if(q(t,w,E.strictNumbers),()=>g.assign(O,w))),g.if((0,S._)`${O} !== undefined`);for(let e of s)(j.has(e)||e===`array`&&E.coerceTypes===`array`)&&k(e);g.else(),J(e),g.endIf(),g.if((0,S._)`${O} !== undefined`,()=>{g.assign(w,O),B(e,O)});function k(e){switch(e){case`string`:g.elseIf((0,S._)`${D} == "number" || ${D} == "boolean"`).assign(O,(0,S._)`"" + ${w}`).elseIf((0,S._)`${w} === null`).assign(O,(0,S._)`""`);return;case`number`:g.elseIf((0,S._)`${D} == "boolean" || ${w} === null
@@ -47,7 +47,7 @@ To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.w
47
47
  || ${D} === "boolean" || ${w} === null`).assign(O,(0,S._)`[${w}]`)}}}function B({gen:e,parentData:t,parentDataProperty:s},g){e.if((0,S._)`${t} !== undefined`,()=>e.assign((0,S._)`${t}[${s}]`,g))}function H(e,t,s,g=E.Correct){let w=g===E.Correct?S.operators.EQ:S.operators.NEQ,D;switch(e){case`null`:return(0,S._)`${t} ${w} null`;case`array`:D=(0,S._)`Array.isArray(${t})`;break;case`object`:D=(0,S._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:D=O((0,S._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:D=O();break;default:return(0,S._)`typeof ${t} ${w} ${e}`}return g===E.Correct?D:(0,S.not)(D);function O(e=S.nil){return(0,S.and)((0,S._)`typeof ${t} == "number"`,e,s?(0,S._)`isFinite(${t})`:S.nil)}}e.checkDataType=H;function q(e,t,s,g){if(e.length===1)return H(e[0],t,s,g);let E,D=(0,w.toHash)(e);if(D.array&&D.object){let e=(0,S._)`typeof ${t} != "object"`;E=D.null?e:(0,S._)`!${t} || ${e}`,delete D.null,delete D.array,delete D.object}else E=S.nil;D.number&&delete D.integer;for(let e in D)E=(0,S.and)(E,H(e,t,s,g));return E}e.checkDataTypes=q;let ee={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,S._)`{type: ${e}}`:(0,S._)`{type: ${t}}`};function J(e){let t=Y(e);(0,g.reportError)(t,ee)}e.reportTypeError=J;function Y(e){let{gen:t,data:s,schema:g}=e,S=(0,w.schemaRefOrVal)(e,g,`type`);return{gen:t,keyword:`type`,data:s,schema:g.type,schemaCode:S,schemaValue:S,parentSchema:g,params:{},it:e}}})),require_defaults=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=require_codegen(),s=require_util();function g(e,t){let{properties:s,items:g}=e.schema;if(t===`object`&&s)for(let t in s)S(e,t,s[t].default);else t===`array`&&Array.isArray(g)&&g.forEach((t,s)=>S(e,s,t.default))}e.assignDefaults=g;function S(e,g,S){let{gen:w,compositeRule:E,data:D,opts:O}=e;if(S===void 0)return;let k=(0,t._)`${D}${(0,t.getProperty)(g)}`;if(E){(0,s.checkStrictMode)(e,`default is ignored for: ${k}`);return}let j=(0,t._)`${k} === undefined`;O.useDefaults===`empty`&&(j=(0,t._)`${j} || ${k} === null || ${k} === ""`),w.if(j,(0,t._)`${k} = ${(0,t.stringify)(S)}`)}})),require_code=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=require_codegen(),s=require_util(),g=require_names(),S=require_util();function w(e,s){let{gen:g,data:S,it:w}=e;g.if(F(g,S,s,w.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${s}`},!0),e.error()})}e.checkReportMissingProp=w;function E({gen:e,data:s,it:{opts:g}},S,w){return(0,t.or)(...S.map(S=>(0,t.and)(F(e,s,S,g.ownProperties),(0,t._)`${w} = ${S}`)))}e.checkMissingProp=E;function D(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=D;function O(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=O;function k(e,s,g){return(0,t._)`${O(e)}.call(${s}, ${g})`}e.isOwnProperty=k;function j(e,s,g,S){let w=(0,t._)`${s}${(0,t.getProperty)(g)} !== undefined`;return S?(0,t._)`${w} && ${k(e,s,g)}`:w}e.propertyInData=j;function F(e,s,g,S){let w=(0,t._)`${s}${(0,t.getProperty)(g)} === undefined`;return S?(0,t.or)(w,(0,t.not)(k(e,s,g))):w}e.noPropertyInData=F;function L(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=L;function B(e,t){return L(t).filter(g=>!(0,s.alwaysValidSchema)(e,t[g]))}e.schemaProperties=B;function H({schemaCode:e,data:s,it:{gen:S,topSchemaRef:w,schemaPath:E,errorPath:D},it:O},k,j,F){let L=F?(0,t._)`${e}, ${s}, ${w}${E}`:s,B=[[g.default.instancePath,(0,t.strConcat)(g.default.instancePath,D)],[g.default.parentData,O.parentData],[g.default.parentDataProperty,O.parentDataProperty],[g.default.rootData,g.default.rootData]];O.opts.dynamicRef&&B.push([g.default.dynamicAnchors,g.default.dynamicAnchors]);let H=(0,t._)`${L}, ${S.object(...B)}`;return j===t.nil?(0,t._)`${k}(${H})`:(0,t._)`${k}.call(${j}, ${H})`}e.callValidateCode=H;let q=(0,t._)`new RegExp`;function ee({gen:e,it:{opts:s}},g){let w=s.unicodeRegExp?`u`:``,{regExp:E}=s.code,D=E(g,w);return e.scopeValue(`pattern`,{key:D.toString(),ref:D,code:(0,t._)`${E.code===`new RegExp`?q:(0,S.useFunc)(e,E)}(${g}, ${w})`})}e.usePattern=ee;function J(e){let{gen:g,data:S,keyword:w,it:E}=e,D=g.name(`valid`);if(E.allErrors){let e=g.let(`valid`,!0);return O(()=>g.assign(e,!1)),e}return g.var(D,!0),O(()=>g.break()),D;function O(E){let O=g.const(`len`,(0,t._)`${S}.length`);g.forRange(`i`,0,O,S=>{e.subschema({keyword:w,dataProp:S,dataPropType:s.Type.Num},D),g.if((0,t.not)(D),E)})}}e.validateArray=J;function Y(e){let{gen:g,schema:S,keyword:w,it:E}=e;if(!Array.isArray(S))throw Error(`ajv implementation error`);if(S.some(e=>(0,s.alwaysValidSchema)(E,e))&&!E.opts.unevaluated)return;let D=g.let(`valid`,!1),O=g.name(`_valid`);g.block(()=>S.forEach((s,S)=>{let E=e.subschema({keyword:w,schemaProp:S,compositeRule:!0},O);g.assign(D,(0,t._)`${D} || ${O}`),e.mergeValidEvaluated(E,O)||g.if((0,t.not)(D))})),e.result(D,()=>e.reset(),()=>e.error(!0))}e.validateUnion=Y})),require_keyword=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=require_codegen(),s=require_names(),g=require_code(),S=require_errors();function w(e,s){let{gen:g,keyword:S,schema:w,parentSchema:E,it:D}=e,O=s.macro.call(D.self,w,E,D),k=j(g,S,O);D.opts.validateSchema!==!1&&D.self.validateSchema(O,!0);let F=g.name(`valid`);e.subschema({schema:O,schemaPath:t.nil,errSchemaPath:`${D.errSchemaPath}/${S}`,topSchemaRef:k,compositeRule:!0},F),e.pass(F,()=>e.error(!0))}e.macroKeywordCode=w;function E(e,S){var w;let{gen:E,keyword:F,schema:L,parentSchema:B,$data:H,it:q}=e;k(q,S);let ee=j(E,F,!H&&S.compile?S.compile.call(q.self,L,B,q):S.validate),J=E.let(`valid`);e.block$data(J,Y),e.ok(S.valid??J);function Y(){if(S.errors===!1)ae(),S.modifying&&D(e),oe(()=>e.error());else{let t=S.async?te():ne();S.modifying&&D(e),oe(()=>O(e,t))}}function te(){let e=E.let(`ruleErrs`,null);return E.try(()=>ae((0,t._)`await `),s=>E.assign(J,!1).if((0,t._)`${s} instanceof ${q.ValidationError}`,()=>E.assign(e,(0,t._)`${s}.errors`),()=>E.throw(s))),e}function ne(){let e=(0,t._)`${ee}.errors`;return E.assign(e,null),ae(t.nil),e}function ae(w=S.async?(0,t._)`await `:t.nil){let D=q.opts.passContext?s.default.this:s.default.self,O=!(`compile`in S&&!H||S.schema===!1);E.assign(J,(0,t._)`${w}${(0,g.callValidateCode)(e,ee,D,O)}`,S.modifying)}function oe(e){var s;E.if((0,t.not)(S.valid??J),e)}}e.funcKeywordCode=E;function D(e){let{gen:s,data:g,it:S}=e;s.if(S.parentData,()=>s.assign(g,(0,t._)`${S.parentData}[${S.parentDataProperty}]`))}function O(e,g){let{gen:w}=e;w.if((0,t._)`Array.isArray(${g})`,()=>{w.assign(s.default.vErrors,(0,t._)`${s.default.vErrors} === null ? ${g} : ${s.default.vErrors}.concat(${g})`).assign(s.default.errors,(0,t._)`${s.default.vErrors}.length`),(0,S.extendErrors)(e)},()=>e.error())}function k({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function j(e,s,g){if(g===void 0)throw Error(`keyword "${s}" failed to compile`);return e.scopeValue(`keyword`,typeof g==`function`?{ref:g}:{ref:g,code:(0,t.stringify)(g)})}function F(e,t,s=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||s&&e===void 0)}e.validSchemaType=F;function L({schema:e,opts:t,self:s,errSchemaPath:g},S,w){if(Array.isArray(S.keyword)?!S.keyword.includes(w):S.keyword!==w)throw Error(`ajv implementation error`);let E=S.dependencies;if(E?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${w}: ${E.join(`,`)}`);if(S.validateSchema&&!S.validateSchema(e[w])){let e=`keyword "${w}" value is invalid at path "${g}": `+s.errorsText(S.validateSchema.errors);if(t.validateSchema===`log`)s.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=L})),require_subschema=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=require_codegen(),s=require_util();function g(e,{keyword:g,schemaProp:S,schema:w,schemaPath:E,errSchemaPath:D,topSchemaRef:O}){if(g!==void 0&&w!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(g!==void 0){let w=e.schema[g];return S===void 0?{schema:w,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(g)}`,errSchemaPath:`${e.errSchemaPath}/${g}`}:{schema:w[S],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(g)}${(0,t.getProperty)(S)}`,errSchemaPath:`${e.errSchemaPath}/${g}/${(0,s.escapeFragment)(S)}`}}if(w!==void 0){if(E===void 0||D===void 0||O===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:w,schemaPath:E,topSchemaRef:O,errSchemaPath:D}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=g;function S(e,g,{dataProp:S,dataPropType:w,data:E,dataTypes:D,propertyName:O}){if(E!==void 0&&S!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:k}=g;if(S!==void 0){let{errorPath:E,dataPathArr:D,opts:O}=g;j(k.let(`data`,(0,t._)`${g.data}${(0,t.getProperty)(S)}`,!0)),e.errorPath=(0,t.str)`${E}${(0,s.getErrorPath)(S,w,O.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${S}`,e.dataPathArr=[...D,e.parentDataProperty]}E!==void 0&&(j(E instanceof t.Name?E:k.let(`data`,E,!0)),O!==void 0&&(e.propertyName=O)),D&&(e.dataTypes=D);function j(t){e.data=t,e.dataLevel=g.dataLevel+1,e.dataTypes=[],g.definedProperties=new Set,e.parentData=g.data,e.dataNames=[...g.dataNames,t]}}e.extendSubschemaData=S;function w(e,{jtdDiscriminator:t,jtdMetadata:s,compositeRule:g,createErrors:S,allErrors:w}){g!==void 0&&(e.compositeRule=g),S!==void 0&&(e.createErrors=S),w!==void 0&&(e.allErrors=w),e.jtdDiscriminator=t,e.jtdMetadata=s}e.extendSubschemaMode=w})),require_fast_deep_equal=__commonJSMin$2(((e,t)=>{t.exports=function e(t,s){if(t===s)return!0;if(t&&s&&typeof t==`object`&&typeof s==`object`){if(t.constructor!==s.constructor)return!1;var g,S,w;if(Array.isArray(t)){if(g=t.length,g!=s.length)return!1;for(S=g;S--!==0;)if(!e(t[S],s[S]))return!1;return!0}if(t.constructor===RegExp)return t.source===s.source&&t.flags===s.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===s.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===s.toString();if(w=Object.keys(t),g=w.length,g!==Object.keys(s).length)return!1;for(S=g;S--!==0;)if(!Object.prototype.hasOwnProperty.call(s,w[S]))return!1;for(S=g;S--!==0;){var E=w[S];if(!e(t[E],s[E]))return!1}return!0}return t!==t&&s!==s}})),require_json_schema_traverse=__commonJSMin$2(((e,t)=>{var s=t.exports=function(e,t,s){typeof t==`function`&&(s=t,t={}),s=t.cb||s;var S=typeof s==`function`?s:s.pre||function(){},w=s.post||function(){};g(t,S,w,e,``,e)};s.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},s.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},s.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},s.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function g(e,t,w,E,D,O,k,j,F,L){if(E&&typeof E==`object`&&!Array.isArray(E)){for(var B in t(E,D,O,k,j,F,L),E){var H=E[B];if(Array.isArray(H)){if(B in s.arrayKeywords)for(var q=0;q<H.length;q++)g(e,t,w,H[q],D+`/`+B+`/`+q,O,D,B,E,q)}else if(B in s.propsKeywords){if(H&&typeof H==`object`)for(var ee in H)g(e,t,w,H[ee],D+`/`+B+`/`+S(ee),O,D,B,E,ee)}else (B in s.keywords||e.allKeys&&!(B in s.skipKeywords))&&g(e,t,w,H,D+`/`+B,O,D,B,E)}w(E,D,O,k,j,F,L)}}function S(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),require_resolve=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=require_util(),s=require_fast_deep_equal(),g=require_json_schema_traverse(),S=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function w(e,t=!0){return typeof e==`boolean`?!0:t===!0?!D(e):t?O(e)<=t:!1}e.inlineRef=w;let E=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function D(e){for(let t in e){if(E.has(t))return!0;let s=e[t];if(Array.isArray(s)&&s.some(D)||typeof s==`object`&&D(s))return!0}return!1}function O(e){let s=0;for(let g in e)if(g===`$ref`||(s++,!S.has(g)&&(typeof e[g]==`object`&&(0,t.eachItem)(e[g],e=>s+=O(e)),s===1/0)))return 1/0;return s}function k(e,t=``,s){return s!==!1&&(t=L(t)),j(e,e.parse(t))}e.getFullPath=k;function j(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=j;let F=/#\/?$/;function L(e){return e?e.replace(F,``):``}e.normalizeId=L;function B(e,t,s){return s=L(s),e.resolve(t,s)}e.resolveUrl=B;let H=/^[a-z_][-a-z0-9._]*$/i;function q(e,t){if(typeof e==`boolean`)return{};let{schemaId:S,uriResolver:w}=this.opts,E=L(e[S]||t),D={"":E},O=k(w,E,!1),j={},F=new Set;return g(e,{allKeys:!0},(e,t,s,g)=>{if(g===void 0)return;let w=O+t,E=D[g];typeof e[S]==`string`&&(E=k.call(this,e[S])),ee.call(this,e.$anchor),ee.call(this,e.$dynamicAnchor),D[t]=E;function k(t){let s=this.opts.uriResolver.resolve;if(t=L(E?s(E,t):t),F.has(t))throw q(t);F.add(t);let g=this.refs[t];return typeof g==`string`&&(g=this.refs[g]),typeof g==`object`?B(e,g.schema,t):t!==L(w)&&(t[0]===`#`?(B(e,j[t],t),j[t]=e):this.refs[t]=w),t}function ee(e){if(typeof e==`string`){if(!H.test(e))throw Error(`invalid anchor "${e}"`);k.call(this,`#${e}`)}}}),j;function B(e,t,g){if(t!==void 0&&!s(e,t))throw q(g)}function q(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=q})),require_validate=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=require_boolSchema(),s=require_dataType(),g=require_applicability(),S=require_dataType(),w=require_defaults(),E=require_keyword(),D=require_subschema(),O=require_codegen(),k=require_names(),j=require_resolve(),F=require_util(),L=require_errors();function B(e){if(oe(e)&&(ce(e),ae(e))){J(e);return}H(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=B;function H({gen:e,validateName:t,schema:s,schemaEnv:g,opts:S},w){S.code.es5?e.func(t,(0,O._)`${k.default.data}, ${k.default.valCxt}`,g.$async,()=>{e.code((0,O._)`"use strict"; ${te(s,S)}`),ee(e,S),e.code(w)}):e.func(t,(0,O._)`${k.default.data}, ${q(S)}`,g.$async,()=>e.code(te(s,S)).code(w))}function q(e){return(0,O._)`{${k.default.instancePath}="", ${k.default.parentData}, ${k.default.parentDataProperty}, ${k.default.rootData}=${k.default.data}${e.dynamicRef?(0,O._)`, ${k.default.dynamicAnchors}={}`:O.nil}}={}`}function ee(e,t){e.if(k.default.valCxt,()=>{e.var(k.default.instancePath,(0,O._)`${k.default.valCxt}.${k.default.instancePath}`),e.var(k.default.parentData,(0,O._)`${k.default.valCxt}.${k.default.parentData}`),e.var(k.default.parentDataProperty,(0,O._)`${k.default.valCxt}.${k.default.parentDataProperty}`),e.var(k.default.rootData,(0,O._)`${k.default.valCxt}.${k.default.rootData}`),t.dynamicRef&&e.var(k.default.dynamicAnchors,(0,O._)`${k.default.valCxt}.${k.default.dynamicAnchors}`)},()=>{e.var(k.default.instancePath,(0,O._)`""`),e.var(k.default.parentData,(0,O._)`undefined`),e.var(k.default.parentDataProperty,(0,O._)`undefined`),e.var(k.default.rootData,k.default.data),t.dynamicRef&&e.var(k.default.dynamicAnchors,(0,O._)`{}`)})}function J(e){let{schema:t,opts:s,gen:g}=e;H(e,()=>{s.$comment&&t.$comment&&_e(e),fe(e),g.let(k.default.vErrors,null),g.let(k.default.errors,0),s.unevaluated&&Y(e),ue(e),ve(e)})}function Y(e){let{gen:t,validateName:s}=e;e.evaluated=t.const(`evaluated`,(0,O._)`${s}.evaluated`),t.if((0,O._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,O._)`${e.evaluated}.props`,(0,O._)`undefined`)),t.if((0,O._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,O._)`${e.evaluated}.items`,(0,O._)`undefined`))}function te(e,t){let s=typeof e==`object`&&e[t.schemaId];return s&&(t.code.source||t.code.process)?(0,O._)`/*# sourceURL=${s} */`:O.nil}function ne(e,s){if(oe(e)&&(ce(e),ae(e))){se(e,s);return}(0,t.boolOrEmptySchema)(e,s)}function ae({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let s in e)if(t.RULES.all[s])return!0;return!1}function oe(e){return typeof e.schema!=`boolean`}function se(e,t){let{schema:s,gen:g,opts:S}=e;S.$comment&&s.$comment&&_e(e),me(e),ge(e);let w=g.const(`_errs`,k.default.errors);ue(e,w),g.var(t,(0,O._)`${w} === ${k.default.errors}`)}function ce(e){(0,F.checkUnknownRules)(e),de(e)}function ue(e,t){if(e.opts.jtd)return Ce(e,[],!1,t);let g=(0,s.getSchemaTypes)(e.schema);Ce(e,g,!(0,s.coerceAndCheckDataType)(e,g),t)}function de(e){let{schema:t,errSchemaPath:s,opts:g,self:S}=e;t.$ref&&g.ignoreKeywordsWithRef&&(0,F.schemaHasRulesButRef)(t,S.RULES)&&S.logger.warn(`$ref: keywords ignored in schema at path "${s}"`)}function fe(e){let{schema:t,opts:s}=e;t.default!==void 0&&s.useDefaults&&s.strictSchema&&(0,F.checkStrictMode)(e,`default is ignored in the schema root`)}function me(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,j.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ge(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function _e({gen:e,schemaEnv:t,schema:s,errSchemaPath:g,opts:S}){let w=s.$comment;if(S.$comment===!0)e.code((0,O._)`${k.default.self}.logger.log(${w})`);else if(typeof S.$comment==`function`){let s=(0,O.str)`${g}/$comment`,S=e.scopeValue(`root`,{ref:t.root});e.code((0,O._)`${k.default.self}.opts.$comment(${w}, ${s}, ${S}.schema)`)}}function ve(e){let{gen:t,schemaEnv:s,validateName:g,ValidationError:S,opts:w}=e;s.$async?t.if((0,O._)`${k.default.errors} === 0`,()=>t.return(k.default.data),()=>t.throw((0,O._)`new ${S}(${k.default.vErrors})`)):(t.assign((0,O._)`${g}.errors`,k.default.vErrors),w.unevaluated&&ye(e),t.return((0,O._)`${k.default.errors} === 0`))}function ye({gen:e,evaluated:t,props:s,items:g}){s instanceof O.Name&&e.assign((0,O._)`${t}.props`,s),g instanceof O.Name&&e.assign((0,O._)`${t}.items`,g)}function Ce(e,t,s,w){let{gen:E,schema:D,data:j,allErrors:L,opts:B,self:H}=e,{RULES:q}=H;if(D.$ref&&(B.ignoreKeywordsWithRef||!(0,F.schemaHasRulesButRef)(D,q))){E.block(()=>Ve(e,`$ref`,q.all.$ref.definition));return}B.jtd||Te(e,t),E.block(()=>{for(let e of q.rules)ee(e);ee(q.post)});function ee(F){(0,g.shouldUseGroup)(D,F)&&(F.type?(E.if((0,S.checkDataType)(F.type,j,B.strictNumbers)),we(e,F),t.length===1&&t[0]===F.type&&s&&(E.else(),(0,S.reportTypeError)(e)),E.endIf()):we(e,F),L||E.if((0,O._)`${k.default.errors} === ${w||0}`))}}function we(e,t){let{gen:s,schema:S,opts:{useDefaults:E}}=e;E&&(0,w.assignDefaults)(e,t.type),s.block(()=>{for(let s of t.rules)(0,g.shouldUseRule)(S,s)&&Ve(e,s.keyword,s.definition,t.type)})}function Te(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(De(e,t),e.opts.allowUnionTypes||je(e,t),Me(e,e.dataTypes))}function De(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{Ie(e.dataTypes,t)||ze(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),Re(e,t)}}function je(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ze(e,`use allowUnionTypes to allow union type keyword`)}function Me(e,t){let s=e.self.RULES.all;for(let S in s){let w=s[S];if(typeof w==`object`&&(0,g.shouldUseRule)(e.schema,w)){let{type:s}=w.definition;s.length&&!s.some(e=>Pe(t,e))&&ze(e,`missing type "${s.join(`,`)}" for keyword "${S}"`)}}}function Pe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function Ie(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function Re(e,t){let s=[];for(let g of e.dataTypes)Ie(t,g)?s.push(g):t.includes(`integer`)&&g===`number`&&s.push(`integer`);e.dataTypes=s}function ze(e,t){let s=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${s}" (strictTypes)`,(0,F.checkStrictMode)(e,t,e.opts.strictTypes)}var Be=class{constructor(e,t,s){if((0,E.validateKeywordUsage)(e,t,s),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=s,this.data=e.data,this.schema=e.schema[s],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,F.schemaRefOrVal)(e,this.schema,s,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,Ge(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,E.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${s} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,k.default.errors))}result(e,t,s){this.failResult((0,O.not)(e),t,s)}failResult(e,t,s){this.gen.if(e),s?s():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,O.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,O._)`${t} !== undefined && (${(0,O.or)(this.invalid$data(),e)})`)}error(e,t,s){if(t){this.setParams(t),this._error(e,s),this.setParams({});return}this._error(e,s)}_error(e,t){(e?L.reportExtraError:L.reportError)(this,this.def.error,t)}$dataError(){(0,L.reportError)(this,this.def.$dataError||L.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,L.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,s=O.nil){this.gen.block(()=>{this.check$data(e,s),t()})}check$data(e=O.nil,t=O.nil){if(!this.$data)return;let{gen:s,schemaCode:g,schemaType:S,def:w}=this;s.if((0,O.or)((0,O._)`${g} === undefined`,t)),e!==O.nil&&s.assign(e,!0),(S.length||w.validateSchema)&&(s.elseIf(this.invalid$data()),this.$dataError(),e!==O.nil&&s.assign(e,!1)),s.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:s,def:g,it:w}=this;return(0,O.or)(E(),D());function E(){if(s.length){if(!(t instanceof O.Name))throw Error(`ajv implementation error`);let e=Array.isArray(s)?s:[s];return(0,O._)`${(0,S.checkDataTypes)(e,t,w.opts.strictNumbers,S.DataType.Wrong)}`}return O.nil}function D(){if(g.validateSchema){let s=e.scopeValue(`validate$data`,{ref:g.validateSchema});return(0,O._)`!${s}(${t})`}return O.nil}}subschema(e,t){let s=(0,D.getSubschema)(this.it,e);(0,D.extendSubschemaData)(s,this.it,e),(0,D.extendSubschemaMode)(s,e);let g={...this.it,...s,items:void 0,props:void 0};return ne(g,t),g}mergeEvaluated(e,t){let{it:s,gen:g}=this;s.opts.unevaluated&&(s.props!==!0&&e.props!==void 0&&(s.props=F.mergeEvaluated.props(g,e.props,s.props,t)),s.items!==!0&&e.items!==void 0&&(s.items=F.mergeEvaluated.items(g,e.items,s.items,t)))}mergeValidEvaluated(e,t){let{it:s,gen:g}=this;if(s.opts.unevaluated&&(s.props!==!0||s.items!==!0))return g.if(t,()=>this.mergeEvaluated(e,O.Name)),!0}};e.KeywordCxt=Be;function Ve(e,t,s,g){let S=new Be(e,s,t);`code`in s?s.code(S,g):S.$data&&s.validate?(0,E.funcKeywordCode)(S,s):`macro`in s?(0,E.macroKeywordCode)(S,s):(s.compile||s.validate)&&(0,E.funcKeywordCode)(S,s)}let Ue=/^\/(?:[^~]|~0|~1)*$/,We=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ge(e,{dataLevel:t,dataNames:s,dataPathArr:g}){let S,w;if(e===``)return k.default.rootData;if(e[0]===`/`){if(!Ue.test(e))throw Error(`Invalid JSON-pointer: ${e}`);S=e,w=k.default.rootData}else{let E=We.exec(e);if(!E)throw Error(`Invalid JSON-pointer: ${e}`);let D=+E[1];if(S=E[2],S===`#`){if(D>=t)throw Error(j(`property/index`,D));return g[t-D]}if(D>t)throw Error(j(`data`,D));if(w=s[t-D],!S)return w}let E=w,D=S.split(`/`);for(let e of D)e&&(w=(0,O._)`${w}${(0,O.getProperty)((0,F.unescapeJsonPointer)(e))}`,E=(0,O._)`${E} && ${w}`);return E;function j(e,s){return`Cannot access ${e} ${s} levels up, current level is ${t}`}}e.getData=Ge})),require_validation_error=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),require_ref_error=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_resolve();e.default=class extends Error{constructor(e,s,g,S){super(S||`can't resolve reference ${g} from id ${s}`),this.missingRef=(0,t.resolveUrl)(e,s,g),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),require_compile=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=require_codegen(),s=require_validation_error(),g=require_names(),S=require_resolve(),w=require_util(),E=require_validate();var D=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let s;typeof e.schema==`object`&&(s=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,S.normalizeId)(s?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=s?.$async,this.refs={}}};e.SchemaEnv=D;function O(e){let w=F.call(this,e);if(w)return w;let D=(0,S.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:O,lines:k}=this.opts.code,{ownProperties:j}=this.opts,L=new t.CodeGen(this.scope,{es5:O,lines:k,ownProperties:j}),B;e.$async&&(B=L.scopeValue(`Error`,{ref:s.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let H=L.scopeName(`validate`);e.validateName=H;let q={gen:L,allErrors:this.opts.allErrors,data:g.default.data,parentData:g.default.parentData,parentDataProperty:g.default.parentDataProperty,dataNames:[g.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:L.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:H,ValidationError:B,schema:e.schema,schemaEnv:e,rootId:D,baseId:e.baseId||D,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},ee;try{this._compilations.add(e),(0,E.validateFunctionCode)(q),L.optimize(this.opts.code.optimize);let s=L.toString();ee=`${L.scopeRefs(g.default.scope)}return ${s}`,this.opts.code.process&&(ee=this.opts.code.process(ee,e));let S=Function(`${g.default.self}`,`${g.default.scope}`,ee)(this,this.scope.get());if(this.scope.value(H,{ref:S}),S.errors=null,S.schema=e.schema,S.schemaEnv=e,e.$async&&(S.$async=!0),this.opts.code.source===!0&&(S.source={validateName:H,validateCode:s,scopeValues:L._values}),this.opts.unevaluated){let{props:e,items:s}=q;S.evaluated={props:e instanceof t.Name?void 0:e,items:s instanceof t.Name?void 0:s,dynamicProps:e instanceof t.Name,dynamicItems:s instanceof t.Name},S.source&&(S.source.evaluated=(0,t.stringify)(S.evaluated))}return e.validate=S,e}catch(t){throw delete e.validate,delete e.validateName,ee&&this.logger.error(`Error compiling schema, function code:`,ee),t}finally{this._compilations.delete(e)}}e.compileSchema=O;function k(e,t,s){var g;s=(0,S.resolveUrl)(this.opts.uriResolver,t,s);let w=e.refs[s];if(w)return w;let E=B.call(this,e,s);if(E===void 0){let g=e.localRefs?.[s],{schemaId:S}=this.opts;g&&(E=new D({schema:g,schemaId:S,root:e,baseId:t}))}if(E!==void 0)return e.refs[s]=j.call(this,E)}e.resolveRef=k;function j(e){return(0,S.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:O.call(this,e)}function F(e){for(let t of this._compilations)if(L(t,e))return t}e.getCompilingSchema=F;function L(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function B(e,t){let s;for(;typeof(s=this.refs[t])==`string`;)t=s;return s||this.schemas[t]||H.call(this,e,t)}function H(e,t){let s=this.opts.uriResolver.parse(t),g=(0,S._getFullPath)(this.opts.uriResolver,s),w=(0,S.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&g===w)return ee.call(this,s,e);let E=(0,S.normalizeId)(g),k=this.refs[E]||this.schemas[E];if(typeof k==`string`){let t=H.call(this,e,k);return typeof t?.schema==`object`?ee.call(this,s,t):void 0}if(typeof k?.schema==`object`){if(k.validate||O.call(this,k),E===(0,S.normalizeId)(t)){let{schema:t}=k,{schemaId:s}=this.opts,g=t[s];return g&&(w=(0,S.resolveUrl)(this.opts.uriResolver,w,g)),new D({schema:t,schemaId:s,root:e,baseId:w})}return ee.call(this,s,k)}}e.resolveSchema=H;let q=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function ee(e,{baseId:t,schema:s,root:g}){var E;if(e.fragment?.[0]!==`/`)return;for(let g of e.fragment.slice(1).split(`/`)){if(typeof s==`boolean`)return;let e=s[(0,w.unescapeFragment)(g)];if(e===void 0)return;s=e;let E=typeof s==`object`&&s[this.opts.schemaId];!q.has(g)&&E&&(t=(0,S.resolveUrl)(this.opts.uriResolver,t,E))}let O;if(typeof s!=`boolean`&&s.$ref&&!(0,w.schemaHasRulesButRef)(s,this.RULES)){let e=(0,S.resolveUrl)(this.opts.uriResolver,t,s.$ref);O=H.call(this,g,e)}let{schemaId:k}=this.opts;if(O||=new D({schema:s,schemaId:k,root:g,baseId:t}),O.schema!==O.root.schema)return O}})),require_data=__commonJSMin$2(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),require_utils$1=__commonJSMin$2(((e,t)=>{let s=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),g=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function S(e){let t=``,s=0,g=0;for(g=0;g<e.length;g++)if(s=e[g].charCodeAt(0),s!==48){if(!(s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102))return``;t+=e[g];break}for(g+=1;g<e.length;g++){if(s=e[g].charCodeAt(0),!(s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102))return``;t+=e[g]}return t}let w=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function E(e){return e.length=0,!0}function D(e,t,s){if(e.length){let g=S(e);if(g!==``)t.push(g);else return s.error=!0,!1;e.length=0}return!0}function O(e){let t=0,s={error:!1,address:``,zone:``},g=[],w=[],O=!1,k=!1,j=D;for(let S=0;S<e.length;S++){let D=e[S];if(!(D===`[`||D===`]`))if(D===`:`){if(O===!0&&(k=!0),!j(w,g,s))break;if(++t>7){s.error=!0;break}S>0&&e[S-1]===`:`&&(O=!0),g.push(`:`);continue}else if(D===`%`){if(!j(w,g,s))break;j=E}else{w.push(D);continue}}return w.length&&(j===E?s.zone=w.join(``):k?g.push(w.join(``)):g.push(S(w))),s.address=g.join(``),s}function k(e){if(j(e,`:`)<2)return{host:e,isIPV6:!1};let t=O(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,s=t.address;return t.zone&&(e+=`%`+t.zone,s+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:s}}}function j(e,t){let s=0;for(let g=0;g<e.length;g++)e[g]===t&&s++;return s}function F(e){let t=e,s=[],g=-1,S=0;for(;S=t.length;){if(S===1){if(t===`.`)break;if(t===`/`){s.push(`/`);break}else{s.push(t);break}}else if(S===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){s.push(`/`);break}}else if(S===3&&t===`/..`){s.length!==0&&s.pop(),s.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),s.length!==0&&s.pop();continue}}if((g=t.indexOf(`/`,1))===-1){s.push(t);break}else s.push(t.slice(0,g)),t=t.slice(g)}return s.join(``)}function L(e,t){let s=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=s(e.scheme)),e.userinfo!==void 0&&(e.userinfo=s(e.userinfo)),e.host!==void 0&&(e.host=s(e.host)),e.path!==void 0&&(e.path=s(e.path)),e.query!==void 0&&(e.query=s(e.query)),e.fragment!==void 0&&(e.fragment=s(e.fragment)),e}function B(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let s=unescape(e.host);if(!g(s)){let t=k(s);s=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(s)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:w,recomposeAuthority:B,normalizeComponentEncoding:L,removeDotSegments:F,isIPv4:g,isUUID:s,normalizeIPv6:k,stringArrayToHexStripped:S}})),require_schemes=__commonJSMin$2(((e,t)=>{let{isUUID:s}=require_utils$1(),g=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,S=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function w(e){return S.indexOf(e)!==-1}function E(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function D(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function O(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function k(e){return e.secure=E(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function j(e){if((e.port===(E(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,s]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=s,e.resourceName=void 0}return e.fragment=void 0,e}function F(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let s=e.path.match(g);if(s){let g=t.scheme||e.scheme||`urn`;e.nid=s[1].toLowerCase(),e.nss=s[2];let S=oe(`${g}:${t.nid||e.nid}`);e.path=void 0,S&&(e=S.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function L(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let s=t.scheme||e.scheme||`urn`,g=e.nid.toLowerCase(),S=oe(`${s}:${t.nid||g}`);S&&(e=S.serialize(e,t));let w=e,E=e.nss;return w.path=`${g||t.nid}:${E}`,t.skipEscape=!0,w}function B(e,t){let g=e;return g.uuid=g.nss,g.nss=void 0,!t.tolerant&&(!g.uuid||!s(g.uuid))&&(g.error=g.error||`UUID is not valid.`),g}function H(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let q={scheme:`http`,domainHost:!0,parse:D,serialize:O},ee={scheme:`https`,domainHost:q.domainHost,parse:D,serialize:O},J={scheme:`ws`,domainHost:!0,parse:k,serialize:j},Y={scheme:`wss`,domainHost:J.domainHost,parse:J.parse,serialize:J.serialize},te={scheme:`urn`,parse:F,serialize:L,skipNormalize:!0},ne={scheme:`urn:uuid`,parse:B,serialize:H,skipNormalize:!0},ae={http:q,https:ee,ws:J,wss:Y,urn:te,"urn:uuid":ne};Object.setPrototypeOf(ae,null);function oe(e){return e&&(ae[e]||ae[e.toLowerCase()])||void 0}t.exports={wsIsSecure:E,SCHEMES:ae,isValidSchemeName:w,getSchemeHandler:oe}})),require_fast_uri=__commonJSMin$2(((e,t)=>{let{normalizeIPv6:s,removeDotSegments:g,recomposeAuthority:S,normalizeComponentEncoding:w,isIPv4:E,nonSimpleDomain:D}=require_utils$1(),{SCHEMES:O,getSchemeHandler:k}=require_schemes();function j(e,t){return typeof e==`string`?e=H(ee(e,t),t):typeof e==`object`&&(e=ee(H(e,t),t)),e}function F(e,t,s){let g=s?Object.assign({scheme:`null`},s):{scheme:`null`},S=L(ee(e,g),ee(t,g),g,!0);return g.skipEscape=!0,H(S,g)}function L(e,t,s,S){let w={};return S||(e=ee(H(e,s),s),t=ee(H(t,s),s)),s||={},!s.tolerant&&t.scheme?(w.scheme=t.scheme,w.userinfo=t.userinfo,w.host=t.host,w.port=t.port,w.path=g(t.path||``),w.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(w.userinfo=t.userinfo,w.host=t.host,w.port=t.port,w.path=g(t.path||``),w.query=t.query):(t.path?(t.path[0]===`/`?w.path=g(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?w.path=`/`+t.path:e.path?w.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:w.path=t.path,w.path=g(w.path)),w.query=t.query):(w.path=e.path,t.query===void 0?w.query=e.query:w.query=t.query),w.userinfo=e.userinfo,w.host=e.host,w.port=e.port),w.scheme=e.scheme),w.fragment=t.fragment,w}function B(e,t,s){return typeof e==`string`?(e=unescape(e),e=H(w(ee(e,s),!0),{...s,skipEscape:!0})):typeof e==`object`&&(e=H(w(e,!0),{...s,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=H(w(ee(t,s),!0),{...s,skipEscape:!0})):typeof t==`object`&&(t=H(w(t,!0),{...s,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function H(e,t){let s={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},w=Object.assign({},t),E=[],D=k(w.scheme||s.scheme);D&&D.serialize&&D.serialize(s,w),s.path!==void 0&&(w.skipEscape?s.path=unescape(s.path):(s.path=escape(s.path),s.scheme!==void 0&&(s.path=s.path.split(`%3A`).join(`:`)))),w.reference!==`suffix`&&s.scheme&&E.push(s.scheme,`:`);let O=S(s);if(O!==void 0&&(w.reference!==`suffix`&&E.push(`//`),E.push(O),s.path&&s.path[0]!==`/`&&E.push(`/`)),s.path!==void 0){let e=s.path;!w.absolutePath&&(!D||!D.absolutePath)&&(e=g(e)),O===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),E.push(e)}return s.query!==void 0&&E.push(`?`,s.query),s.fragment!==void 0&&E.push(`#`,s.fragment),E.join(``)}let q=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ee(e,t){let g=Object.assign({},t),S={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},w=!1;g.reference===`suffix`&&(e=g.scheme?g.scheme+`:`+e:`//`+e);let O=e.match(q);if(O){if(S.scheme=O[1],S.userinfo=O[3],S.host=O[4],S.port=parseInt(O[5],10),S.path=O[6]||``,S.query=O[7],S.fragment=O[8],isNaN(S.port)&&(S.port=O[5]),S.host)if(E(S.host)===!1){let e=s(S.host);S.host=e.host.toLowerCase(),w=e.isIPV6}else w=!0;S.scheme===void 0&&S.userinfo===void 0&&S.host===void 0&&S.port===void 0&&S.query===void 0&&!S.path?S.reference=`same-document`:S.scheme===void 0?S.reference=`relative`:S.fragment===void 0?S.reference=`absolute`:S.reference=`uri`,g.reference&&g.reference!==`suffix`&&g.reference!==S.reference&&(S.error=S.error||`URI is not a `+g.reference+` reference.`);let t=k(g.scheme||S.scheme);if(!g.unicodeSupport&&(!t||!t.unicodeSupport)&&S.host&&(g.domainHost||t&&t.domainHost)&&w===!1&&D(S.host))try{S.host=URL.domainToASCII(S.host.toLowerCase())}catch(e){S.error=S.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(S.scheme!==void 0&&(S.scheme=unescape(S.scheme)),S.host!==void 0&&(S.host=unescape(S.host))),S.path&&=escape(unescape(S.path)),S.fragment&&=encodeURI(decodeURIComponent(S.fragment))),t&&t.parse&&t.parse(S,g)}else S.error=S.error||`URI can not be parsed.`;return S}let J={SCHEMES:O,normalize:j,resolve:F,resolveComponent:L,equal:B,serialize:H,parse:ee};t.exports=J,t.exports.default=J,t.exports.fastUri=J})),require_uri=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_fast_uri();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),require_core$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var s=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return s._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return s.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return s.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return s.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return s.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return s.CodeGen}});let g=require_validation_error(),S=require_ref_error(),w=require_rules(),E=require_compile(),D=require_codegen(),O=require_resolve(),k=require_dataType(),j=require_util(),F=require_data(),L=require_uri(),B=(e,t)=>new RegExp(e,t);B.code=`new RegExp`;let H=[`removeAdditional`,`useDefaults`,`coerceTypes`],q=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),ee={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},J={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`},Y=200;function te(e){var t,s,g,S,w,E,D,O,k,j,F,H,q,ee,J,Y,te,ne,ae,oe,se,ce,ue,de,fe;let me=e.strict,ge=e.code?.optimize,_e=ge===!0||ge===void 0?1:ge||0,ve=e.code?.regExp??B,ye=e.uriResolver??L.default;return{strictSchema:e.strictSchema??me??!0,strictNumbers:e.strictNumbers??me??!0,strictTypes:e.strictTypes??me??`log`,strictTuples:e.strictTuples??me??`log`,strictRequired:e.strictRequired??me??!1,code:e.code?{...e.code,optimize:_e,regExp:ve}:{optimize:_e,regExp:ve},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:ye}}var ne=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...te(e)};let{es5:t,lines:s}=this.opts.code;this.scope=new D.ValueScope({scope:{},prefixes:q,es5:t,lines:s}),this.logger=me(e.logger);let g=e.validateFormats;e.validateFormats=!1,this.RULES=(0,w.getRules)(),ae.call(this,ee,e,`NOT SUPPORTED`),ae.call(this,J,e,`DEPRECATED`,`warn`),this._metaOpts=de.call(this),e.formats&&ce.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ue.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),se.call(this),e.validateFormats=g}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:s}=this.opts,g=F;s===`id`&&(g={...F},g.id=g.$id,delete g.$id),t&&e&&this.addMetaSchema(g,g[s],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let s;if(typeof e==`string`){if(s=this.getSchema(e),!s)throw Error(`no schema with key or ref "${e}"`)}else s=this.compile(e);let g=s(t);return`$async`in s||(this.errors=s.errors),g}compile(e,t){let s=this._addSchema(e,t);return s.validate||this._compileSchemaEnv(s)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:s}=this.opts;return g.call(this,e,t);async function g(e,t){await w.call(this,e.$schema);let s=this._addSchema(e,t);return s.validate||E.call(this,s)}async function w(e){e&&!this.getSchema(e)&&await g.call(this,{$ref:e},!0)}async function E(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof S.default))throw t;return D.call(this,t),await O.call(this,t.missingSchema),E.call(this,e)}}function D({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function O(e){let s=await k.call(this,e);this.refs[e]||await w.call(this,s.$schema),this.refs[e]||this.addSchema(s,e,t)}async function k(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=s(e))}finally{delete this._loading[e]}}}addSchema(e,t,s,g=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,s,g);return this}let S;if(typeof e==`object`){let{schemaId:t}=this.opts;if(S=e[t],S!==void 0&&typeof S!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,O.normalizeId)(t||S),this._checkUnique(t),this.schemas[t]=this._addSchema(e,s,t,g,!0),this}addMetaSchema(e,t,s=this.opts.validateSchema){return this.addSchema(e,t,!0,s),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let s;if(s=e.$schema,s!==void 0&&typeof s!=`string`)throw Error(`$schema must be a string`);if(s=s||this.opts.defaultMeta||this.defaultMeta(),!s)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let g=this.validate(s,e);if(!g&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return g}getSchema(e){let t;for(;typeof(t=oe.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:s}=this.opts,g=new E.SchemaEnv({schema:{},schemaId:s});if(t=E.resolveSchema.call(this,g,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=oe.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let s=e[this.opts.schemaId];return s&&(s=(0,O.normalizeId)(s),delete this.schemas[s],delete this.refs[s]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let s;if(typeof e==`string`)s=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=s);else if(typeof e==`object`&&t===void 0){if(t=e,s=t.keyword,Array.isArray(s)&&!s.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(_e.call(this,s,t),!t)return(0,j.eachItem)(s,e=>ve.call(this,e)),this;Ce.call(this,t);let g={...t,type:(0,k.getJSONTypes)(t.type),schemaType:(0,k.getJSONTypes)(t.schemaType)};return(0,j.eachItem)(s,g.type.length===0?e=>ve.call(this,e,g):e=>g.type.forEach(t=>ve.call(this,e,g,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let s of t.rules){let t=s.rules.findIndex(t=>t.keyword===e);t>=0&&s.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:s=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${s}${e.instancePath} ${e.message}`).reduce((e,s)=>e+t+s)}$dataMetaSchema(e,t){let s=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let g of t){let t=g.split(`/`).slice(1),S=e;for(let e of t)S=S[e];for(let e in s){let t=s[e];if(typeof t!=`object`)continue;let{$data:g}=t.definition,w=S[e];g&&w&&(S[e]=Te(w))}}return e}_removeAllSchemas(e,t){for(let s in e){let g=e[s];(!t||t.test(s))&&(typeof g==`string`?delete e[s]:g&&!g.meta&&(this._cache.delete(g.schema),delete e[s]))}}_addSchema(e,t,s,g=this.opts.validateSchema,S=this.opts.addUsedSchema){let w,{schemaId:D}=this.opts;if(typeof e==`object`)w=e[D];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let k=this._cache.get(e);if(k!==void 0)return k;s=(0,O.normalizeId)(w||s);let j=O.getSchemaRefs.call(this,e,s);return k=new E.SchemaEnv({schema:e,schemaId:D,meta:t,baseId:s,localRefs:j}),this._cache.set(k.schema,k),S&&!s.startsWith(`#`)&&(s&&this._checkUnique(s),this.refs[s]=k),g&&this.validateSchema(e,!0),k}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):E.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{E.compileSchema.call(this,e)}finally{this.opts=t}}};ne.ValidationError=g.default,ne.MissingRefError=S.default,e.default=ne;function ae(e,t,s,g=`error`){for(let S in e){let w=S;w in t&&this.logger[g](`${s}: option ${S}. ${e[w]}`)}}function oe(e){return e=(0,O.normalizeId)(e),this.schemas[e]||this.refs[e]}function se(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function ce(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ue(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let s=e[t];s.keyword||=t,this.addKeyword(s)}}function de(){let e={...this.opts};for(let t of H)delete e[t];return e}let fe={log(){},warn(){},error(){}};function me(e){if(e===!1)return fe;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let ge=/^[a-z_$][a-z0-9_$:-]*$/i;function _e(e,t){let{RULES:s}=this;if((0,j.eachItem)(e,e=>{if(s.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!ge.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function ve(e,t,s){var g;let S=t?.post;if(s&&S)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:w}=this,E=S?w.post:w.rules.find(({type:e})=>e===s);if(E||(E={type:s,rules:[]},w.rules.push(E)),w.keywords[e]=!0,!t)return;let D={keyword:e,definition:{...t,type:(0,k.getJSONTypes)(t.type),schemaType:(0,k.getJSONTypes)(t.schemaType)}};t.before?ye.call(this,E,D,t.before):E.rules.push(D),w.all[e]=D,(g=t.implements)==null||g.forEach(e=>this.addKeyword(e))}function ye(e,t,s){let g=e.rules.findIndex(e=>e.keyword===s);g>=0?e.rules.splice(g,0,t):(e.rules.push(t),this.logger.warn(`rule ${s} is not defined`))}function Ce(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Te(t)),e.validateSchema=this.compile(t,!0))}let we={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function Te(e){return{anyOf:[e,we]}}})),require_id=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),require_ref=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=require_ref_error(),s=require_code(),g=require_codegen(),S=require_names(),w=require_compile(),E=require_util(),D={keyword:`$ref`,schemaType:`string`,code(e){let{gen:s,schema:S,it:E}=e,{baseId:D,schemaEnv:j,validateName:F,opts:L,self:B}=E,{root:H}=j;if((S===`#`||S===`#/`)&&D===H.baseId)return ee();let q=w.resolveRef.call(B,H,D,S);if(q===void 0)throw new t.default(E.opts.uriResolver,D,S);if(q instanceof w.SchemaEnv)return J(q);return Y(q);function ee(){if(j===H)return k(e,F,j,j.$async);let t=s.scopeValue(`root`,{ref:H});return k(e,(0,g._)`${t}.validate`,H,H.$async)}function J(t){k(e,O(e,t),t,t.$async)}function Y(t){let w=s.scopeValue(`schema`,L.code.source===!0?{ref:t,code:(0,g.stringify)(t)}:{ref:t}),E=s.name(`valid`),D=e.subschema({schema:t,dataTypes:[],schemaPath:g.nil,topSchemaRef:w,errSchemaPath:S},E);e.mergeEvaluated(D),e.ok(E)}}};function O(e,t){let{gen:s}=e;return t.validate?s.scopeValue(`validate`,{ref:t.validate}):(0,g._)`${s.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=O;function k(e,t,w,D){let{gen:O,it:k}=e,{allErrors:j,schemaEnv:F,opts:L}=k,B=L.passContext?S.default.this:g.nil;D?H():q();function H(){if(!F.$async)throw Error(`async schema referenced by sync schema`);let S=O.let(`valid`);O.try(()=>{O.code((0,g._)`await ${(0,s.callValidateCode)(e,t,B)}`),J(t),j||O.assign(S,!0)},e=>{O.if((0,g._)`!(${e} instanceof ${k.ValidationError})`,()=>O.throw(e)),ee(e),j||O.assign(S,!1)}),e.ok(S)}function q(){e.result((0,s.callValidateCode)(e,t,B),()=>J(t),()=>ee(t))}function ee(e){let t=(0,g._)`${e}.errors`;O.assign(S.default.vErrors,(0,g._)`${S.default.vErrors} === null ? ${t} : ${S.default.vErrors}.concat(${t})`),O.assign(S.default.errors,(0,g._)`${S.default.vErrors}.length`)}function J(e){var t;if(!k.opts.unevaluated)return;let s=w?.validate?.evaluated;if(k.props!==!0)if(s&&!s.dynamicProps)s.props!==void 0&&(k.props=E.mergeEvaluated.props(O,s.props,k.props));else{let t=O.var(`props`,(0,g._)`${e}.evaluated.props`);k.props=E.mergeEvaluated.props(O,t,k.props,g.Name)}if(k.items!==!0)if(s&&!s.dynamicItems)s.items!==void 0&&(k.items=E.mergeEvaluated.items(O,s.items,k.items));else{let t=O.var(`items`,(0,g._)`${e}.evaluated.items`);k.items=E.mergeEvaluated.items(O,t,k.items,g.Name)}}}e.callRef=k,e.default=D})),require_core=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_id(),s=require_ref();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,s.default]})),require_limitNumber=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=t.operators,g={maximum:{okStr:`<=`,ok:s.LTE,fail:s.GT},minimum:{okStr:`>=`,ok:s.GTE,fail:s.LT},exclusiveMaximum:{okStr:`<`,ok:s.LT,fail:s.GTE},exclusiveMinimum:{okStr:`>`,ok:s.GT,fail:s.LTE}};e.default={keyword:Object.keys(g),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:s})=>(0,t.str)`must be ${g[e].okStr} ${s}`,params:({keyword:e,schemaCode:s})=>(0,t._)`{comparison: ${g[e].okStr}, limit: ${s}}`},code(e){let{keyword:s,data:S,schemaCode:w}=e;e.fail$data((0,t._)`${S} ${g[s].fail} ${w} || isNaN(${S})`)}}})),require_multipleOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:s,data:g,schemaCode:S,it:w}=e,E=w.opts.multipleOfPrecision,D=s.let(`res`),O=E?(0,t._)`Math.abs(Math.round(${D}) - ${D}) > 1e-${E}`:(0,t._)`${D} !== parseInt(${D})`;e.fail$data((0,t._)`(${S} === 0 || (${D} = ${g}/${S}, ${O}))`)}}})),require_ucs2length=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,s=0,g=0,S;for(;g<t;)s++,S=e.charCodeAt(g++),S>=55296&&S<=56319&&g<t&&(S=e.charCodeAt(g),(S&64512)==56320&&g++);return s}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),require_limitLength=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_ucs2length();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:s}){let g=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${g} than ${s} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:S,data:w,schemaCode:E,it:D}=e,O=S===`maxLength`?t.operators.GT:t.operators.LT,k=D.opts.unicode===!1?(0,t._)`${w}.length`:(0,t._)`${(0,s.useFunc)(e.gen,g.default)}(${w})`;e.fail$data((0,t._)`${k} ${O} ${E}`)}}})),require_pattern=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_util(),g=require_codegen();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,g.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,g._)`{pattern: ${e}}`},code(e){let{gen:S,data:w,$data:E,schema:D,schemaCode:O,it:k}=e,j=k.opts.unicodeRegExp?`u`:``;if(E){let{regExp:t}=k.opts.code,E=t.code===`new RegExp`?(0,g._)`new RegExp`:(0,s.useFunc)(S,t),D=S.let(`valid`);S.try(()=>S.assign(D,(0,g._)`${E}(${O}, ${j}).test(${w})`),()=>S.assign(D,!1)),e.fail$data((0,g._)`!${D}`)}else{let s=(0,t.usePattern)(e,D);e.fail$data((0,g._)`!${s}.test(${w})`)}}}})),require_limitProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:s}){let g=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${g} than ${s} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:s,data:g,schemaCode:S}=e,w=s===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${g}).length ${w} ${S}`)}}})),require_required=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_util();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,s.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,s._)`{missingProperty: ${e}}`},code(e){let{gen:S,schema:w,schemaCode:E,data:D,$data:O,it:k}=e,{opts:j}=k;if(!O&&w.length===0)return;let F=w.length>=j.loopRequired;if(k.allErrors?L():B(),j.strictRequired){let t=e.parentSchema.properties,{definedProperties:s}=e.it;for(let e of w)if(t?.[e]===void 0&&!s.has(e)){let t=`required property "${e}" is not defined at "${k.schemaEnv.baseId+k.errSchemaPath}" (strictRequired)`;(0,g.checkStrictMode)(k,t,k.opts.strictRequired)}}function L(){if(F||O)e.block$data(s.nil,H);else for(let s of w)(0,t.checkReportMissingProp)(e,s)}function B(){let s=S.let(`missing`);if(F||O){let t=S.let(`valid`,!0);e.block$data(t,()=>q(s,t)),e.ok(t)}else S.if((0,t.checkMissingProp)(e,w,s)),(0,t.reportMissingProp)(e,s),S.else()}function H(){S.forOf(`prop`,E,s=>{e.setParams({missingProperty:s}),S.if((0,t.noPropertyInData)(S,D,s,j.ownProperties),()=>e.error())})}function q(g,w){e.setParams({missingProperty:g}),S.forOf(g,E,()=>{S.assign(w,(0,t.propertyInData)(S,D,g,j.ownProperties)),S.if((0,s.not)(w),()=>{e.error(),S.break()})},s.nil)}}}})),require_limitItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:s}){let g=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${g} than ${s} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:s,data:g,schemaCode:S}=e,w=s===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${g}.length ${w} ${S}`)}}})),require_equal=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_fast_deep_equal();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),require_uniqueItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_dataType(),s=require_codegen(),g=require_util(),S=require_equal();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,s.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,s._)`{i: ${e}, j: ${t}}`},code(e){let{gen:w,data:E,$data:D,schema:O,parentSchema:k,schemaCode:j,it:F}=e;if(!D&&!O)return;let L=w.let(`valid`),B=k.items?(0,t.getSchemaTypes)(k.items):[];e.block$data(L,H,(0,s._)`${j} === false`),e.ok(L);function H(){let t=w.let(`i`,(0,s._)`${E}.length`),g=w.let(`j`);e.setParams({i:t,j:g}),w.assign(L,!0),w.if((0,s._)`${t} > 1`,()=>(q()?ee:J)(t,g))}function q(){return B.length>0&&!B.some(e=>e===`object`||e===`array`)}function ee(g,S){let D=w.name(`item`),O=(0,t.checkDataTypes)(B,D,F.opts.strictNumbers,t.DataType.Wrong),k=w.const(`indices`,(0,s._)`{}`);w.for((0,s._)`;${g}--;`,()=>{w.let(D,(0,s._)`${E}[${g}]`),w.if(O,(0,s._)`continue`),B.length>1&&w.if((0,s._)`typeof ${D} == "string"`,(0,s._)`${D} += "_"`),w.if((0,s._)`typeof ${k}[${D}] == "number"`,()=>{w.assign(S,(0,s._)`${k}[${D}]`),e.error(),w.assign(L,!1).break()}).code((0,s._)`${k}[${D}] = ${g}`)})}function J(t,D){let O=(0,g.useFunc)(w,S.default),k=w.name(`outer`);w.label(k).for((0,s._)`;${t}--;`,()=>w.for((0,s._)`${D} = ${t}; ${D}--;`,()=>w.if((0,s._)`${O}(${E}[${t}], ${E}[${D}])`,()=>{e.error(),w.assign(L,!1).break(k)})))}}}})),require_const=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_equal();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:S,data:w,$data:E,schemaCode:D,schema:O}=e;E||O&&typeof O==`object`?e.fail$data((0,t._)`!${(0,s.useFunc)(S,g.default)}(${w}, ${D})`):e.fail((0,t._)`${O} !== ${w}`)}}})),require_enum=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_equal();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:S,data:w,$data:E,schema:D,schemaCode:O,it:k}=e;if(!E&&D.length===0)throw Error(`enum must have non-empty array`);let j=D.length>=k.opts.loopEnum,F,L=()=>F??=(0,s.useFunc)(S,g.default),B;if(j||E)B=S.let(`valid`),e.block$data(B,H);else{if(!Array.isArray(D))throw Error(`ajv implementation error`);let e=S.const(`vSchema`,O);B=(0,t.or)(...D.map((t,s)=>q(e,s)))}e.pass(B);function H(){S.assign(B,!1),S.forOf(`v`,O,e=>S.if((0,t._)`${L()}(${w}, ${e})`,()=>S.assign(B,!0).break()))}function q(e,s){let g=D[s];return typeof g==`object`&&g?(0,t._)`${L()}(${w}, ${e}[${s}])`:(0,t._)`${w} === ${g}`}}}})),require_validation$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_limitNumber(),s=require_multipleOf(),g=require_limitLength(),S=require_pattern(),w=require_limitProperties(),E=require_required(),D=require_limitItems(),O=require_uniqueItems(),k=require_const(),j=require_enum();e.default=[t.default,s.default,g.default,S.default,w.default,E.default,D.default,O.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},k.default,j.default]})),require_additionalItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=require_codegen(),s=require_util(),g={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:g}=e,{items:w}=t;if(!Array.isArray(w)){(0,s.checkStrictMode)(g,`"additionalItems" is ignored when "items" is not an array of schemas`);return}S(e,w)}};function S(e,g){let{gen:S,schema:w,data:E,keyword:D,it:O}=e;O.items=!0;let k=S.const(`len`,(0,t._)`${E}.length`);if(w===!1)e.setParams({len:g.length}),e.pass((0,t._)`${k} <= ${g.length}`);else if(typeof w==`object`&&!(0,s.alwaysValidSchema)(O,w)){let s=S.var(`valid`,(0,t._)`${k} <= ${g.length}`);S.if((0,t.not)(s),()=>j(s)),e.ok(s)}function j(w){S.forRange(`i`,g.length,k,g=>{e.subschema({keyword:D,dataProp:g,dataPropType:s.Type.Num},w),O.allErrors||S.if((0,t.not)(w),()=>S.break())})}}e.validateAdditionalItems=S,e.default=g})),require_items=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=require_codegen(),s=require_util(),g=require_code(),S={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:S}=e;if(Array.isArray(t))return w(e,`additionalItems`,t);S.items=!0,!(0,s.alwaysValidSchema)(S,t)&&e.ok((0,g.validateArray)(e))}};function w(e,g,S=e.schema){let{gen:w,parentSchema:E,data:D,keyword:O,it:k}=e;L(E),k.opts.unevaluated&&S.length&&k.items!==!0&&(k.items=s.mergeEvaluated.items(w,S.length,k.items));let j=w.name(`valid`),F=w.const(`len`,(0,t._)`${D}.length`);S.forEach((g,S)=>{(0,s.alwaysValidSchema)(k,g)||(w.if((0,t._)`${F} > ${S}`,()=>e.subschema({keyword:O,schemaProp:S,dataProp:S},j)),e.ok(j))});function L(e){let{opts:t,errSchemaPath:w}=k,E=S.length,D=E===e.minItems&&(E===e.maxItems||e[g]===!1);if(t.strictTuples&&!D){let e=`"${O}" is ${E}-tuple, but minItems or maxItems/${g} are not specified or different at path "${w}"`;(0,s.checkStrictMode)(k,e,t.strictTuples)}}}e.validateTuple=w,e.default=S})),require_prefixItems=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_items();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),require_items2020=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g=require_code(),S=require_additionalItems();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:w,it:E}=e,{prefixItems:D}=w;E.items=!0,!(0,s.alwaysValidSchema)(E,t)&&(D?(0,S.validateAdditionalItems)(e,D):e.ok((0,g.validateArray)(e)))}}})),require_contains=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:s}})=>s===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${s} valid item(s)`,params:({params:{min:e,max:s}})=>s===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${s}}`},code(e){let{gen:g,schema:S,parentSchema:w,data:E,it:D}=e,O,k,{minContains:j,maxContains:F}=w;D.opts.next?(O=j===void 0?1:j,k=F):O=1;let L=g.const(`len`,(0,t._)`${E}.length`);if(e.setParams({min:O,max:k}),k===void 0&&O===0){(0,s.checkStrictMode)(D,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(k!==void 0&&O>k){(0,s.checkStrictMode)(D,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,s.alwaysValidSchema)(D,S)){let s=(0,t._)`${L} >= ${O}`;k!==void 0&&(s=(0,t._)`${s} && ${L} <= ${k}`),e.pass(s);return}D.items=!0;let B=g.name(`valid`);k===void 0&&O===1?q(B,()=>g.if(B,()=>g.break())):O===0?(g.let(B,!0),k!==void 0&&g.if((0,t._)`${E}.length > 0`,H)):(g.let(B,!1),H()),e.result(B,()=>e.reset());function H(){let e=g.name(`_valid`),t=g.let(`count`,0);q(e,()=>g.if(e,()=>ee(t)))}function q(t,S){g.forRange(`i`,0,L,g=>{e.subschema({keyword:`contains`,dataProp:g,dataPropType:s.Type.Num,compositeRule:!0},t),S()})}function ee(e){g.code((0,t._)`${e}++`),k===void 0?g.if((0,t._)`${e} >= ${O}`,()=>g.assign(B,!0).break()):(g.if((0,t._)`${e} > ${k}`,()=>g.assign(B,!1).break()),O===1?g.assign(B,!0):g.if((0,t._)`${e} >= ${O}`,()=>g.assign(B,!0)))}}}})),require_dependencies=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=require_codegen(),s=require_util(),g=require_code();e.error={message:({params:{property:e,depsCount:s,deps:g}})=>{let S=s===1?`property`:`properties`;return(0,t.str)`must have ${S} ${g} when property ${e} is present`},params:({params:{property:e,depsCount:s,deps:g,missingProperty:S}})=>(0,t._)`{property: ${e},
48
48
  missingProperty: ${S},
49
49
  depsCount: ${s},
50
- deps: ${g}}`};let S={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,s]=w(e);E(e,t),D(e,s)}};function w({schema:e}){let t={},s={};for(let g in e){if(g===`__proto__`)continue;let S=Array.isArray(e[g])?t:s;S[g]=e[g]}return[t,s]}function E(e,s=e.schema){let{gen:S,data:w,it:E}=e;if(Object.keys(s).length===0)return;let D=S.let(`missing`);for(let O in s){let k=s[O];if(k.length===0)continue;let j=(0,g.propertyInData)(S,w,O,E.opts.ownProperties);e.setParams({property:O,depsCount:k.length,deps:k.join(`, `)}),E.allErrors?S.if(j,()=>{for(let t of k)(0,g.checkReportMissingProp)(e,t)}):(S.if((0,t._)`${j} && (${(0,g.checkMissingProp)(e,k,D)})`),(0,g.reportMissingProp)(e,D),S.else())}}e.validatePropertyDeps=E;function D(e,t=e.schema){let{gen:S,data:w,keyword:E,it:D}=e,O=S.name(`valid`);for(let k in t)(0,s.alwaysValidSchema)(D,t[k])||(S.if((0,g.propertyInData)(S,w,k,D.opts.ownProperties),()=>{let t=e.subschema({keyword:E,schemaProp:k},O);e.mergeValidEvaluated(t,O)},()=>S.var(O,!0)),e.ok(O))}e.validateSchemaDeps=D,e.default=S})),require_propertyNames=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:g,schema:S,data:w,it:E}=e;if((0,s.alwaysValidSchema)(E,S))return;let D=g.name(`valid`);g.forIn(`key`,w,s=>{e.setParams({propertyName:s}),e.subschema({keyword:`propertyNames`,data:s,dataTypes:[`string`],propertyName:s,compositeRule:!0},D),g.if((0,t.not)(D),()=>{e.error(!0),E.allErrors||g.break()})}),e.ok(D)}}})),require_additionalProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_names(),S=require_util();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,s._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:w,schema:E,parentSchema:D,data:O,errsCount:k,it:j}=e;if(!k)throw Error(`ajv implementation error`);let{allErrors:F,opts:L}=j;if(j.props=!0,L.removeAdditional!==`all`&&(0,S.alwaysValidSchema)(j,E))return;let B=(0,t.allSchemaProperties)(D.properties),H=(0,t.allSchemaProperties)(D.patternProperties);q(),e.ok((0,s._)`${k} === ${g.default.errors}`);function q(){w.forIn(`key`,O,e=>{!B.length&&!H.length?Y(e):w.if(ee(e),()=>Y(e))})}function ee(g){let E;if(B.length>8){let e=(0,S.schemaRefOrVal)(j,D.properties,`properties`);E=(0,t.isOwnProperty)(w,e,g)}else E=B.length?(0,s.or)(...B.map(e=>(0,s._)`${g} === ${e}`)):s.nil;return H.length&&(E=(0,s.or)(E,...H.map(S=>(0,s._)`${(0,t.usePattern)(e,S)}.test(${g})`))),(0,s.not)(E)}function J(e){w.code((0,s._)`delete ${O}[${e}]`)}function Y(t){if(L.removeAdditional===`all`||L.removeAdditional&&E===!1){J(t);return}if(E===!1){e.setParams({additionalProperty:t}),e.error(),F||w.break();return}if(typeof E==`object`&&!(0,S.alwaysValidSchema)(j,E)){let g=w.name(`valid`);L.removeAdditional===`failing`?(te(t,g,!1),w.if((0,s.not)(g),()=>{e.reset(),J(t)})):(te(t,g),F||w.if((0,s.not)(g),()=>w.break()))}}function te(t,s,g){let w={keyword:`additionalProperties`,dataProp:t,dataPropType:S.Type.Str};g===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,s)}}}})),require_properties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_validate(),s=require_code(),g=require_util(),S=require_additionalProperties();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,parentSchema:D,data:O,it:k}=e;k.opts.removeAdditional===`all`&&D.additionalProperties===void 0&&S.default.code(new t.KeywordCxt(k,S.default,`additionalProperties`));let j=(0,s.allSchemaProperties)(E);for(let e of j)k.definedProperties.add(e);k.opts.unevaluated&&j.length&&k.props!==!0&&(k.props=g.mergeEvaluated.props(w,(0,g.toHash)(j),k.props));let F=j.filter(e=>!(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0)return;let L=w.name(`valid`);for(let t of F)B(t)?H(t):(w.if((0,s.propertyInData)(w,O,t,k.opts.ownProperties)),H(t),k.allErrors||w.else().var(L,!0),w.endIf()),e.it.definedProperties.add(t),e.ok(L);function B(e){return k.opts.useDefaults&&!k.compositeRule&&E[e].default!==void 0}function H(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},L)}}}})),require_patternProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_util(),S=require_util();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,data:D,parentSchema:O,it:k}=e,{opts:j}=k,F=(0,t.allSchemaProperties)(E),L=F.filter(e=>(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0||L.length===F.length&&(!k.opts.unevaluated||k.props===!0))return;let B=j.strictSchema&&!j.allowMatchingProperties&&O.properties,H=w.name(`valid`);k.props!==!0&&!(k.props instanceof s.Name)&&(k.props=(0,S.evaluatedPropsToName)(w,k.props));let{props:q}=k;ee();function ee(){for(let e of F)B&&J(e),k.allErrors?Y(e):(w.var(H,!0),Y(e),w.if(H))}function J(e){for(let t in B)new RegExp(e).test(t)&&(0,g.checkStrictMode)(k,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function Y(g){w.forIn(`key`,D,E=>{w.if((0,s._)`${(0,t.usePattern)(e,g)}.test(${E})`,()=>{let t=L.includes(g);t||e.subschema({keyword:`patternProperties`,schemaProp:g,dataProp:E,dataPropType:S.Type.Str},H),k.opts.unevaluated&&q!==!0?w.assign((0,s._)`${q}[${E}]`,!0):!t&&!k.allErrors&&w.if((0,s.not)(H),()=>w.break())})})}}}})),require_not=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:s,schema:g,it:S}=e;if((0,t.alwaysValidSchema)(S,g)){e.fail();return}let w=s.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},w),e.failResult(w,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),require_anyOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:require_code().validateUnion,error:{message:`must match a schema in anyOf`}}})),require_oneOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:g,schema:S,parentSchema:w,it:E}=e;if(!Array.isArray(S))throw Error(`ajv implementation error`);if(E.opts.discriminator&&w.discriminator)return;let D=S,O=g.let(`valid`,!1),k=g.let(`passing`,null),j=g.name(`_valid`);e.setParams({passing:k}),g.block(F),e.result(O,()=>e.reset(),()=>e.error(!0));function F(){D.forEach((S,w)=>{let D;(0,s.alwaysValidSchema)(E,S)?g.var(j,!0):D=e.subschema({keyword:`oneOf`,schemaProp:w,compositeRule:!0},j),w>0&&g.if((0,t._)`${j} && ${O}`).assign(O,!1).assign(k,(0,t._)`[${k}, ${w}]`).else(),g.if(j,()=>{g.assign(O,!0),g.assign(k,w),D&&e.mergeEvaluated(D,t.Name)})})}}}})),require_allOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:s,schema:g,it:S}=e;if(!Array.isArray(g))throw Error(`ajv implementation error`);let w=s.name(`valid`);g.forEach((s,g)=>{if((0,t.alwaysValidSchema)(S,s))return;let E=e.subschema({keyword:`allOf`,schemaProp:g},w);e.ok(w),e.mergeEvaluated(E)})}}})),require_if=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:g,parentSchema:w,it:E}=e;w.then===void 0&&w.else===void 0&&(0,s.checkStrictMode)(E,`"if" without "then" and "else" is ignored`);let D=S(E,`then`),O=S(E,`else`);if(!D&&!O)return;let k=g.let(`valid`,!0),j=g.name(`_valid`);if(F(),e.reset(),D&&O){let t=g.let(`ifClause`);e.setParams({ifClause:t}),g.if(j,L(`then`,t),L(`else`,t))}else D?g.if(j,L(`then`)):g.if((0,t.not)(j),L(`else`));e.pass(k,()=>e.error(!0));function F(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},j);e.mergeEvaluated(t)}function L(s,S){return()=>{let w=e.subschema({keyword:s},j);g.assign(k,j),e.mergeValidEvaluated(w,k),S?g.assign(S,(0,t._)`${s}`):e.setParams({ifClause:s})}}}};function S(e,t){let g=e.schema[t];return g!==void 0&&!(0,s.alwaysValidSchema)(e,g)}e.default=g})),require_thenElse=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:s,it:g}){s.if===void 0&&(0,t.checkStrictMode)(g,`"${e}" without "if" is ignored`)}}})),require_applicator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_additionalItems(),s=require_prefixItems(),g=require_items(),S=require_items2020(),w=require_contains(),E=require_dependencies(),D=require_propertyNames(),O=require_additionalProperties(),k=require_properties(),j=require_patternProperties(),F=require_not(),L=require_anyOf(),B=require_oneOf(),H=require_allOf(),q=require_if(),ee=require_thenElse();function J(e=!1){let J=[F.default,L.default,B.default,H.default,q.default,ee.default,D.default,O.default,E.default,k.default,j.default];return e?J.push(s.default,S.default):J.push(t.default,g.default),J.push(w.default),J}e.default=J})),require_format$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,s){let{gen:g,data:S,$data:w,schema:E,schemaCode:D,it:O}=e,{opts:k,errSchemaPath:j,schemaEnv:F,self:L}=O;if(!k.validateFormats)return;w?B():H();function B(){let w=g.scopeValue(`formats`,{ref:L.formats,code:k.code.formats}),E=g.const(`fDef`,(0,t._)`${w}[${D}]`),O=g.let(`fType`),j=g.let(`format`);g.if((0,t._)`typeof ${E} == "object" && !(${E} instanceof RegExp)`,()=>g.assign(O,(0,t._)`${E}.type || "string"`).assign(j,(0,t._)`${E}.validate`),()=>g.assign(O,(0,t._)`"string"`).assign(j,E)),e.fail$data((0,t.or)(B(),H()));function B(){return k.strictSchema===!1?t.nil:(0,t._)`${D} && !${j}`}function H(){let e=F.$async?(0,t._)`(${E}.async ? await ${j}(${S}) : ${j}(${S}))`:(0,t._)`${j}(${S})`,g=(0,t._)`(typeof ${j} == "function" ? ${e} : ${j}.test(${S}))`;return(0,t._)`${j} && ${j} !== true && ${O} === ${s} && !${g}`}}function H(){let w=L.formats[E];if(!w){H();return}if(w===!0)return;let[D,O,B]=q(w);D===s&&e.pass(ee());function H(){if(k.strictSchema===!1){L.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${E}" ignored in schema at path "${j}"`}}function q(e){let s=e instanceof RegExp?(0,t.regexpCode)(e):k.code.formats?(0,t._)`${k.code.formats}${(0,t.getProperty)(E)}`:void 0,S=g.scopeValue(`formats`,{key:E,ref:e,code:s});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${S}.validate`]:[`string`,e,S]}function ee(){if(typeof w==`object`&&!(w instanceof RegExp)&&w.async){if(!F.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${B}(${S})`}return typeof O==`function`?(0,t._)`${B}(${S})`:(0,t._)`${B}.test(${S})`}}}}})),require_format=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[require_format$1().default]})),require_metadata=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),require_draft7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_core(),s=require_validation$1(),g=require_applicator(),S=require_format(),w=require_metadata();e.default=[t.default,s.default,(0,g.default)(),S.default,w.metadataVocabulary,w.contentVocabulary]})),require_types=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),require_discriminator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_types(),g=require_compile(),S=require_ref_error(),w=require_util();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===s.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:s,tagName:g}})=>(0,t._)`{error: ${e}, tag: ${g}, tagValue: ${s}}`},code(e){let{gen:E,data:D,schema:O,parentSchema:k,it:j}=e,{oneOf:F}=k;if(!j.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let L=O.propertyName;if(typeof L!=`string`)throw Error(`discriminator: requires propertyName`);if(O.mapping)throw Error(`discriminator: mapping is not supported`);if(!F)throw Error(`discriminator: requires oneOf keyword`);let B=E.let(`valid`,!1),H=E.const(`tag`,(0,t._)`${D}${(0,t.getProperty)(L)}`);E.if((0,t._)`typeof ${H} == "string"`,()=>q(),()=>e.error(!1,{discrError:s.DiscrError.Tag,tag:H,tagName:L})),e.ok(B);function q(){let g=J();E.if(!1);for(let e in g)E.elseIf((0,t._)`${H} === ${e}`),E.assign(B,ee(g[e]));E.else(),e.error(!1,{discrError:s.DiscrError.Mapping,tag:H,tagName:L}),E.endIf()}function ee(s){let g=E.name(`valid`),S=e.subschema({keyword:`oneOf`,schemaProp:s},g);return e.mergeEvaluated(S,t.Name),g}function J(){var e;let t={},s=D(k),E=!0;for(let e=0;e<F.length;e++){let t=F[e];if(t?.$ref&&!(0,w.schemaHasRulesButRef)(t,j.self.RULES)){let e=t.$ref;if(t=g.resolveRef.call(j.self,j.schemaEnv.root,j.baseId,e),t instanceof g.SchemaEnv&&(t=t.schema),t===void 0)throw new S.default(j.opts.uriResolver,j.baseId,e)}let k=t?.properties?.[L];if(typeof k!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${L}"`);E&&=s||D(t),O(k,e)}if(!E)throw Error(`discriminator: "${L}" must be required`);return t;function D({required:e}){return Array.isArray(e)&&e.includes(L)}function O(e,t){if(e.const)B(e.const,t);else if(e.enum)for(let s of e.enum)B(s,t);else throw Error(`discriminator: "properties/${L}" must have "const" or "enum"`)}function B(e,s){if(typeof e!=`string`||e in t)throw Error(`discriminator: "${L}" values must be unique strings`);t[e]=s}}}}})),require_json_schema_draft_07=__commonJSMin$2(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),require_ajv=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let s=require_core$1(),g=require_draft7(),S=require_discriminator(),w=require_json_schema_draft_07(),E=[`/properties`],D=`http://json-schema.org/draft-07/schema`;var O=class extends s.default{_addVocabularies(){super._addVocabularies(),g.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(S.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(w,E):w;this.addMetaSchema(e,D,!1),this.refs[`http://json-schema.org/schema`]=D}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(D)?D:void 0)}};e.Ajv=O,t.exports=e=O,t.exports.Ajv=O,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=O;var k=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return k.KeywordCxt}});var j=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return j._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return j.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return j.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return j.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return j.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return j.CodeGen}});var F=require_validation_error();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return F.default}});var L=require_ref_error();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return L.default}})})),require_formats=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(w,E),time:t(O(!0),k),"date-time":t(L(!0),B),"iso-time":t(O(),j),"iso-date-time":t(L(),H),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:J,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:de,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:te,int32:{type:`number`,validate:oe},int64:{type:`number`,validate:se},float:{type:`number`,validate:ce},double:{type:`number`,validate:ce},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,E),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,k),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,B),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,j),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,H),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function s(e){return e%4==0&&(e%100!=0||e%400==0)}let g=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,S=[0,31,28,31,30,31,30,31,31,30,31,30,31];function w(e){let t=g.exec(e);if(!t)return!1;let w=+t[1],E=+t[2],D=+t[3];return E>=1&&E<=12&&D>=1&&D<=(E===2&&s(w)?29:S[E])}function E(e,t){if(e&&t)return e>t?1:e<t?-1:0}let D=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function O(e){return function(t){let s=D.exec(t);if(!s)return!1;let g=+s[1],S=+s[2],w=+s[3],E=s[4],O=s[5]===`-`?-1:1,k=+(s[6]||0),j=+(s[7]||0);if(k>23||j>59||e&&!E)return!1;if(g<=23&&S<=59&&w<60)return!0;let F=S-j*O,L=g-k*O-(F<0?1:0);return(L===23||L===-1)&&(F===59||F===-1)&&w<61}}function k(e,t){if(!(e&&t))return;let s=new Date(`2020-01-01T`+e).valueOf(),g=new Date(`2020-01-01T`+t).valueOf();if(s&&g)return s-g}function j(e,t){if(!(e&&t))return;let s=D.exec(e),g=D.exec(t);if(s&&g)return e=s[1]+s[2]+s[3],t=g[1]+g[2]+g[3],e>t?1:e<t?-1:0}let F=/t|\s/i;function L(e){let t=O(e);return function(e){let s=e.split(F);return s.length===2&&w(s[0])&&t(s[1])}}function B(e,t){if(!(e&&t))return;let s=new Date(e).valueOf(),g=new Date(t).valueOf();if(s&&g)return s-g}function H(e,t){if(!(e&&t))return;let[s,g]=e.split(F),[S,w]=t.split(F),D=E(s,S);if(D!==void 0)return D||k(g,w)}let q=/\/|:/,ee=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function J(e){return q.test(e)&&ee.test(e)}let Y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function te(e){return Y.lastIndex=0,Y.test(e)}let ne=-(2**31),ae=2**31-1;function oe(e){return Number.isInteger(e)&&e<=ae&&e>=ne}function se(e){return Number.isInteger(e)}function ce(){return!0}let ue=/[^\\]\\Z/;function de(e){if(ue.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),require_limit=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=require_ajv(),s=require_codegen(),g=s.operators,S={formatMaximum:{okStr:`<=`,ok:g.LTE,fail:g.GT},formatMinimum:{okStr:`>=`,ok:g.GTE,fail:g.LT},formatExclusiveMaximum:{okStr:`<`,ok:g.LT,fail:g.GTE},formatExclusiveMinimum:{okStr:`>`,ok:g.GT,fail:g.LTE}};e.formatLimitDefinition={keyword:Object.keys(S),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,s.str)`should be ${S[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,s._)`{comparison: ${S[e].okStr}, limit: ${t}}`},code(e){let{gen:g,data:w,schemaCode:E,keyword:D,it:O}=e,{opts:k,self:j}=O;if(!k.validateFormats)return;let F=new t.KeywordCxt(O,j.RULES.all.format.definition,`format`);F.$data?L():B();function L(){let t=g.scopeValue(`formats`,{ref:j.formats,code:k.code.formats}),S=g.const(`fmt`,(0,s._)`${t}[${F.schemaCode}]`);e.fail$data((0,s.or)((0,s._)`typeof ${S} != "object"`,(0,s._)`${S} instanceof RegExp`,(0,s._)`typeof ${S}.compare != "function"`,H(S)))}function B(){let t=F.schema,S=j.formats[t];if(!S||S===!0)return;if(typeof S!=`object`||S instanceof RegExp||typeof S.compare!=`function`)throw Error(`"${D}": format "${t}" does not define "compare" function`);let w=g.scopeValue(`formats`,{key:t,ref:S,code:k.code.formats?(0,s._)`${k.code.formats}${(0,s.getProperty)(t)}`:void 0});e.fail$data(H(w))}function H(e){return(0,s._)`${e}.compare(${w}, ${E}) ${S[D].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),require_dist=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let s=require_formats(),g=require_limit(),S=require_codegen(),w=new S.Name(`fullFormats`),E=new S.Name(`fastFormats`),D=(e,t={keywords:!0})=>{if(Array.isArray(t))return O(e,t,s.fullFormats,w),e;let[S,D]=t.mode===`fast`?[s.fastFormats,E]:[s.fullFormats,w];return O(e,t.formats||s.formatNames,S,D),t.keywords&&(0,g.default)(e),e};D.get=(e,t=`full`)=>{let g=(t===`fast`?s.fastFormats:s.fullFormats)[e];if(!g)throw Error(`Unknown format "${e}"`);return g};function O(e,t,s,g){var w,E;(E=e.opts.code).formats??(E.formats=(0,S._)`require("ajv-formats/dist/formats").${g}`);for(let g of t)e.addFormat(g,s[g])}t.exports=e=D,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=D})),import_ajv=__toESM$2(require_ajv(),1),import_dist=__toESM$2(require_dist(),1);function createDefaultAjvInstance(){let e=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_dist.default)(e),e}var AjvJsonSchemaValidator=class{constructor(e){this._ajv=e??createDefaultAjvInstance()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},ExperimentalServerTasks=class{constructor(e){this._server=e}requestStream(e,t,s){return this._server.requestStream(e,t,s)}createMessageStream(e,t){let s=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!s?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}elicitInputStream(e,t){let s=this._server.getClientCapabilities(),g=e.mode??`form`;switch(g){case`url`:if(!s?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!s?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let S=g===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:S},ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,s){return this._server.getTaskResult({taskId:e},t,s)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function assertToolsCallTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${s} does not support task creation for tools/call (required for ${t})`);break;default:break}}function assertClientRequestTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${s} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${s} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Server=class extends Protocol{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let s=this._loggingLevels.get(t);return s?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(e,t)=>{let s=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:g}=e.params,S=LoggingLevelSchema.safeParse(g);return S.success&&this._loggingLevels.set(s,S.data),{}})}get experimental(){return this._experimental||={tasks:new ExperimentalServerTasks(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=mergeCapabilities(this._capabilities,e)}setRequestHandler(e,t){let s=getObjectShape(e)?.method;if(!s)throw Error(`Schema is missing a method literal`);let g;if(isZ4Schema(s)){let e=s;g=e._zod?.def?.value??e.value}else{let e=s;g=e._def?.value??e.value}if(typeof g!=`string`)throw Error(`Schema method literal must be a string`);return g===`tools/call`?super.setRequestHandler(e,async(e,s)=>{let g=safeParse(CallToolRequestSchema,e);if(!g.success){let e=g.error instanceof Error?g.error.message:String(g.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:S}=g.data,w=await Promise.resolve(t(e,s));if(S.task){let e=safeParse(CreateTaskResultSchema,w);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let E=safeParse(CallToolResultSchema,w);if(!E.success){let e=E.error instanceof Error?E.error.message:String(E.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return E.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},CreateMessageResultWithToolsSchema,t):this.request({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let s=e;return this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let s=e.mode===`form`?e:{...e,mode:`form`},g=await this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t);if(g.action===`accept`&&g.content&&s.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(s.requestedSchema)(g.content);if(!e.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return g}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const COMPLETABLE_SYMBOL=Symbol.for(`mcp.completable`);function isCompletable(e){return!!e&&typeof e==`object`&&COMPLETABLE_SYMBOL in e}function getCompleter(e){return e[COMPLETABLE_SYMBOL]?.complete}var McpZodTypeKind;(function(e){e.Completable=`McpCompletable`})(McpZodTypeKind||={});const TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!TOOL_NAME_REGEX.test(e)){let s=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,s)=>s.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${s.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function issueToolNameWarning(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function validateAndWarnToolName(e){let t=validateToolName(e);return issueToolNameWarning(e,t.warnings),t.isValid}var ExperimentalMcpServerTasks=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,s){let g={taskSupport:`required`,...t.execution};if(g.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,g,t._meta,s)}},McpServer=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(e,t)}get experimental(){return this._experimental||={tasks:new ExperimentalMcpServerTasks(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let s={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=normalizeObjectSchema(t.inputSchema);return e?toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`input`}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=normalizeObjectSchema(t.outputSchema);e&&(s.outputSchema=toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`output`}))}return s})})),this.server.setRequestHandler(CallToolRequestSchema,async(e,t)=>{try{let s=this._registeredTools[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let g=!!e.params.task,S=s.execution?.taskSupport,w=`createTask`in s.handler;if((S===`required`||S===`optional`)&&!w)throw new McpError(ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${S}' but was not registered with registerToolTask`);if(S===`required`&&!g)throw new McpError(ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(S===`optional`&&!g&&w)return await this.handleAutomaticTaskPolling(s,e,t);let E=await this.validateToolInput(s,e.params.arguments,e.params.name),D=await this.executeToolHandler(s,E,t);return g||await this.validateToolOutput(s,D,e.params.name),D}catch(e){if(e instanceof McpError&&e.code===ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,s){if(!e.inputSchema)return;let g=await safeParseAsync(normalizeObjectSchema(e.inputSchema)??e.inputSchema,t);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${s}: ${e}`)}return g.data}async validateToolOutput(e,t,s){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${s} has an output schema but no structured content was provided`);let g=await safeParseAsync(normalizeObjectSchema(e.outputSchema),t.structuredContent);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${s}: ${e}`)}}async executeToolHandler(e,t,s){let g=e.handler;if(`createTask`in g){if(!s.taskStore)throw Error(`No task store provided.`);let S={...s,taskStore:s.taskStore};if(e.inputSchema){let e=g;return await Promise.resolve(e.createTask(t,S))}else{let e=g;return await Promise.resolve(e.createTask(S))}}if(e.inputSchema){let e=g;return await Promise.resolve(e(t,s))}else{let e=g;return await Promise.resolve(e(s))}}async handleAutomaticTaskPolling(e,t,s){if(!s.taskStore)throw Error(`No task store provided for task-capable tool.`);let g=await this.validateToolInput(e,t.params.arguments,t.params.name),S=e.handler,w={...s,taskStore:s.taskStore},E=g?await Promise.resolve(S.createTask(g,w)):await Promise.resolve(S.createTask(w)),D=E.task.taskId,O=E.task,k=O.pollInterval??5e3;for(;O.status!==`completed`&&O.status!==`failed`&&O.status!==`cancelled`;){await new Promise(e=>setTimeout(e,k));let e=await s.taskStore.getTask(D);if(!e)throw new McpError(ErrorCode.InternalError,`Task ${D} not found during polling`);O=e}return await s.taskStore.getTaskResult(D)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async e=>{switch(e.params.ref.type){case`ref/prompt`:return assertCompleteRequestPrompt(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return assertCompleteRequestResourceTemplate(e),this.handleResourceCompletion(e,e.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let s=this._registeredPrompts[t.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!s.argsSchema)return EMPTY_COMPLETION_RESULT;let g=getObjectShape(s.argsSchema)?.[e.params.argument.name];if(!isCompletable(g))return EMPTY_COMPLETION_RESULT;let S=getCompleter(g);return S?createCompletionResult(await S(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}async handleResourceCompletion(e,t){let s=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!s){if(this._registeredResources[t.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let g=s.resourceTemplate.completeCallback(e.params.argument.name);return g?createCompletionResult(await g(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(e,t)=>{let s=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),g=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let s=await e.resourceTemplate.listCallback(t);for(let t of s.resources)g.push({...e.metadata,...t})}return{resources:[...s,...g]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(e,t)=>{let s=new URL(e.params.uri),g=this._registeredResources[s.toString()];if(g){if(!g.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${s} disabled`);return g.readCallback(s,t)}for(let e of Object.values(this._registeredResourceTemplates)){let g=e.resourceTemplate.uriTemplate.match(s.toString());if(g)return e.readCallback(s,g,t)}throw new McpError(ErrorCode.InvalidParams,`Resource ${s} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?promptArgumentsFromSchema(t.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(e,t)=>{let s=this._registeredPrompts[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(s.argsSchema){let g=await safeParseAsync(normalizeObjectSchema(s.argsSchema),e.params.arguments);if(!g.success){let t=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let S=g.data,w=s.callback;return await Promise.resolve(w(S,t))}else{let e=s.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...s){let g;typeof s[0]==`object`&&(g=s.shift());let S=s[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,s,g){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let S=this._createRegisteredResource(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let S=this._createRegisteredResourceTemplate(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}}_createRegisteredResource(e,t,s,g,S){let w={name:e,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==s&&(delete this._registeredResources[s],e.uri&&(this._registeredResources[e.uri]=w)),e.name!==void 0&&(w.name=e.name),e.title!==void 0&&(w.title=e.title),e.metadata!==void 0&&(w.metadata=e.metadata),e.callback!==void 0&&(w.readCallback=e.callback),e.enabled!==void 0&&(w.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[s]=w,w}_createRegisteredResourceTemplate(e,t,s,g,S){let w={resourceTemplate:s,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.template!==void 0&&(w.resourceTemplate=t.template),t.metadata!==void 0&&(w.metadata=t.metadata),t.callback!==void 0&&(w.readCallback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=w;let E=s.uriTemplate.variableNames;return Array.isArray(E)&&E.some(e=>!!s.completeCallback(e))&&this.setCompletionRequestHandler(),w}_createRegisteredPrompt(e,t,s,g,S){let w={title:t,description:s,argsSchema:g===void 0?void 0:objectFromShape(g),callback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.description!==void 0&&(w.description=t.description),t.argsSchema!==void 0&&(w.argsSchema=objectFromShape(t.argsSchema)),t.callback!==void 0&&(w.callback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=w,g&&Object.values(g).some(e=>isCompletable(e instanceof ZodOptional$1?e._def?.innerType:e))&&this.setCompletionRequestHandler(),w}_createRegisteredTool(e,t,s,g,S,w,E,D,O){validateAndWarnToolName(e);let k={title:t,description:s,inputSchema:getZodSchemaObject(g),outputSchema:getZodSchemaObject(S),annotations:w,execution:E,_meta:D,handler:O,enabled:!0,disable:()=>k.update({enabled:!1}),enable:()=>k.update({enabled:!0}),remove:()=>k.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&validateAndWarnToolName(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=k)),t.title!==void 0&&(k.title=t.title),t.description!==void 0&&(k.description=t.description),t.paramsSchema!==void 0&&(k.inputSchema=objectFromShape(t.paramsSchema)),t.outputSchema!==void 0&&(k.outputSchema=objectFromShape(t.outputSchema)),t.callback!==void 0&&(k.handler=t.callback),t.annotations!==void 0&&(k.annotations=t.annotations),t._meta!==void 0&&(k._meta=t._meta),t.enabled!==void 0&&(k.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=k,this.setToolRequestHandlers(),this.sendToolListChanged(),k}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let s,g,S,w;if(typeof t[0]==`string`&&(s=t.shift()),t.length>1){let s=t[0];if(isZodRawShapeCompat(s))g=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!isZodRawShapeCompat(t[0])&&(w=t.shift());else if(typeof s==`object`&&s){if(Object.values(s).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);w=t.shift()}}let E=t[0];return this._createRegisteredTool(e,void 0,s,g,void 0,w,{taskSupport:`forbidden`},void 0,E)}registerTool(e,t,s){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:g,description:S,inputSchema:w,outputSchema:E,annotations:D,_meta:O}=t;return this._createRegisteredTool(e,g,S,w,E,D,{taskSupport:`forbidden`},O,s)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let s;typeof t[0]==`string`&&(s=t.shift());let g;t.length>1&&(g=t.shift());let S=t[0],w=this._createRegisteredPrompt(e,void 0,s,g,S);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),w}registerPrompt(e,t,s){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:g,description:S,argsSchema:w}=t,E=this._createRegisteredPrompt(e,g,S,w,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),E}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const EMPTY_OBJECT_JSON_SCHEMA={type:`object`,properties:{}};function isZodTypeLike(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function isZodSchemaInstance(e){return`_def`in e||`_zod`in e||isZodTypeLike(e)}function isZodRawShapeCompat(e){return typeof e!=`object`||!e||isZodSchemaInstance(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(isZodTypeLike)}function getZodSchemaObject(e){if(e){if(isZodRawShapeCompat(e))return objectFromShape(e);if(!isZodSchemaInstance(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function promptArgumentsFromSchema(e){let t=getObjectShape(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:getSchemaDescription(t),required:!isSchemaOptional(t)})):[]}function getMethodValue(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let s=getLiteralValue(t);if(typeof s==`string`)return s;throw Error(`Schema method literal must be a string`)}function createCompletionResult(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var RequestError=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),GlobalRequest=global.Request,Request$1=class extends GlobalRequest{constructor(e,t){typeof e==`object`&&getRequestCache in e&&(e=e[getRequestCache]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},newHeadersFromIncoming=e=>{let t=[],s=e.rawHeaders;for(let e=0;e<s.length;e+=2){let{[e]:g,[e+1]:S}=s;g.charCodeAt(0)!==58&&t.push([g,S])}return new Headers(t)},wrapBodyStream=Symbol(`wrapBodyStream`),newRequestFromIncoming=(e,t,s,g,S)=>{let w={method:e,headers:s,signal:S.signal};if(e===`TRACE`){w.method=`GET`;let e=new Request$1(t,w);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in g&&g.rawBody instanceof Buffer)w.body=new ReadableStream({start(e){e.enqueue(g.rawBody),e.close()}});else if(g[wrapBodyStream]){let e;w.body=new ReadableStream({async pull(t){try{e||=Readable$1.toWeb(g).getReader();let{done:s,value:S}=await e.read();s?t.close():t.enqueue(S)}catch(e){t.error(e)}}})}else w.body=Readable$1.toWeb(g);return new Request$1(t,w)},getRequestCache=Symbol(`getRequestCache`),requestCache=Symbol(`requestCache`),incomingKey=Symbol(`incomingKey`),urlKey=Symbol(`urlKey`),headersKey=Symbol(`headersKey`),abortControllerKey=Symbol(`abortControllerKey`),requestPrototype={get method(){return this[incomingKey].method||`GET`},get url(){return this[urlKey]},get headers(){return this[headersKey]||=newHeadersFromIncoming(this[incomingKey])},[Symbol(`getAbortController`)](){return this[getRequestCache](),this[abortControllerKey]},[getRequestCache](){return this[abortControllerKey]||=new AbortController,this[requestCache]||=newRequestFromIncoming(this.method,this[urlKey],this.headers,this[incomingKey],this[abortControllerKey])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(requestPrototype,e,{get(){return this[getRequestCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(requestPrototype,e,{value:function(){return this[getRequestCache]()[e]()}})}),Object.setPrototypeOf(requestPrototype,Request$1.prototype);var newRequest=(e,t)=>{let s=Object.create(requestPrototype);s[incomingKey]=e;let g=e.url||``;if(g[0]!==`/`&&(g.startsWith(`http://`)||g.startsWith(`https://`))){if(e instanceof Http2ServerRequest)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{s[urlKey]=new URL(g).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return s}let S=(e instanceof Http2ServerRequest?e.authority:e.headers.host)||t;if(!S)throw new RequestError(`Missing host header`);let w;if(e instanceof Http2ServerRequest){if(w=e.scheme,!(w===`http`||w===`https`))throw new RequestError(`Unsupported scheme`)}else w=e.socket&&e.socket.encrypted?`https`:`http`;let E=new URL(`${w}://${S}${g}`);if(E.hostname.length!==S.length&&E.hostname!==S.replace(/:\d+$/,``))throw new RequestError(`Invalid host header`);return s[urlKey]=E.href,s},responseCache=Symbol(`responseCache`),getResponseCache=Symbol(`getResponseCache`),cacheKey=Symbol(`cache`),GlobalResponse=global.Response,Response2=class e{#e;#t;[getResponseCache](){return delete this[cacheKey],this[responseCache]||=new GlobalResponse(this.#e,this.#t)}constructor(t,s){let g;if(this.#e=t,s instanceof e){let e=s[responseCache];if(e){this.#t=e,this[getResponseCache]();return}else this.#t=s.#t,g=new Headers(s.#t.headers)}else this.#t=s;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[cacheKey]=[s?.status||200,t,g||s?.headers])}get headers(){let e=this[cacheKey];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[getResponseCache]().headers}get status(){return this[cacheKey]?.[0]??this[getResponseCache]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{get(){return this[getResponseCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{value:function(){return this[getResponseCache]()[e]()}})}),Object.setPrototypeOf(Response2,GlobalResponse),Object.setPrototypeOf(Response2.prototype,GlobalResponse.prototype);async function readWithoutBlocking(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function writeFromReadableStreamDefaultReader(e,t,s){let g=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,g),t.on(`error`,g),(s??e.read()).then(E,S),e.closed.finally(()=>{t.off(`close`,g),t.off(`error`,g)});function S(e){e&&t.destroy(e)}function w(){e.read().then(E,S)}function E({done:s,value:g}){try{if(s)t.end();else if(!t.write(g))t.once(`drain`,w);else return e.read().then(E,S)}catch(e){S(e)}}}function writeFromReadableStream(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:writeFromReadableStreamDefaultReader(e.getReader(),t)}var buildOutgoingHttpHeaders=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let s=[];for(let[g,S]of e)g===`set-cookie`?s.push(S):t[g]=S;return s.length>0&&(t[`set-cookie`]=s),t[`content-type`]??=`text/plain; charset=UTF-8`,t},X_ALREADY_SENT=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=crypto$2);var outgoingEnded=Symbol(`outgoingEnded`),incomingDraining=Symbol(`incomingDraining`),DRAIN_TIMEOUT_MS=500,MAX_DRAIN_BYTES=64*1024*1024,drainIncoming=e=>{let t=e;if(e.destroyed||t[incomingDraining])return;if(t[incomingDraining]=!0,e instanceof Http2ServerRequest){try{e.stream?.close?.(constants$2.NGHTTP2_NO_ERROR)}catch{}return}let s=0,g=()=>{clearTimeout(w),e.off(`data`,E),e.off(`end`,g),e.off(`error`,g)},S=()=>{g();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},w=setTimeout(S,DRAIN_TIMEOUT_MS);w.unref?.();let E=e=>{s+=e.length,s>MAX_DRAIN_BYTES&&S()};e.on(`data`,E),e.on(`end`,g),e.on(`error`,g),e.resume()},handleRequestError=()=>new Response(null,{status:400}),handleFetchError=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),handleResponseError=(e,t)=>{let s=e instanceof Error?e:Error(`unknown error`,{cause:e});s.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${s.message}`),t.destroy(s))},flushHeaders=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},responseViaCache=async(e,t)=>{let[s,g,S]=e[cacheKey],w=!1;if(!S)S={"content-type":`text/plain; charset=UTF-8`};else if(S instanceof Headers)w=S.has(`content-length`),S=buildOutgoingHttpHeaders(S);else if(Array.isArray(S)){let e=new Headers(S);w=e.has(`content-length`),S=buildOutgoingHttpHeaders(e)}else for(let e in S)if(e.length===14&&e.toLowerCase()===`content-length`){w=!0;break}w||(typeof g==`string`?S[`Content-Length`]=Buffer.byteLength(g):g instanceof Uint8Array?S[`Content-Length`]=g.byteLength:g instanceof Blob&&(S[`Content-Length`]=g.size)),t.writeHead(s,S),typeof g==`string`||g instanceof Uint8Array?t.end(g):g instanceof Blob?t.end(new Uint8Array(await g.arrayBuffer())):(flushHeaders(t),await writeFromReadableStream(g,t)?.catch(e=>handleResponseError(e,t))),t[outgoingEnded]?.()},isPromise=e=>typeof e.then==`function`,responseViaResponseObject=async(e,t,s={})=>{if(isPromise(e))if(s.errorHandler)try{e=await e}catch(t){let g=await s.errorHandler(t);if(!g)return;e=g}else e=await e.catch(handleFetchError);if(cacheKey in e)return responseViaCache(e,t);let g=buildOutgoingHttpHeaders(e.headers);if(e.body){let s=e.body.getReader(),S=[],w=!1,E;if(g[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){E||=s.read();let g=await readWithoutBlocking(E).catch(e=>{console.error(e),w=!0});if(!g){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(E=void 0,g.value&&S.push(g.value),g.done){w=!0;break}}w&&!(`content-length`in g)&&(g[`content-length`]=S.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,g),S.forEach(e=>{t.write(e)}),w?t.end():(S.length===0&&flushHeaders(t),await writeFromReadableStreamDefaultReader(s,t,E))}else g[X_ALREADY_SENT]||(t.writeHead(e.status,g),t.end());t[outgoingEnded]?.()},getRequestListener=(e,t={})=>{let s=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Request$1&&(Object.defineProperty(global,`Request`,{value:Request$1}),Object.defineProperty(global,`Response`,{value:Response2})),async(g,S)=>{let w,E;try{E=newRequest(g,t.hostname);let D=!s||g.method===`GET`||g.method===`HEAD`;if(D||(g[wrapBodyStream]=!0,g.on(`end`,()=>{D=!0}),g instanceof Http2ServerRequest&&(S[outgoingEnded]=()=>{D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),S.on(`finish`,()=>{D||drainIncoming(g)})),S.on(`close`,()=>{E[abortControllerKey]&&(g.errored?E[abortControllerKey].abort(g.errored.toString()):S.writableFinished||E[abortControllerKey].abort(`Client connection prematurely closed.`)),D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),w=e(E,{incoming:g,outgoing:S}),cacheKey in w)return responseViaCache(w,S)}catch(e){if(w)return handleResponseError(e,S);if(t.errorHandler){if(w=await t.errorHandler(E?e:toRequestError(e)),!w)return}else w=E?handleFetchError(e):handleRequestError()}try{return await responseViaResponseObject(w,S,t)}catch(e){return handleResponseError(e,S)}}},WebStandardStreamableHTTPServerTransport=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,s,g){let S={code:t,message:s};return g?.data!==void 0&&(S.data=g.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:S,id:null}),{status:e,headers:{"Content-Type":`application/json`,...g?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let s=this.validateRequestHeaders(e);if(s)return s;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,s,g){if(!this._eventStore||g<`2025-11-25`)return;let S=await this._eventStore.storeEvent(s,{}),w=`id: ${S}\ndata: \n\n`;this._retryInterval!==void 0&&(w=`id: ${S}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(w))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),E={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(E[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{S.close()}catch{}}}),new Response(w,{headers:E})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let s={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(s[`mcp-session-id`]=this.sessionId);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{}}),E=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(S,g,t,e)){this.onerror?.(Error(`Failed replay events`));try{S.close()}catch{}}}});return this._streamMapping.set(E,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(E);try{S.close()}catch{}}}),new Response(w,{headers:s})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,s,g){try{let S=`event: message
50
+ deps: ${g}}`};let S={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,s]=w(e);E(e,t),D(e,s)}};function w({schema:e}){let t={},s={};for(let g in e){if(g===`__proto__`)continue;let S=Array.isArray(e[g])?t:s;S[g]=e[g]}return[t,s]}function E(e,s=e.schema){let{gen:S,data:w,it:E}=e;if(Object.keys(s).length===0)return;let D=S.let(`missing`);for(let O in s){let k=s[O];if(k.length===0)continue;let j=(0,g.propertyInData)(S,w,O,E.opts.ownProperties);e.setParams({property:O,depsCount:k.length,deps:k.join(`, `)}),E.allErrors?S.if(j,()=>{for(let t of k)(0,g.checkReportMissingProp)(e,t)}):(S.if((0,t._)`${j} && (${(0,g.checkMissingProp)(e,k,D)})`),(0,g.reportMissingProp)(e,D),S.else())}}e.validatePropertyDeps=E;function D(e,t=e.schema){let{gen:S,data:w,keyword:E,it:D}=e,O=S.name(`valid`);for(let k in t)(0,s.alwaysValidSchema)(D,t[k])||(S.if((0,g.propertyInData)(S,w,k,D.opts.ownProperties),()=>{let t=e.subschema({keyword:E,schemaProp:k},O);e.mergeValidEvaluated(t,O)},()=>S.var(O,!0)),e.ok(O))}e.validateSchemaDeps=D,e.default=S})),require_propertyNames=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:g,schema:S,data:w,it:E}=e;if((0,s.alwaysValidSchema)(E,S))return;let D=g.name(`valid`);g.forIn(`key`,w,s=>{e.setParams({propertyName:s}),e.subschema({keyword:`propertyNames`,data:s,dataTypes:[`string`],propertyName:s,compositeRule:!0},D),g.if((0,t.not)(D),()=>{e.error(!0),E.allErrors||g.break()})}),e.ok(D)}}})),require_additionalProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_names(),S=require_util();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,s._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:w,schema:E,parentSchema:D,data:O,errsCount:k,it:j}=e;if(!k)throw Error(`ajv implementation error`);let{allErrors:F,opts:L}=j;if(j.props=!0,L.removeAdditional!==`all`&&(0,S.alwaysValidSchema)(j,E))return;let B=(0,t.allSchemaProperties)(D.properties),H=(0,t.allSchemaProperties)(D.patternProperties);q(),e.ok((0,s._)`${k} === ${g.default.errors}`);function q(){w.forIn(`key`,O,e=>{!B.length&&!H.length?Y(e):w.if(ee(e),()=>Y(e))})}function ee(g){let E;if(B.length>8){let e=(0,S.schemaRefOrVal)(j,D.properties,`properties`);E=(0,t.isOwnProperty)(w,e,g)}else E=B.length?(0,s.or)(...B.map(e=>(0,s._)`${g} === ${e}`)):s.nil;return H.length&&(E=(0,s.or)(E,...H.map(S=>(0,s._)`${(0,t.usePattern)(e,S)}.test(${g})`))),(0,s.not)(E)}function J(e){w.code((0,s._)`delete ${O}[${e}]`)}function Y(t){if(L.removeAdditional===`all`||L.removeAdditional&&E===!1){J(t);return}if(E===!1){e.setParams({additionalProperty:t}),e.error(),F||w.break();return}if(typeof E==`object`&&!(0,S.alwaysValidSchema)(j,E)){let g=w.name(`valid`);L.removeAdditional===`failing`?(te(t,g,!1),w.if((0,s.not)(g),()=>{e.reset(),J(t)})):(te(t,g),F||w.if((0,s.not)(g),()=>w.break()))}}function te(t,s,g){let w={keyword:`additionalProperties`,dataProp:t,dataPropType:S.Type.Str};g===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,s)}}}})),require_properties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_validate(),s=require_code(),g=require_util(),S=require_additionalProperties();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,parentSchema:D,data:O,it:k}=e;k.opts.removeAdditional===`all`&&D.additionalProperties===void 0&&S.default.code(new t.KeywordCxt(k,S.default,`additionalProperties`));let j=(0,s.allSchemaProperties)(E);for(let e of j)k.definedProperties.add(e);k.opts.unevaluated&&j.length&&k.props!==!0&&(k.props=g.mergeEvaluated.props(w,(0,g.toHash)(j),k.props));let F=j.filter(e=>!(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0)return;let L=w.name(`valid`);for(let t of F)B(t)?H(t):(w.if((0,s.propertyInData)(w,O,t,k.opts.ownProperties)),H(t),k.allErrors||w.else().var(L,!0),w.endIf()),e.it.definedProperties.add(t),e.ok(L);function B(e){return k.opts.useDefaults&&!k.compositeRule&&E[e].default!==void 0}function H(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},L)}}}})),require_patternProperties=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_code(),s=require_codegen(),g=require_util(),S=require_util();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:w,schema:E,data:D,parentSchema:O,it:k}=e,{opts:j}=k,F=(0,t.allSchemaProperties)(E),L=F.filter(e=>(0,g.alwaysValidSchema)(k,E[e]));if(F.length===0||L.length===F.length&&(!k.opts.unevaluated||k.props===!0))return;let B=j.strictSchema&&!j.allowMatchingProperties&&O.properties,H=w.name(`valid`);k.props!==!0&&!(k.props instanceof s.Name)&&(k.props=(0,S.evaluatedPropsToName)(w,k.props));let{props:q}=k;ee();function ee(){for(let e of F)B&&J(e),k.allErrors?Y(e):(w.var(H,!0),Y(e),w.if(H))}function J(e){for(let t in B)new RegExp(e).test(t)&&(0,g.checkStrictMode)(k,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function Y(g){w.forIn(`key`,D,E=>{w.if((0,s._)`${(0,t.usePattern)(e,g)}.test(${E})`,()=>{let t=L.includes(g);t||e.subschema({keyword:`patternProperties`,schemaProp:g,dataProp:E,dataPropType:S.Type.Str},H),k.opts.unevaluated&&q!==!0?w.assign((0,s._)`${q}[${E}]`,!0):!t&&!k.allErrors&&w.if((0,s.not)(H),()=>w.break())})})}}}})),require_not=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:s,schema:g,it:S}=e;if((0,t.alwaysValidSchema)(S,g)){e.fail();return}let w=s.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},w),e.failResult(w,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),require_anyOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:require_code().validateUnion,error:{message:`must match a schema in anyOf`}}})),require_oneOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:g,schema:S,parentSchema:w,it:E}=e;if(!Array.isArray(S))throw Error(`ajv implementation error`);if(E.opts.discriminator&&w.discriminator)return;let D=S,O=g.let(`valid`,!1),k=g.let(`passing`,null),j=g.name(`_valid`);e.setParams({passing:k}),g.block(F),e.result(O,()=>e.reset(),()=>e.error(!0));function F(){D.forEach((S,w)=>{let D;(0,s.alwaysValidSchema)(E,S)?g.var(j,!0):D=e.subschema({keyword:`oneOf`,schemaProp:w,compositeRule:!0},j),w>0&&g.if((0,t._)`${j} && ${O}`).assign(O,!1).assign(k,(0,t._)`[${k}, ${w}]`).else(),g.if(j,()=>{g.assign(O,!0),g.assign(k,w),D&&e.mergeEvaluated(D,t.Name)})})}}}})),require_allOf=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:s,schema:g,it:S}=e;if(!Array.isArray(g))throw Error(`ajv implementation error`);let w=s.name(`valid`);g.forEach((s,g)=>{if((0,t.alwaysValidSchema)(S,s))return;let E=e.subschema({keyword:`allOf`,schemaProp:g},w);e.ok(w),e.mergeEvaluated(E)})}}})),require_if=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_util(),g={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:g,parentSchema:w,it:E}=e;w.then===void 0&&w.else===void 0&&(0,s.checkStrictMode)(E,`"if" without "then" and "else" is ignored`);let D=S(E,`then`),O=S(E,`else`);if(!D&&!O)return;let k=g.let(`valid`,!0),j=g.name(`_valid`);if(F(),e.reset(),D&&O){let t=g.let(`ifClause`);e.setParams({ifClause:t}),g.if(j,L(`then`,t),L(`else`,t))}else D?g.if(j,L(`then`)):g.if((0,t.not)(j),L(`else`));e.pass(k,()=>e.error(!0));function F(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},j);e.mergeEvaluated(t)}function L(s,S){return()=>{let w=e.subschema({keyword:s},j);g.assign(k,j),e.mergeValidEvaluated(w,k),S?g.assign(S,(0,t._)`${s}`):e.setParams({ifClause:s})}}}};function S(e,t){let g=e.schema[t];return g!==void 0&&!(0,s.alwaysValidSchema)(e,g)}e.default=g})),require_thenElse=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_util();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:s,it:g}){s.if===void 0&&(0,t.checkStrictMode)(g,`"${e}" without "if" is ignored`)}}})),require_applicator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_additionalItems(),s=require_prefixItems(),g=require_items(),S=require_items2020(),w=require_contains(),E=require_dependencies(),D=require_propertyNames(),O=require_additionalProperties(),k=require_properties(),j=require_patternProperties(),F=require_not(),L=require_anyOf(),B=require_oneOf(),H=require_allOf(),q=require_if(),ee=require_thenElse();function J(e=!1){let J=[F.default,L.default,B.default,H.default,q.default,ee.default,D.default,O.default,E.default,k.default,j.default];return e?J.push(s.default,S.default):J.push(t.default,g.default),J.push(w.default),J}e.default=J})),require_format$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,s){let{gen:g,data:S,$data:w,schema:E,schemaCode:D,it:O}=e,{opts:k,errSchemaPath:j,schemaEnv:F,self:L}=O;if(!k.validateFormats)return;w?B():H();function B(){let w=g.scopeValue(`formats`,{ref:L.formats,code:k.code.formats}),E=g.const(`fDef`,(0,t._)`${w}[${D}]`),O=g.let(`fType`),j=g.let(`format`);g.if((0,t._)`typeof ${E} == "object" && !(${E} instanceof RegExp)`,()=>g.assign(O,(0,t._)`${E}.type || "string"`).assign(j,(0,t._)`${E}.validate`),()=>g.assign(O,(0,t._)`"string"`).assign(j,E)),e.fail$data((0,t.or)(B(),H()));function B(){return k.strictSchema===!1?t.nil:(0,t._)`${D} && !${j}`}function H(){let e=F.$async?(0,t._)`(${E}.async ? await ${j}(${S}) : ${j}(${S}))`:(0,t._)`${j}(${S})`,g=(0,t._)`(typeof ${j} == "function" ? ${e} : ${j}.test(${S}))`;return(0,t._)`${j} && ${j} !== true && ${O} === ${s} && !${g}`}}function H(){let w=L.formats[E];if(!w){H();return}if(w===!0)return;let[D,O,B]=q(w);D===s&&e.pass(ee());function H(){if(k.strictSchema===!1){L.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${E}" ignored in schema at path "${j}"`}}function q(e){let s=e instanceof RegExp?(0,t.regexpCode)(e):k.code.formats?(0,t._)`${k.code.formats}${(0,t.getProperty)(E)}`:void 0,S=g.scopeValue(`formats`,{key:E,ref:e,code:s});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${S}.validate`]:[`string`,e,S]}function ee(){if(typeof w==`object`&&!(w instanceof RegExp)&&w.async){if(!F.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${B}(${S})`}return typeof O==`function`?(0,t._)`${B}(${S})`:(0,t._)`${B}.test(${S})`}}}}})),require_format=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[require_format$1().default]})),require_metadata=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),require_draft7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_core(),s=require_validation$1(),g=require_applicator(),S=require_format(),w=require_metadata();e.default=[t.default,s.default,(0,g.default)(),S.default,w.metadataVocabulary,w.contentVocabulary]})),require_types=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),require_discriminator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen(),s=require_types(),g=require_compile(),S=require_ref_error(),w=require_util();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===s.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:s,tagName:g}})=>(0,t._)`{error: ${e}, tag: ${g}, tagValue: ${s}}`},code(e){let{gen:E,data:D,schema:O,parentSchema:k,it:j}=e,{oneOf:F}=k;if(!j.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let L=O.propertyName;if(typeof L!=`string`)throw Error(`discriminator: requires propertyName`);if(O.mapping)throw Error(`discriminator: mapping is not supported`);if(!F)throw Error(`discriminator: requires oneOf keyword`);let B=E.let(`valid`,!1),H=E.const(`tag`,(0,t._)`${D}${(0,t.getProperty)(L)}`);E.if((0,t._)`typeof ${H} == "string"`,()=>q(),()=>e.error(!1,{discrError:s.DiscrError.Tag,tag:H,tagName:L})),e.ok(B);function q(){let g=J();E.if(!1);for(let e in g)E.elseIf((0,t._)`${H} === ${e}`),E.assign(B,ee(g[e]));E.else(),e.error(!1,{discrError:s.DiscrError.Mapping,tag:H,tagName:L}),E.endIf()}function ee(s){let g=E.name(`valid`),S=e.subschema({keyword:`oneOf`,schemaProp:s},g);return e.mergeEvaluated(S,t.Name),g}function J(){var e;let t={},s=D(k),E=!0;for(let e=0;e<F.length;e++){let t=F[e];if(t?.$ref&&!(0,w.schemaHasRulesButRef)(t,j.self.RULES)){let e=t.$ref;if(t=g.resolveRef.call(j.self,j.schemaEnv.root,j.baseId,e),t instanceof g.SchemaEnv&&(t=t.schema),t===void 0)throw new S.default(j.opts.uriResolver,j.baseId,e)}let k=t?.properties?.[L];if(typeof k!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${L}"`);E&&=s||D(t),O(k,e)}if(!E)throw Error(`discriminator: "${L}" must be required`);return t;function D({required:e}){return Array.isArray(e)&&e.includes(L)}function O(e,t){if(e.const)B(e.const,t);else if(e.enum)for(let s of e.enum)B(s,t);else throw Error(`discriminator: "properties/${L}" must have "const" or "enum"`)}function B(e,s){if(typeof e!=`string`||e in t)throw Error(`discriminator: "${L}" values must be unique strings`);t[e]=s}}}}})),require_json_schema_draft_07=__commonJSMin$2(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),require_ajv=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let s=require_core$1(),g=require_draft7(),S=require_discriminator(),w=require_json_schema_draft_07(),E=[`/properties`],D=`http://json-schema.org/draft-07/schema`;var O=class extends s.default{_addVocabularies(){super._addVocabularies(),g.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(S.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(w,E):w;this.addMetaSchema(e,D,!1),this.refs[`http://json-schema.org/schema`]=D}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(D)?D:void 0)}};e.Ajv=O,t.exports=e=O,t.exports.Ajv=O,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=O;var k=require_validate();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return k.KeywordCxt}});var j=require_codegen();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return j._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return j.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return j.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return j.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return j.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return j.CodeGen}});var F=require_validation_error();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return F.default}});var L=require_ref_error();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return L.default}})})),require_formats=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(w,E),time:t(O(!0),k),"date-time":t(L(!0),B),"iso-time":t(O(),j),"iso-date-time":t(L(),H),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:J,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:de,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:te,int32:{type:`number`,validate:oe},int64:{type:`number`,validate:se},float:{type:`number`,validate:ce},double:{type:`number`,validate:ce},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,E),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,k),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,B),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,j),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,H),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function s(e){return e%4==0&&(e%100!=0||e%400==0)}let g=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,S=[0,31,28,31,30,31,30,31,31,30,31,30,31];function w(e){let t=g.exec(e);if(!t)return!1;let w=+t[1],E=+t[2],D=+t[3];return E>=1&&E<=12&&D>=1&&D<=(E===2&&s(w)?29:S[E])}function E(e,t){if(e&&t)return e>t?1:e<t?-1:0}let D=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function O(e){return function(t){let s=D.exec(t);if(!s)return!1;let g=+s[1],S=+s[2],w=+s[3],E=s[4],O=s[5]===`-`?-1:1,k=+(s[6]||0),j=+(s[7]||0);if(k>23||j>59||e&&!E)return!1;if(g<=23&&S<=59&&w<60)return!0;let F=S-j*O,L=g-k*O-(F<0?1:0);return(L===23||L===-1)&&(F===59||F===-1)&&w<61}}function k(e,t){if(!(e&&t))return;let s=new Date(`2020-01-01T`+e).valueOf(),g=new Date(`2020-01-01T`+t).valueOf();if(s&&g)return s-g}function j(e,t){if(!(e&&t))return;let s=D.exec(e),g=D.exec(t);if(s&&g)return e=s[1]+s[2]+s[3],t=g[1]+g[2]+g[3],e>t?1:e<t?-1:0}let F=/t|\s/i;function L(e){let t=O(e);return function(e){let s=e.split(F);return s.length===2&&w(s[0])&&t(s[1])}}function B(e,t){if(!(e&&t))return;let s=new Date(e).valueOf(),g=new Date(t).valueOf();if(s&&g)return s-g}function H(e,t){if(!(e&&t))return;let[s,g]=e.split(F),[S,w]=t.split(F),D=E(s,S);if(D!==void 0)return D||k(g,w)}let q=/\/|:/,ee=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function J(e){return q.test(e)&&ee.test(e)}let Y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function te(e){return Y.lastIndex=0,Y.test(e)}let ne=-(2**31),ae=2**31-1;function oe(e){return Number.isInteger(e)&&e<=ae&&e>=ne}function se(e){return Number.isInteger(e)}function ce(){return!0}let ue=/[^\\]\\Z/;function de(e){if(ue.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),require_limit=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=require_ajv(),s=require_codegen(),g=s.operators,S={formatMaximum:{okStr:`<=`,ok:g.LTE,fail:g.GT},formatMinimum:{okStr:`>=`,ok:g.GTE,fail:g.LT},formatExclusiveMaximum:{okStr:`<`,ok:g.LT,fail:g.GTE},formatExclusiveMinimum:{okStr:`>`,ok:g.GT,fail:g.LTE}};e.formatLimitDefinition={keyword:Object.keys(S),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,s.str)`should be ${S[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,s._)`{comparison: ${S[e].okStr}, limit: ${t}}`},code(e){let{gen:g,data:w,schemaCode:E,keyword:D,it:O}=e,{opts:k,self:j}=O;if(!k.validateFormats)return;let F=new t.KeywordCxt(O,j.RULES.all.format.definition,`format`);F.$data?L():B();function L(){let t=g.scopeValue(`formats`,{ref:j.formats,code:k.code.formats}),S=g.const(`fmt`,(0,s._)`${t}[${F.schemaCode}]`);e.fail$data((0,s.or)((0,s._)`typeof ${S} != "object"`,(0,s._)`${S} instanceof RegExp`,(0,s._)`typeof ${S}.compare != "function"`,H(S)))}function B(){let t=F.schema,S=j.formats[t];if(!S||S===!0)return;if(typeof S!=`object`||S instanceof RegExp||typeof S.compare!=`function`)throw Error(`"${D}": format "${t}" does not define "compare" function`);let w=g.scopeValue(`formats`,{key:t,ref:S,code:k.code.formats?(0,s._)`${k.code.formats}${(0,s.getProperty)(t)}`:void 0});e.fail$data(H(w))}function H(e){return(0,s._)`${e}.compare(${w}, ${E}) ${S[D].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),require_dist=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let s=require_formats(),g=require_limit(),S=require_codegen(),w=new S.Name(`fullFormats`),E=new S.Name(`fastFormats`),D=(e,t={keywords:!0})=>{if(Array.isArray(t))return O(e,t,s.fullFormats,w),e;let[S,D]=t.mode===`fast`?[s.fastFormats,E]:[s.fullFormats,w];return O(e,t.formats||s.formatNames,S,D),t.keywords&&(0,g.default)(e),e};D.get=(e,t=`full`)=>{let g=(t===`fast`?s.fastFormats:s.fullFormats)[e];if(!g)throw Error(`Unknown format "${e}"`);return g};function O(e,t,s,g){var w,E;(E=e.opts.code).formats??(E.formats=(0,S._)`require("ajv-formats/dist/formats").${g}`);for(let g of t)e.addFormat(g,s[g])}t.exports=e=D,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=D})),import_ajv=__toESM$2(require_ajv(),1),import_dist=__toESM$2(require_dist(),1);function createDefaultAjvInstance(){let e=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_dist.default)(e),e}var AjvJsonSchemaValidator=class{constructor(e){this._ajv=e??createDefaultAjvInstance()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},ExperimentalServerTasks=class{constructor(e){this._server=e}requestStream(e,t,s){return this._server.requestStream(e,t,s)}createMessageStream(e,t){let s=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!s?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}elicitInputStream(e,t){let s=this._server.getClientCapabilities(),g=e.mode??`form`;switch(g){case`url`:if(!s?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!s?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let S=g===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:S},ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,s){return this._server.getTaskResult({taskId:e},t,s)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function assertToolsCallTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${s} does not support task creation for tools/call (required for ${t})`);break;default:break}}function assertClientRequestTaskCapability(e,t,s){if(!e)throw Error(`${s} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${s} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${s} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Server=class extends Protocol{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let s=this._loggingLevels.get(t);return s?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(e,t)=>{let s=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:g}=e.params,S=LoggingLevelSchema.safeParse(g);return S.success&&this._loggingLevels.set(s,S.data),{}})}get experimental(){return this._experimental||={tasks:new ExperimentalServerTasks(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=mergeCapabilities(this._capabilities,e)}setRequestHandler(e,t){let s=getObjectShape(e)?.method;if(!s)throw Error(`Schema is missing a method literal`);let g;if(isZ4Schema(s)){let e=s;g=e._zod?.def?.value??e.value}else{let e=s;g=e._def?.value??e.value}if(typeof g!=`string`)throw Error(`Schema method literal must be a string`);return g===`tools/call`?super.setRequestHandler(e,async(e,s)=>{let g=safeParse(CallToolRequestSchema,e);if(!g.success){let e=g.error instanceof Error?g.error.message:String(g.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:S}=g.data,w=await Promise.resolve(t(e,s));if(S.task){let e=safeParse(CreateTaskResultSchema,w);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let E=safeParse(CallToolResultSchema,w);if(!E.success){let e=E.error instanceof Error?E.error.message:String(E.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return E.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],s=Array.isArray(t.content)?t.content:[t.content],g=s.some(e=>e.type===`tool_result`),S=e.messages.length>1?e.messages[e.messages.length-2]:void 0,w=S?Array.isArray(S.content)?S.content:[S.content]:[],E=w.some(e=>e.type===`tool_use`);if(g){if(s.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!E)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(E){let e=new Set(w.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(s.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},CreateMessageResultWithToolsSchema,t):this.request({method:`sampling/createMessage`,params:e},CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let s=e;return this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let s=e.mode===`form`?e:{...e,mode:`form`},g=await this.request({method:`elicitation/create`,params:s},ElicitResultSchema,t);if(g.action===`accept`&&g.content&&s.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(s.requestedSchema)(g.content);if(!e.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return g}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const COMPLETABLE_SYMBOL=Symbol.for(`mcp.completable`);function isCompletable(e){return!!e&&typeof e==`object`&&COMPLETABLE_SYMBOL in e}function getCompleter(e){return e[COMPLETABLE_SYMBOL]?.complete}var McpZodTypeKind;(function(e){e.Completable=`McpCompletable`})(McpZodTypeKind||={});const TOOL_NAME_REGEX=/^[A-Za-z0-9._-]{1,128}$/;function validateToolName(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!TOOL_NAME_REGEX.test(e)){let s=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,s)=>s.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${s.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function issueToolNameWarning(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function validateAndWarnToolName(e){let t=validateToolName(e);return issueToolNameWarning(e,t.warnings),t.isValid}var ExperimentalMcpServerTasks=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,s){let g={taskSupport:`required`,...t.execution};if(g.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,g,t._meta,s)}},McpServer=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Server(e,t)}get experimental(){return this._experimental||={tasks:new ExperimentalMcpServerTasks(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let s={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=normalizeObjectSchema(t.inputSchema);return e?toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`input`}):EMPTY_OBJECT_JSON_SCHEMA})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=normalizeObjectSchema(t.outputSchema);e&&(s.outputSchema=toJsonSchemaCompat(e,{strictUnions:!0,pipeStrategy:`output`}))}return s})})),this.server.setRequestHandler(CallToolRequestSchema,async(e,t)=>{try{let s=this._registeredTools[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let g=!!e.params.task,S=s.execution?.taskSupport,w=`createTask`in s.handler;if((S===`required`||S===`optional`)&&!w)throw new McpError(ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${S}' but was not registered with registerToolTask`);if(S===`required`&&!g)throw new McpError(ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(S===`optional`&&!g&&w)return await this.handleAutomaticTaskPolling(s,e,t);let E=await this.validateToolInput(s,e.params.arguments,e.params.name),D=await this.executeToolHandler(s,E,t);return g||await this.validateToolOutput(s,D,e.params.name),D}catch(e){if(e instanceof McpError&&e.code===ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,s){if(!e.inputSchema)return;let g=await safeParseAsync(normalizeObjectSchema(e.inputSchema)??e.inputSchema,t);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${s}: ${e}`)}return g.data}async validateToolOutput(e,t,s){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new McpError(ErrorCode.InvalidParams,`Output validation error: Tool ${s} has an output schema but no structured content was provided`);let g=await safeParseAsync(normalizeObjectSchema(e.outputSchema),t.structuredContent);if(!g.success){let e=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${s}: ${e}`)}}async executeToolHandler(e,t,s){let g=e.handler;if(`createTask`in g){if(!s.taskStore)throw Error(`No task store provided.`);let S={...s,taskStore:s.taskStore};if(e.inputSchema){let e=g;return await Promise.resolve(e.createTask(t,S))}else{let e=g;return await Promise.resolve(e.createTask(S))}}if(e.inputSchema){let e=g;return await Promise.resolve(e(t,s))}else{let e=g;return await Promise.resolve(e(s))}}async handleAutomaticTaskPolling(e,t,s){if(!s.taskStore)throw Error(`No task store provided for task-capable tool.`);let g=await this.validateToolInput(e,t.params.arguments,t.params.name),S=e.handler,w={...s,taskStore:s.taskStore},E=g?await Promise.resolve(S.createTask(g,w)):await Promise.resolve(S.createTask(w)),D=E.task.taskId,O=E.task,k=O.pollInterval??5e3;for(;O.status!==`completed`&&O.status!==`failed`&&O.status!==`cancelled`;){await new Promise(e=>setTimeout(e,k));let e=await s.taskStore.getTask(D);if(!e)throw new McpError(ErrorCode.InternalError,`Task ${D} not found during polling`);O=e}return await s.taskStore.getTaskResult(D)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CompleteRequestSchema,async e=>{switch(e.params.ref.type){case`ref/prompt`:return assertCompleteRequestPrompt(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return assertCompleteRequestResourceTemplate(e),this.handleResourceCompletion(e,e.params.ref);default:throw new McpError(ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let s=this._registeredPrompts[t.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!s.argsSchema)return EMPTY_COMPLETION_RESULT;let g=getObjectShape(s.argsSchema)?.[e.params.argument.name];if(!isCompletable(g))return EMPTY_COMPLETION_RESULT;let S=getCompleter(g);return S?createCompletionResult(await S(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}async handleResourceCompletion(e,t){let s=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!s){if(this._registeredResources[t.uri])return EMPTY_COMPLETION_RESULT;throw new McpError(ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let g=s.resourceTemplate.completeCallback(e.params.argument.name);return g?createCompletionResult(await g(e.params.argument.value,e.params.context)):EMPTY_COMPLETION_RESULT}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ListResourcesRequestSchema,async(e,t)=>{let s=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),g=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let s=await e.resourceTemplate.listCallback(t);for(let t of s.resources)g.push({...e.metadata,...t})}return{resources:[...s,...g]}}),this.server.setRequestHandler(ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ReadResourceRequestSchema,async(e,t)=>{let s=new URL(e.params.uri),g=this._registeredResources[s.toString()];if(g){if(!g.enabled)throw new McpError(ErrorCode.InvalidParams,`Resource ${s} disabled`);return g.readCallback(s,t)}for(let e of Object.values(this._registeredResourceTemplates)){let g=e.resourceTemplate.uriTemplate.match(s.toString());if(g)return e.readCallback(s,g,t)}throw new McpError(ErrorCode.InvalidParams,`Resource ${s} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?promptArgumentsFromSchema(t.argsSchema):void 0}))})),this.server.setRequestHandler(GetPromptRequestSchema,async(e,t)=>{let s=this._registeredPrompts[e.params.name];if(!s)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!s.enabled)throw new McpError(ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(s.argsSchema){let g=await safeParseAsync(normalizeObjectSchema(s.argsSchema),e.params.arguments);if(!g.success){let t=getParseErrorMessage(`error`in g?g.error:`Unknown error`);throw new McpError(ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let S=g.data,w=s.callback;return await Promise.resolve(w(S,t))}else{let e=s.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...s){let g;typeof s[0]==`object`&&(g=s.shift());let S=s[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,g,S);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,s,g){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let S=this._createRegisteredResource(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let S=this._createRegisteredResourceTemplate(e,s.title,t,s,g);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),S}}_createRegisteredResource(e,t,s,g,S){let w={name:e,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==s&&(delete this._registeredResources[s],e.uri&&(this._registeredResources[e.uri]=w)),e.name!==void 0&&(w.name=e.name),e.title!==void 0&&(w.title=e.title),e.metadata!==void 0&&(w.metadata=e.metadata),e.callback!==void 0&&(w.readCallback=e.callback),e.enabled!==void 0&&(w.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[s]=w,w}_createRegisteredResourceTemplate(e,t,s,g,S){let w={resourceTemplate:s,title:t,metadata:g,readCallback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.template!==void 0&&(w.resourceTemplate=t.template),t.metadata!==void 0&&(w.metadata=t.metadata),t.callback!==void 0&&(w.readCallback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=w;let E=s.uriTemplate.variableNames;return Array.isArray(E)&&E.some(e=>!!s.completeCallback(e))&&this.setCompletionRequestHandler(),w}_createRegisteredPrompt(e,t,s,g,S){let w={title:t,description:s,argsSchema:g===void 0?void 0:objectFromShape(g),callback:S,enabled:!0,disable:()=>w.update({enabled:!1}),enable:()=>w.update({enabled:!0}),remove:()=>w.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=w)),t.title!==void 0&&(w.title=t.title),t.description!==void 0&&(w.description=t.description),t.argsSchema!==void 0&&(w.argsSchema=objectFromShape(t.argsSchema)),t.callback!==void 0&&(w.callback=t.callback),t.enabled!==void 0&&(w.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=w,g&&Object.values(g).some(e=>isCompletable(e instanceof ZodOptional$1?e._def?.innerType:e))&&this.setCompletionRequestHandler(),w}_createRegisteredTool(e,t,s,g,S,w,E,D,O){validateAndWarnToolName(e);let k={title:t,description:s,inputSchema:getZodSchemaObject(g),outputSchema:getZodSchemaObject(S),annotations:w,execution:E,_meta:D,handler:O,enabled:!0,disable:()=>k.update({enabled:!1}),enable:()=>k.update({enabled:!0}),remove:()=>k.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&validateAndWarnToolName(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=k)),t.title!==void 0&&(k.title=t.title),t.description!==void 0&&(k.description=t.description),t.paramsSchema!==void 0&&(k.inputSchema=objectFromShape(t.paramsSchema)),t.outputSchema!==void 0&&(k.outputSchema=objectFromShape(t.outputSchema)),t.callback!==void 0&&(k.handler=t.callback),t.annotations!==void 0&&(k.annotations=t.annotations),t._meta!==void 0&&(k._meta=t._meta),t.enabled!==void 0&&(k.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=k,this.setToolRequestHandlers(),this.sendToolListChanged(),k}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let s,g,S,w;if(typeof t[0]==`string`&&(s=t.shift()),t.length>1){let s=t[0];if(isZodRawShapeCompat(s))g=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!isZodRawShapeCompat(t[0])&&(w=t.shift());else if(typeof s==`object`&&s){if(Object.values(s).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);w=t.shift()}}let E=t[0];return this._createRegisteredTool(e,void 0,s,g,void 0,w,{taskSupport:`forbidden`},void 0,E)}registerTool(e,t,s){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:g,description:S,inputSchema:w,outputSchema:E,annotations:D,_meta:O}=t;return this._createRegisteredTool(e,g,S,w,E,D,{taskSupport:`forbidden`},O,s)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let s;typeof t[0]==`string`&&(s=t.shift());let g;t.length>1&&(g=t.shift());let S=t[0],w=this._createRegisteredPrompt(e,void 0,s,g,S);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),w}registerPrompt(e,t,s){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:g,description:S,argsSchema:w}=t,E=this._createRegisteredPrompt(e,g,S,w,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),E}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const EMPTY_OBJECT_JSON_SCHEMA={type:`object`,properties:{}};function isZodTypeLike(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function isZodSchemaInstance(e){return`_def`in e||`_zod`in e||isZodTypeLike(e)}function isZodRawShapeCompat(e){return typeof e!=`object`||!e||isZodSchemaInstance(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(isZodTypeLike)}function getZodSchemaObject(e){if(e){if(isZodRawShapeCompat(e))return objectFromShape(e);if(!isZodSchemaInstance(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function promptArgumentsFromSchema(e){let t=getObjectShape(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:getSchemaDescription(t),required:!isSchemaOptional(t)})):[]}function getMethodValue(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let s=getLiteralValue(t);if(typeof s==`string`)return s;throw Error(`Schema method literal must be a string`)}function createCompletionResult(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const EMPTY_COMPLETION_RESULT={completion:{values:[],hasMore:!1}};var RequestError=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},toRequestError=e=>e instanceof RequestError?e:new RequestError(e.message,{cause:e}),GlobalRequest=global.Request,Request$1=class extends GlobalRequest{constructor(e,t){typeof e==`object`&&getRequestCache in e&&(e=e[getRequestCache]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},newHeadersFromIncoming=e=>{let t=[],s=e.rawHeaders;for(let e=0;e<s.length;e+=2){let{[e]:g,[e+1]:S}=s;g.charCodeAt(0)!==58&&t.push([g,S])}return new Headers(t)},wrapBodyStream=Symbol(`wrapBodyStream`),newRequestFromIncoming=(e,t,s,g,S)=>{let w={method:e,headers:s,signal:S.signal};if(e===`TRACE`){w.method=`GET`;let e=new Request$1(t,w);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in g&&g.rawBody instanceof Buffer)w.body=new ReadableStream({start(e){e.enqueue(g.rawBody),e.close()}});else if(g[wrapBodyStream]){let e;w.body=new ReadableStream({async pull(t){try{e||=Readable$1.toWeb(g).getReader();let{done:s,value:S}=await e.read();s?t.close():t.enqueue(S)}catch(e){t.error(e)}}})}else w.body=Readable$1.toWeb(g);return new Request$1(t,w)},getRequestCache=Symbol(`getRequestCache`),requestCache=Symbol(`requestCache`),incomingKey=Symbol(`incomingKey`),urlKey=Symbol(`urlKey`),headersKey=Symbol(`headersKey`),abortControllerKey=Symbol(`abortControllerKey`),requestPrototype={get method(){return this[incomingKey].method||`GET`},get url(){return this[urlKey]},get headers(){return this[headersKey]||=newHeadersFromIncoming(this[incomingKey])},[Symbol(`getAbortController`)](){return this[getRequestCache](),this[abortControllerKey]},[getRequestCache](){return this[abortControllerKey]||=new AbortController,this[requestCache]||=newRequestFromIncoming(this.method,this[urlKey],this.headers,this[incomingKey],this[abortControllerKey])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(requestPrototype,e,{get(){return this[getRequestCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(requestPrototype,e,{value:function(){return this[getRequestCache]()[e]()}})}),Object.setPrototypeOf(requestPrototype,Request$1.prototype);var newRequest=(e,t)=>{let s=Object.create(requestPrototype);s[incomingKey]=e;let g=e.url||``;if(g[0]!==`/`&&(g.startsWith(`http://`)||g.startsWith(`https://`))){if(e instanceof Http2ServerRequest)throw new RequestError(`Absolute URL for :path is not allowed in HTTP/2`);try{s[urlKey]=new URL(g).href}catch(e){throw new RequestError(`Invalid absolute URL`,{cause:e})}return s}let S=(e instanceof Http2ServerRequest?e.authority:e.headers.host)||t;if(!S)throw new RequestError(`Missing host header`);let w;if(e instanceof Http2ServerRequest){if(w=e.scheme,!(w===`http`||w===`https`))throw new RequestError(`Unsupported scheme`)}else w=e.socket&&e.socket.encrypted?`https`:`http`;let E=new URL(`${w}://${S}${g}`);if(E.hostname.length!==S.length&&E.hostname!==S.replace(/:\d+$/,``))throw new RequestError(`Invalid host header`);return s[urlKey]=E.href,s},responseCache=Symbol(`responseCache`),getResponseCache=Symbol(`getResponseCache`),cacheKey=Symbol(`cache`),GlobalResponse=global.Response,Response2=class e{#e;#t;[getResponseCache](){return delete this[cacheKey],this[responseCache]||=new GlobalResponse(this.#e,this.#t)}constructor(t,s){let g;if(this.#e=t,s instanceof e){let e=s[responseCache];if(e){this.#t=e,this[getResponseCache]();return}else this.#t=s.#t,g=new Headers(s.#t.headers)}else this.#t=s;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[cacheKey]=[s?.status||200,t,g||s?.headers])}get headers(){let e=this[cacheKey];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[getResponseCache]().headers}get status(){return this[cacheKey]?.[0]??this[getResponseCache]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{get(){return this[getResponseCache]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Response2.prototype,e,{value:function(){return this[getResponseCache]()[e]()}})}),Object.setPrototypeOf(Response2,GlobalResponse),Object.setPrototypeOf(Response2.prototype,GlobalResponse.prototype);async function readWithoutBlocking(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function writeFromReadableStreamDefaultReader(e,t,s){let g=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,g),t.on(`error`,g),(s??e.read()).then(E,S),e.closed.finally(()=>{t.off(`close`,g),t.off(`error`,g)});function S(e){e&&t.destroy(e)}function w(){e.read().then(E,S)}function E({done:s,value:g}){try{if(s)t.end();else if(!t.write(g))t.once(`drain`,w);else return e.read().then(E,S)}catch(e){S(e)}}}function writeFromReadableStream(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:writeFromReadableStreamDefaultReader(e.getReader(),t)}var buildOutgoingHttpHeaders=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let s=[];for(let[g,S]of e)g===`set-cookie`?s.push(S):t[g]=S;return s.length>0&&(t[`set-cookie`]=s),t[`content-type`]??=`text/plain; charset=UTF-8`,t},X_ALREADY_SENT=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=crypto$2);var outgoingEnded=Symbol(`outgoingEnded`),incomingDraining=Symbol(`incomingDraining`),DRAIN_TIMEOUT_MS=500,MAX_DRAIN_BYTES=64*1024*1024,drainIncoming=e=>{let t=e;if(e.destroyed||t[incomingDraining])return;if(t[incomingDraining]=!0,e instanceof Http2ServerRequest){try{e.stream?.close?.(constants$3.NGHTTP2_NO_ERROR)}catch{}return}let s=0,g=()=>{clearTimeout(w),e.off(`data`,E),e.off(`end`,g),e.off(`error`,g)},S=()=>{g();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},w=setTimeout(S,DRAIN_TIMEOUT_MS);w.unref?.();let E=e=>{s+=e.length,s>MAX_DRAIN_BYTES&&S()};e.on(`data`,E),e.on(`end`,g),e.on(`error`,g),e.resume()},handleRequestError=()=>new Response(null,{status:400}),handleFetchError=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),handleResponseError=(e,t)=>{let s=e instanceof Error?e:Error(`unknown error`,{cause:e});s.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${s.message}`),t.destroy(s))},flushHeaders=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},responseViaCache=async(e,t)=>{let[s,g,S]=e[cacheKey],w=!1;if(!S)S={"content-type":`text/plain; charset=UTF-8`};else if(S instanceof Headers)w=S.has(`content-length`),S=buildOutgoingHttpHeaders(S);else if(Array.isArray(S)){let e=new Headers(S);w=e.has(`content-length`),S=buildOutgoingHttpHeaders(e)}else for(let e in S)if(e.length===14&&e.toLowerCase()===`content-length`){w=!0;break}w||(typeof g==`string`?S[`Content-Length`]=Buffer.byteLength(g):g instanceof Uint8Array?S[`Content-Length`]=g.byteLength:g instanceof Blob&&(S[`Content-Length`]=g.size)),t.writeHead(s,S),typeof g==`string`||g instanceof Uint8Array?t.end(g):g instanceof Blob?t.end(new Uint8Array(await g.arrayBuffer())):(flushHeaders(t),await writeFromReadableStream(g,t)?.catch(e=>handleResponseError(e,t))),t[outgoingEnded]?.()},isPromise=e=>typeof e.then==`function`,responseViaResponseObject=async(e,t,s={})=>{if(isPromise(e))if(s.errorHandler)try{e=await e}catch(t){let g=await s.errorHandler(t);if(!g)return;e=g}else e=await e.catch(handleFetchError);if(cacheKey in e)return responseViaCache(e,t);let g=buildOutgoingHttpHeaders(e.headers);if(e.body){let s=e.body.getReader(),S=[],w=!1,E;if(g[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){E||=s.read();let g=await readWithoutBlocking(E).catch(e=>{console.error(e),w=!0});if(!g){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(E=void 0,g.value&&S.push(g.value),g.done){w=!0;break}}w&&!(`content-length`in g)&&(g[`content-length`]=S.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,g),S.forEach(e=>{t.write(e)}),w?t.end():(S.length===0&&flushHeaders(t),await writeFromReadableStreamDefaultReader(s,t,E))}else g[X_ALREADY_SENT]||(t.writeHead(e.status,g),t.end());t[outgoingEnded]?.()},getRequestListener=(e,t={})=>{let s=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Request$1&&(Object.defineProperty(global,`Request`,{value:Request$1}),Object.defineProperty(global,`Response`,{value:Response2})),async(g,S)=>{let w,E;try{E=newRequest(g,t.hostname);let D=!s||g.method===`GET`||g.method===`HEAD`;if(D||(g[wrapBodyStream]=!0,g.on(`end`,()=>{D=!0}),g instanceof Http2ServerRequest&&(S[outgoingEnded]=()=>{D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),S.on(`finish`,()=>{D||drainIncoming(g)})),S.on(`close`,()=>{E[abortControllerKey]&&(g.errored?E[abortControllerKey].abort(g.errored.toString()):S.writableFinished||E[abortControllerKey].abort(`Client connection prematurely closed.`)),D||setTimeout(()=>{D||setTimeout(()=>{drainIncoming(g)})})}),w=e(E,{incoming:g,outgoing:S}),cacheKey in w)return responseViaCache(w,S)}catch(e){if(w)return handleResponseError(e,S);if(t.errorHandler){if(w=await t.errorHandler(E?e:toRequestError(e)),!w)return}else w=E?handleFetchError(e):handleRequestError()}try{return await responseViaResponseObject(w,S,t)}catch(e){return handleResponseError(e,S)}}},WebStandardStreamableHTTPServerTransport=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,s,g){let S={code:t,message:s};return g?.data!==void 0&&(S.data=g.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:S,id:null}),{status:e,headers:{"Content-Type":`application/json`,...g?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let s=this.validateRequestHeaders(e);if(s)return s;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,s,g){if(!this._eventStore||g<`2025-11-25`)return;let S=await this._eventStore.storeEvent(s,{}),w=`id: ${S}\ndata: \n\n`;this._retryInterval!==void 0&&(w=`id: ${S}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(w))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),E={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(E[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{S.close()}catch{}}}),new Response(w,{headers:E})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let s={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(s[`mcp-session-id`]=this.sessionId);let g=new TextEncoder,S,w=new ReadableStream({start:e=>{S=e},cancel:()=>{}}),E=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(S,g,t,e)){this.onerror?.(Error(`Failed replay events`));try{S.close()}catch{}}}});return this._streamMapping.set(E,{controller:S,encoder:g,cleanup:()=>{this._streamMapping.delete(E);try{S.close()}catch{}}}),new Response(w,{headers:s})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,s,g){try{let S=`event: message
51
51
  `;return g&&(S+=`id: ${g}\n`),S+=`data: ${JSON.stringify(s)}\n\n`,e.enqueue(t.encode(S)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let s=e.headers.get(`accept`);if(!s?.includes(`application/json`)||!s.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let g=e.headers.get(`content-type`);if(!g||!g.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let S={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},w;if(t?.parsedBody!==void 0)w=t.parsedBody;else try{w=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let E;try{E=Array.isArray(w)?w.map(e=>JSONRPCMessageSchema.parse(e)):[JSONRPCMessageSchema.parse(w)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let D=E.some(isInitializeRequest);if(D){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(E.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!D){let t=this.validateSession(e);if(t)return t;let s=this.validateProtocolVersion(e);if(s)return s}if(!E.some(isJSONRPCRequest)){for(let e of E)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S});return new Response(null,{status:202})}let O=crypto.randomUUID(),k=E.find(e=>isInitializeRequest(e)),j=k?k.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(O,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(O)}});for(let e of E)isJSONRPCRequest(e)&&this._requestToStreamMapping.set(e.id,O);for(let e of E)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S})});let F=new TextEncoder,L,B=new ReadableStream({start:e=>{L=e},cancel:()=>{this._streamMapping.delete(O)}}),H={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(H[`mcp-session-id`]=this.sessionId);for(let e of E)isJSONRPCRequest(e)&&(this._streamMapping.set(O,{controller:L,encoder:F,cleanup:()=>{this._streamMapping.delete(O);try{L.close()}catch{}}}),this._requestToStreamMapping.set(e.id,O));await this.writePrimingEvent(L,F,O,j);for(let e of E){let s,g;isJSONRPCRequest(e)&&this._eventStore&&j>=`2025-11-25`&&(s=()=>{this.closeSSEStream(e.id)},g=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:S,closeSSEStream:s,closeStandaloneSSEStream:g})}return new Response(B,{status:200,headers:H})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!SUPPORTED_PROTOCOL_VERSIONS.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let s=this._streamMapping.get(t);s&&s.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let s=t?.relatedRequestId;if((isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))&&(s=e.id),s===void 0){if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let s=this._streamMapping.get(this._standaloneSseStreamId);if(s===void 0)return;s.controller&&s.encoder&&this.writeSSEEvent(s.controller,s.encoder,e,t);return}let g=this._requestToStreamMapping.get(s);if(!g)throw Error(`No connection established for request ID: ${String(s)}`);let S=this._streamMapping.get(g);if(!this._enableJsonResponse&&S?.controller&&S?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(g,e)),this.writeSSEEvent(S.controller,S.encoder,e,t)}if(isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)){this._requestResponseMap.set(s,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===g).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!S)throw Error(`No connection established for request ID: ${String(s)}`);if(this._enableJsonResponse&&S.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let s=t.map(e=>this._requestResponseMap.get(e));s.length===1?S.resolveJson(new Response(JSON.stringify(s[0]),{status:200,headers:e})):S.resolveJson(new Response(JSON.stringify(s),{status:200,headers:e}))}else S.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},StreamableHTTPServerTransport=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new WebStandardStreamableHTTPServerTransport(e),this._requestListener=getRequestListener(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,s){let g=e.auth;await getRequestListener(async e=>this._webStandardTransport.handleRequest(e,{authInfo:g,parsedBody:s}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}},Ye=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-WsFSMrjp.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-CokinDWR.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-m6K8MBPi.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-BMq2C6AP.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-9ppkyu1-.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-BcuPRlwS.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-CjAZX3M6.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-kkSjZLZ9.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-DiV6v-rq.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-CZIq395W.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-CpScyeFk.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-BgW31dpi.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-DTcVtxaf.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-BaR3b_s7.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-CQ8o4Vkb.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-mZjo68yb.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-bJMe7ljH.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-CN4E-TuS.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-2HUTXO5U-C40o2gtS.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-2HUTXO5U-C40o2gtS.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-2HUTXO5U-C40o2gtS.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-XNF3R3II-BK6WaEMK.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-JAPPVBEU-BGk7n3so.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-BBAGSFUB-J2xHCDg9.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-g5MLXkqb.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-CEP8kP6J.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-CHmFSxue.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-Dh_rqL_i.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-D89jcQ7Z.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-CehGhb2g.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-CiowreCc.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-DdxB9n-y.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-Cgx6V7hj.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-BSxRnNK8.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-DfngOCy5.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-CbCHpRt7.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-DgZtYh2-.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-D4CsWORw.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-DWqB9tv7.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-BKm8apzS.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-DH2ALKQS-DSbKkobO.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-2wWbuvGo.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-COuSzSN5.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-CwBffKRV.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-BrzeR0-x.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-BJC9qdBG.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-BJC9qdBG.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-DCQQF1DX.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-DCQQF1DX.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-CW1hmcPP.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-Bp4XAy4N.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-Uj-a5-Dz.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-Uj-a5-Dz.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-CvTPqJ5U.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-DZw47AKL.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-DZw47AKL.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-LYZFFBZB-Bq_F0mxX.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-7sdZaIym.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-Be83Imv3.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-BUi7854q.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-CrstvTLq.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-CEWGEjty.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-BOZv1JPT.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-HvlCfepP.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-YYCVMXE3-DEtS2Bb0.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-BbHBkH1A.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-DIj6JJG_.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-DDy3JdOM.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-IGDTDPLG-DlvUkVAa.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-DxAcnDx-.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-CiA7qg3p.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-sa5veBMg.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-BGgbS4Fn.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-BeHMNLVT.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-BbTFjdCR.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-DIQMQQUN.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-D7nHvr3D.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-D7nHvr3D.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-D7nHvr3D.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ye.push({name:`tar`,load:async()=>(await import(`./tar-MZQD7NO4-CsVdP0sN.mjs`)).tarCommand}),Ye.push({name:`yq`,load:async()=>(await import(`./yq-OAKYHSXH-tZjjvK0i.mjs`)).yqCommand}),Ye.push({name:`xan`,load:async()=>(await import(`./xan-UD7JYIL2-2nWetB-o.mjs`)).xanCommand}),Ye.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-TE5AIOTF-Dj7QrkUm.mjs`)).sqlite3Command}));var qt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(qt.push({name:`python3`,load:async()=>(await import(`./python3-DNGS4G3E-7DCL_jPA.mjs`)).python3Command}),qt.push({name:`python`,load:async()=>(await import(`./python3-DNGS4G3E-7DCL_jPA.mjs`)).pythonCommand}));var Gt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Gt.push({name:`js-exec`,load:async()=>(await import(`./js-exec-VXN6TZ7U-DRTFMoYG.mjs`)).jsExecCommand}),Gt.push({name:`node`,load:async()=>(await import(`./js-exec-VXN6TZ7U-DRTFMoYG.mjs`)).nodeStubCommand}));var on=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-C96qO4u5.mjs`)).curlCommand}],nn=new Map;function Kt(e){return{name:e.name,async execute(t,s){let g=nn.get(e.name);if(g||(g=await _$1.runTrustedAsync(()=>e.load()),nn.set(e.name,g)),s.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:g}=await import(`./flag-coverage-6JEX67RU-BpprwupD.mjs`);g(s.coverage,e.name,t)}return g.execute(t,s)}}}function an(e){return(e?Ye.filter(t=>e.includes(t.name)):Ye).map(Kt)}function ln(){return on.map(Kt)}function cn(){return qt.map(Kt)}function un(){return Gt.map(Kt)}function fn(e){return`load`in e&&typeof e.load==`function`}function dn(e){let t=null;return{name:e.name,trusted:!0,async execute(s,g){return t||=await e.load(),t.execute(s,g)}}}var ot=new TextEncoder;function ro(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var Le=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,s]of Object.entries(e))typeof s==`function`?this.writeFileLazy(t,s):ro(s)?this.writeFileSync(t,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(t,s)}ensureParentDirs(e){let t=p$1(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,s,g){h$1(e,`write`);let S=c$1(e);this.ensureParentDirs(S);let w=o(t,l$1(s));this.data.set(S,{type:`file`,content:w,mode:g?.mode??420,mtime:g?.mtime??new Date})}writeFileLazy(e,t,s){h$1(e,`write`);let g=c$1(e);this.ensureParentDirs(g),this.data.set(g,{type:`file`,lazy:t,mode:s?.mode??420,mtime:s?.mtime??new Date})}async materializeLazy(e,t){let s=await t.lazy(),g={type:`file`,content:typeof s==`string`?ot.encode(s):s,mode:t.mode,mtime:t.mtime};return this.data.set(e,g),g}async readFile(e,t){return h$2(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$1(e,`open`);let t=this.resolvePathWithSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(s.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in s){let e=await this.materializeLazy(t,s);return e.content instanceof Uint8Array?e.content:ot.encode(e.content)}return s.content instanceof Uint8Array?s.content:ot.encode(s.content)}async writeFile(e,t,s){this.writeFileSync(e,t,s)}async appendFile(e,t,s){h$1(e,`append`);let g=c$1(e),S=this.data.get(g);if(S&&S.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let w=o(t,l$1(s));if(S?.type===`file`){let e=S;`lazy`in e&&(e=await this.materializeLazy(g,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:ot.encode(`content`in e?e.content:``),s=new Uint8Array(t.length+w.length);s.set(t),s.set(w,t.length),this.data.set(g,{type:`file`,content:s,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,s)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){h$1(e,`stat`);let t=this.resolvePathWithSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, stat '${e}'`);s.type===`file`&&`lazy`in s&&(s=await this.materializeLazy(t,s));let g=0;return s.type===`file`&&`content`in s&&s.content&&(g=s.content instanceof Uint8Array?s.content.length:ot.encode(s.content).length),{isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:!1,mode:s.mode,size:g,mtime:s.mtime||new Date}}async lstat(e){h$1(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(s.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:s.mode,size:s.target.length,mtime:s.mtime||new Date};s.type===`file`&&`lazy`in s&&(s=await this.materializeLazy(t,s));let g=0;return s.type===`file`&&`content`in s&&s.content&&(g=s.content instanceof Uint8Array?s.content.length:ot.encode(s.content).length),{isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:!1,mode:s.mode,size:g,mtime:s.mtime||new Date}}resolveIntermediateSymlinks(e){let t=c$1(e);if(t===`/`)return`/`;let s=t.slice(1).split(`/`);if(s.length<=1)return t;let g=``,S=new Set;for(let t=0;t<s.length-1;t++){let w=s[t];g=`${g}/${w}`;let E=this.data.get(g),D=0,O=40;for(;E&&E.type===`symlink`&&D<40;){if(S.has(g))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);S.add(g),g=v$1(g,E.target),E=this.data.get(g),D++}if(D>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${g}/${s[s.length-1]}`}resolvePathWithSymlinks(e){let t=c$1(e);if(t===`/`)return`/`;let s=t.slice(1).split(`/`),g=``,S=new Set;for(let t of s){g=`${g}/${t}`;let s=this.data.get(g),w=0,E=40;for(;s&&s.type===`symlink`&&w<40;){if(S.has(g))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);S.add(g),g=v$1(g,s.target),s=this.data.get(g),w++}if(w>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return g}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){h$1(e,`mkdir`);let s=c$1(e);if(this.data.has(s)){if(this.data.get(s)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let g=p$1(s);if(g!==`/`&&!this.data.has(g))if(t?.recursive)this.mkdirSync(g,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(s,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){h$1(e,`scandir`);let t=c$1(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let g=new Set;for(;s&&s.type===`symlink`;){if(g.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);g.add(t),t=v$1(t,s.target),s=this.data.get(t)}if(!s)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(s.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let S=t===`/`?`/`:`${t}/`,w=new Map;for(let[e,s]of this.data.entries())if(e!==t&&e.startsWith(S)){let t=e.slice(S.length),g=t.split(`/`)[0];g&&!t.includes(`/`,g.length)&&!w.has(g)&&w.set(g,{name:g,isFile:s.type===`file`,isDirectory:s.type===`directory`,isSymbolicLink:s.type===`symlink`})}return Array.from(w.values()).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}async rm(e,t){h$1(e,`rm`);let s=c$1(e),g=this.data.get(s);if(!g){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(g.type===`directory`){let g=await this.readdir(s);if(g.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of g){let g=m$1(s,e);await this.rm(g,t)}}}this.data.delete(s)}async cp(e,t,s){h$1(e,`cp`),h$1(t,`cp`);let g=c$1(e),S=c$1(t),w=this.data.get(g);if(!w)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(w.type===`file`)if(this.ensureParentDirs(S),`content`in w){let e=w.content instanceof Uint8Array?new Uint8Array(w.content):w.content;this.data.set(S,{...w,content:e})}else this.data.set(S,{...w});else if(w.type===`symlink`)this.ensureParentDirs(S),this.data.set(S,{...w});else if(w.type===`directory`){if(!s?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(S,{recursive:!0});let t=await this.readdir(g);for(let e of t){let t=m$1(g,e),w=m$1(S,e);await this.cp(t,w,s)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return y(e,t)}async chmod(e,t){h$1(e,`chmod`);let s=c$1(e),g=this.data.get(s);if(!g)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);g.mode=t}async symlink(e,t){h$1(t,`symlink`);let s=c$1(t);if(this.data.has(s))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(s),this.data.set(s,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){h$1(e,`link`),h$1(t,`link`);let s=c$1(e),g=c$1(t),S=this.data.get(s);if(!S)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(S.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(g))throw Error(`EEXIST: file already exists, link '${t}'`);let w=S;`lazy`in w&&(w=await this.materializeLazy(s,w)),this.ensureParentDirs(g),this.data.set(g,{type:`file`,content:w.content,mode:w.mode,mtime:w.mtime})}async readlink(e){h$1(e,`readlink`);let t=c$1(e),s=this.data.get(t);if(!s)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(s.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return s.target}async realpath(e){h$1(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,s){h$1(e,`utimes`);let g=c$1(e),S=this.resolvePathWithSymlinks(g),w=this.data.get(S);if(!w)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);w.mtime=s}};function no(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function io(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function oo(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function ao(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${xi$1}
52
52
  `),e.writeFileSync(`/proc/self/exe`,`/bin/bash`),e.writeFileSync(`/proc/self/cmdline`,`bash\0`),e.writeFileSync(`/proc/self/comm`,`bash
53
53
  `),e.writeFileLazy?e.writeFileLazy(`/proc/self/status`,()=>_i$1(t)):e.writeFileSync(`/proc/self/status`,_i$1(t)),e.writeFileSync(`/proc/self/fd/0`,`/dev/stdin`),e.writeFileSync(`/proc/self/fd/1`,`/dev/stdout`),e.writeFileSync(`/proc/self/fd/2`,`/dev/stderr`)}function hn(e,t,s={pid:1,ppid:0,uid:1e3,gid:1e3}){no(e)&&(io(e,t),oo(e),ao(e,s))}var lo=[`allexport`,`errexit`,`noglob`,`noclobber`,`noexec`,`nounset`,`pipefail`,`posix`,`verbose`,`xtrace`],co=[`braceexpand`,`hashall`,`interactive-comments`];function Ws(e){let t=[],s=[...co.map(e=>({name:e,enabled:!0})),...lo.map(t=>({name:t,enabled:e[t]}))].sort((e,t)=>e.name.localeCompare(t.name));for(let e of s)e.enabled&&t.push(e.name);return t.join(`:`)}function lt(e){e.state.env.set(`SHELLOPTS`,Ws(e.state.options))}var uo=[`dotglob`,`expand_aliases`,`extglob`,`failglob`,`globskipdots`,`globstar`,`lastpipe`,`nocaseglob`,`nocasematch`,`nullglob`,`xpg_echo`];function zs(e){let t=[];for(let s of uo)e[s]&&t.push(s);return t.join(`:`)}function Vs(e){e.state.env.set(`BASHOPTS`,zs(e.state.shoptOptions))}var fo=`BASH_ALIAS_`;function pn(e){return e.parts.length===1?e.parts[0].type===`Literal`:!1}function mn(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===`Literal`?t.value:null}function yn(e,t){return e.env.get(`${fo}${t}`)}function Bs(e,t,s){if(!t.name||!pn(t.name))return t;let g=mn(t.name);if(!g)return t;let S=yn(e,g);if(!S||s.has(g))return t;try{s.add(g);let w=new V,E=S,D=S.endsWith(` `);if(!D)for(let e of t.args){let t=wn(e);E+=` ${t}`}let O;try{O=w.parse(E)}catch(e){if(e instanceof G$1)throw e;return t}if(O.statements.length!==1||O.statements[0].pipelines.length!==1||O.statements[0].pipelines[0].commands.length!==1)return gn(t,S);let k=O.statements[0].pipelines[0].commands[0];if(k.type!==`SimpleCommand`)return gn(t,S);let j={...k,assignments:[...t.assignments,...k.assignments],redirections:[...k.redirections,...t.redirections],line:t.line};if(D&&t.args.length>0&&(j={...j,args:[...j.args,...t.args]},j.args.length>0)){let t=j.args[0];if(pn(t)){let g=mn(t);if(g&&yn(e,g)){let g={type:`SimpleCommand`,name:t,args:j.args.slice(1),assignments:[],redirections:[]},S=Bs(e,g,s);S!==g&&(j={...j,name:S.name,args:[...S.args]})}}}return j}catch(e){throw s.delete(g),e}}function gn(e,t){let s=t;for(let t of e.args){let e=wn(t);s+=` ${e}`}let g=new V;return{type:`SimpleCommand`,name:g.parseWordFromString(`eval`,!1,!1),args:[g.parseWordFromString(`'${s.replace(/'/g,`'\\''`)}'`,!1,!1)],assignments:e.assignments,redirections:e.redirections,line:e.line}}function wn(e){let t=``;for(let s of e.parts)switch(s.type){case`Literal`:t+=s.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,`\\$1`);break;case`SingleQuoted`:t+=`'${s.value}'`;break;case`DoubleQuoted`:t+=`"${s.parts.map(e=>e.type===`Literal`?e.value:`$${e.type}`).join(``)}"`;break;case`ParameterExpansion`:t+=`\${${s.parameter}}`;break;case`CommandSubstitution`:t+=`$(...)`;break;case`ArithmeticExpansion`:t+=`$((${s.expression}))`;break;case`Glob`:t+=s.pattern;break;default:break}return t}async function vn(e,t){let s=t.parts.map(e=>e.type===`Literal`?e.value:`\0`).join(``),g=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!g||!s.endsWith(`)`))return null;let S=g[1],w=[],E=!1,D=``,O=!1;for(let s of t.parts)if(s.type===`Literal`){let e=s.value;if(!E){let t=e.indexOf(`=(`);t!==-1&&(E=!0,e=e.slice(t+2))}if(E){e.endsWith(`)`)&&(e=e.slice(0,-1));let t=e.split(/(\s+)/);for(let e of t)/^\s+$/.test(e)?(D||O)&&(w.push(D),D=``,O=!1):e&&(D+=e)}}else if(E)if(s.type===`BraceExpansion`)if(/^\[.+\]=/.test(D))D+=En$1({type:`Word`,parts:[s]});else{(D||O)&&(w.push(D),D=``,O=!1);let t=await wl(e,{type:`Word`,parts:[s]});w.push(...t.values)}else{(s.type===`SingleQuoted`||s.type===`DoubleQuoted`||s.type===`Escaped`)&&(O=!0);let t=await Pt$1(e,{type:`Word`,parts:[s]});D+=t}return(D||O)&&w.push(D),`${S}=(${w.map(e=>/^\[.+\]=/.test(e)?e:e===``?`''`:/[\s"'\\$`!*?[\]{}|&;<>()]/.test(e)&&!e.startsWith(`'`)&&!e.startsWith(`"`)?`'${e.replace(/'/g,`'\\''`)}'`:e).join(` `)})`}async function bn(e,t){let s=-1,g=-1,S=!1;for(let e=0;e<t.parts.length;e++){let w=t.parts[e];if(w.type===`Literal`){let t=w.value.indexOf(`+=`);if(t!==-1){let E=w.value.slice(0,t);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(E)){s=e,g=t,S=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(E)){s=e,g=t,S=!0;break}}let E=w.value.indexOf(`=`);if(E!==-1&&(E===0||w.value[E-1]!==`+`)){let t=w.value.slice(0,E);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(t)){s=e,g=E;break}}}}if(s===-1)return null;let w=t.parts.slice(0,s),E=t.parts[s];if(E.type!==`Literal`)return null;let D=S?2:1,O=E.value.slice(0,g),k=E.value.slice(g+D),j=t.parts.slice(s+1),F=``;for(let t of w)F+=await Pt$1(e,{type:`Word`,parts:[t]});F+=O;let L={type:`Word`,parts:k===``?j:[{type:`Literal`,value:k},...j]},B=L.parts.length>0?await Pt$1(e,L):``;return`${F}${S?`+=`:`=`}${B}`}var ho=[`tar`,`yq`,`xan`,`sqlite3`,`python3`,`python`];function En(e){return ho.includes(e)}var W=Object.freeze({stdout:``,stderr:``,exitCode:0});function z(e=``){return{stdout:e,stderr:``,exitCode:0}}function A(e,t=1){return{stdout:``,stderr:e,exitCode:t}}function _(e,t,s){return{stdout:e,stderr:t,exitCode:s}}function Q(e){return{stdout:``,stderr:``,exitCode:e?0:1}}function Ne(e,t,s=``,g=``){throw new b(e,t,s,g)}function le(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new b(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,`file_descriptors`)}function js(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new f;return W}if(t.length>1)throw new d(1,``,`bash: break: too many arguments
@@ -721,7 +721,7 @@ sys 0m0.000s
721
721
  `,127)}if(k===`exec`&&(j.length===0||j[0]===`--`)){for(let t of e.redirections){if(t.target.type===`HereDoc`||t.fdVariable)continue;let e=await Pt$1(this.ctx,t.target),s=t.fd??(t.operator===`<`||t.operator===`<>`?0:1);switch(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),t.operator){case`>`:case`>|`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);await this.ctx.fs.writeFile(t,``,`utf8`),le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__file__:${t}`);break}case`>>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__file_append__:${t}`);break}case`<`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);le(this.ctx),this.ctx.state.fileDescriptors.set(s,e)}catch{return A(`bash: ${e}: No such file or directory
722
722
  `)}break}case`<>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__rw__:${t.length}:${t}:0:${e}`)}catch{await this.ctx.fs.writeFile(t,``,`utf8`),le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__rw__:${t.length}:${t}:0:`)}break}case`>&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(s);else if(e.endsWith(`-`)){let t=e.slice(0,-1),g=Number.parseInt(t,10);if(!Number.isNaN(g)){let e=this.ctx.state.fileDescriptors.get(g);e===void 0?this.ctx.state.fileDescriptors.set(s,`__dupout__:${g}`):this.ctx.state.fileDescriptors.set(s,e),this.ctx.state.fileDescriptors.delete(g)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__dupout__:${t}`))}break;case`<&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(s);else if(e.endsWith(`-`)){let t=e.slice(0,-1),g=Number.parseInt(t,10);if(!Number.isNaN(g)){let e=this.ctx.state.fileDescriptors.get(g);e===void 0?this.ctx.state.fileDescriptors.set(s,`__dupin__:${g}`):this.ctx.state.fileDescriptors.set(s,e),this.ctx.state.fileDescriptors.delete(g)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__dupin__:${t}`))}break}}for(let[e,t]of g)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);if(this.ctx.state.tempExportedVars)for(let e of g.keys())this.ctx.state.tempExportedVars.delete(e);return W}if(this.ctx.state.extraArgs){j.push(...this.ctx.state.extraArgs);for(let e=0;e<this.ctx.state.extraArgs.length;e++)F.push(!0);this.ctx.state.extraArgs=void 0}let L=await Pi(this.ctx,k,j);g.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(g)));let B,H=null;try{B=await this.runCommand(k,j,F,t,!1,!1,O)}catch(e){if(e instanceof c||e instanceof a)H=e,B=W;else throw e}let q=S+L;if(q&&(B={...B,stderr:q+B.stderr}),B=await G(this.ctx,B,e.redirections),H)throw H;if(j.length>0){let e=j[j.length-1];if((k===`declare`||k===`local`||k===`typeset`)&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(e)){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);t&&(e=t[1])}this.ctx.state.lastArg=e}else this.ctx.state.lastArg=k;let ee=Rn(k)&&k!==`unset`&&k!==`eval`;if(!this.ctx.state.options.posix||!ee)for(let[e,t]of g)this.ctx.state.fullyUnsetLocals?.has(e)||(t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t));if(this.ctx.state.tempExportedVars)for(let e of g.keys())this.ctx.state.tempExportedVars.delete(e);return g.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(B={...B,stderr:this.ctx.state.expansionStderr+B.stderr},this.ctx.state.expansionStderr=``),B}async runCommand(e,t,s,g,S=!1,w=!1,E=-1){let D={ctx:this.ctx,runCommand:(e,t,s,g,S,w,E)=>this.runCommand(e,t,s,g,S,w,E),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(e,t,s)=>this.executeUserScript(e,t,s)},O=await hi(D,e,t,s,g,S,w,E);return O===null?pi(D,e,t,g,w):O}aliasExpansionStack=new Set;expandAlias(e){return Bs(this.ctx.state,e,this.aliasExpansionStack)}async findCommandInPath(e){return ws(this.ctx,e)}async executeSubshell(e,t=``){return Ni(this.ctx,e,t,e=>this.executeStatement(e))}async executeGroup(e,t=``){return Oi(this.ctx,e,t,e=>this.executeStatement(e))}async executeArithmeticCommand(e){e.line!==void 0&&(this.ctx.state.currentLine=e.line);let t=await xe(this.ctx,e.redirections);if(t)return t;try{let t=Q(await R(this.ctx,e.expression.expression)!==0);return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),G(this.ctx,t,e.redirections)}catch(t){let s=A(`bash: arithmetic expression: ${t.message}
723
723
  `);return G(this.ctx,s,e.redirections)}}async executeConditionalCommand(e){e.line!==void 0&&(this.ctx.state.currentLine=e.line);let t=await xe(this.ctx,e.redirections);if(t)return t;try{let t=Q(await He(this.ctx,e.expression));return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),G(this.ctx,t,e.redirections)}catch(t){let s=t instanceof p?1:2,g=A(`bash: conditional expression: ${t.message}
724
- `,s);return G(this.ctx,g,e.redirections)}}},re={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxSourceDepth:100};function Di(e){return e?{maxCallDepth:e.maxCallDepth??re.maxCallDepth,maxCommandCount:e.maxCommandCount??re.maxCommandCount,maxLoopIterations:e.maxLoopIterations??re.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??re.maxAwkIterations,maxSedIterations:e.maxSedIterations??re.maxSedIterations,maxJqIterations:e.maxJqIterations??re.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??re.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??re.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??re.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??re.maxGlobOperations,maxStringLength:e.maxStringLength??re.maxStringLength,maxArrayElements:e.maxArrayElements??re.maxArrayElements,maxHeredocSize:e.maxHeredocSize??re.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??re.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??re.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??re.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??re.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??re.maxSourceDepth}:{...re}}function Rr(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Aa(e){let t=Rr(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Ti(e){if(e.includes(`\\`))return!0;let t=e.toLowerCase();return t.includes(`%2f`)||t.includes(`%5c`)}function ka(e,t){return t===`/`||t===``?!0:t.endsWith(`/`)?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function Ir(e,t){let s=Rr(e);if(!s)return!1;let g=Aa(t);return!g||s.origin!==g.origin||g.pathPrefix!==`/`&&g.pathPrefix!==``&&Ti(s.pathname)?!1:ka(s.pathname,g.pathPrefix)}function Ri(e){return typeof e==`string`?e:e.url}function Ii(e,t){return!t||t.length===0?!1:t.some(t=>Ir(e,Ri(t)))}function Lr(e){let t=_a(e);if(t===`localhost`||t.endsWith(`.localhost`))return!0;let s=Li(t);if(s)return bs(s);let g=Na(t);return g?Oa(g):!1}function _a(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function Ca(e){if(!e)return null;let t=10,s=e;if(s.startsWith(`0x`)||s.startsWith(`0X`)?(t=16,s=s.slice(2)):s.length>1&&s.startsWith(`0`)&&(t=8),!s||t===16&&!/^[0-9a-fA-F]+$/.test(s)||t===10&&!/^\d+$/.test(s)||t===8&&!/^[0-7]+$/.test(s))return null;let g=Number.parseInt(s,t);return!Number.isFinite(g)||g<0?null:g}function Li(e){let t=e.split(`.`);if(t.length===0||t.length>4)return null;let s=t.map(e=>Ca(e));if(s.some(e=>e===null))return null;let g=s;if(t.length===1){let e=g[0];return e>4294967295?null:[e>>>24&255,e>>>16&255,e>>>8&255,e&255]}if(t.length===2){let[e,t]=g;return e>255||t>16777215?null:[e,t>>>16&255,t>>>8&255,t&255]}if(t.length===3){let[e,t,s]=g;return e>255||t>255||s>65535?null:[e,t,s>>>8&255,s&255]}let[S,w,E,D]=g;return S>255||w>255||E>255||D>255?null:[S,w,E,D]}function Na(e){let t=e,s=null;if(t.includes(`.`)){let e=t.lastIndexOf(`:`);if(e<0)return null;let g=Li(t.slice(e+1));if(!g)return null;s=g,t=t.slice(0,e)}let g=t.includes(`::`)?t.split(`::`).length-1:0;if(g>1)return null;let[S,w]=t.split(`::`),E=S?S.split(`:`).filter(Boolean):[],D=w?w.split(`:`).filter(Boolean):[],O=e=>/^[0-9a-f]{1,4}$/i.test(e)?Number.parseInt(e,16):null,k=E.map(O),j=D.map(O);if(k.some(e=>e===null)||j.some(e=>e===null))return null;let F=s?2:0,L=k.length+j.length+F,B=0;if(g===1){if(B=8-L,B<0)return null}else if(L!==8)return null;let H=[...k,...Array(B).fill(0),...j];return s&&(H.push(s[0]<<8|s[1]),H.push(s[2]<<8|s[3])),H.length===8?H:null}function bs(e){let[t,s]=e;return t===127||t===10||t===172&&s>=16&&s<=31||t===192&&s===168||t===169&&s===254||t===0||t===100&&s>=64&&s<=127||t===198&&(s===18||s===19)||t===192&&s===0&&e[2]===0||t===192&&s===0&&e[2]===2||t===198&&s===51&&e[2]===100||t===203&&s===0&&e[2]===113||t>=240}function Oa(e){return e.every(e=>e===0)||e.slice(0,7).every(e=>e===0)&&e[7]===1||(e[0]&65472)==65152||(e[0]&65024)==64512?!0:e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535?bs([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===8193&&e[1]===3512?!0:e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0?bs([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===100&&e[1]===65435&&e[2]===1?!0:e[0]===8194?bs([e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255]):!1}function Fi(e){let t=[];for(let s of e){if(typeof s!=`string`&&(typeof s!=`object`||!s||!(`url`in s)||typeof s.url!=`string`)){t.push(`Invalid allow-list entry: must be a string URL or an object with a "url" string property`);continue}let e=Ri(s);if(!Rr(e)){t.push(`Invalid URL in allow-list: "${e}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let g=new URL(e);if(g.protocol!==`http:`&&g.protocol!==`https:`){t.push(`Only http and https URLs are allowed in allow-list: "${e}"`);continue}if(!g.hostname){t.push(`Allow-list entry must include a hostname: "${e}"`);continue}if(g.pathname!==`/`&&g.pathname!==``&&Ti(g.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${e}"`);continue}(g.search||g.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${e}"`)}return t}var xa=typeof __BROWSER__<`u`&&__BROWSER__,pt=null,Es=null,Mi=!1;function Da(){if(pt===null&&!xa)try{let e=m$2(`node:async_hooks`);Es=m$2(`node:dns`),pt=new e.AsyncLocalStorage}catch{}}function Ta(){if(Mi||(Da(),!pt||!Es))return;Mi=!0;let e=pt,t=Es.lookup;function s(...s){let g=s[0],S=e.getStore();if(typeof g!=`string`||!S||S.hostname.toLowerCase()!==g.toLowerCase())return t.apply(this,s);let w={},E;if(s.length===2)E=s[1];else if(s.length>=3){let e=s[1];typeof e==`number`?w={family:e}:e&&typeof e==`object`&&(w=e),E=s[2]}if(typeof E!=`function`)return t.apply(this,s);let D=E;if(w.family!==void 0&&w.family!==0&&w.family!==S.family){let e=Error(`ENOTFOUND ${g}`);e.code=`ENOTFOUND`,e.errno=-3008,e.syscall=`getaddrinfo`,e.hostname=g,process.nextTick(()=>D(e));return}process.nextTick(()=>{w.all?D(null,[{address:S.address,family:S.family}]):D(null,S.address,S.family)})}Object.defineProperty(Es,`lookup`,{value:s,writable:!0,configurable:!0})}function Wi(e,t){return Ta(),pt?pt.run(e,t):t()}var Ae=class extends Error{constructor(e,t){super(`Network access denied: ${t??`URL not in allow-list`}: ${e}`),this.name=`NetworkAccessDeniedError`}},mt=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name=`TooManyRedirectsError`}},yt=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name=`RedirectNotAllowedError`}},$s=class extends Error{constructor(e,t){super(`HTTP method '${e}' not allowed. Allowed methods: ${t.join(`, `)}`),this.name=`MethodNotAllowedError`}},gt=class extends Error{constructor(e){super(`Response body too large (max: ${e} bytes)`),this.name=`ResponseTooLargeError`}};function Ia(e){return new Promise((t,s)=>{lookup(e,{all:!0},(e,g)=>{e?s(e):t(g)})})}var La=20,Fa=3e4,Ma=10485760,Wa=[`GET`,`HEAD`],za=new Set([`GET`,`HEAD`,`OPTIONS`]),Va=new Set([301,302,303,307,308]);function Fr(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let e=Fi(t);if(e.length>0)throw Error(`Invalid network allow-list:
724
+ `,s);return G(this.ctx,g,e.redirections)}}},re={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxSourceDepth:100};function Di(e){return e?{maxCallDepth:e.maxCallDepth??re.maxCallDepth,maxCommandCount:e.maxCommandCount??re.maxCommandCount,maxLoopIterations:e.maxLoopIterations??re.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??re.maxAwkIterations,maxSedIterations:e.maxSedIterations??re.maxSedIterations,maxJqIterations:e.maxJqIterations??re.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??re.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??re.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??re.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??re.maxGlobOperations,maxStringLength:e.maxStringLength??re.maxStringLength,maxArrayElements:e.maxArrayElements??re.maxArrayElements,maxHeredocSize:e.maxHeredocSize??re.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??re.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??re.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??re.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??re.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??re.maxSourceDepth}:{...re}}function Rr(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Aa(e){let t=Rr(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Ti(e){if(e.includes(`\\`))return!0;let t=e.toLowerCase();return t.includes(`%2f`)||t.includes(`%5c`)}function ka(e,t){return t===`/`||t===``?!0:t.endsWith(`/`)?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function Ir(e,t){let s=Rr(e);if(!s)return!1;let g=Aa(t);return!g||s.origin!==g.origin||g.pathPrefix!==`/`&&g.pathPrefix!==``&&Ti(s.pathname)?!1:ka(s.pathname,g.pathPrefix)}function Ri(e){return typeof e==`string`?e:e.url}function Ii(e,t){return!t||t.length===0?!1:t.some(t=>Ir(e,Ri(t)))}function Lr(e){let t=_a(e);if(t===`localhost`||t.endsWith(`.localhost`))return!0;let s=Li(t);if(s)return bs(s);let g=Na(t);return g?Oa(g):!1}function _a(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function Ca(e){if(!e)return null;let t=10,s=e;if(s.startsWith(`0x`)||s.startsWith(`0X`)?(t=16,s=s.slice(2)):s.length>1&&s.startsWith(`0`)&&(t=8),!s||t===16&&!/^[0-9a-fA-F]+$/.test(s)||t===10&&!/^\d+$/.test(s)||t===8&&!/^[0-7]+$/.test(s))return null;let g=Number.parseInt(s,t);return!Number.isFinite(g)||g<0?null:g}function Li(e){let t=e.split(`.`);if(t.length===0||t.length>4)return null;let s=t.map(e=>Ca(e));if(s.some(e=>e===null))return null;let g=s;if(t.length===1){let e=g[0];return e>4294967295?null:[e>>>24&255,e>>>16&255,e>>>8&255,e&255]}if(t.length===2){let[e,t]=g;return e>255||t>16777215?null:[e,t>>>16&255,t>>>8&255,t&255]}if(t.length===3){let[e,t,s]=g;return e>255||t>255||s>65535?null:[e,t,s>>>8&255,s&255]}let[S,w,E,D]=g;return S>255||w>255||E>255||D>255?null:[S,w,E,D]}function Na(e){let t=e,s=null;if(t.includes(`.`)){let e=t.lastIndexOf(`:`);if(e<0)return null;let g=Li(t.slice(e+1));if(!g)return null;s=g,t=t.slice(0,e)}let g=t.includes(`::`)?t.split(`::`).length-1:0;if(g>1)return null;let[S,w]=t.split(`::`),E=S?S.split(`:`).filter(Boolean):[],D=w?w.split(`:`).filter(Boolean):[],O=e=>/^[0-9a-f]{1,4}$/i.test(e)?Number.parseInt(e,16):null,k=E.map(O),j=D.map(O);if(k.some(e=>e===null)||j.some(e=>e===null))return null;let F=s?2:0,L=k.length+j.length+F,B=0;if(g===1){if(B=8-L,B<0)return null}else if(L!==8)return null;let H=[...k,...Array(B).fill(0),...j];return s&&(H.push(s[0]<<8|s[1]),H.push(s[2]<<8|s[3])),H.length===8?H:null}function bs(e){let[t,s]=e;return t===127||t===10||t===172&&s>=16&&s<=31||t===192&&s===168||t===169&&s===254||t===0||t===100&&s>=64&&s<=127||t===198&&(s===18||s===19)||t===192&&s===0&&e[2]===0||t===192&&s===0&&e[2]===2||t===198&&s===51&&e[2]===100||t===203&&s===0&&e[2]===113||t>=240}function Oa(e){return e.every(e=>e===0)||e.slice(0,7).every(e=>e===0)&&e[7]===1||(e[0]&65472)==65152||(e[0]&65024)==64512?!0:e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535?bs([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===8193&&e[1]===3512?!0:e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0?bs([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===100&&e[1]===65435&&e[2]===1?!0:e[0]===8194?bs([e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255]):!1}function Fi(e){let t=[];for(let s of e){if(typeof s!=`string`&&(typeof s!=`object`||!s||!(`url`in s)||typeof s.url!=`string`)){t.push(`Invalid allow-list entry: must be a string URL or an object with a "url" string property`);continue}let e=Ri(s);if(!Rr(e)){t.push(`Invalid URL in allow-list: "${e}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let g=new URL(e);if(g.protocol!==`http:`&&g.protocol!==`https:`){t.push(`Only http and https URLs are allowed in allow-list: "${e}"`);continue}if(!g.hostname){t.push(`Allow-list entry must include a hostname: "${e}"`);continue}if(g.pathname!==`/`&&g.pathname!==``&&Ti(g.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${e}"`);continue}(g.search||g.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${e}"`)}return t}var xa=typeof __BROWSER__<`u`&&__BROWSER__,pt=null,Es=null,Mi=!1;function Da(){if(pt===null&&!xa)try{let e=m$2(`node:async_hooks`);Es=m$2(`node:dns`),pt=new e.AsyncLocalStorage}catch{}}function Ta(){if(Mi||(Da(),!pt||!Es))return;Mi=!0;let e=pt,t=Es.lookup;function s(...s){let g=s[0],S=e.getStore();if(typeof g!=`string`||!S||S.hostname.toLowerCase()!==g.toLowerCase())return t.apply(this,s);let w={},E;if(s.length===2)E=s[1];else if(s.length>=3){let e=s[1];typeof e==`number`?w={family:e}:e&&typeof e==`object`&&(w=e),E=s[2]}if(typeof E!=`function`)return t.apply(this,s);let D=E;if(w.family!==void 0&&w.family!==0&&w.family!==S.family){let e=Error(`ENOTFOUND ${g}`);e.code=`ENOTFOUND`,e.errno=-3008,e.syscall=`getaddrinfo`,e.hostname=g,process.nextTick(()=>D(e));return}process.nextTick(()=>{w.all?D(null,[{address:S.address,family:S.family}]):D(null,S.address,S.family)})}Object.defineProperty(Es,`lookup`,{value:s,writable:!0,configurable:!0})}function Wi(e,t){return Ta(),pt?pt.run(e,t):t()}var Ae=class extends Error{constructor(e,t){super(`Network access denied: ${t??`URL not in allow-list`}: ${e}`),this.name=`NetworkAccessDeniedError`}},mt=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name=`TooManyRedirectsError`}},yt=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name=`RedirectNotAllowedError`}},$s=class extends Error{constructor(e,t){super(`HTTP method '${e}' not allowed. Allowed methods: ${t.join(`, `)}`),this.name=`MethodNotAllowedError`}},gt=class extends Error{constructor(e){super(`Response body too large (max: ${e} bytes)`),this.name=`ResponseTooLargeError`}};function Ia(e){return new Promise((t,s)=>{lookup$1(e,{all:!0},(e,g)=>{e?s(e):t(g)})})}var La=20,Fa=3e4,Ma=10485760,Wa=[`GET`,`HEAD`],za=new Set([`GET`,`HEAD`,`OPTIONS`]),Va=new Set([301,302,303,307,308]);function Fr(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let e=Fi(t);if(e.length>0)throw Error(`Invalid network allow-list:
725
725
  ${e.join(`
726
726
  `)}`)}let s=[];for(let e of t)typeof e==`object`&&e.transform&&e.transform.length>0&&s.push(e);function g(e){if(s.length===0)return null;let t=null;for(let g of s)if(Ir(e,g.url)&&g.transform){t||=new Headers;for(let e of g.transform)for(let[s,g]of Object.entries(e.headers))t.set(s,g)}return t}let S=e.maxRedirects??La,w=e.timeoutMs??Fa,E=e.maxResponseSize??Ma,D=e.dangerouslyAllowFullInternetAccess?[`GET`,`HEAD`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`]:e.allowedMethods??Wa,O=e.denyPrivateRanges??(typeof process<`u`&&process.env?.NODE_ENV===`production`),k=e._dnsResolve??Ia;async function j(s){if(!e.dangerouslyAllowFullInternetAccess&&!Ii(s,t))throw new Ae(s);if(O)try{let e=new URL(s);if(Lr(e.hostname))throw new Ae(s,`private/loopback IP address blocked`);let t=e.hostname;if(/[a-zA-Z]/.test(t))try{let e=await k(t);for(let{address:t}of e)if(Lr(t))throw new Ae(s,`hostname resolves to private/loopback IP address`);let g=e[0];if(g)return{hostname:t,address:g.address,family:g.family===6?6:4}}catch(e){if(e instanceof Ae)throw e;let t=e?.code;if(!(t===`ENOTFOUND`||t===`ENODATA`))throw new Ae(s,`DNS resolution failed for private IP check`)}}catch(e){if(e instanceof Ae)throw e}return null}function F(t){if(e.dangerouslyAllowFullInternetAccess)return;let s=t.toUpperCase();if(!D.includes(s))throw new $s(s,D)}async function L(e,t={}){let s=t.method?.toUpperCase()??`GET`,D=await j(e);F(s);let O=e,k=0,L=t.followRedirects??!0,B=t.timeoutMs===void 0?w:Math.min(t.timeoutMs,w);for(;;){let e=new AbortController,w=b$1(()=>e.abort(),B);try{let w=await _$1.runTrustedAsync(()=>{let S=g(O),w={method:s,headers:Ba(t.headers,S),signal:e.signal,redirect:`manual`};return t.body&&!za.has(s)&&(w.body=t.body),D?Wi(D,()=>fetch(O,w)):fetch(O,w)});if(Va.has(w.status)&&L){let e=w.headers.get(`location`);if(!e)return await zi(w,O,E);let t=new URL(e,O).href;try{D=await j(t)}catch{throw new yt(t)}if(k++,k>S)throw new mt(S);O=t;continue}return await zi(w,O,E)}finally{u$1(w)}}}return L}function Ba(e,t){if(!e&&!t)return;if(!t)return e;let s=(e instanceof Headers,new Headers(e));for(let[e,g]of t)s.set(e,g);return s}async function zi(e,t,s){let g=Object.create(null);if(e.headers.forEach((e,t)=>{g[t.toLowerCase()]=e}),s>0){let t=e.headers.get(`content-length`);if(t){let e=parseInt(t,10);if(!Number.isNaN(e)&&e>s)throw new gt(s)}}let S;if(s>0&&e.body){let t=e.body.getReader(),g=[],w=0;for(;;){let{done:e,value:S}=await t.read();if(e)break;if(S){if(w+=S.byteLength,w>s)throw t.cancel(),new gt(s);g.push(S)}}S=new Uint8Array(w);let E=0;for(let e of g)S.set(e,E),E+=e.byteLength}else{let t=await e.arrayBuffer();if(s>0&&t.byteLength>s)throw new gt(s);S=new Uint8Array(t)}return{status:e.status,statusText:e.statusText,headers:g,body:S,url:t}}function xt(e){return tt(e)}function tt(e){return e.statements.map(Vi).join(`
727
727
  `)}function Vi(e){let t=[];for(let s=0;s<e.pipelines.length;s++)t.push(ja(e.pipelines[s])),s<e.operators.length&&t.push(e.operators[s]);let s=t.join(` `);return e.background&&(s+=` &`),s}function ja(e){let t=[];e.timed&&t.push(e.timePosix?`time -p`:`time`),e.negated&&t.push(`!`);let s=[];for(let t=0;t<e.commands.length;t++)if(s.push(Bi(e.commands[t])),t<e.commands.length-1){let g=e.pipeStderr?.[t];s.push(g?`|&`:`|`)}return(t.length>0?`${t.join(` `)} `:``)+s.join(` `)}function Bi(e){switch(e.type){case`SimpleCommand`:return Ua(e);case`If`:return Ja(e);case`For`:return el(e);case`CStyleFor`:return tl(e);case`While`:return sl(e);case`Until`:return rl(e);case`Case`:return nl(e);case`Subshell`:return ol(e);case`Group`:return al(e);case`ArithmeticCommand`:return ll(e);case`ConditionalCommand`:return cl(e);case`FunctionDef`:return ul(e);default:throw Error(`Unsupported command type: ${e.type}`)}}function Ua(e){let t=[];for(let s of e.assignments)t.push(Ha(s));e.name&&t.push(ie(e.name));for(let s of e.args)t.push(ie(s));for(let s of e.redirections)t.push(Hi(s));return t.join(` `)}function Ha(e){let t=e.append?`+=`:`=`;if(e.array){let s=e.array.map(ie).join(` `);return`${e.name}${t}(${s})`}return e.value?`${e.name}${t}${ie(e.value)}`:`${e.name}${t}`}function ie(e){return e.parts.map(e=>Ss(e,!1)).join(``)}function qe(e){return e.parts.map(e=>Ss(e,!0)).join(``)}function Ss(e,t){switch(e.type){case`Literal`:return t?qa(e.value):Za(e.value);case`SingleQuoted`:return`'${e.value}'`;case`DoubleQuoted`:return`"${e.parts.map(e=>Ss(e,!0)).join(``)}"`;case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return ji(e);case`CommandSubstitution`:return e.legacy?`\`${tt(e.body)}\``:`$(${tt(e.body)})`;case`ArithmeticExpansion`:return`$((${Z(e.expression.expression)}))`;case`ProcessSubstitution`:return e.direction===`input`?`<(${tt(e.body)})`:`>(${tt(e.body)})`;case`BraceExpansion`:return Ya(e);case`TildeExpansion`:return e.user===null?`~`:`~${e.user}`;case`Glob`:return e.pattern;default:throw Error(`Unsupported word part type: ${e.type}`)}}function Za(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,`\\$&`)}function qa(e){return e.replace(/[$`"\\]/g,`\\$&`)}function Ga(e,t){return e.parts.map(e=>Ka(e,t)).join(``)}function Ka(e,t){switch(e.type){case`Literal`:return t?e.value:e.value.replace(/[$`]/g,`\\$&`);case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return ji(e);case`CommandSubstitution`:return e.legacy?`\`${tt(e.body)}\``:`$(${tt(e.body)})`;case`ArithmeticExpansion`:return`$((${Z(e.expression.expression)}))`;default:return Ss(e,!1)}}function ji(e){return e.operation?`\${${Ui(e.parameter,e.operation)}}`:Xa(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function Xa(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function Ui(e,t){switch(t.type){case`Length`:return`#${e}`;case`LengthSliceError`:return`#${e}:`;case`BadSubstitution`:return t.text;case`DefaultValue`:return`${e}${t.checkEmpty?`:`:``}-${qe(t.word)}`;case`AssignDefault`:return`${e}${t.checkEmpty?`:`:``}=${qe(t.word)}`;case`ErrorIfUnset`:return`${e}${t.checkEmpty?`:`:``}?${t.word?qe(t.word):``}`;case`UseAlternative`:return`${e}${t.checkEmpty?`:`:``}+${qe(t.word)}`;case`Substring`:{let s=Z(t.offset.expression);return t.length?`${e}:${s}:${Z(t.length.expression)}`:`${e}:${s}`}case`PatternRemoval`:{let s=t.side===`prefix`?`#`:`%`;return`${e}${t.greedy?`${s}${s}`:s}${qe(t.pattern)}`}case`PatternReplacement`:{let s=`/`;t.all?s=`//`:t.anchor===`start`?s=`/#`:t.anchor===`end`&&(s=`/%`);let g=t.replacement?`/${qe(t.replacement)}`:``;return`${e}${s}${qe(t.pattern)}${g}`}case`CaseModification`:{let s=t.direction===`upper`?`^`:`,`;return`${e}${t.all?`${s}${s}`:s}${t.pattern?qe(t.pattern):``}`}case`Transform`:return`${e}@${t.operator}`;case`Indirection`:return t.innerOp?`!${Ui(e,t.innerOp)}`:`!${e}`;case`ArrayKeys`:return`!${t.array}[${t.star?`*`:`@`}]`;case`VarNamePrefix`:return`!${t.prefix}${t.star?`*`:`@`}`;default:throw Error(`Unsupported parameter operation type: ${t.type}`)}}function Ya(e){return`{${e.items.map(Qa).join(`,`)}}`}function Qa(e){if(e.type===`Word`)return ie(e.word);let t=e.startStr??String(e.start),s=e.endStr??String(e.end);return e.step===void 0?`${t}..${s}`:`${t}..${s}..${e.step}`}function Hi(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd===null?``:String(e.fd);if(e.operator===`<<`||e.operator===`<<-`){let s=e.target,g=s.quoted?`'${s.delimiter}'`:s.delimiter,S=Ga(s.content,s.quoted);return`${t}${e.operator}${g}
@@ -759,7 +759,7 @@ ${e.terminator}`}function ol(e){return`(${Ee(e.body)})${ke(e.redirections)}`}fun
759
759
  `)),S.removeListener(`error`,te),B.setSocket(S,O,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(B),B.on(`close`,()=>{this.clients.delete(B),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Y,this)})),k(B,g)}};function J(e,t){for(let s of Object.keys(t))e.on(s,t[s]);return function(){for(let s of Object.keys(t))e.removeListener(s,t[s])}}function Y(e){e._state=2,e.emit(`close`)}function te(){this.destroy()}function ne(e,t,s,S){s||=g.STATUS_CODES[t],S={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(s),...S},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${g.STATUS_CODES[t]}\r\n`+Object.keys(S).map(e=>`${e}: ${S[e]}`).join(`\r
760
760
  `)+`\r
761
761
  \r
762
- `+s)}function ae(e,t,s,g,S,w){if(e.listenerCount(`wsClientError`)){let g=Error(S);Error.captureStackTrace(g,ae),e.emit(`wsClientError`,g,s,t)}else ne(s,g,S,w)}}));require_stream(),require_receiver(),require_sender(),require_websocket();var import_websocket_server=__toESM$1(require_websocket_server(),1),require_ignore=__commonJSMin$2(((e,t)=>{function s(e){return Array.isArray(e)?e:[e]}let g=``,S=` `,w=`\\`,E=/^\s+$/,D=/(?:[^\\]|^)\\$/,O=/^\\!/,k=/^\\#/,j=/\r?\n/g,F=/^\.*\/|^\.+$/,L=`/`,B=`node-ignore`;typeof Symbol<`u`&&(B=Symbol.for(`node-ignore`));let H=B,q=(e,t,s)=>Object.defineProperty(e,t,{value:s}),ee=/([0-z])-([0-z])/g,J=()=>!1,Y=e=>e.replace(ee,(e,t,s)=>t.charCodeAt(0)<=s.charCodeAt(0)?e:``),te=e=>{let{length:t}=e;return e.slice(0,t-t%2)},ne=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,s)=>t+(s.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:s}=t;return t.slice(0,s-s%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,s)=>t+6<s.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,s)=>t+s.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,s,g,S)=>t===`\\`?`\\[${s}${te(g)}${S}`:S===`]`&&g.length%2==0?`[${Y(s)}${g}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],ae=Object.create(null),oe=(e,t)=>{let s=ae[e];return s||(s=ne.reduce((t,[s,g])=>t.replace(s,g.bind(e)),e),ae[e]=s),t?new RegExp(s,`i`):new RegExp(s)},se=e=>typeof e==`string`,ce=e=>e&&se(e)&&!E.test(e)&&!D.test(e)&&e.indexOf(`#`)!==0,ue=e=>e.split(j);var de=class{constructor(e,t,s,g){this.origin=e,this.pattern=t,this.negative=s,this.regex=g}};let fe=(e,t)=>{let s=e,g=!1;e.indexOf(`!`)===0&&(g=!0,e=e.substr(1)),e=e.replace(O,`!`).replace(k,`#`);let S=oe(e,t);return new de(s,e,g,S)},me=(e,t)=>{throw new t(e)},ge=(e,t,s)=>se(e)?e?ge.isNotRelative(e)?s(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:s(`path must not be empty`,TypeError):s(`path must be a string, but got \`${t}\``,TypeError),_e=e=>F.test(e);ge.isNotRelative=_e,ge.convert=e=>e;var ve=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:s=!1}={}){q(this,H,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=s,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[H]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(ce(e)){let t=fe(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,s(se(e)?ue(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let s=!1,g=!1;return this._rules.forEach(S=>{let{negative:w}=S;g===w&&s!==g||w&&!s&&!g&&!t||S.regex.test(e)&&(s=!w,g=w)}),{ignored:s,unignored:g}}_test(e,t,s,g){let S=e&&ge.convert(e);return ge(S,e,this._allowRelativePaths?J:me),this._t(S,t,s,g)}_t(e,t,s,g){if(e in t)return t[e];if(g||=e.split(`/`),g.pop(),!g.length)return t[e]=this._testOne(e,s);let S=this._t(g.join(`/`)+`/`,t,s,g);return t[e]=S.ignored?S:this._testOne(e,s)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return s(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let ye=e=>new ve(e);if(ye.isPathValid=e=>ge(e&&ge.convert(e),e,J),ye.default=ye,t.exports=ye,typeof process<`u`&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform===`win32`)){ge.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;ge.isNotRelative=t=>e.test(t)||_e(t)}}));init_esm$2();var import_src=require_src$14(),import_src$1=require_src$10(),import_src$2=require_src$9(),import_src$3=require_src$4(),import_src$4=require_src$3(),import_src$5=require_src$2(),import_src$6=require_src$1(),import_src$7=require_src();init_esm$1();var import_lib=__toESM$2(require_lib(),1),import_yazl=__toESM$2(require_yazl(),1),import_shell_quote=__toESM$2(require_shell_quote(),1),import_ignore=__toESM$2(require_ignore(),1),__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__copyProps=(e,t,s,g)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var S=__getOwnPropNames(t),w=0,E=S.length,D;w<E;w++)D=S[w],!__hasOwnProp.call(e,D)&&D!==s&&__defProp(e,D,{get:(e=>t[e]).bind(null,D),enumerable:!(g=__getOwnPropDesc(t,D))||g.enumerable});return e},__toESM=(e,t,s)=>(s=e==null?{}:__create(__getProtoOf(e)),__copyProps(t||!e||!e.__esModule?__defProp(s,`default`,{value:e,enumerable:!0}):s,e)),__require=createRequire(import.meta.url);const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const AGENT_ID_RE=/^[a-zA-Z0-9_-]+$/,AGENT_ID_MAX_LEN=64;function validateAgentId(e){return typeof e!=`string`||e.length===0||e.length>64||!AGENT_ID_RE.test(e)?null:e}function toBroadcasterKey(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function isPresenceEligibleAgentId(e){return!e.startsWith(`principal-`)}function resolveAgentType(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)||t.startsWith(`local-agent-mode-`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function parseAgentBodyFields(e){let t=validateAgentId(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:toBroadcasterKey(t),displayName:typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?sanitizeGitIdentity(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?sanitizeGitIdentity(e.clientVersion):void 0,label:typeof e.label==`string`?sanitizeGitIdentity(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}var require_err_helpers=__commonJSMin(((e,t)=>{let s=e=>e&&typeof e.message==`string`,g=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return s(t)?t:void 0}else return s(t)?t:void 0},S=(e,t)=>{if(!s(e))return``;let w=e.stack||``;if(t.has(e))return w+`
762
+ `+s)}function ae(e,t,s,g,S,w){if(e.listenerCount(`wsClientError`)){let g=Error(S);Error.captureStackTrace(g,ae),e.emit(`wsClientError`,g,s,t)}else ne(s,g,S,w)}}));require_stream(),require_receiver(),require_sender(),require_websocket();var import_websocket_server=__toESM$1(require_websocket_server(),1),require_ignore=__commonJSMin$2(((e,t)=>{function s(e){return Array.isArray(e)?e:[e]}let g=``,S=` `,w=`\\`,E=/^\s+$/,D=/(?:[^\\]|^)\\$/,O=/^\\!/,k=/^\\#/,j=/\r?\n/g,F=/^\.*\/|^\.+$/,L=`/`,B=`node-ignore`;typeof Symbol<`u`&&(B=Symbol.for(`node-ignore`));let H=B,q=(e,t,s)=>Object.defineProperty(e,t,{value:s}),ee=/([0-z])-([0-z])/g,J=()=>!1,Y=e=>e.replace(ee,(e,t,s)=>t.charCodeAt(0)<=s.charCodeAt(0)?e:``),te=e=>{let{length:t}=e;return e.slice(0,t-t%2)},ne=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,s)=>t+(s.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:s}=t;return t.slice(0,s-s%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,s)=>t+6<s.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,s)=>t+s.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,s,g,S)=>t===`\\`?`\\[${s}${te(g)}${S}`:S===`]`&&g.length%2==0?`[${Y(s)}${g}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],ae=Object.create(null),oe=(e,t)=>{let s=ae[e];return s||(s=ne.reduce((t,[s,g])=>t.replace(s,g.bind(e)),e),ae[e]=s),t?new RegExp(s,`i`):new RegExp(s)},se=e=>typeof e==`string`,ce=e=>e&&se(e)&&!E.test(e)&&!D.test(e)&&e.indexOf(`#`)!==0,ue=e=>e.split(j);var de=class{constructor(e,t,s,g){this.origin=e,this.pattern=t,this.negative=s,this.regex=g}};let fe=(e,t)=>{let s=e,g=!1;e.indexOf(`!`)===0&&(g=!0,e=e.substr(1)),e=e.replace(O,`!`).replace(k,`#`);let S=oe(e,t);return new de(s,e,g,S)},me=(e,t)=>{throw new t(e)},ge=(e,t,s)=>se(e)?e?ge.isNotRelative(e)?s(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:s(`path must not be empty`,TypeError):s(`path must be a string, but got \`${t}\``,TypeError),_e=e=>F.test(e);ge.isNotRelative=_e,ge.convert=e=>e;var ve=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:s=!1}={}){q(this,H,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=s,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[H]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(ce(e)){let t=fe(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,s(se(e)?ue(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let s=!1,g=!1;return this._rules.forEach(S=>{let{negative:w}=S;g===w&&s!==g||w&&!s&&!g&&!t||S.regex.test(e)&&(s=!w,g=w)}),{ignored:s,unignored:g}}_test(e,t,s,g){let S=e&&ge.convert(e);return ge(S,e,this._allowRelativePaths?J:me),this._t(S,t,s,g)}_t(e,t,s,g){if(e in t)return t[e];if(g||=e.split(`/`),g.pop(),!g.length)return t[e]=this._testOne(e,s);let S=this._t(g.join(`/`)+`/`,t,s,g);return t[e]=S.ignored?S:this._testOne(e,s)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return s(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let ye=e=>new ve(e);if(ye.isPathValid=e=>ge(e&&ge.convert(e),e,J),ye.default=ye,t.exports=ye,typeof process<`u`&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform===`win32`)){ge.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;ge.isNotRelative=t=>e.test(t)||_e(t)}}));init_esm$2();var import_src=require_src$14(),import_src$1=require_src$10(),import_src$2=require_src$9(),import_src$3=require_src$4(),import_src$4=require_src$3(),import_src$5=require_src$2(),import_src$6=require_src$1(),import_src$7=require_src();init_esm$1();var import_lib=__toESM$2(require_lib(),1),import_yazl=__toESM$2(require_yazl(),1),import_ipaddr=__toESM$2(require_ipaddr(),1),import_shell_quote=__toESM$2(require_shell_quote(),1),import_ignore=__toESM$2(require_ignore(),1),__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__copyProps=(e,t,s,g)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var S=__getOwnPropNames(t),w=0,E=S.length,D;w<E;w++)D=S[w],!__hasOwnProp.call(e,D)&&D!==s&&__defProp(e,D,{get:(e=>t[e]).bind(null,D),enumerable:!(g=__getOwnPropDesc(t,D))||g.enumerable});return e},__toESM=(e,t,s)=>(s=e==null?{}:__create(__getProtoOf(e)),__copyProps(t||!e||!e.__esModule?__defProp(s,`default`,{value:e,enumerable:!0}):s,e)),__require=createRequire(import.meta.url);const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const AGENT_ID_RE=/^[a-zA-Z0-9_-]+$/,AGENT_ID_MAX_LEN=64;function validateAgentId(e){return typeof e!=`string`||e.length===0||e.length>64||!AGENT_ID_RE.test(e)?null:e}function toBroadcasterKey(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function isPresenceEligibleAgentId(e){return!e.startsWith(`principal-`)}function resolveAgentType(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)||t.startsWith(`local-agent-mode-`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function parseAgentBodyFields(e){let t=validateAgentId(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:toBroadcasterKey(t),displayName:typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?sanitizeGitIdentity(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?sanitizeGitIdentity(e.clientVersion):void 0,label:typeof e.label==`string`?sanitizeGitIdentity(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}var require_err_helpers=__commonJSMin(((e,t)=>{let s=e=>e&&typeof e.message==`string`,g=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return s(t)?t:void 0}else return s(t)?t:void 0},S=(e,t)=>{if(!s(e))return``;let w=e.stack||``;if(t.has(e))return w+`
763
763
  causes have become circular...`;let E=g(e);return E?(t.add(e),w+`
764
764
  caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?``:e.message||``;if(t.has(e))return w+`: ...`;let D=g(e);if(D){t.add(e);let s=typeof e.cause==`function`;return w+(s?``:`: `)+E(D,t,s)}else return w};t.exports={isErrorLike:s,getErrorCause:g,stackWithCauses:w,messageWithCauses:e=>E(e,new Set)}})),require_err_proto=__commonJSMin(((e,t)=>{let s=Symbol(`circular-ref-tag`),g=Symbol(`pino-raw-err-ref`),S=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[g]},set:function(e){this[g]=e}}});Object.defineProperty(S,g,{writable:!0,value:{}}),t.exports={pinoErrProto:S,pinoErrorSymbols:{seen:s,rawSymbol:g}}})),require_err=__commonJSMin(((e,t)=>{t.exports=k;let{messageWithCauses:s,stackWithCauses:g,isErrorLike:S}=require_err_helpers(),{pinoErrProto:w,pinoErrorSymbols:E}=require_err_proto(),{seen:D}=E,{toString:O}=Object.prototype;function k(e){if(!S(e))return e;e[D]=void 0;let t=Object.create(w);t.type=O.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=s(e),t.stack=g(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>k(e)));for(let s in e)if(t[s]===void 0){let g=e[s];S(g)?s!==`cause`&&!Object.prototype.hasOwnProperty.call(g,D)&&(t[s]=k(g)):t[s]=g}return delete e[D],t.raw=e,t}})),require_err_with_cause=__commonJSMin(((e,t)=>{t.exports=D;let{isErrorLike:s}=require_err_helpers(),{pinoErrProto:g,pinoErrorSymbols:S}=require_err_proto(),{seen:w}=S,{toString:E}=Object.prototype;function D(e){if(!s(e))return e;e[w]=void 0;let t=Object.create(g);t.type=E.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>D(e))),s(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,w)&&(t.cause=D(e.cause));for(let g in e)if(t[g]===void 0){let S=e[g];s(S)?Object.prototype.hasOwnProperty.call(S,w)||(t[g]=D(S)):t[g]=S}return delete e[w],t.raw=e,t}})),require_req=__commonJSMin(((e,t)=>{t.exports={mapHttpRequest:w,reqSerializer:S};let s=Symbol(`pino-raw-req-ref`),g=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[s]},set:function(e){this[s]=e}}});Object.defineProperty(g,s,{writable:!0,value:{}});function S(e){let t=e.info||e.socket,s=Object.create(g);if(s.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),s.method=e.method,e.originalUrl)s.url=e.originalUrl;else{let t=e.path;s.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(s.query=e.query),e.params&&(s.params=e.params),s.headers=e.headers,s.remoteAddress=t&&t.remoteAddress,s.remotePort=t&&t.remotePort,s.raw=e.raw||e,s}function w(e){return{req:S(e)}}})),require_res=__commonJSMin(((e,t)=>{t.exports={mapHttpResponse:w,resSerializer:S};let s=Symbol(`pino-raw-res-ref`),g=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[s]},set:function(e){this[s]=e}}});Object.defineProperty(g,s,{writable:!0,value:{}});function S(e){let t=Object.create(g);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function w(e){return{res:S(e)}}})),require_pino_std_serializers=__commonJSMin(((e,t)=>{let s=require_err(),g=require_err_with_cause(),S=require_req(),w=require_res();t.exports={err:s,errWithCause:g,mapHttpRequest:S.mapHttpRequest,mapHttpResponse:w.mapHttpResponse,req:S.reqSerializer,res:w.resSerializer,wrapErrorSerializer:function(e){return e===s?e:function(t){return e(s(t))}},wrapRequestSerializer:function(e){return e===S.reqSerializer?e:function(t){return e(S.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===w.resSerializer?e:function(t){return e(w.resSerializer(t))}}}})),require_caller=__commonJSMin(((e,t)=>{function s(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=s;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let g=t.slice(2),S=[];for(let e of g)e&&S.push(e.getFileName());return S}})),require_redact=__commonJSMin(((e,t)=>{function s(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let g=0;g<e.length;g++)t[g]=s(e[g]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let g in e)Object.prototype.hasOwnProperty.call(e,g)&&(t[g]=s(e[g]));return t}return e}function g(e){let t=[],s=``,g=!1,S=!1,w=``;for(let E=0;E<e.length;E++){let D=e[E];!g&&D===`.`?s&&=(t.push(s),``):D===`[`?(s&&=(t.push(s),``),g=!0):D===`]`&&g?(t.push(s),s=``,g=!1,S=!1):(D===`"`||D===`'`)&&g?S?D===w?(S=!1,w=``):s+=D:(S=!0,w=D):s+=D}return s&&t.push(s),t}function S(e,t,s){let g=e;for(let e=0;e<t.length-1;e++){let s=t[e];if(typeof g!=`object`||!g||!(s in g)||typeof g[s]!=`object`||g[s]===null)return!1;g=g[s]}let S=t[t.length-1];if(S===`*`){if(Array.isArray(g))for(let e=0;e<g.length;e++)g[e]=s;else if(typeof g==`object`&&g)for(let e in g)Object.prototype.hasOwnProperty.call(g,e)&&(g[e]=s)}else typeof g==`object`&&g&&S in g&&Object.prototype.hasOwnProperty.call(g,S)&&(g[S]=s);return!0}function w(e,t){let s=e;for(let e=0;e<t.length-1;e++){let g=t[e];if(typeof s!=`object`||!s||!(g in s)||typeof s[g]!=`object`||s[g]===null)return!1;s=s[g]}let g=t[t.length-1];if(g===`*`){if(Array.isArray(s))for(let e=0;e<s.length;e++)s[e]=void 0;else if(typeof s==`object`&&s)for(let e in s)Object.prototype.hasOwnProperty.call(s,e)&&delete s[e]}else typeof s==`object`&&s&&g in s&&Object.prototype.hasOwnProperty.call(s,g)&&delete s[g];return!0}let E=Symbol(`PATH_NOT_FOUND`);function D(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s||!s||!(e in s))return E;s=s[e]}return s}function O(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s||!s)return;s=s[e]}return s}function k(e,t,s,O=!1){for(let k of t){let t=g(k);if(t.includes(`*`))j(e,t,s,k,O);else if(O)w(e,t);else{let g=D(e,t);if(g===E)continue;S(e,t,typeof s==`function`?s(g,t):s)}}}function j(e,t,s,g,S=!1){let w=t.indexOf(`*`);if(w===t.length-1){let g=t.slice(0,-1),w=e;for(let e of g){if(typeof w!=`object`||!w||!w)return;w=w[e]}if(Array.isArray(w))if(S)for(let e=0;e<w.length;e++)w[e]=void 0;else for(let e=0;e<w.length;e++){let t=[...g,e.toString()],S=typeof s==`function`?s(w[e],t):s;w[e]=S}else if(typeof w==`object`&&w)if(S){let e=[];for(let t in w)Object.prototype.hasOwnProperty.call(w,t)&&e.push(t);for(let t of e)delete w[t]}else for(let e in w){let t=[...g,e],S=typeof s==`function`?s(w[e],t):s;w[e]=S}}else F(e,t,s,w,g,S)}function F(e,t,s,g,E,D=!1){let k=t.slice(0,g),F=t.slice(g+1),L=[];function B(e,t){if(t===k.length){if(Array.isArray(e))for(let s=0;s<e.length;s++)L[t]=s.toString(),B(e[s],t+1);else if(typeof e==`object`&&e)for(let s in e)L[t]=s,B(e[s],t+1)}else if(t<k.length){let s=k[t];e&&typeof e==`object`&&e&&s in e&&(L[t]=s,B(e[s],t+1))}else F.includes(`*`)?j(e,F,typeof s==`function`?(e,g)=>s(e,[...L.slice(0,t),...g]):s,E,D):D?w(e,F):S(e,F,typeof s==`function`?s(O(e,F),[...L.slice(0,t),...F]):s)}if(k.length===0)B(e,0);else{let t=e;for(let e=0;e<k.length;e++){let s=k[e];if(typeof t!=`object`||!t||!t)return;t=t[s],L[e]=s}t!=null&&B(t,k.length)}}function L(e){if(e.length===0)return null;let t=new Map;for(let s of e){let e=g(s),S=t;for(let t=0;t<e.length;t++){let s=e[t];S.has(s)||S.set(s,new Map),S=S.get(s)}}return t}function B(e,t){if(!t)return e;function s(e,t,g=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let g=[];for(let S=0;S<e.length;S++){let w=S.toString();t.has(w)||t.has(`*`)?g[S]=s(e[S],t.get(w)||t.get(`*`)):g[S]=e[S]}return g}let S=Object.create(Object.getPrototypeOf(e));for(let g in e)Object.prototype.hasOwnProperty.call(e,g)&&(t.has(g)||t.has(`*`)?S[g]=s(e[g],t.get(g)||t.get(`*`)):S[g]=e[g]);return S}return s(e,t)}function H(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,s=!1,g=``;for(let S=0;S<e.length;S++){let w=e[S];if((w===`"`||w===`'`)&&t>0)s?w===g&&(s=!1,g=``):(s=!0,g=w);else if(w===`[`&&!s)t++;else if(w===`]`&&!s&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function q(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)H(t)}function ee(e={}){let{paths:t=[],censor:g=`[REDACTED]`,serialize:S=JSON.stringify,strict:w=!0,remove:E=!1}=e;q(t);let D=L(t);return function(e){if(w&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return S?S(e):e;let O=B(e,D),j=e,F=g;return typeof g==`function`&&(F=g),k(O,t,F,E),S===!1?(O.restore=function(){return s(j)},O):typeof S==`function`?S(O):JSON.stringify(O)}}t.exports=ee})),require_symbols=__commonJSMin(((e,t)=>{let s=Symbol(`pino.setLevel`),g=Symbol(`pino.getLevel`),S=Symbol(`pino.levelVal`),w=Symbol(`pino.levelComp`),E=Symbol(`pino.useLevelLabels`),D=Symbol(`pino.useOnlyCustomLevels`),O=Symbol(`pino.mixin`),k=Symbol(`pino.lsCache`),j=Symbol(`pino.chindings`),F=Symbol(`pino.asJson`),L=Symbol(`pino.write`),B=Symbol(`pino.redactFmt`),H=Symbol(`pino.time`),q=Symbol(`pino.timeSliceIndex`),ee=Symbol(`pino.stream`),J=Symbol(`pino.stringify`),Y=Symbol(`pino.stringifySafe`),te=Symbol(`pino.stringifiers`),ne=Symbol(`pino.end`),ae=Symbol(`pino.formatOpts`),oe=Symbol(`pino.messageKey`),se=Symbol(`pino.errorKey`),ce=Symbol(`pino.nestedKey`),ue=Symbol(`pino.nestedKeyStr`),de=Symbol(`pino.mixinMergeStrategy`),fe=Symbol(`pino.msgPrefix`),me=Symbol(`pino.wildcardFirst`),ge=Symbol.for(`pino.serializers`),_e=Symbol.for(`pino.formatters`),ve=Symbol.for(`pino.hooks`);t.exports={setLevelSym:s,getLevelSym:g,levelValSym:S,levelCompSym:w,useLevelLabelsSym:E,mixinSym:O,lsCacheSym:k,chindingsSym:j,asJsonSym:F,writeSym:L,serializersSym:ge,redactFmtSym:B,timeSym:H,timeSliceIndexSym:q,streamSym:ee,stringifySym:J,stringifySafeSym:Y,stringifiersSym:te,endSym:ne,formatOptsSym:ae,messageKeySym:oe,errorKeySym:se,nestedKeySym:ce,wildcardFirstSym:me,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:D,formattersSym:_e,hooksSym:ve,nestedKeyStrSym:ue,mixinMergeStrategySym:de,msgPrefixSym:fe}})),require_redaction=__commonJSMin(((e,t)=>{let s=require_redact(),{redactFmtSym:g,wildcardFirstSym:S}=require_symbols(),w=/[^.[\]]+|\[([^[\]]*?)\]/g,E=`[Redacted]`,D=!1;function O(e,t){let{paths:E,censor:D,remove:O}=k(e),j=E.reduce((e,t)=>{w.lastIndex=0;let s=w.exec(t),g=w.exec(t),E=s[1]===void 0?s[0]:s[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(E===`*`&&(E=S),g===null)return e[E]=null,e;if(e[E]===null)return e;let{index:D}=g,O=`${t.substr(D,t.length-1)}`;return e[E]=e[E]||[],E!==S&&e[E].length===0&&e[E].push(...e[S]||[]),E===S&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(O)}),e[E].push(O),e},{}),F={[g]:s({paths:E,censor:D,serialize:t,strict:!1,remove:O})},L=(...e)=>t(typeof D==`function`?D(...e):D);return[...Object.keys(j),...Object.getOwnPropertySymbols(j)].reduce((e,g)=>{if(j[g]===null)e[g]=e=>L(e,[g]);else{let S=typeof D==`function`?(e,t)=>D(e,[g,...t]):D;e[g]=s({paths:j[g],censor:S,serialize:t,strict:!1,remove:O})}return e},F)}function k(e){if(Array.isArray(e))return e={paths:e,censor:E},e;let{paths:t,censor:s=E,remove:g}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return g===!0&&(s=void 0),{paths:t,censor:s,remove:g}}t.exports=O})),require_time=__commonJSMin(((e,t)=>{let s=()=>``,g=()=>`,"time":${Date.now()}`,S=()=>`,"time":${Math.round(Date.now()/1e3)}`,w=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,E=1000000n,D=1000000000n,O=BigInt(Date.now())*1000000n,k=process.hrtime.bigint();t.exports={nullTime:s,epochTime:g,unixTime:S,isoTime:w,isoTimeNano:()=>{let e=O+(process.hrtime.bigint()-k),t=e/D,s=e%D,g=Number(t*1000n+s/1000000n),S=new Date(g);return`,"time":"${S.getUTCFullYear()}-${(S.getUTCMonth()+1).toString().padStart(2,`0`)}-${S.getUTCDate().toString().padStart(2,`0`)}T${S.getUTCHours().toString().padStart(2,`0`)}:${S.getUTCMinutes().toString().padStart(2,`0`)}:${S.getUTCSeconds().toString().padStart(2,`0`)}.${s.toString().padStart(9,`0`)}Z"`}}})),require_quick_format_unescaped=__commonJSMin(((e,t)=>{function s(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=g;function g(e,t,g){var S=g&&g.stringify||s,w=1;if(typeof e==`object`&&e){var E=t.length+w;if(E===1)return e;var D=Array(E);D[0]=S(e);for(var O=1;O<E;O++)D[O]=S(t[O]);return D.join(` `)}if(typeof e!=`string`)return e;var k=t.length;if(k===0)return e;for(var j=``,F=1-w,L=-1,B=e&&e.length||0,H=0;H<B;){if(e.charCodeAt(H)===37&&H+1<B){switch(L=L>-1?L:0,e.charCodeAt(H+1)){case 100:case 102:if(F>=k||t[F]==null)break;L<H&&(j+=e.slice(L,H)),j+=Number(t[F]),L=H+2,H++;break;case 105:if(F>=k||t[F]==null)break;L<H&&(j+=e.slice(L,H)),j+=Math.floor(Number(t[F])),L=H+2,H++;break;case 79:case 111:case 106:if(F>=k||t[F]===void 0)break;L<H&&(j+=e.slice(L,H));var q=typeof t[F];if(q===`string`){j+=`'`+t[F]+`'`,L=H+2,H++;break}if(q===`function`){j+=t[F].name||`<anonymous>`,L=H+2,H++;break}j+=S(t[F]),L=H+2,H++;break;case 115:if(F>=k)break;L<H&&(j+=e.slice(L,H)),j+=String(t[F]),L=H+2,H++;break;case 37:L<H&&(j+=e.slice(L,H)),j+=`%`,L=H+2,H++,F--;break}++F}++H}return L===-1?e:(L<B&&(j+=e.slice(L)),j)}})),require_atomic_sleep=__commonJSMin(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function s(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=s}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),require_sonic_boom=__commonJSMin(((e,t)=>{let s=__require(`fs`),g=__require(`events`),S=__require(`util`).inherits,w=__require(`path`),E=require_atomic_sleep(),D=__require(`assert`),O=100,k=Buffer.allocUnsafe(0),j=16*1024,F=`buffer`,L=`utf8`,[B,H]=(process.versions.node||`0.0`).split(`.`).map(Number),q=B>=22&&H>=7;function ee(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function g(s,g){if(s){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,s)}):t.emit(`error`,s);return}let S=t._reopening;t.fd=g,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():S&&process.nextTick(()=>t.emit(`drain`)))}let S=t.append?`a`:`w`,E=t.mode;if(t.sync)try{t.mkdir&&s.mkdirSync(w.dirname(e),{recursive:!0}),g(null,s.openSync(e,S,E))}catch(e){throw g(e),e}else t.mkdir?s.mkdir(w.dirname(e),{recursive:!0},t=>{if(t)return g(t);s.open(e,S,E,g)}):s.open(e,S,E,g)}function J(e){if(!(this instanceof J))return new J(e);let{fd:t,dest:g,minLength:S,maxLength:w,maxWrite:D,periodicFlush:O,sync:j,append:B=!0,mkdir:H,retryEAGAIN:q,fsync:ne,contentMode:se,mode:ve}=e||{};t||=g,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(S||0,16387),this.file=null,this.destroyed=!1,this.minLength=S||0,this.maxLength=w||0,this.maxWrite=D||16384,this._periodicFlush=O||0,this._periodicFlushTimer=void 0,this.sync=j||!1,this.writable=!0,this._fsync=ne||!1,this.append=B||!1,this.mode=ve,this.retryEAGAIN=q||(()=>!0),this.mkdir=H||!1;let ye,Ce;if(se===F)this._writingBuf=k,this.write=oe,this.flush=ue,this.flushSync=fe,this._actualWrite=ge,ye=()=>s.writeSync(this.fd,this._writingBuf),Ce=()=>s.write(this.fd,this._writingBuf,this.release);else if(se===void 0||se===L)this._writingBuf=``,this.write=ae,this.flush=ce,this.flushSync=de,this._actualWrite=me,ye=()=>Buffer.isBuffer(this._writingBuf)?s.writeSync(this.fd,this._writingBuf):s.writeSync(this.fd,this._writingBuf,`utf8`),Ce=()=>Buffer.isBuffer(this._writingBuf)?s.write(this.fd,this._writingBuf,this.release):s.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${L}" and "${F}", but passed ${se}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)ee(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{E(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(Ce,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let g=Y(this._writingBuf,this._len,t);if(this._len=g.len,this._writingBuf=g.writingBuf,this._writingBuf.length){if(!this.sync){Ce();return}try{do{let e=ye(),t=Y(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&s.fsyncSync(this.fd);let S=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):S>this.minLength?this._actualWrite():this._ending?S>0?this._actualWrite():(this._writing=!1,_e(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(te,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Y(e,t,s){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-s,0),e=e.subarray(s),{writingBuf:e,len:t}}function te(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}S(J,g);function ne(e,t){return e.length===0?k:e.length===1?e[0]:Buffer.concat(e,t)}function ae(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),s=this._len+t,g=this._bufs;return this.maxLength&&s>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(g.length===0||Buffer.byteLength(g[g.length-1])+t>this.maxWrite?g.push(e):g[g.length-1]+=e,this._len=s,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function oe(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,s=this._bufs,g=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(s.length===0||g[g.length-1]+e.length>this.maxWrite?(s.push([e]),g.push(e.length)):(s[s.length-1].push(e),g[g.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function se(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{s.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,g)},g=s=>{this._flushPending=!1,e(s),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,g)}function ce(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&se.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function ue(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&se.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}J.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&s.close(t,e=>{if(e)return this.emit(`error`,e)})}),ee(this.file,this)},J.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():_e(this)))};function de(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?s.writeSync(this.fd,e):s.writeSync(this.fd,e,`utf8`),g=Y(e,this._len,t);e=g.writingBuf,this._len=g.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;E(100)}}try{s.fsyncSync(this.fd)}catch{}}function fe(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=k);let e=k;for(;this._bufs.length||e.length;){e.length<=0&&(e=ne(this._bufs[0],this._lens[0]));try{let t=s.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;E(100)}}}J.prototype.destroy=function(){this.destroyed||_e(this)};function me(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?s.writeSync(this.fd,this._writingBuf):s.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else s.write(this.fd,this._writingBuf,e)}function ge(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:ne(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,s.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else q&&(this._writingBuf=Buffer.from(this._writingBuf)),s.write(this.fd,this._writingBuf,e)}function _e(e){if(e.fd===-1){e.once(`ready`,_e.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],D(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{s.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?s.close(e.fd,g):g()}function g(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}J.SonicBoom=J,J.default=J,t.exports=J})),require_on_exit_leak_free=__commonJSMin(((e,t)=>{let s={exit:[],beforeExit:[]},g={exit:O,beforeExit:k},S;function w(){S===void 0&&(S=new FinalizationRegistry(F))}function E(e){s[e].length>0||process.on(e,g[e])}function D(e){s[e].length>0||(process.removeListener(e,g[e]),s.exit.length===0&&s.beforeExit.length===0&&(S=void 0))}function O(){j(`exit`)}function k(){j(`beforeExit`)}function j(e){for(let t of s[e]){let s=t.deref(),g=t.fn;s!==void 0&&g(s,e)}s[e]=[]}function F(e){for(let t of[`exit`,`beforeExit`]){let g=s[t].indexOf(e);s[t].splice(g,g+1),D(t)}}function L(e,t,g){if(t===void 0)throw Error(`the object can't be undefined`);E(e);let D=new WeakRef(t);D.fn=g,w(),S.register(t,D),s[e].push(D)}function B(e,t){L(`exit`,e,t)}function H(e,t){L(`beforeExit`,e,t)}function q(e){if(S!==void 0){S.unregister(e);for(let t of[`exit`,`beforeExit`])s[t]=s[t].filter(t=>{let s=t.deref();return s&&s!==e}),D(t)}}t.exports={register:B,registerBeforeExit:H,unregister:q}})),require_package=__commonJSMin(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),require_wait=__commonJSMin(((e,t)=>{let s=1e4;function g(e,t,g,S,w){let E=S===1/0?1/0:Date.now()+S,D=()=>{let S=Atomics.load(e,t);if(S===g){w(null,`ok`);return}if(E!==1/0&&Date.now()>E){w(null,`timed-out`);return}let O=E===1/0?s:Math.min(s,Math.max(1,E-Date.now())),k=Atomics.waitAsync(e,t,S,O);k.async?k.value.then(D):setImmediate(D)};D()}function S(e,t,g,S,w){let E=S===1/0?1/0:Date.now()+S,D=()=>{if(Atomics.load(e,t)!==g){w(null,`ok`);return}if(E!==1/0&&Date.now()>E){w(null,`timed-out`);return}let S=E===1/0?s:Math.min(s,Math.max(1,E-Date.now())),O=Atomics.waitAsync(e,t,g,S);O.async?O.value.then(D):setImmediate(D)};D()}t.exports={wait:g,waitDiff:S}})),require_indexes=__commonJSMin(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),require_thread_stream=__commonJSMin(((e,t)=>{let{version:s}=require_package(),{EventEmitter:g}=__require(`events`),{Worker:S}=__require(`worker_threads`),{join:w}=__require(`path`),{pathToFileURL:E}=__require(`url`),{wait:D}=require_wait(),{WRITE_INDEX:O,READ_INDEX:k}=require_indexes(),j=__require(`buffer`),F=__require(`assert`),L=Symbol(`kImpl`),B=j.constants.MAX_STRING_LENGTH;var H=class{constructor(e){this._value=e}deref(){return this._value}},q=class{register(){}unregister(){}};let ee=process.env.NODE_V8_COVERAGE?q:global.FinalizationRegistry||q,J=process.env.NODE_V8_COVERAGE?H:global.WeakRef||H,Y=new ee(e=>{e.exited||e.terminate()});function te(e,t){let{filename:g,workerData:D}=t,O=new S((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||w(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:g.indexOf(`file://`)===0?g:E(g).href,dataBuf:e[L].dataBuf,stateBuf:e[L].stateBuf,workerData:{$context:{threadStreamVersion:s},...D}}});return O.stream=new H(e),O.on(`message`,oe),O.on(`exit`,se),Y.register(e,O),O}function ne(e){F(!e[L].sync),e[L].needDrain&&(e[L].needDrain=!1,e.emit(`drain`))}function ae(e){let t=Atomics.load(e[L].state,O),s=e[L].data.length-t;if(s>0){if(e[L].buf.length===0){e[L].flushing=!1,e[L].ending?me(e):e[L].needDrain&&process.nextTick(ne,e);return}let t=e[L].buf.slice(0,s),g=Buffer.byteLength(t);g<=s?(e[L].buf=e[L].buf.slice(s),fe(e,t,ae.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k);g>e[L].data.length;)s/=2,t=e[L].buf.slice(0,s),g=Buffer.byteLength(t);e[L].buf=e[L].buf.slice(s),fe(e,t,ae.bind(null,e))}})}else if(s===0){if(t===0&&e[L].buf.length===0)return;e.flush(()=>{Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k),ae(e)})}else de(e,Error(`overwritten`))}function oe(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new J(t),t.flush(()=>{t[L].ready=!0,t.emit(`ready`)});break;case`ERROR`:de(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:de(t,Error(`this should not happen: `+e.code))}}function se(e){let t=this.stream.deref();t!==void 0&&(Y.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,se),de(t,e===0?null:Error(`the worker thread exited`)))}var ce=class extends g{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[L]={},this[L].stateBuf=new SharedArrayBuffer(128),this[L].state=new Int32Array(this[L].stateBuf),this[L].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[L].data=Buffer.from(this[L].dataBuf),this[L].sync=e.sync||!1,this[L].ending=!1,this[L].ended=!1,this[L].needDrain=!1,this[L].destroyed=!1,this[L].flushing=!1,this[L].ready=!1,this[L].finished=!1,this[L].errored=null,this[L].closed=!1,this[L].buf=``,this.worker=te(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[L].destroyed)return ue(this,Error(`the worker has exited`)),!1;if(this[L].ending)return ue(this,Error(`the worker is ending`)),!1;if(this[L].flushing&&this[L].buf.length+e.length>=B)try{ge(this),this[L].flushing=!0}catch(e){return de(this,e),!1}if(this[L].buf+=e,this[L].sync)try{return ge(this),!0}catch(e){return de(this,e),!1}return this[L].flushing||(this[L].flushing=!0,setImmediate(ae,this)),this[L].needDrain=this[L].data.length-this[L].buf.length-Atomics.load(this[L].state,O)<=0,!this[L].needDrain}end(){this[L].destroyed||(this[L].ending=!0,me(this))}flush(e){if(this[L].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[L].state,O);D(this[L].state,k,t,1/0,(t,s)=>{if(t){de(this,t),process.nextTick(e,t);return}if(s===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[L].destroyed||(ge(this),_e(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[L].ready}get destroyed(){return this[L].destroyed}get closed(){return this[L].closed}get writable(){return!this[L].destroyed&&!this[L].ending}get writableEnded(){return this[L].ending}get writableFinished(){return this[L].finished}get writableNeedDrain(){return this[L].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[L].errored}};function ue(e,t){setImmediate(()=>{e.emit(`error`,t)})}function de(e,t){e[L].destroyed||(e[L].destroyed=!0,t&&(e[L].errored=t,ue(e,t)),e.worker.exited?setImmediate(()=>{e[L].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[L].closed=!0,e.emit(`close`)}))}function fe(e,t,s){let g=Atomics.load(e[L].state,O),S=Buffer.byteLength(t);return e[L].data.write(t,g),Atomics.store(e[L].state,O,g+S),Atomics.notify(e[L].state,O),s(),!0}function me(e){if(!(e[L].ended||!e[L].ending||e[L].flushing)){e[L].ended=!0;try{e.flushSync();let t=Atomics.load(e[L].state,k);Atomics.store(e[L].state,O,-1),Atomics.notify(e[L].state,O);let s=0;for(;t!==-1;){if(Atomics.wait(e[L].state,k,t,1e3),t=Atomics.load(e[L].state,k),t===-2){de(e,Error(`end() failed`));return}if(++s===10){de(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[L].finished=!0,e.emit(`finish`)})}catch(t){de(e,t)}}}function ge(e){let t=()=>{e[L].ending?me(e):e[L].needDrain&&process.nextTick(ne,e)};for(e[L].flushing=!1;e[L].buf.length!==0;){let s=Atomics.load(e[L].state,O),g=e[L].data.length-s;if(g===0){_e(e),Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k);continue}else if(g<0)throw Error(`overwritten`);let S=e[L].buf.slice(0,g),w=Buffer.byteLength(S);if(w<=g)e[L].buf=e[L].buf.slice(g),fe(e,S,t);else{for(_e(e),Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k);w>e[L].buf.length;)g/=2,S=e[L].buf.slice(0,g),w=Buffer.byteLength(S);e[L].buf=e[L].buf.slice(g),fe(e,S,t)}}}function _e(e){if(e[L].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[L].state,O),s=0;for(;;){let g=Atomics.load(e[L].state,k);if(g===-2)throw Error(`_flushSync failed`);if(g!==t)Atomics.wait(e[L].state,k,g,1e3);else break;if(++s===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=ce})),require_transport=__commonJSMin(((e,t)=>{let{createRequire:s}=__require(`module`),{existsSync:g}=__require(`node:fs`),S=require_caller(),{join:w,isAbsolute:E,sep:D}=__require(`node:path`),{fileURLToPath:O}=__require(`node:url`),k=require_atomic_sleep(),j=require_on_exit_leak_free(),F=require_thread_stream();function L(e){j.register(e,Y),j.registerBeforeExit(e,te),e.on(`close`,function(){j.unregister(e)})}function B(){let e=process.execArgv;for(let t=0;t<e.length;t++){let s=e[t];if(s===`--import`||s===`--require`||s===`-r`||s.startsWith(`--import=`)||s.startsWith(`--require=`)||s.startsWith(`-r=`))return!0}return!1}function H(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let s=[],g=!1;for(let e=0;e<t.length;e++){let S=t[e];if(S===`--require`||S===`-r`||S===`--import`){let w=t[e+1];if(w&&q(w)){g=!0,e++;continue}s.push(S),w&&(s.push(w),e++);continue}if((S.startsWith(`--require=`)||S.startsWith(`-r=`)||S.startsWith(`--import=`))&&q(S.slice(S.indexOf(`=`)+1))){g=!0;continue}s.push(S)}return g?s.join(` `):e}function q(e){let t=ee(e);if(!t)return!1;let s=t;if(s.startsWith(`file://`))try{s=O(s)}catch{return!1}return E(s)&&!g(s)}function ee(e){let t=e[0],s=e[e.length-1];return t===`"`&&s===`"`||t===`'`&&s===`'`?e.slice(1,-1):e}function J(e,t,s,g,S){if(!s.execArgv&&B()&&__require.main===void 0&&(s={...s,execArgv:[]}),!s.env&&process.env.NODE_OPTIONS){let e=H(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(s={...s,env:{...process.env,NODE_OPTIONS:e}})}s={...s,name:S};let w=new F({filename:e,workerData:t,workerOpts:s,sync:g});w.on(`ready`,E),w.on(`close`,function(){process.removeListener(`exit`,D)}),process.on(`exit`,D);function E(){process.removeListener(`exit`,D),w.unref(),s.autoEnd!==!1&&L(w)}function D(){w.closed||(w.flushSync(),k(100),w.end())}return w}function Y(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function te(e){e.flushSync()}function ne(e){let{pipeline:t,targets:g,levels:O,dedupe:k,worker:j={},caller:F=S(),sync:L=!1}=e,B={...e.options},H=typeof F==`string`?[F]:F,q=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),ee=e.target;if(ee&&g)throw Error(`only one of target or targets can be specified`);g?(ee=q[`pino-worker`]||w(__dirname,`worker.js`),B.targets=g.filter(e=>e.target).map(e=>({...e,target:te(e.target)})),B.pipelines=g.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:te(t.target)})))):t&&(ee=q[`pino-worker`]||w(__dirname,`worker.js`),B.pipelines=[t.map(e=>({...e,target:te(e.target)}))]),O&&(B.levels=O),k&&(B.dedupe=k),B.pinoWillSendConfig=!0;let Y=g||t?`pino.transport`:ee;return J(te(ee),B,j,L,Y);function te(e){if(e=q[e]||e,E(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return w(__dirname,`..`,`file.js`);let t;for(let g of H)try{t=s(g===`node:repl`?process.cwd()+D:g).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=ne})),require_tools=__commonJSMin(((e,t)=>{let s=__require(`node:diagnostics_channel`),g=require_quick_format_unescaped(),{mapHttpRequest:S,mapHttpResponse:w}=require_pino_std_serializers(),E=require_sonic_boom(),D=require_on_exit_leak_free(),{lsCacheSym:O,chindingsSym:k,writeSym:j,serializersSym:F,formatOptsSym:L,endSym:B,stringifiersSym:H,stringifySym:q,stringifySafeSym:ee,wildcardFirstSym:J,nestedKeySym:Y,formattersSym:te,messageKeySym:ne,errorKeySym:ae,nestedKeyStrSym:oe,msgPrefixSym:se}=require_symbols(),{isMainThread:ce}=__require(`worker_threads`),ue=require_transport(),[de]=process.versions.node.split(`.`).map(e=>Number(e)),fe=s.tracingChannel(`pino_asJson`),me=de>=25?e=>JSON.stringify(e):ve;function ge(){}function _e(e,t){if(!t)return s;return function(...g){t.call(this,g,s,e)};function s(t,...s){if(typeof t==`object`){let E=t;t!==null&&(t.method&&t.headers&&t.socket?t=S(t):typeof t.setHeader==`function`&&(t=w(t)));let D;E===null&&s.length===0?D=[null]:(E=s.shift(),D=s),typeof this[se]==`string`&&E!=null&&(E=this[se]+E),this[j](t,g(E,D,this[L]),e)}else{let S=t===void 0?s.shift():t;typeof this[se]==`string`&&S!=null&&(S=this[se]+S),this[j](null,g(S,s,this[L]),e)}}}function ve(e){let t=``,s=0,g=!1,S=255,w=e.length;if(w>100)return JSON.stringify(e);for(var E=0;E<w&&S>=32;E++)S=e.charCodeAt(E),(S===34||S===92)&&(t+=e.slice(s,E)+`\\`,s=E,g=!0);return g?t+=e.slice(s):t=e,S<32?JSON.stringify(e):`"`+t+`"`}function ye(e,t,s,g){if(fe.hasSubscribers===!1)return Ce.call(this,e,t,s,g);let S={instance:this,arguments};return fe.traceSync(Ce,S,this,e,t,s,g)}function Ce(e,t,s,g){let S=this[q],w=this[ee],E=this[H],D=this[B],j=this[k],L=this[F],se=this[te],ce=this[ne],ue=this[ae],de=this[O][s]+g;de+=j;let fe;se.log&&(e=se.log(e));let ge=E[J],_e=``;for(let t in e)if(fe=e[t],Object.prototype.hasOwnProperty.call(e,t)&&fe!==void 0){L[t]?fe=L[t](fe):t===ue&&L.err&&(fe=L.err(fe));let e=E[t]||ge;switch(typeof fe){case`undefined`:case`function`:continue;case`number`:Number.isFinite(fe)===!1&&(fe=null);case`boolean`:e&&(fe=e(fe));break;case`string`:fe=(e||me)(fe);break;default:fe=(e||S)(fe,w)}if(fe===void 0)continue;let s=me(t);_e+=`,`+s+`:`+fe}let ve=``;if(t!==void 0){fe=L[ce]?L[ce](t):t;let e=E[ce]||ge;switch(typeof fe){case`function`:break;case`number`:Number.isFinite(fe)===!1&&(fe=null);case`boolean`:e&&(fe=e(fe)),ve=`,"`+ce+`":`+fe;break;case`string`:fe=(e||me)(fe),ve=`,"`+ce+`":`+fe;break;default:fe=(e||S)(fe,w),ve=`,"`+ce+`":`+fe}}return this[Y]&&_e?de+this[oe]+_e.slice(1)+`}`+ve+D:de+_e+ve+D}function we(e,t){let s,g=e[k],S=e[q],w=e[ee],E=e[H],D=E[J],O=e[F],j=e[te].bindings;t=j(t);for(let e in t)if(s=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&s!==void 0)===!0){if(s=O[e]?O[e](s):s,s=(E[e]||D||S)(s,w),s===void 0)continue;g+=`,"`+e+`":`+s}return g}function Te(e){return e.write!==e.constructor.prototype.write}function De(e){let t=new E(e);return t.on(`error`,s),!e.sync&&ce&&(D.register(t,je),t.on(`close`,function(){D.unregister(t)})),t;function s(e){if(e.code===`EPIPE`){t.write=ge,t.end=ge,t.flushSync=ge,t.destroy=ge;return}t.removeListener(`error`,s),t.emit(`error`,e)}}function je(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function Me(e){return function(t,s,g={},S){if(typeof g==`string`)S=De({dest:g}),g={};else if(typeof S==`string`){if(g&&g.transport)throw Error(`only one of option.transport or stream can be specified`);S=De({dest:S})}else if(g instanceof E||g.writable||g._writableState)S=g,g={};else if(g.transport){if(g.transport instanceof E||g.transport.writable||g.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(g.transport.targets&&g.transport.targets.length&&g.formatters&&typeof g.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;g.customLevels&&(e=g.useOnlyCustomLevels?g.customLevels:Object.assign({},g.levels,g.customLevels)),S=ue({caller:s,...g.transport,levels:e})}if(g=Object.assign({},e,g),g.serializers=Object.assign({},e.serializers,g.serializers),g.formatters=Object.assign({},e.formatters,g.formatters),g.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:w,onChild:D}=g;return w===!1&&(g.level=`silent`),D||(g.onChild=ge),S||=Te(process.stdout)?process.stdout:De({fd:process.stdout.fd||1}),{opts:g,stream:S}}}function Pe(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[ee])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function Ie(e,t,s){return{level:e,bindings:t,log:s}}function Re(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:ge,buildSafeSonicBoom:De,asChindings:we,asJson:ye,genLog:_e,createArgsNormalizer:Me,stringify:Pe,buildFormatters:Ie,normalizeDestFileDescriptor:Re}})),require_constants$1=__commonJSMin(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),require_levels=__commonJSMin(((e,t)=>{let{lsCacheSym:s,levelValSym:g,useOnlyCustomLevelsSym:S,streamSym:w,formattersSym:E,hooksSym:D,levelCompSym:O}=require_symbols(),{noop:k,genLog:j}=require_tools(),{DEFAULT_LEVELS:F,SORTING_ORDER:L}=require_constants$1(),B={fatal:e=>{let t=j(F.fatal,e);return function(...e){let s=this[w];if(t.call(this,...e),typeof s.flushSync==`function`)try{s.flushSync()}catch{}}},error:e=>j(F.error,e),warn:e=>j(F.warn,e),info:e=>j(F.info,e),debug:e=>j(F.debug,e),trace:e=>j(F.trace,e)},H=Object.keys(F).reduce((e,t)=>(e[F[t]]=t,e),{}),q=Object.keys(H).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function ee(e){let t=e[E].level,{labels:g}=e.levels,S={};for(let e in g){let s=t(g[e],Number(e));S[e]=JSON.stringify(s).slice(0,-1)}return e[s]=S,e}function J(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function Y(e){let{labels:t,values:s}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(s[e]===void 0)throw Error(`unknown level `+e);let w=this[g],E=this[g]=s[e],F=this[S],L=this[O],H=this[D].logMethod;for(let e in s){if(L(s[e],E)===!1){this[e]=k;continue}this[e]=J(e,F)?B[e](H):j(s[e],H)}this.emit(`level-change`,e,E,t[w],w,this)}function te(e){let{levels:t,levelVal:s}=this;return t&&t.labels?t.labels[s]:``}function ne(e){let{values:t}=this.levels,s=t[e];return s!==void 0&&this[O](s,this[g])}function ae(e,t,s){return e===L.DESC?t<=s:t>=s}function oe(e){return typeof e==`string`?ae.bind(null,e):e}function se(e=null,t=!1){let s=e?Object.keys(e).reduce((t,s)=>(t[e[s]]=s,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:H,s),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:F,e)}}function ce(e,t,s){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),s?[]:Object.keys(H).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),s?null:F,t)))throw Error(`default level:${e} must be included in custom levels`)}function ue(e,t){let{labels:s,values:g}=e;for(let e in t){if(e in g)throw Error(`levels cannot be overridden`);if(t[e]in s)throw Error(`pre-existing level values cannot be used for new levels`)}}function de(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(L).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:q,genLsCache:ee,levelMethods:B,getLevel:te,setLevel:Y,isLevelEnabled:ne,mappings:se,assertNoLevelCollisions:ue,assertDefaultLevelFound:ce,genLevelComparison:oe,assertLevelComparison:de}})),require_meta=__commonJSMin(((e,t)=>{t.exports={version:`10.3.1`}})),require_proto=__commonJSMin(((e,t)=>{let{EventEmitter:s}=__require(`node:events`),{lsCacheSym:g,levelValSym:S,setLevelSym:w,getLevelSym:E,chindingsSym:D,mixinSym:O,asJsonSym:k,writeSym:j,mixinMergeStrategySym:F,timeSym:L,timeSliceIndexSym:B,streamSym:H,serializersSym:q,formattersSym:ee,errorKeySym:J,messageKeySym:Y,useOnlyCustomLevelsSym:te,needsMetadataGsym:ne,redactFmtSym:ae,stringifySym:oe,formatOptsSym:se,stringifiersSym:ce,msgPrefixSym:ue,hooksSym:de}=require_symbols(),{getLevel:fe,setLevel:me,isLevelEnabled:ge,mappings:_e,initialLsCache:ve,genLsCache:ye,assertNoLevelCollisions:Ce}=require_levels(),{asChindings:we,asJson:Te,buildFormatters:De,stringify:je,noop:Me}=require_tools(),{version:Pe}=require_meta(),Ie=require_redaction(),Re={constructor:class{},child:Be,bindings:Ve,setBindings:Ue,flush:Ke,isLevelEnabled:ge,version:Pe,get level(){return this[E]()},set level(e){this[w](e)},get levelVal(){return this[S]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[ue]},get[Symbol.toStringTag](){return`Pino`},[g]:ve,[j]:Ge,[k]:Te,[E]:fe,[w]:me};Object.setPrototypeOf(Re,s.prototype),t.exports=function(){return Object.create(Re)};let ze=e=>e;function Be(e,t){if(!e)throw Error(`missing bindings for child Pino`);let s=this[q],g=this[ee],S=Object.create(this);if(t==null)return S[ee].bindings!==ze&&(S[ee]=De(g.level,ze,g.log)),S[D]=we(S,e),this.onChild!==Me&&this.onChild(S),S;if(t.hasOwnProperty(`serializers`)===!0){S[q]=Object.create(null);for(let e in s)S[q][e]=s[e];let e=Object.getOwnPropertySymbols(s);for(var E=0;E<e.length;E++){let t=e[E];S[q][t]=s[t]}for(let e in t.serializers)S[q][e]=t.serializers[e];let g=Object.getOwnPropertySymbols(t.serializers);for(var O=0;O<g.length;O++){let e=g[O];S[q][e]=t.serializers[e]}}else S[q]=s;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:s,log:w}=t.formatters;S[ee]=De(e||g.level,s||ze,w||g.log)}else S[ee]=De(g.level,ze,g.log);if(t.hasOwnProperty(`customLevels`)===!0&&(Ce(this.levels,t.customLevels),S.levels=_e(t.customLevels,S[te]),ye(S)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){S.redact=t.redact;let e=Ie(S.redact,je),s={stringify:e[ae]};S[oe]=je,S[ce]=e,S[se]=s}if(typeof t.msgPrefix==`string`&&(S[ue]=(this[ue]||``)+t.msgPrefix),S[D]=we(S,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;S[w](e)}return this.onChild(S),S}function Ve(){let e=`{${this[D].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function Ue(e){this[D]=we(this,e)}function We(e,t){return Object.assign(t,e)}function Ge(e,t,s){let g=this[L](),S=this[O],w=this[J],E=this[Y],D=this[F]||We,j,q=this[de].streamWrite;e==null?j={}:e instanceof Error?(j={[w]:e},t===void 0&&(t=e.message)):(j=e,t===void 0&&e[E]===void 0&&e[w]&&(t=e[w].message)),S&&(j=D(j,S(j,s,this)));let ee=this[k](j,t,s,g),te=this[H];te[ne]===!0&&(te.lastLevel=s,te.lastObj=j,te.lastMsg=t,te.lastTime=g.slice(this[B]),te.lastLogger=this),te.write(q?q(ee):ee)}function Ke(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[H];typeof t.flush==`function`?t.flush(e||Me):e&&e()}})),require_safe_stable_stringify=__commonJSMin(((e,t)=>{let{hasOwnProperty:s}=Object.prototype,g=J();g.configure=J,g.stringify=g,g.default=g,e.stringify=g,e.configure=J,t.exports=g;let S=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function w(e){return e.length<5e3&&!S.test(e)?`"${e}"`:JSON.stringify(e)}function E(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let s=e[t],g=t;for(;g!==0&&e[g-1]>s;)e[g]=e[g-1],g--;e[g]=s}return e}let D=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function O(e){return D.call(e)!==void 0&&e.length!==0}function k(e,t,s){e.length<s&&(s=e.length);let g=t===`,`?``:` `,S=`"0":${g}${e[0]}`;for(let w=1;w<s;w++)S+=`${t}"${w}":${g}${e[w]}`;return S}function j(e){if(s.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function F(e){let t;if(s.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function L(e,t){let g;if(s.call(e,t)&&(g=e[t],typeof g!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return g===void 0?!0:g}function B(e,t){let g;if(s.call(e,t)){if(g=e[t],typeof g!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(g))throw TypeError(`The "${t}" argument must be an integer`);if(g<1)throw RangeError(`The "${t}" argument must be >= 1`)}return g===void 0?1/0:g}function H(e){return e===1?`1 item`:`${e} items`}function q(e){let t=new Set;for(let s of e)(typeof s==`string`||typeof s==`number`)&&t.add(String(s));return t}function ee(e){if(s.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function J(e){e={...e};let t=ee(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let s=j(e),g=L(e,`bigint`),S=F(e),D=typeof S==`function`?S:void 0,J=B(e,`maximumDepth`),Y=B(e,`maximumBreadth`);function te(e,k,j,F,L,B){let q=k[e];switch(typeof q==`object`&&q&&typeof q.toJSON==`function`&&(q=q.toJSON(e)),q=F.call(k,e,q),typeof q){case`string`:return w(q);case`object`:{if(q===null)return`null`;if(j.indexOf(q)!==-1)return s;let e=``,t=`,`,g=B;if(Array.isArray(q)){if(q.length===0)return`[]`;if(J<j.length+1)return`"[Array]"`;j.push(q),L!==``&&(B+=L,e+=`\n${B}`,t=`,\n${B}`);let s=Math.min(q.length,Y),S=0;for(;S<s-1;S++){let s=te(String(S),q,j,F,L,B);e+=s===void 0?`null`:s,e+=t}let w=te(String(S),q,j,F,L,B);if(e+=w===void 0?`null`:w,q.length-1>Y){let s=q.length-Y-1;e+=`${t}"... ${H(s)} not stringified"`}return L!==``&&(e+=`\n${g}`),j.pop(),`[${e}]`}let k=Object.keys(q),ee=k.length;if(ee===0)return`{}`;if(J<j.length+1)return`"[Object]"`;let ne=``,ae=``;L!==``&&(B+=L,t=`,\n${B}`,ne=` `);let oe=Math.min(ee,Y);S&&!O(q)&&(k=E(k,D)),j.push(q);for(let s=0;s<oe;s++){let g=k[s],S=te(g,q,j,F,L,B);S!==void 0&&(e+=`${ae}${w(g)}:${ne}${S}`,ae=t)}if(ee>Y){let s=ee-Y;e+=`${ae}"...":${ne}"${H(s)} not stringified"`,ae=t}return L!==``&&ae.length>1&&(e=`\n${B}${e}\n${g}`),j.pop(),`{${e}}`}case`number`:return isFinite(q)?String(q):t?t(q):`null`;case`boolean`:return q===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(q);default:return t?t(q):void 0}}function ne(e,S,E,D,O,k){switch(typeof S==`object`&&S&&typeof S.toJSON==`function`&&(S=S.toJSON(e)),typeof S){case`string`:return w(S);case`object`:{if(S===null)return`null`;if(E.indexOf(S)!==-1)return s;let e=k,t=``,g=`,`;if(Array.isArray(S)){if(S.length===0)return`[]`;if(J<E.length+1)return`"[Array]"`;E.push(S),O!==``&&(k+=O,t+=`\n${k}`,g=`,\n${k}`);let s=Math.min(S.length,Y),w=0;for(;w<s-1;w++){let e=ne(String(w),S[w],E,D,O,k);t+=e===void 0?`null`:e,t+=g}let j=ne(String(w),S[w],E,D,O,k);if(t+=j===void 0?`null`:j,S.length-1>Y){let e=S.length-Y-1;t+=`${g}"... ${H(e)} not stringified"`}return O!==``&&(t+=`\n${e}`),E.pop(),`[${t}]`}E.push(S);let j=``;O!==``&&(k+=O,g=`,\n${k}`,j=` `);let F=``;for(let e of D){let s=ne(e,S[e],E,D,O,k);s!==void 0&&(t+=`${F}${w(e)}:${j}${s}`,F=g)}return O!==``&&F.length>1&&(t=`\n${k}${t}\n${e}`),E.pop(),`{${t}}`}case`number`:return isFinite(S)?String(S):t?t(S):`null`;case`boolean`:return S===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(S);default:return t?t(S):void 0}}function ae(e,j,F,L,B){switch(typeof j){case`string`:return w(j);case`object`:{if(j===null)return`null`;if(typeof j.toJSON==`function`){if(j=j.toJSON(e),typeof j!=`object`)return ae(e,j,F,L,B);if(j===null)return`null`}if(F.indexOf(j)!==-1)return s;let t=B;if(Array.isArray(j)){if(j.length===0)return`[]`;if(J<F.length+1)return`"[Array]"`;F.push(j),B+=L;let e=`\n${B}`,s=`,\n${B}`,g=Math.min(j.length,Y),S=0;for(;S<g-1;S++){let t=ae(String(S),j[S],F,L,B);e+=t===void 0?`null`:t,e+=s}let w=ae(String(S),j[S],F,L,B);if(e+=w===void 0?`null`:w,j.length-1>Y){let t=j.length-Y-1;e+=`${s}"... ${H(t)} not stringified"`}return e+=`\n${t}`,F.pop(),`[${e}]`}let g=Object.keys(j),q=g.length;if(q===0)return`{}`;if(J<F.length+1)return`"[Object]"`;B+=L;let ee=`,\n${B}`,te=``,ne=``,oe=Math.min(q,Y);O(j)&&(te+=k(j,ee,Y),g=g.slice(j.length),oe-=j.length,ne=ee),S&&(g=E(g,D)),F.push(j);for(let e=0;e<oe;e++){let t=g[e],s=ae(t,j[t],F,L,B);s!==void 0&&(te+=`${ne}${w(t)}: ${s}`,ne=ee)}if(q>Y){let e=q-Y;te+=`${ne}"...": "${H(e)} not stringified"`,ne=ee}return ne!==``&&(te=`\n${B}${te}\n${t}`),F.pop(),`{${te}}`}case`number`:return isFinite(j)?String(j):t?t(j):`null`;case`boolean`:return j===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(j);default:return t?t(j):void 0}}function oe(e,j,F){switch(typeof j){case`string`:return w(j);case`object`:{if(j===null)return`null`;if(typeof j.toJSON==`function`){if(j=j.toJSON(e),typeof j!=`object`)return oe(e,j,F);if(j===null)return`null`}if(F.indexOf(j)!==-1)return s;let t=``,g=j.length!==void 0;if(g&&Array.isArray(j)){if(j.length===0)return`[]`;if(J<F.length+1)return`"[Array]"`;F.push(j);let e=Math.min(j.length,Y),s=0;for(;s<e-1;s++){let e=oe(String(s),j[s],F);t+=e===void 0?`null`:e,t+=`,`}let g=oe(String(s),j[s],F);if(t+=g===void 0?`null`:g,j.length-1>Y){let e=j.length-Y-1;t+=`,"... ${H(e)} not stringified"`}return F.pop(),`[${t}]`}let L=Object.keys(j),B=L.length;if(B===0)return`{}`;if(J<F.length+1)return`"[Object]"`;let q=``,ee=Math.min(B,Y);g&&O(j)&&(t+=k(j,`,`,Y),L=L.slice(j.length),ee-=j.length,q=`,`),S&&(L=E(L,D)),F.push(j);for(let e=0;e<ee;e++){let s=L[e],g=oe(s,j[s],F);g!==void 0&&(t+=`${q}${w(s)}:${g}`,q=`,`)}if(B>Y){let e=B-Y;t+=`${q}"...":"${H(e)} not stringified"`}return F.pop(),`{${t}}`}case`number`:return isFinite(j)?String(j):t?t(j):`null`;case`boolean`:return j===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(j);default:return t?t(j):void 0}}function se(e,t,s){if(arguments.length>1){let g=``;if(typeof s==`number`?g=` `.repeat(Math.min(s,10)):typeof s==`string`&&(g=s.slice(0,10)),t!=null){if(typeof t==`function`)return te(``,{"":e},[],t,g,``);if(Array.isArray(t))return ne(``,e,[],q(t),g,``)}if(g.length!==0)return ae(``,e,[],g,``)}return oe(``,e,[])}return se}})),require_multistream=__commonJSMin(((e,t)=>{let s=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:g}=require_constants$1(),S=g.info;function w(e,t){e||=[],t||={dedupe:!1};let w=Object.create(g);w.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{w[e]=t.levels[e]});let j={write:F,add:H,remove:q,emit:L,flushSync:B,end:ee,minLevel:0,lastId:0,streams:[],clone:J,[s]:!0,streamLevels:w};return Array.isArray(e)?e.forEach(H,j):H.call(j,e),e=null,j;function F(e){let g,S=this.lastLevel,{streams:w}=this,E=0,j;for(let F=D(w.length,t.dedupe);k(F,w.length,t.dedupe);F=O(F,t.dedupe))if(g=w[F],g.level<=S){if(E!==0&&E!==g.level)break;if(j=g.stream,j[s]){let{lastTime:e,lastMsg:t,lastObj:s,lastLogger:g}=this;j.lastLevel=S,j.lastTime=e,j.lastMsg=t,j.lastObj=s,j.lastLogger=g}j.write(e),t.dedupe&&(E=g.level)}else if(!t.dedupe)break}function L(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function B(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function H(e){if(!e)return j;let t=typeof e.write==`function`||e.stream,s=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:g,streamLevels:w}=this,D;D=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?w[e.level]:typeof e.level==`number`?e.level:S;let O={stream:s,level:D,levelVal:void 0,id:++j.lastId};return g.unshift(O),g.sort(E),this.minLevel=g[0].level,j}function q(e){let{streams:t}=this,s=t.findIndex(t=>t.id===e);return s>=0&&(t.splice(s,1),t.sort(E),this.minLevel=t.length>0?t[0].level:-1),j}function ee(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function J(e){let t=Array(this.streams.length);for(let s=0;s<t.length;s++)t[s]={level:e,stream:this.streams[s].stream};return{write:F,add:H,remove:q,minLevel:e,streams:t,clone:J,emit:L,flushSync:B,[s]:!0}}}function E(e,t){return e.level-t.level}function D(e,t){return t?e-1:0}function O(e,t){return t?e-1:e+1}function k(e,t,s){return s?e>=0:e<t}t.exports=w})),require_pino=__commonJSMin(((e,t)=>{let s=__require(`node:os`),g=require_pino_std_serializers(),S=require_caller(),w=require_redaction(),E=require_time(),D=require_proto(),O=require_symbols(),{configure:k}=require_safe_stable_stringify(),{assertDefaultLevelFound:j,mappings:F,genLsCache:L,genLevelComparison:B,assertLevelComparison:H}=require_levels(),{DEFAULT_LEVELS:q,SORTING_ORDER:ee}=require_constants$1(),{createArgsNormalizer:J,asChindings:Y,buildSafeSonicBoom:te,buildFormatters:ne,stringify:ae,normalizeDestFileDescriptor:oe,noop:se}=require_tools(),{version:ce}=require_meta(),{chindingsSym:ue,redactFmtSym:de,serializersSym:fe,timeSym:me,timeSliceIndexSym:ge,streamSym:_e,stringifySym:ve,stringifySafeSym:ye,stringifiersSym:Ce,setLevelSym:we,endSym:Te,formatOptsSym:De,messageKeySym:je,errorKeySym:Me,nestedKeySym:Pe,mixinSym:Ie,levelCompSym:Re,useOnlyCustomLevelsSym:ze,formattersSym:Be,hooksSym:Ve,nestedKeyStrSym:Ue,mixinMergeStrategySym:We,msgPrefixSym:Ge}=O,{epochTime:Ke,nullTime:Xe}=E,{pid:$e}=process,nt=s.hostname(),rt=g.err,it=J({level:`info`,levelComparison:ee.ASC,levels:q,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:$e,hostname:nt},serializers:Object.assign(Object.create(null),{err:rt}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Ke,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),at=Object.assign(Object.create(null),g);function st(...e){let t={},{opts:s,stream:g}=it(t,S(),...e);s.level&&typeof s.level==`string`&&q[s.level.toLowerCase()]!==void 0&&(s.level=s.level.toLowerCase());let{redact:E,crlf:O,serializers:ee,timestamp:J,messageKey:te,errorKey:oe,nestedKey:ce,base:$e,name:nt,level:rt,customLevels:at,levelComparison:st,mixin:vt,mixinMergeStrategy:St,useOnlyCustomLevels:Tt,formatters:Et,hooks:jt,depthLimit:Mt,edgeLimit:Ft,onChild:It,msgPrefix:Lt}=s,Rt=k({maximumDepth:Mt,maximumBreadth:Ft}),zt=ne(Et.level,Et.bindings,Et.log),Bt=ae.bind({[ye]:Rt}),Vt=E?w(E,Bt):{},Ht=E?{stringify:Vt[de]}:{stringify:Bt},Ut=`}`+(O?`\r
765
765
  `:`
@@ -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,persistenceStoreRemovedDocCount: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,bridgeMergeContentGrowth:0,bridgeMergeCheckpointCreated:0,producerGuardFires:0,producerGuardFiresSuppressed:0,producerGuardCheckpointCreated: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,observerADuplicationRederives:0,observerADuplicationCheckpointCreated: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 incrementPersistenceStoreRemovedDoc(){counters$1.persistenceStoreRemovedDocCount++}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 incrementBridgeMergeContentGrowth(){counters$1.bridgeMergeContentGrowth++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementProducerGuardCheckpointCreated(){counters$1.producerGuardCheckpointCreated++}function incrementProducerGuardFires(){counters$1.producerGuardFires++}function incrementProducerGuardFiresSuppressed(){counters$1.producerGuardFiresSuppressed++}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 incrementObserverADuplicationRederives(){counters$1.observerADuplicationRederives++}function incrementObserverADuplicationCheckpointCreated(){counters$1.observerADuplicationCheckpointCreated++}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.persistenceStoreRemovedDocCount=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.bridgeMergeContentGrowth=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.producerGuardFires=0,counters$1.producerGuardFiresSuppressed=0,counters$1.producerGuardCheckpointCreated=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.observerADuplicationRederives=0,counters$1.observerADuplicationCheckpointCreated=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,deriveStructuralFreshness:!0}),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)}function isManagedArtifactDoc(e){return isManagedArtifactDocName(e)}function isMermaidDoc(e){return isMermaidDocFile(e)}function isReservedForUserTree(e){return isSystemDoc(e)||isConfigDoc(e)||isManagedArtifactDoc(e)}function isLinkIndexExcludedDoc(e){return isSystemDoc(e)||isConfigDoc(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 docNameToRelativePath(e){return isSupportedDocFile(e)||isMermaidDocFile(e)?e:`${e}${getDocExtension(e)}`}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$21=()=>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()}`;if(e.headersSent||e.writableEnded||e.destroyed){log$21().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$21().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$21()[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$21().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()}`,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$21().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$21()[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$21().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$21().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$20=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$20.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$20.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$20.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$20.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$20.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 createDocCanonicalizer(e,t){let s=t.resolveEmbed&&t.docName?{resolveEmbed:t.resolveEmbed,resolveSize:t.resolveSize,sourcePath:t.docName}:void 0;return t=>e.serialize(e.parseWithFallback(t,s))}function assertBridgeInvariant(e,t,s){let g=g=>{let 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}))},S=normalizeBridge(e),w=normalizeBridge(t);if(S===w)return e!==t&&g(detectAppliedToleranceClasses(e,t)),!0;if(s.canonicalizeBody&&isParseEquivalentBridge(e,t,s.canonicalizeBody))return g([...detectAppliedToleranceClasses(e,t),PARSE_EQUIVALENCE_TOLERANCE]),!0;let E={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${S.slice(0,300)}\n frag: ${w.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(E);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let D=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(E,{verbose:D}))),!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 tracedSymlinkSync(e,t,s){withSpanSync(`fs.symlinkSync`,{attributes:buildAttrs(`symlinkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{symlinkSync(e,t,s)})}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)})}const tracedAtomicFs={writeFile:(e,t,s)=>tracedWriteFile(e,t,s),rename:(e,t)=>tracedRename(e,t)};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,persistenceStoreRemovedDocCount: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,bridgeMergeContentGrowth:0,bridgeMergeCheckpointCreated:0,producerGuardFires:0,producerGuardFiresSuppressed:0,producerGuardCheckpointCreated: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,observerADuplicationRederives:0,observerADuplicationCheckpointCreated: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 incrementPersistenceStoreRemovedDoc(){counters$1.persistenceStoreRemovedDocCount++}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 incrementBridgeMergeContentGrowth(){counters$1.bridgeMergeContentGrowth++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementProducerGuardCheckpointCreated(){counters$1.producerGuardCheckpointCreated++}function incrementProducerGuardFires(){counters$1.producerGuardFires++}function incrementProducerGuardFiresSuppressed(){counters$1.producerGuardFiresSuppressed++}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 incrementObserverADuplicationRederives(){counters$1.observerADuplicationRederives++}function incrementObserverADuplicationCheckpointCreated(){counters$1.observerADuplicationCheckpointCreated++}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.persistenceStoreRemovedDocCount=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.bridgeMergeContentGrowth=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.producerGuardFires=0,counters$1.producerGuardFiresSuppressed=0,counters$1.producerGuardCheckpointCreated=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.observerADuplicationRederives=0,counters$1.observerADuplicationCheckpointCreated=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,deriveStructuralFreshness:!0}),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)}function isManagedArtifactDoc(e){return isManagedArtifactDocName(e)}function isMermaidDoc(e){return isMermaidDocFile(e)}function isReservedForUserTree(e){return isSystemDoc(e)||isConfigDoc(e)||isManagedArtifactDoc(e)}function isLinkIndexExcludedDoc(e){return isSystemDoc(e)||isConfigDoc(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 docNameToRelativePath(e){return isSupportedDocFile(e)||isMermaidDocFile(e)?e:`${e}${getDocExtension(e)}`}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$22=()=>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()}`;if(e.headersSent||e.writableEnded||e.destroyed){log$22().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$22().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$22()[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$22().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()}`,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$22().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$22()[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$22().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$22().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$21=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$21.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$21.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$21.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$21.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$21.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 createDocCanonicalizer(e,t){let s=t.resolveEmbed&&t.docName?{resolveEmbed:t.resolveEmbed,resolveSize:t.resolveSize,sourcePath:t.docName}:void 0;return t=>e.serialize(e.parseWithFallback(t,s))}function assertBridgeInvariant(e,t,s){let g=g=>{let 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}))},S=normalizeBridge(e),w=normalizeBridge(t);if(S===w)return e!==t&&g(detectAppliedToleranceClasses(e,t)),!0;if(s.canonicalizeBody&&isParseEquivalentBridge(e,t,s.canonicalizeBody))return g([...detectAppliedToleranceClasses(e,t),PARSE_EQUIVALENCE_TOLERANCE]),!0;let E={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${S.slice(0,300)}\n frag: ${w.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(E);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let D=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(E,{verbose:D}))),!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 tracedSymlinkSync(e,t,s){withSpanSync(`fs.symlinkSync`,{attributes:buildAttrs(`symlinkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{symlinkSync(e,t,s)})}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)})}const tracedAtomicFs={writeFile:(e,t,s)=>tracedWriteFile(e,t,s),rename:(e,t)=>tracedRename(e,t)};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 dropPendingDocs(e){let t=e instanceof Set?e:new Set(e);if(t.size!==0)for(let[e,s]of pendingContributors){for(let e of t)s.docs.delete(e);s.docs.size===0&&pendingContributors.delete(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(`
@@ -778,7 +778,7 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
778
778
  `).filter(Boolean)}catch{return[]}let S=[];for(let e of g){let[t=``,s=``,g=``,w=``]=e.split(`\0`),E=t.split(`/`).slice(3).join(`/`);if(!E)continue;let D=Number.parseInt(g,10);S.push({writerId:E,tipSha:s,classification:parseWriterId(E).classification,isPark:w.startsWith(`park:`),committedAtMs:Number.isFinite(D)?D*1e3:0})}return S}async function initShadowRepo(e){let t=resolveShadowDir(e),s=resolve(e,`.git/openknowledge`),g=existsSync(s),S=existsSync(t);if(g&&!S?tracedRenameSync(s,t):g&&S&&console.warn(`[shadow-repo] unexpected legacy + new shadow both present — no rename performed`),!existsSync(resolve(t,`HEAD`))){tracedMkdirSync(t,{recursive:!0}),await esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS$3}}).raw(`init`,`--bare`,t);let s=esm_default({timeout:{block:GIT_TIMEOUT_MS$3}}).env({GIT_DIR:t});await s.raw(`config`,`--unset`,`core.bare`),await s.raw(`config`,`core.worktree`,e),await s.raw(`config`,`user.name`,`openknowledge`),await s.raw(`config`,`user.email`,`noreply@openknowledge.local`)}let w={gitDir:t,workTree:e};try{await configureShadowGc(w)}catch(e){console.warn(`[shadow-repo] failed to write gc config (non-fatal):`,e)}return await sweepLegacyShadowRefs(w),sweepOrphanedTmpIndexFiles(w),acquireLock(t,e),w}function destroyShadowRepo(e){releaseLock(e.gitDir)}async function sweepLegacyShadowRefs(e){let t=shadowGit(e),s;try{s=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip`)).trim().split(`
779
779
  `).filter(e=>e.length>0)}catch{return 0}let g=[],S={server:0,"human-":0,upstream:0};for(let e of s){let t=e.split(`/`);if(t.length<4)continue;let s=t.slice(3).join(`/`);parseWriterId(s).classification===`unknown`&&(s===`server`?(g.push(e),S.server++):s.startsWith(`human-`)?(g.push(e),S[`human-`]++):s===`upstream`&&(g.push(e),S.upstream++))}if(g.length===0)return 0;for(let e of g)try{await t.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[shadow-migration] failed to delete legacy ref ${e}:`,t)}let w=g.length;return incrementShadowMigrationLegacyRefsDeleted(w),console.warn(`[shadow-migration] deleted ${w} legacy refs: server=${S.server} human-=${S[`human-`]} upstream=${S.upstream}`),w}async function commitWip(e,t,s,g,S=`main`,w){return withSpan(`shadow.commitWip`,{attributes:{"shadow.writer":t.id,"shadow.branch":S}},async()=>commitWipInner(e,t,s,g,S,w?.date))}async function commitWipInner(e,t,s,g,S=`main`,w){let E=resolve(e.gitDir,`index-wip-${t.id}`),D=`refs/wip/${S}/${t.id}`,O=shadowGit(e),k=s||`.`;try{try{let t=(await O.raw(`rev-parse`,`${D}^{tree}`)).trim();await O.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw console.error(`[shadow-repo] Unexpected error seeding index for ${D}:`,e),e}await O.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:E}).raw(`add`,k);let s=(await O.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),S=null;try{S=(await O.raw(`rev-parse`,D)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${D}:`,e),e}let j=[`commit-tree`,s,`-m`,g];S&&j.push(`-p`,S);let F={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};w&&(F.GIT_AUTHOR_DATE=w,F.GIT_COMMITTER_DATE=w);let L=(await O.env(F).raw(...j)).trim();return await O.raw(`update-ref`,D,L),L}finally{try{rmSync(E)}catch{}}}function sweepOrphanedTmpIndexFiles(e){let t=0;try{for(let s of readdirSync(e.gitDir))if(s.startsWith(`index-wip-fanout-`))try{rmSync(resolve(e.gitDir,s)),t++}catch{}}catch{}return t}async function buildWipTree(e,t){let s=resolve(e.gitDir,`index-wip-fanout-${randomUUID()}`),g=shadowGit(e),S=t||`.`;try{return await g.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:s}).raw(`add`,S),(await g.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:s}).raw(`write-tree`)).trim()}finally{try{rmSync(s)}catch{}}}async function commitWipFromTree(e,t,s,g,S=`main`){return withSpan(`shadow.commitWipFromTree`,{attributes:{"shadow.writer":t.id,"shadow.branch":S,"shadow.tree":s.slice(0,8)}},async()=>commitWipFromTreeInner(e,t,s,g,S))}async function commitWipFromTreeInner(e,t,s,g,S=`main`){let w=`refs/wip/${S}/${t.id}`,E=shadowGit(e),D=null;try{D=(await E.raw(`rev-parse`,w)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${w}:`,e),e}let O=[`commit-tree`,s,`-m`,g];D&&O.push(`-p`,D);let k=(await E.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...O)).trim();return await E.raw(`update-ref`,w,k),k}const FILE_SYSTEM_WRITER={id:`file-system`,name:`File System`,email:`file-system@openknowledge.local`},GIT_UPSTREAM_WRITER={id:`git-upstream`,name:`Git (upstream)`,email:`git@openknowledge.local`},SERVICE_WRITER={id:`openknowledge-service`,name:`OpenKnowledge (service)`,email:`service@openknowledge.local`},UPSTREAM_WRITER=GIT_UPSTREAM_WRITER;async function commitUpstreamImport(e,t,s,g,S=`main`){return withSpan(`shadow.commitUpstreamImport`,{attributes:{"shadow.branch":S,"shadow.new_head":g.slice(0,8)}},async()=>commitUpstreamImportInner(e,t,s,g,S))}async function commitUpstreamImportInner(e,t,s,g,S=`main`){return commitWip(e,UPSTREAM_WRITER,t,`${formatImportSubject(s,g)}\n\n${formatOkActor({v:1,writer_id:UPSTREAM_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:UPSTREAM_WRITER.name,color_seed:UPSTREAM_WRITER.id,docs:[]})}`,S)}const SAFETY_WRITER=SERVICE_WRITER;async function safetyCheckpoint(e,t,s,g=`main`){return commitWip(e,SAFETY_WRITER,t,`${formatCheckpointSubject(`pre-${s.action}`)}\n\n${formatOkActor({v:1,writer_id:SAFETY_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SAFETY_WRITER.name,color_seed:SAFETY_WRITER.id,docs:[]})}`,g)}async function saveInMemoryCheckpoint(e,t,s){let g=s.branch??`main`,S=shadowGit(e),w=randomUUID(),E=resolve(e.gitDir,`index-checkpoint-${w}`),D=resolve(e.gitDir,`tmp-checkpoint-blob-${w}`),O=t?`${t.replace(/\/$/,``)}/${s.docName}`:s.docName,k=Buffer.byteLength(s.contents,`utf-8`),j;switch(s.kind){case`bridge-merge-loss`:j={kind:`bridge-merge-loss`,docName:s.docName,size:k,metadata:s.metadata};break;case`producer-guard-loss`:j={kind:`producer-guard-loss`,docName:s.docName,size:k,metadata:s.metadata};break;case`observer-a-duplication`:j={kind:`observer-a-duplication`,docName:s.docName,size:k,metadata:s.metadata};break;case`external-change-rescue`:j={kind:`external-change-rescue`,docName:s.docName,size:k,metadata:s.metadata};break}let F=formatCheckpointBodyLine(j),L=`checkpoint: ${s.label}\n\n${F}`;try{tracedWriteFileSync(D,s.contents,`utf-8`);let t=(await S.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,D)).trim();await S.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${t},${O}`);let w=(await S.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),k=(await S.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(`commit-tree`,w,`-m`,L)).trim();return await S.raw(`update-ref`,`refs/checkpoints/${g}/${k}`,k),k}finally{try{rmSync(E)}catch{}try{rmSync(D)}catch{}}}async function listRescueCheckpoints(e,t=`main`){let s=shadowGit(e),g;try{g=await s.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let S=g.trim().split(`
780
780
  `).filter(e=>e.length===40);if(S.length===0)return[];let w;try{w=await s.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%s%x00%B%x1e`,...S)}catch{return[]}let E=[];for(let e of w.split(``)){let t=e.trimStart();if(!t)continue;let[g=``,S=``,w=``,D=``]=t.split(`\0`),O=parseCheckpoint(D);if(O?.kind!==`external-change-rescue`)continue;let k=O.docName??``,j=O.size??0;if(!k)try{let e=(await listTreeLongEntries(s,[`ls-tree`,`-r`,`--long`,g]))[0];e&&(j===0&&(j=e.size),k=e.path.replace(/\.mdx?$/,``).split(`/`).slice(-1)[0]??``)}catch{}k&&E.push({docName:k,timestamp:S,size:j,sha:g,label:w.replace(/^checkpoint:\s*/,``),incomingDiskSha:O.metadata.incomingDiskSha})}return E}const DEFAULT_CHECKPOINT_RETENTION={maxBridgeMergeLoss:50,maxProducerGuardLoss:50,maxObserverADuplication:50,maxExternalChangeRescue:50,maxAutoConsolidation:2,ttlMs:720*60*60*1e3};async function gcCheckpointRefs(e,t=`main`,s=DEFAULT_CHECKPOINT_RETENTION){let g={scanned:0,deletedBridgeMergeLoss:0,deletedProducerGuardLoss:0,deletedObserverADuplication:0,deletedExternalChangeRescue:0,deletedAutoConsolidation:0,retained:0},S=shadowGit(e),w;try{w=await S.raw(`for-each-ref`,`--format=%(objectname) %(refname)`,`refs/checkpoints/${t}/`)}catch{return g}let E=w.trim().split(`
781
- `).map(e=>e.trim()).filter(Boolean);if(E.length===0)return g;let D=new Map,O=[];for(let e of E){let t=e.indexOf(` `);if(t<0)continue;let s=e.slice(0,t),g=e.slice(t+1);s.length===40&&(D.set(s,g),O.push(s))}if(g.scanned=O.length,O.length===0)return g;let k;try{k=await S.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%B%x1e`,...O)}catch{return g}let j=[];for(let e of k.split(``)){let t=e.trimStart();if(!t)continue;let[s=``,g=``,S=``]=t.split(`\0`);if(!s)continue;let w=parseCheckpoint(S)?.kind??null,E=Date.parse(g);j.push({sha:s,timestamp:Number.isFinite(E)?E:0,kind:w})}let F={"bridge-merge-loss":[],"producer-guard-loss":[],"observer-a-duplication":[],"external-change-rescue":[],"auto-consolidation":[]},L=0;for(let e of j){if(e.kind===null){L++;continue}F[e.kind].push(e)}let B=Date.now(),H=[],q=(e,t,S,w=!0)=>{e.sort((e,t)=>t.timestamp-e.timestamp);for(let E=0;E<e.length;E++){let O=e[E];if(!O)continue;let k=E>=t,j=w&&s.ttlMs>0&&O.timestamp>0&&B-O.timestamp>s.ttlMs;if(k||j){let e=D.get(O.sha);e&&(H.push(e),g[S]++)}}};q(F[`bridge-merge-loss`],s.maxBridgeMergeLoss,`deletedBridgeMergeLoss`),q(F[`producer-guard-loss`],s.maxProducerGuardLoss,`deletedProducerGuardLoss`),q(F[`observer-a-duplication`],s.maxObserverADuplication,`deletedObserverADuplication`),q(F[`external-change-rescue`],s.maxExternalChangeRescue,`deletedExternalChangeRescue`),q(F[`auto-consolidation`],s.maxAutoConsolidation,`deletedAutoConsolidation`,!1);for(let e of H)try{await S.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[checkpoint-gc] failed to delete`,e,t)}return g.retained=L+(g.scanned-H.length-L),g}async function parkBranch(e,t,s,g,S){return g.length===0?null:withSpan(`shadow.parkBranch`,{attributes:{"shadow.branch":t,"shadow.new_branch":S??``,"shadow.doc_count":g.length}},async()=>parkBranchInner(e,t,s,g,S))}async function parkBranchInner(e,t,s,g,S){let w=shadowGit(e),E=resolve(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),D=`refs/wip/${t}/${s}`,O=resolve(e.gitDir,`tmp-park-blob`);try{for(let t of g){tracedWriteFileSync(O,t.markdown,`utf-8`);let s=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,O)).trim();await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${s},${t.docName}`),tracedWriteFileSync(O,t.diskSnapshot,`utf-8`);let g=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,O)).trim();await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${g},.park-base/${t.docName}`)}let s=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),k=null;try{k=(await w.raw(`rev-parse`,D)).trim()}catch{}let j={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:g.map(e=>e.docName)},F=[`commit-tree`,s,`-m`,`${formatParkSubject(t,S??t)}\n\n${formatOkActor(j)}`];k&&F.push(`-p`,k);let L=(await w.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...F)).trim();return await w.raw(`update-ref`,D,L),L}finally{try{rmSync(E)}catch{}try{rmSync(O)}catch{}}}async function readParkedState(e,t,s,g){let S=shadowGit(e),w=`refs/wip/${t}/${s}`,E;try{E=(await S.raw(`rev-parse`,w)).trim()}catch{return null}try{return(await S.raw(`log`,`-1`,`--format=%s`,E)).trim().startsWith(`park:`)?{markdown:(await S.raw(`show`,`${E}:${g}`)).trim(),diskSnapshot:(await S.raw(`show`,`${E}:.park-base/${g}`)).trim()}:null}catch(e){throw console.error(`[shadow] Failed to read parked state for ${g} from ${w}:`,e),e}}async function saveVersion(e,t,s,g=`main`,S,w){return withSpan(`shadow.saveVersion`,{attributes:{"shadow.branch":g,"shadow.writer_count":s.length,"shadow.checkpoint_kind":w?.checkpointKind?`auto-consolidation`:`user`}},async()=>saveVersionInner(e,t,s,g,S,w))}async function saveVersionInner(e,t,s,g=`main`,S,w){let E=shadowGit(e,w?.timeoutMs?{timeoutMs:w.timeoutMs}:void 0),D=t||`.`,O=resolve(e.gitDir,`index-checkpoint-${randomUUID()}`);try{await E.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:O}).raw(`add`,D);let t=(await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`write-tree`)).trim(),k=w?.includeUpstream===!1?s:[...s,GIT_UPSTREAM_WRITER],j=[],F=new Map;for(let e of k)try{let t=(await E.raw(`rev-parse`,`refs/wip/${g}/${e.id}`)).trim();j.push(t),F.set(e.id,t)}catch{}let L=[...new Set(j)];try{let e=(await E.raw(`for-each-ref`,`--sort=-creatordate`,`--count=1`,`--format=%(objectname)`,`refs/checkpoints/${g}/`)).trim();e&&!L.includes(e)&&L.push(e)}catch{}let B={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},H=`${formatCheckpointSubject(S?.trim()?S.trim():`Checkpoint version`)}\n\n${formatOkActor(B)}`;w?.checkpointKind&&(H+=`\n${formatCheckpointBodyLine({kind:`auto-consolidation`,docName:null,size:null,metadata:{foldedRefs:w.checkpointKind.foldedRefs,trigger:w.checkpointKind.trigger}})}`);let q=[`commit-tree`,t,`-m`,H];for(let e of L)q.push(`-p`,e);let ee={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};w?.date&&(ee.GIT_AUTHOR_DATE=w.date,ee.GIT_COMMITTER_DATE=w.date);let J=(await E.env(ee).raw(...q)).trim(),Y=`refs/checkpoints/${g}/${J}`;return await E.raw(`update-ref`,Y,J),await resetFoldedWipRefs(E,g,k,F),{checkpointRef:Y}}finally{try{rmSync(O)}catch{}}}async function resetFoldedWipRefs(e,t,s,g){for(let S of s){let s=`refs/wip/${t}/${S.id}`,w=g.get(S.id);if(w!==void 0)try{await e.raw(`update-ref`,`-d`,s,w)}catch{}}}const FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function applyDiskContentToDoc(e,t,s,g,S){composeAndWriteRawBody(e,t,`file-watcher`,s&&g?{resolveEmbed:s,resolveSize:S,sourcePath:g}:void 0)}function applyExternalChange(e,t,s,g,S){if(isSystemDoc(t)||isConfigDoc(t)||isMermaidDoc(t))return;let w=e.documents.get(t);if(!w)return;let E=w.getText(`source`).toString(),D=E===s,O=stripFrontmatter(E).frontmatter,{frontmatter:k}=stripFrontmatter(s);try{w.transact(()=>{applyDiskContentToDoc(w,s,g,t,S)},FILE_WATCHER_ORIGIN)}catch(e){throw setReconciledBase(t,w.getText(`source`).toString()),e}O!==k&&recordFrontmatterEditSurface(`file-watcher`),D||recordContributor(t,FILE_SYSTEM_WRITER.id,FILE_SYSTEM_WRITER.name,FILE_SYSTEM_WRITER.id,formatReconcileSubject(t)),setReconciledBase(t,s)}function createExternalChangeHandler(e,t,s){return async(g,S)=>{try{applyExternalChange(e,g,S,t,s),getLogger(`file-watcher`).info({docName:g},`applied external change`)}catch(e){if(e instanceof BridgeInvariantViolationError||e instanceof BridgeMergeContentLossError)throw e;incrementExternalChangeHandlerErrors(),console.error(`[file-watcher] Failed to apply external change for ${g}:`,e)}}}const NOT_RECONCILED={reconciled:!1,baseBytes:0,diskBytes:0};function serializeYDocSource(e){let{frontmatter:t,body:s}=stripFrontmatter(e.getText(`source`).toString());return prependFrontmatter(t,s)}function reconcileDiskBeforeAgentWrite(e,t,s,g){if(isSystemDoc(t)||isConfigDoc(t)||isMermaidDoc(t))return NOT_RECONCILED;let S=e.documents.get(t);if(S&&isDocInConflict(S))return NOT_RECONCILED;let w=getReconciledBase(t);if(w===void 0)return NOT_RECONCILED;let E;try{let e=safeContentPath(t,s);if(!existsSync(e))return NOT_RECONCILED;E=realpathSync(e)}catch{return NOT_RECONCILED}if(!isWithinContentDir(E,s))return getLogger(`reconcile`).warn({docName:t,canonical:E,contentDir:s},`[reconcile] symlink-escape on disk read for ${t}; skipping reconcile`),NOT_RECONCILED;let D;try{D=readFileSync(E,`utf-8`)}catch(e){let s=e?.code;return s!==`ENOENT`&&getLogger(`reconcile`).warn({docName:t,canonical:E,code:s},`[reconcile] disk read failed for ${t} (${s??`unknown`}); skipping reconcile`),NOT_RECONCILED}if(normalizeBridge(D)===normalizeBridge(w))return NOT_RECONCILED;let O=peekInFlightFlush(t);if(O!==void 0){if(normalizeBridge(D)===O)return incrementReconcileOwnFlushSkips(),getLogger(`reconcile`).debug({docName:t,diskBytes:D.length},`[reconcile] disk matches own in-flight flush for ${t}; skipping reconcile`),NOT_RECONCILED;incrementReconcileInFlightFallthroughs(),getLogger(`reconcile`).warn({docName:t,diskBytes:D.length},`[reconcile] in-flight flush present but disk differs from snapshot for ${t}; falling through to merge`)}if(!S)return NOT_RECONCILED;let k=reconcile({docName:t,base:w,ours:serializeYDocSource(S),theirs:D});switch(getLogger(`reconcile`).info({docName:t,result:k.kind,baseBytes:w.length,diskBytes:D.length},`[reconcile] before-agent-write ${t} result=${k.kind}`),k.kind){case`noop`:return NOT_RECONCILED;case`conflicts`:case`refused`:{let e=S.getMap(`lifecycle`);return e.set(`status`,`conflict`),e.set(`reason`,k.kind===`refused`?k.reason:`reconcile-conflicts`),NOT_RECONCILED}case`clean`:case`merged`:return applyExternalChange(e,t,k.kind===`clean`?D:k.newContent,g),k.kind===`merged`&&setReconciledBase(t,D),{reconciled:!0,baseBytes:Buffer.byteLength(w,`utf8`),diskBytes:Buffer.byteLength(D,`utf8`),mergeOutcome:k.kind}}}function splitFrontmatterLines(e){return e?unwrapFrontmatterFences(e).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let s=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(s))return normalizeFrontmatterScalar(t.slice(s.length))||null;return null}function parseInlineAliases(e){let t=[],s=``,g=null;for(let S of e){if(g){s+=S,S===g&&(g=null);continue}if(S===`"`||S===`'`){g=S,s+=S;continue}if(S===`,`){let e=normalizeFrontmatterScalar(s);e&&t.push(e),s=``;continue}s+=S}let S=normalizeFrontmatterScalar(s);return S&&t.push(S),t}function dedupeExact(e){let t=[],s=new Set;for(let g of e)!g||s.has(g)||(s.add(g),t.push(g));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let s=splitFrontmatterLines(t);for(let e=0;e<s.length;e+=1){let t=s[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let g=t[1]?.trim()??``;if(g){if(g.startsWith(`[`)&&g.endsWith(`]`))return dedupeExact(parseInlineAliases(g.slice(1,-1)));let e=normalizeFrontmatterScalar(g);return e?[e]:[]}let S=[];for(let t=e+1;t<s.length;t+=1){let e=s[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&S.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(S)}return[]}function extractPageTitle(e,t){let{frontmatter:s,body:g}=stripFrontmatter(e),S=extractFrontmatterScalar(s,`title`);if(S)return S;let w=g.match(/^# (.+)$/m);return w?w[1].trim():t}const ICON_VALUE_LENGTH_CAP=2048;function extractPageIcon(e){let{frontmatter:t}=stripFrontmatter(e),s=extractFrontmatterScalar(t,`icon`);if(!(!s||s.length>ICON_VALUE_LENGTH_CAP))return s}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let s=`${t}:`,g=splitFrontmatterLines(e);for(let e=0;e<g.length;e+=1){let t=g[e];if(!t?.startsWith(s))continue;let S=t.slice(s.length).trim();if(S){if(S.startsWith(`[`)&&S.endsWith(`]`)){let e=parseInlineAliases(S.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(S);return e?[e]:void 0}let w=[];for(let t=e+1;t<g.length;t+=1){let e=g[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&w.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return w.length>0?w:void 0}}function extractPageIdentity(e,t){let s=extractPageTitle(e,t),g=extractPageAliases(e),S=dedupeExact([s,...g]),w=[],E=new Set;for(let e of S){let t=toWikiLinkSlug(e);!t||E.has(t)||(E.add(t),w.push(t))}return{docName:t,title:s,aliases:g,matchLabels:S,normalizedMatchLabels:w}}function toPosix(e){return e.replace(/\\/g,`/`)}function isWithinDir(e,t){let s=toPosix(e),g=toPosix(t);return s===g||s.startsWith(`${g}/`)}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}function derivePageMeta(e,t){return{title:extractPageTitle(e,t),icon:extractPageIcon(e)}}function markdownIndexView(e){let t=new Map;for(let[s,g]of e)g.kind===`markdown`&&t.set(s,g);return t}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let s=writeTracker.get(e)??[];s.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,s)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,s]of writeTracker){let g=s.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);g.length===0?writeTracker.delete(t):g.length!==s.length&&writeTracker.set(t,g)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let s;try{s=lstatSync(e)}catch(t){let s=t.code;return s===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${s}), dropping event`),!0)}if(!s.isSymbolicLink())return!1;let g;try{g=realpathSync(e)}catch(t){let s=t.code;return s!==`ENOENT`&&s!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${s}), dropping event`),!0}return!isWithinContentDir(g,t)}function pathToDocName(e,t){return stripDocExtension(toPosix(relative(t,e)))}function contentRelativePath(e,t){let s=relative(e,t).replaceAll(`\\`,`/`);return!s||s===`.`||s===`..`||s.startsWith(`../`)?null:s}function upsertFolderIndexEntry(e,t,s,g,S=s){let w=contentRelativePath(t,s);return w?(e.set(w,{size:0,modified:g.mtime.toISOString(),canonicalPath:S,inode:Number(g.ino)}),w):null}function removeFolderIndexEntries(e,t){let s=!1;for(let g of e.keys())(g===t||g.startsWith(`${t}/`))&&(e.delete(g),s=!0);return s}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let s=t.toLowerCase();return s===`.mdx`||s===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,s,g){let S=[],w=[],E=[];for(let g of e)if(isSupportedDocFile(g.path)){if(s){let e=toPosix(relative(t,g.path));if(s.isExcluded(e))continue}switch(g.type){case`delete`:S.push(g);break;case`create`:lastKnownHash.has(g.path)?E.push(g):w.push(g);break;case`update`:E.push(g);break}}let D=new Map,O=new Map;for(let e of w)try{D.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of E)try{O.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function k(e){let s=pathToDocName(e,t);if(!g)return s;let S=null;try{S=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),g.has(s)&&g.delete(s),s}if(!S.isSymbolicLink())return g.has(s)&&g.delete(s),s;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),g.delete(s),s}if(!isWithinContentDir(w,t))return g.delete(s),s;let E=pathToDocName(w,t);return E===s?s:(g.set(s,E),E)}let j=[],F=new Set,L=new Set;for(let e of S){let t=removeLastKnownHash(e.path);if(t)for(let s of w){if(F.has(s.path))continue;let g=D.get(s.path);if(g===void 0)continue;let S=contentHash(g);if(S===t){F.add(s.path),L.add(e.path),updateLastKnownHash(s.path,S),j.push({kind:`rename`,oldPath:e.path,newPath:s.path,oldDocName:k(e.path),newDocName:k(s.path),content:g});break}}}for(let e of S)L.has(e.path)||(removeLastKnownHash(e.path),j.push({kind:`delete`,path:e.path,docName:k(e.path)}));for(let e of w){if(F.has(e.path))continue;let t=D.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`create`,path:e.path,docName:k(e.path),content:t})}for(let e of E){let t=O.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`update`,path:e.path,docName:k(e.path),content:t})}return j}function isSelfWrite(e,t){let s=writeTracker.get(e);if(!s)return!1;let g=s.findIndex(e=>e.hash===t);return g<0?!1:(s.splice(g,1),s.length===0&&writeTracker.delete(e),!0)}async function seedLastKnownHashes(e,t,s,g,S,w,E,D){let O=D??new Set;try{let D=await readdir(e,{withFileTypes:!0});for(let k of D){let D=join(e,k.name),j;try{j=await lstat(D)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${D}, skipping:`,e);continue}if(j.isSymbolicLink()){let e;try{e=await realpath(D)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${D}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${D}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${D} → ${e}, skipping`);continue}try{let j=await stat$1(e);if(O.has(j.ino)){if(j.isFile()&&isSupportedDocFile(k.name)){let s=pathToDocName(D,t),S=pathToDocName(e,t);w.set(s,S);let E=g.get(S);E&&!E.aliases.includes(s)&&E.aliases.push(s)}else if(j.isDirectory()){let g=contentRelativePath(t,D);(!s||g&&!s.isDirExcluded(g))&&E.set(pathToDocName(D,t),pathToDocName(e,t))}continue}if(O.add(j.ino),j.isDirectory()){let k=contentRelativePath(t,D);if(s&&(!k||s.isDirExcluded(k)))continue;E.set(pathToDocName(D,t),pathToDocName(e,t)),await seedLastKnownHashes(e,t,s,g,S,w,E,O)}else if(j.isFile()&&isSupportedDocFile(k.name)){if(s){let g=toPosix(relative(t,e));if(s.isExcluded(g))continue}let S=pathToDocName(D,t),E=pathToDocName(e,t);w.set(S,E);try{let t=await readFile$1(e,`utf-8`),s=contentHash(t);lastKnownHash.set(e,s);let w=extractDocExtension(e);if(w){let e=registerDocExtension(E,w);if(e.shadowed&&(console.warn(`[file-watcher] docName "${E}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(E,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:e,inode:j.ino,aliases:[S],kind:`markdown`,...derivePageMeta(t,E)})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}else if(j.isFile()){if(s){let g=toPosix(relative(t,e));if(s.isPathIgnored(g))continue}let S=pathToDocName(D,t);if(isSystemDoc(S)||isConfigDoc(S))continue;g.set(S,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:e,inode:j.ino,aliases:[],kind:`file`})}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(j.isDirectory()){let e=contentRelativePath(t,D);if(s&&(!e||s.isDirExcluded(e)))continue;upsertFolderIndexEntry(S,t,D,j),await seedLastKnownHashes(D,t,s,g,S,w,E,O)}else if(j.isFile()&&isSupportedDocFile(k.name)){if(O.has(j.ino))continue;if(O.add(j.ino),s){let e=toPosix(relative(t,D));if(s.isExcluded(e))continue}try{let e=await readFile$1(D,`utf-8`);lastKnownHash.set(D,contentHash(e));let s=pathToDocName(D,t),S=extractDocExtension(D);if(S){let e=registerDocExtension(s,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(s,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:D,inode:j.ino,aliases:[],kind:`markdown`,...derivePageMeta(e,s)})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${D}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${D}:`,e)}}else if(j.isFile()){if(O.has(j.ino))continue;if(O.add(j.ino),s){let e=toPosix(relative(t,D));if(s.isPathIgnored(e))continue}let e=pathToDocName(D,t);if(isSystemDoc(e)||isConfigDoc(e))continue;g.set(e,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:D,inode:j.ino,aliases:[],kind:`file`})}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(!(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)){if(e.kind===`file-create`||e.kind===`file-update`||e.kind===`file-delete`){let s=e.relativePath;if(isSystemDoc(s)||isConfigDoc(s))return;if(e.kind===`file-delete`){let e=t.get(s);e&&e.kind===`file`&&t.delete(s);return}let g=t.get(s);if(g&&g.kind===`markdown`)return;t.set(s,{size:e.size,modified:new Date(e.modifiedTs).toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:e.inode||g?.inode||0,aliases:g?.aliases??[],kind:`file`});return}if(!isReservedForUserTree(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let s=e.docName,g=t.get(s),S=extractDocExtension(e.path);S&&registerDocExtension(s,S),t.set(s,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:g?.inode??0,aliases:g?.aliases??[],kind:`markdown`,...derivePageMeta(e.content,s)});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,s]of t){let t=s.aliases.indexOf(e.docName);if(t!==-1){s.aliases.splice(t,1);break}}break;case`rename`:{let s=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let g=extractDocExtension(e.newPath);g&&registerDocExtension(e.newDocName,g),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:s?.canonicalPath??e.newPath,inode:s?.inode??0,aliases:s?.aliases??[],kind:`markdown`,...derivePageMeta(e.content,e.newDocName)});break}default:assertNeverDiskEvent(e)}}}function updateFolderIndexFromRawEvents(e,t,s,g){let S=[],w=[];for(let E of e){let e=contentRelativePath(t,E.path);if(!e)continue;if(E.type===`delete`){removeFolderIndexEntries(g,e)&&S.push({kind:`folder-delete`,path:E.path,relativePath:e});continue}let D;try{D=lstatSync(E.path)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder lstat failed for ${E.path} (${t})`);continue}let O=null,k=E.path;if(D.isDirectory())O=D;else if(D.isSymbolicLink())try{if(k=realpathSync(E.path),!isWithinContentDir(k,t))continue;let e=statSync(k);e.isDirectory()&&(O=e)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder symlink resolve failed for ${E.path} (${t})`),O=null}if(!O||s?.isDirExcluded(e))continue;let j=g.has(e);upsertFolderIndexEntry(g,t,E.path,O,k),j||(S.push({kind:`folder-create`,path:E.path,relativePath:e}),scanForUntrackedSubfolders(k,t,s,g,S,w))}return{events:S,untrackedFiles:w}}function scanForUntrackedSubfolders(e,t,s,g,S,w){let E=[e];for(;E.length>0;){let e=E.shift();if(e===void 0)continue;let D;try{D=readdirSync(e,{withFileTypes:!0})}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] folder rescan readdir failed for ${e} (${s})`);continue}for(let O of D){if(O.isFile()){w.push(join(e,O.name));continue}if(!O.isDirectory())continue;let D=join(e,O.name),k=contentRelativePath(t,D);if(!k||s?.isDirExcluded(k))continue;let j;try{j=lstatSync(D)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder rescan lstat failed for ${D} (${t})`);continue}j.isDirectory()&&(g.has(k)||(upsertFolderIndexEntry(g,t,D,j),S.push({kind:`folder-create`,path:D,relativePath:k})),E.push(D))}}}async function handleRawEvents(e,t,s,g,S,w,E){let D=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),{events:O,untrackedFiles:k}=updateFolderIndexFromRawEvents(D,t,s,S),j=[];if(k.length>0){let e=new Set(D.map(e=>e.path)),s=new Set;for(let e of g.values())s.add(e.canonicalPath);j=k.filter(t=>!e.has(t)&&!lastKnownHash.has(t)&&!s.has(t)).filter(e=>!eventEscapesContentDir(e,t)).map(e=>({type:`create`,path:e})),j.length>0&&getLogger(`file-watcher`).debug({count:j.length,paths:j.map(e=>toPosix(relative(t,e.path)))},`[file-watcher] re-injecting rescued file creates from new-folder rescan`)}let F=j.length>0?D.concat(j):D,L=F.filter(e=>isSupportedDocFile(e.path)),B=F.filter(e=>isSupportedAssetFile(e.path,LINKABLE_ASSET_EXTENSIONS)),H=F.filter(e=>!isSupportedDocFile(e.path));if(L.length===0&&B.length===0&&O.length===0&&H.length===0)return;let q=L.length>0?await classifyEvents(L,t,s,E):[];for(let e of q){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let s=contentHash(e.content),g=e.path;try{g=realpathSync(e.path)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${s})`)}t=isSelfWrite(g,s)}else if(e.kind===`rename`){let s=contentHash(e.content),g=e.newPath;try{g=realpathSync(e.newPath)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${s})`)}t=isSelfWrite(g,s)}if(updateFileIndex(e,g),s&&!t)switch(e.kind){case`create`:s.incrementMdDir(dirname(e.docName));break;case`delete`:s.decrementMdDir(dirname(e.docName));break;case`rename`:s.decrementMdDir(dirname(e.oldDocName)),s.incrementMdDir(dirname(e.newDocName));break;case`update`:case`conflict`:break;default:assertNeverDiskEvent(e)}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let S=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(S),"disk.path.role":classifyFsPath(S)}},async()=>w(e))}for(let e of O)getLogger(`file-watcher`).debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1}),await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(e.path),"disk.path.role":classifyFsPath(e.path)}},async()=>w(e));for(let e of B){if(s){let g=toPosix(relative(t,e.path));if(s.isExcluded(g))continue}let g=toPosix(relative(t,e.path));await w(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:g}:{kind:`asset-create`,path:e.path,relativePath:g})}for(let e of H){let S=toPosix(relative(t,e.path));if(s?.isPathIgnored(S)||isSystemDoc(S)||isConfigDoc(S))continue;if(e.type===`delete`){let t={kind:`file-delete`,path:e.path,relativePath:S};updateFileIndex(t,g),await w(t);continue}let E;try{E=lstatSync(e.path),E.isSymbolicLink()&&(E=statSync(e.path))}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] file-event lstat failed for ${e.path} (${s})`);continue}if(!E.isFile())continue;let D=e.type===`create`?{kind:`file-create`,path:e.path,relativePath:S,size:E.size,modifiedTs:E.mtime.getTime(),inode:Number(E.ino)}:{kind:`file-update`,path:e.path,relativePath:S,size:E.size,modifiedTs:E.mtime.getTime(),inode:Number(E.ino)};updateFileIndex(D,g),await w(D)}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,s,g,S,w,E){let D;try{D=await import(`@parcel/watcher`)}catch(e){return getLogger(`file-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let O=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await D.subscribe(e,async(D,O)=>{if(D){console.error(`[file-watcher]`,D);return}try{await handleRawEvents(O.map(e=>({type:e.type,path:e.path})),e,t,s,g,S,w),E()}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},O)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,s,g,S,w,E){let{watch:D}=await import(`./chokidar-987bEGiR.mjs`),O=D(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(s,g)=>{let S=toPosix(relative(e,s));return S===``||S===`.`?!1:g?.isDirectory()?t.isDirExcluded(S):t.isExcluded(S)}:void 0});O.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let k=50,j=[],F=null;function L(D,O){j.push({type:D,path:O}),F||=setTimeout(()=>{let D=j;j=[],F=null,handleRawEvents(D,e,t,s,g,S,w).then(E).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return O.on(`add`,e=>L(`create`,e)),O.on(`change`,e=>L(`update`,e)),O.on(`unlink`,e=>L(`delete`,e)),O.on(`addDir`,e=>L(`create`,e)),O.on(`unlinkDir`,e=>L(`delete`,e)),{unsubscribe:()=>(F&&(clearTimeout(F),F=null,j=[]),O.close())}}async function startWatcher(e,t,s){let g;try{g=realpathSync(e)}catch{g=e}let S=new Map,w=new Map,E=new Map,D=new Map,O=0,k=null,j=-1,F=()=>{O++};await seedLastKnownHashes(g,g,s,S,w,E,D),F();let L=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),B,H;try{let e=await startParcelWatcher(g,s,S,w,t,E,F);e?(B=e,H=`parcel`):(B=await startChokidarWatcher(g,s,S,w,t,E,F),H=`chokidar`)}catch(e){throw clearInterval(L),e}let q=B.unsubscribe.bind(B);return getLogger(`file-watcher`).info({contentDir:g,backend:H},`watching for external .md changes`),{async unsubscribe(){return clearInterval(L),writeTracker.clear(),lastKnownHash.clear(),q()},getFileIndex(){return k&&j===O?k:(k=markdownIndexView(S),j=O,k)},getAllFilesIndex(){return S},getFileIndexGeneration(){return O},getFolderIndex(){return w},getAliasMap(){return E},getFolderAliasIndex(){return D},mutateFileIndex(e){updateFileIndex(e,S),F()},pruneFileIndexNowExcluded(){if(!s)return 0;let e=0;for(let[t,w]of S){let E=toPosix(relative(g,w.canonicalPath));(w.kind===`file`?s.isPathIgnored(E):s.isExcluded(E))&&(S.delete(t),e++)}return e>0&&F(),e},pruneFolderIndexNowExcluded(){if(!s)return 0;let e=0;for(let t of w.keys())s.isDirExcluded(t)&&(w.delete(t),e++);return e},async rescanFromDisk(){await seedLastKnownHashes(g,g,s,S,w,E,D),F()}}}async function reconcileFileIndexAfterFilterRebuild(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),s=e.pruneFolderIndexNowExcluded();return await e.rescanFromDisk(),{prunedFiles:t,prunedFolders:s}}const log$19=getLogger(`managed-artifact-persistence`);function homeFor(e){return e.homedirOverride??homedir()}function managedArtifactContributorAttribution(e){let t=parseManagedArtifactName(e);if(t===null)return null;if(t.kind===`skill`)return t.scope===`project`?{docKey:`${SKILL_CONTENT_ROOT}/${t.name}`,subject:`skill-edit: ${t.name}/SKILL.md`}:null;let s=t.folder.replace(/\/$/,``),g=`${s?`${s}/`:``}.ok/templates/${t.name}`;return{docKey:g,subject:`template-edit: ${g}.md`}}function managedArtifactTimelinePaths(e){let t=parseManagedArtifactName(e);if(!t)return{managed:!1};let s=managedArtifactContributorAttribution(e);if(!s)return{managed:!0,versioned:!1};let g=t.kind===`skill`?`${s.docKey}/SKILL.md`:`${s.docKey}.md`;return{managed:!0,versioned:!0,docKey:s.docKey,filePath:g}}function managedArtifactSkillsRoots(e){return[resolve(homeFor(e),`.ok`,`skills`)]}function managedArtifactAbsPath(e,t){let s=parseManagedArtifactName(e);if(s===null)throw Error(`managedArtifactAbsPath: not a managed-artifact doc name: ${e}`);if(s.kind===`template`)return templateAbsPath(s.folder,s.name,t,e);if(!SKILL_NAME_REGEX.test(s.name)||s.name.length>64)throw Error(`managedArtifactAbsPath: invalid skill name: ${JSON.stringify(s.name)}`);let g=resolve(s.scope===`global`?homeFor(t):t.projectDir,`.ok`,`skills`),S=resolve(g,s.name,`SKILL.md`);if(!S.startsWith(g+sep))throw Error(`managedArtifactAbsPath: path escape for ${e}`);return S}function normalizeTemplateFolder(e){return e.replace(/^\/+/,``).replace(/\/+$/,``)}function templateAbsPath(e,t,s,g){if(!TEMPLATE_NAME_REGEX.test(t)||t.length>64)throw Error(`managedArtifactAbsPath: invalid template name: ${JSON.stringify(t)}`);let S=normalizeTemplateFolder(e);if(S.split(`/`).includes(`..`))throw Error(`managedArtifactAbsPath: template folder escape for ${g}`);let w=resolve(s.projectDir),E=S?resolve(w,S):w;if(E!==w&&!E.startsWith(w+sep))throw Error(`managedArtifactAbsPath: template folder escape for ${g}`);let D=resolve(E,`.ok`,`templates`),O=resolve(D,`${t}.md`);if(!O.startsWith(D+sep))throw Error(`managedArtifactAbsPath: path escape for ${g}`);return O}function managedArtifactDocNameForPath(e,t){let s=resolve(e);if(s.endsWith(`${sep}SKILL.md`)){let e=[[resolve(homeFor(t),`.ok`,`skills`),`global`]];for(let[t,g]of e){if(!s.startsWith(t+sep))continue;let e=s.slice(t.length+1).split(sep);if(e.length!==2||e[1]!==`SKILL.md`)continue;let S=e[0];if(!(!SKILL_NAME_REGEX.test(S)||S.length>64))return`${MANAGED_ARTIFACT_PREFIX_SKILL}${g}/${S}`}return null}if(s.endsWith(`.md`)){let e=resolve(t.projectDir);if(s!==e&&!s.startsWith(e+sep))return null;let g=s===e?``:s.slice(e.length+1),S=`.ok${sep}templates${sep}`,w=g.indexOf(S);if(w<0||w>0&&g[w-1]!==sep)return null;let E=g.slice(w+S.length);if(E.includes(sep)||!E.endsWith(`.md`))return null;let D=E.slice(0,-3);if(!TEMPLATE_NAME_REGEX.test(D)||D.length>64)return null;let O=w===0?``:g.slice(0,w-1),k=O?O.split(sep).map(e=>encodeURIComponent(e)).join(`/`):``;return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${k?`${k}/`:``}${encodeURIComponent(D)}`}return null}function loadManagedArtifactDoc(e,t,s){let g=parseManagedArtifactName(t);if(g?.kind===`skill`&&g.scope===`project`||e.getXmlFragment(`default`).length>0)return;let S=managedArtifactAbsPath(t,s);if(!existsSync(S))return;let w;try{w=readFileSync(S,`utf-8`)}catch(e){log$19.warn({documentName:t,err:e.message},`load: could not read; seeding empty`);return}e.transact(()=>{applyDiskContentToDoc(e,w,void 0,t),e.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},FILE_WATCHER_ORIGIN),s.setReconciledBase(t,w),s.lkgCache.set(t,w)}async function storeManagedArtifactDoc(e,t,s,g){let S=parseManagedArtifactName(t);if(S?.kind===`skill`&&S.scope===`project`||s===FILE_WATCHER_ORIGIN)return`no-op`;let w=e.getText(`source`).toString(),E=g.lkgCache.get(t);if(w===E)return`no-op`;let D=managedArtifactAbsPath(t,g);try{return await tracedMkdir(resolve(D,`..`),{recursive:!0}),await withFileLock(`${D}.lock`,async()=>{if(existsSync(D)){let s=null;try{s=readFileSync(D,`utf-8`)}catch(e){e.code!==`ENOENT`&&log$19.warn({documentName:t,err:e.message},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),s=null}if(s!==null&&s!==E&&s!==w)return e.transact(()=>{applyDiskContentToDoc(e,s,void 0,t)},FILE_WATCHER_ORIGIN),g.setReconciledBase(t,s),g.lkgCache.set(t,s),`reconciled`}return await atomicWriteFile(D,w,{fs:tracedAtomicFs}),g.lkgCache.set(t,w),g.setReconciledBase(t,w),`persisted`})}catch(e){return e instanceof FileLockTimeoutError?(log$19.warn({documentName:t},`store: file lock timeout; skipping write`),`write-failed`):(log$19.warn({documentName:t,err:e.message},`store: write failed`),`write-failed`)}}function applyExternalManagedArtifactChange(e,t,s,g){if(!e)return`no-op`;let S=g.lkgCache.get(t);return S!==void 0&&S===s?`no-op`:(e.transact(()=>{applyDiskContentToDoc(e,s,void 0,t)},FILE_WATCHER_ORIGIN),g.setReconciledBase(t,s),g.lkgCache.set(t,s),`applied`)}const log$18=getLogger(`mermaid-persistence`),MERMAID_SOURCE_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`mermaid-source`}};function mermaidAbsPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let s=resolve(t,docNameToRelativePath(e));if(!isWithinDir(s,t))throw Error(`Invalid document name: ${e}`);return s}function replaceSource(e,t,s){let g=e.getText(`source`);e.transact(()=>{g.length>0&&g.delete(0,g.length),t.length>0&&g.insert(0,t),s&&e.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},MERMAID_SOURCE_ORIGIN)}function loadMermaidDoc(e,t,s){if(e.getText(`source`).length>0)return;let g=mermaidAbsPath(t,s.contentDir);if(!existsSync(g))return;let S;try{S=readFileSync(g,`utf-8`)}catch(e){log$18.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}replaceSource(e,S,!0),s.lkgCache.set(t,S)}async function storeMermaidDoc(e,t,s,g){if(s===MERMAID_SOURCE_ORIGIN)return`no-op`;let S=e.getText(`source`).toString(),w=g.lkgCache.get(t);if(S===w)return`no-op`;let E=mermaidAbsPath(t,g.contentDir);try{if(await tracedMkdir(resolve(E,`..`),{recursive:!0}),existsSync(E)){let s=null;try{s=readFileSync(E,`utf-8`)}catch(e){e.code!==`ENOENT`&&log$18.warn({documentName:t,err:e},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),s=null}if(s!==null&&s!==w&&s!==S)return replaceSource(e,s,!1),g.lkgCache.set(t,s),`reconciled`}return await atomicWriteFile(E,S,{fs:tracedAtomicFs}),g.lkgCache.set(t,S),`persisted`}catch(e){return log$18.warn({documentName:t,err:e},`store: write failed`),`write-failed`}}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
781
+ `).map(e=>e.trim()).filter(Boolean);if(E.length===0)return g;let D=new Map,O=[];for(let e of E){let t=e.indexOf(` `);if(t<0)continue;let s=e.slice(0,t),g=e.slice(t+1);s.length===40&&(D.set(s,g),O.push(s))}if(g.scanned=O.length,O.length===0)return g;let k;try{k=await S.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%B%x1e`,...O)}catch{return g}let j=[];for(let e of k.split(``)){let t=e.trimStart();if(!t)continue;let[s=``,g=``,S=``]=t.split(`\0`);if(!s)continue;let w=parseCheckpoint(S)?.kind??null,E=Date.parse(g);j.push({sha:s,timestamp:Number.isFinite(E)?E:0,kind:w})}let F={"bridge-merge-loss":[],"producer-guard-loss":[],"observer-a-duplication":[],"external-change-rescue":[],"auto-consolidation":[]},L=0;for(let e of j){if(e.kind===null){L++;continue}F[e.kind].push(e)}let B=Date.now(),H=[],q=(e,t,S,w=!0)=>{e.sort((e,t)=>t.timestamp-e.timestamp);for(let E=0;E<e.length;E++){let O=e[E];if(!O)continue;let k=E>=t,j=w&&s.ttlMs>0&&O.timestamp>0&&B-O.timestamp>s.ttlMs;if(k||j){let e=D.get(O.sha);e&&(H.push(e),g[S]++)}}};q(F[`bridge-merge-loss`],s.maxBridgeMergeLoss,`deletedBridgeMergeLoss`),q(F[`producer-guard-loss`],s.maxProducerGuardLoss,`deletedProducerGuardLoss`),q(F[`observer-a-duplication`],s.maxObserverADuplication,`deletedObserverADuplication`),q(F[`external-change-rescue`],s.maxExternalChangeRescue,`deletedExternalChangeRescue`),q(F[`auto-consolidation`],s.maxAutoConsolidation,`deletedAutoConsolidation`,!1);for(let e of H)try{await S.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[checkpoint-gc] failed to delete`,e,t)}return g.retained=L+(g.scanned-H.length-L),g}async function parkBranch(e,t,s,g,S){return g.length===0?null:withSpan(`shadow.parkBranch`,{attributes:{"shadow.branch":t,"shadow.new_branch":S??``,"shadow.doc_count":g.length}},async()=>parkBranchInner(e,t,s,g,S))}async function parkBranchInner(e,t,s,g,S){let w=shadowGit(e),E=resolve(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),D=`refs/wip/${t}/${s}`,O=resolve(e.gitDir,`tmp-park-blob`);try{for(let t of g){tracedWriteFileSync(O,t.markdown,`utf-8`);let s=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,O)).trim();await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${s},${t.docName}`),tracedWriteFileSync(O,t.diskSnapshot,`utf-8`);let g=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,O)).trim();await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${g},.park-base/${t.docName}`)}let s=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),k=null;try{k=(await w.raw(`rev-parse`,D)).trim()}catch{}let j={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:g.map(e=>e.docName)},F=[`commit-tree`,s,`-m`,`${formatParkSubject(t,S??t)}\n\n${formatOkActor(j)}`];k&&F.push(`-p`,k);let L=(await w.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...F)).trim();return await w.raw(`update-ref`,D,L),L}finally{try{rmSync(E)}catch{}try{rmSync(O)}catch{}}}async function readParkedState(e,t,s,g){let S=shadowGit(e),w=`refs/wip/${t}/${s}`,E;try{E=(await S.raw(`rev-parse`,w)).trim()}catch{return null}try{return(await S.raw(`log`,`-1`,`--format=%s`,E)).trim().startsWith(`park:`)?{markdown:(await S.raw(`show`,`${E}:${g}`)).trim(),diskSnapshot:(await S.raw(`show`,`${E}:.park-base/${g}`)).trim()}:null}catch(e){throw console.error(`[shadow] Failed to read parked state for ${g} from ${w}:`,e),e}}async function saveVersion(e,t,s,g=`main`,S,w){return withSpan(`shadow.saveVersion`,{attributes:{"shadow.branch":g,"shadow.writer_count":s.length,"shadow.checkpoint_kind":w?.checkpointKind?`auto-consolidation`:`user`}},async()=>saveVersionInner(e,t,s,g,S,w))}async function saveVersionInner(e,t,s,g=`main`,S,w){let E=shadowGit(e,w?.timeoutMs?{timeoutMs:w.timeoutMs}:void 0),D=t||`.`,O=resolve(e.gitDir,`index-checkpoint-${randomUUID()}`);try{await E.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:O}).raw(`add`,D);let t=(await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`write-tree`)).trim(),k=w?.includeUpstream===!1?s:[...s,GIT_UPSTREAM_WRITER],j=[],F=new Map;for(let e of k)try{let t=(await E.raw(`rev-parse`,`refs/wip/${g}/${e.id}`)).trim();j.push(t),F.set(e.id,t)}catch{}let L=[...new Set(j)];try{let e=(await E.raw(`for-each-ref`,`--sort=-creatordate`,`--count=1`,`--format=%(objectname)`,`refs/checkpoints/${g}/`)).trim();e&&!L.includes(e)&&L.push(e)}catch{}let B={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},H=`${formatCheckpointSubject(S?.trim()?S.trim():`Checkpoint version`)}\n\n${formatOkActor(B)}`;w?.checkpointKind&&(H+=`\n${formatCheckpointBodyLine({kind:`auto-consolidation`,docName:null,size:null,metadata:{foldedRefs:w.checkpointKind.foldedRefs,trigger:w.checkpointKind.trigger}})}`);let q=[`commit-tree`,t,`-m`,H];for(let e of L)q.push(`-p`,e);let ee={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};w?.date&&(ee.GIT_AUTHOR_DATE=w.date,ee.GIT_COMMITTER_DATE=w.date);let J=(await E.env(ee).raw(...q)).trim(),Y=`refs/checkpoints/${g}/${J}`;return await E.raw(`update-ref`,Y,J),await resetFoldedWipRefs(E,g,k,F),{checkpointRef:Y}}finally{try{rmSync(O)}catch{}}}async function resetFoldedWipRefs(e,t,s,g){for(let S of s){let s=`refs/wip/${t}/${S.id}`,w=g.get(S.id);if(w!==void 0)try{await e.raw(`update-ref`,`-d`,s,w)}catch{}}}const FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function applyDiskContentToDoc(e,t,s,g,S){composeAndWriteRawBody(e,t,`file-watcher`,s&&g?{resolveEmbed:s,resolveSize:S,sourcePath:g}:void 0)}function applyExternalChange(e,t,s,g,S){if(isSystemDoc(t)||isConfigDoc(t)||isMermaidDoc(t))return;let w=e.documents.get(t);if(!w)return;let E=w.getText(`source`).toString(),D=E===s,O=stripFrontmatter(E).frontmatter,{frontmatter:k}=stripFrontmatter(s);try{w.transact(()=>{applyDiskContentToDoc(w,s,g,t,S)},FILE_WATCHER_ORIGIN)}catch(e){throw setReconciledBase(t,w.getText(`source`).toString()),e}O!==k&&recordFrontmatterEditSurface(`file-watcher`),D||recordContributor(t,FILE_SYSTEM_WRITER.id,FILE_SYSTEM_WRITER.name,FILE_SYSTEM_WRITER.id,formatReconcileSubject(t)),setReconciledBase(t,s)}function createExternalChangeHandler(e,t,s){return async(g,S)=>{try{applyExternalChange(e,g,S,t,s),getLogger(`file-watcher`).info({docName:g},`applied external change`)}catch(e){if(e instanceof BridgeInvariantViolationError||e instanceof BridgeMergeContentLossError)throw e;incrementExternalChangeHandlerErrors(),console.error(`[file-watcher] Failed to apply external change for ${g}:`,e)}}}const NOT_RECONCILED={reconciled:!1,baseBytes:0,diskBytes:0};function serializeYDocSource(e){let{frontmatter:t,body:s}=stripFrontmatter(e.getText(`source`).toString());return prependFrontmatter(t,s)}function reconcileDiskBeforeAgentWrite(e,t,s,g){if(isSystemDoc(t)||isConfigDoc(t)||isMermaidDoc(t))return NOT_RECONCILED;let S=e.documents.get(t);if(S&&isDocInConflict(S))return NOT_RECONCILED;let w=getReconciledBase(t);if(w===void 0)return NOT_RECONCILED;let E;try{let e=safeContentPath(t,s);if(!existsSync(e))return NOT_RECONCILED;E=realpathSync(e)}catch{return NOT_RECONCILED}if(!isWithinContentDir(E,s))return getLogger(`reconcile`).warn({docName:t,canonical:E,contentDir:s},`[reconcile] symlink-escape on disk read for ${t}; skipping reconcile`),NOT_RECONCILED;let D;try{D=readFileSync(E,`utf-8`)}catch(e){let s=e?.code;return s!==`ENOENT`&&getLogger(`reconcile`).warn({docName:t,canonical:E,code:s},`[reconcile] disk read failed for ${t} (${s??`unknown`}); skipping reconcile`),NOT_RECONCILED}if(normalizeBridge(D)===normalizeBridge(w))return NOT_RECONCILED;let O=peekInFlightFlush(t);if(O!==void 0){if(normalizeBridge(D)===O)return incrementReconcileOwnFlushSkips(),getLogger(`reconcile`).debug({docName:t,diskBytes:D.length},`[reconcile] disk matches own in-flight flush for ${t}; skipping reconcile`),NOT_RECONCILED;incrementReconcileInFlightFallthroughs(),getLogger(`reconcile`).warn({docName:t,diskBytes:D.length},`[reconcile] in-flight flush present but disk differs from snapshot for ${t}; falling through to merge`)}if(!S)return NOT_RECONCILED;let k=reconcile({docName:t,base:w,ours:serializeYDocSource(S),theirs:D});switch(getLogger(`reconcile`).info({docName:t,result:k.kind,baseBytes:w.length,diskBytes:D.length},`[reconcile] before-agent-write ${t} result=${k.kind}`),k.kind){case`noop`:return NOT_RECONCILED;case`conflicts`:case`refused`:{let e=S.getMap(`lifecycle`);return e.set(`status`,`conflict`),e.set(`reason`,k.kind===`refused`?k.reason:`reconcile-conflicts`),NOT_RECONCILED}case`clean`:case`merged`:return applyExternalChange(e,t,k.kind===`clean`?D:k.newContent,g),k.kind===`merged`&&setReconciledBase(t,D),{reconciled:!0,baseBytes:Buffer.byteLength(w,`utf8`),diskBytes:Buffer.byteLength(D,`utf8`),mergeOutcome:k.kind}}}function splitFrontmatterLines(e){return e?unwrapFrontmatterFences(e).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let s=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(s))return normalizeFrontmatterScalar(t.slice(s.length))||null;return null}function parseInlineAliases(e){let t=[],s=``,g=null;for(let S of e){if(g){s+=S,S===g&&(g=null);continue}if(S===`"`||S===`'`){g=S,s+=S;continue}if(S===`,`){let e=normalizeFrontmatterScalar(s);e&&t.push(e),s=``;continue}s+=S}let S=normalizeFrontmatterScalar(s);return S&&t.push(S),t}function dedupeExact(e){let t=[],s=new Set;for(let g of e)!g||s.has(g)||(s.add(g),t.push(g));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let s=splitFrontmatterLines(t);for(let e=0;e<s.length;e+=1){let t=s[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let g=t[1]?.trim()??``;if(g){if(g.startsWith(`[`)&&g.endsWith(`]`))return dedupeExact(parseInlineAliases(g.slice(1,-1)));let e=normalizeFrontmatterScalar(g);return e?[e]:[]}let S=[];for(let t=e+1;t<s.length;t+=1){let e=s[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&S.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(S)}return[]}function extractPageTitle(e,t){let{frontmatter:s,body:g}=stripFrontmatter(e),S=extractFrontmatterScalar(s,`title`);if(S)return S;let w=g.match(/^# (.+)$/m);return w?w[1].trim():t}const ICON_VALUE_LENGTH_CAP=2048;function extractPageIcon(e){let{frontmatter:t}=stripFrontmatter(e),s=extractFrontmatterScalar(t,`icon`);if(!(!s||s.length>ICON_VALUE_LENGTH_CAP))return s}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let s=`${t}:`,g=splitFrontmatterLines(e);for(let e=0;e<g.length;e+=1){let t=g[e];if(!t?.startsWith(s))continue;let S=t.slice(s.length).trim();if(S){if(S.startsWith(`[`)&&S.endsWith(`]`)){let e=parseInlineAliases(S.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(S);return e?[e]:void 0}let w=[];for(let t=e+1;t<g.length;t+=1){let e=g[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&w.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return w.length>0?w:void 0}}function extractPageIdentity(e,t){let s=extractPageTitle(e,t),g=extractPageAliases(e),S=dedupeExact([s,...g]),w=[],E=new Set;for(let e of S){let t=toWikiLinkSlug(e);!t||E.has(t)||(E.add(t),w.push(t))}return{docName:t,title:s,aliases:g,matchLabels:S,normalizedMatchLabels:w}}function toPosix(e){return e.replace(/\\/g,`/`)}function isWithinDir(e,t){let s=toPosix(e),g=toPosix(t);return s===g||s.startsWith(`${g}/`)}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}function derivePageMeta(e,t){return{title:extractPageTitle(e,t),icon:extractPageIcon(e)}}function markdownIndexView(e){let t=new Map;for(let[s,g]of e)g.kind===`markdown`&&t.set(s,g);return t}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let s=writeTracker.get(e)??[];s.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,s)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,s]of writeTracker){let g=s.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);g.length===0?writeTracker.delete(t):g.length!==s.length&&writeTracker.set(t,g)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let s;try{s=lstatSync(e)}catch(t){let s=t.code;return s===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${s}), dropping event`),!0)}if(!s.isSymbolicLink())return!1;let g;try{g=realpathSync(e)}catch(t){let s=t.code;return s!==`ENOENT`&&s!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${s}), dropping event`),!0}return!isWithinContentDir(g,t)}function pathToDocName(e,t){return stripDocExtension(toPosix(relative(t,e)))}function contentRelativePath(e,t){let s=relative(e,t).replaceAll(`\\`,`/`);return!s||s===`.`||s===`..`||s.startsWith(`../`)?null:s}function upsertFolderIndexEntry(e,t,s,g,S=s){let w=contentRelativePath(t,s);return w?(e.set(w,{size:0,modified:g.mtime.toISOString(),canonicalPath:S,inode:Number(g.ino)}),w):null}function removeFolderIndexEntries(e,t){let s=!1;for(let g of e.keys())(g===t||g.startsWith(`${t}/`))&&(e.delete(g),s=!0);return s}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let s=t.toLowerCase();return s===`.mdx`||s===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,s,g){let S=[],w=[],E=[];for(let g of e)if(isSupportedDocFile(g.path)){if(s){let e=toPosix(relative(t,g.path));if(s.isExcluded(e))continue}switch(g.type){case`delete`:S.push(g);break;case`create`:lastKnownHash.has(g.path)?E.push(g):w.push(g);break;case`update`:E.push(g);break}}let D=new Map,O=new Map;for(let e of w)try{D.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of E)try{O.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function k(e){let s=pathToDocName(e,t);if(!g)return s;let S=null;try{S=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),g.has(s)&&g.delete(s),s}if(!S.isSymbolicLink())return g.has(s)&&g.delete(s),s;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),g.delete(s),s}if(!isWithinContentDir(w,t))return g.delete(s),s;let E=pathToDocName(w,t);return E===s?s:(g.set(s,E),E)}let j=[],F=new Set,L=new Set;for(let e of S){let t=removeLastKnownHash(e.path);if(t)for(let s of w){if(F.has(s.path))continue;let g=D.get(s.path);if(g===void 0)continue;let S=contentHash(g);if(S===t){F.add(s.path),L.add(e.path),updateLastKnownHash(s.path,S),j.push({kind:`rename`,oldPath:e.path,newPath:s.path,oldDocName:k(e.path),newDocName:k(s.path),content:g});break}}}for(let e of S)L.has(e.path)||(removeLastKnownHash(e.path),j.push({kind:`delete`,path:e.path,docName:k(e.path)}));for(let e of w){if(F.has(e.path))continue;let t=D.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`create`,path:e.path,docName:k(e.path),content:t})}for(let e of E){let t=O.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`update`,path:e.path,docName:k(e.path),content:t})}return j}function isSelfWrite(e,t){let s=writeTracker.get(e);if(!s)return!1;let g=s.findIndex(e=>e.hash===t);return g<0?!1:(s.splice(g,1),s.length===0&&writeTracker.delete(e),!0)}async function seedLastKnownHashes(e,t,s,g,S,w,E,D){let O=D??new Set;try{let D=await readdir(e,{withFileTypes:!0});for(let k of D){let D=join(e,k.name),j;try{j=await lstat(D)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${D}, skipping:`,e);continue}if(j.isSymbolicLink()){let e;try{e=await realpath(D)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${D}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${D}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${D} → ${e}, skipping`);continue}try{let j=await stat$1(e);if(O.has(j.ino)){if(j.isFile()&&isSupportedDocFile(k.name)){let s=pathToDocName(D,t),S=pathToDocName(e,t);w.set(s,S);let E=g.get(S);E&&!E.aliases.includes(s)&&E.aliases.push(s)}else if(j.isDirectory()){let g=contentRelativePath(t,D);(!s||g&&!s.isDirExcluded(g))&&E.set(pathToDocName(D,t),pathToDocName(e,t))}continue}if(O.add(j.ino),j.isDirectory()){let k=contentRelativePath(t,D);if(s&&(!k||s.isDirExcluded(k)))continue;E.set(pathToDocName(D,t),pathToDocName(e,t)),await seedLastKnownHashes(e,t,s,g,S,w,E,O)}else if(j.isFile()&&isSupportedDocFile(k.name)){if(s){let g=toPosix(relative(t,e));if(s.isExcluded(g))continue}let S=pathToDocName(D,t),E=pathToDocName(e,t);w.set(S,E);try{let t=await readFile$1(e,`utf-8`),s=contentHash(t);lastKnownHash.set(e,s);let w=extractDocExtension(e);if(w){let e=registerDocExtension(E,w);if(e.shadowed&&(console.warn(`[file-watcher] docName "${E}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(E,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:e,inode:j.ino,aliases:[S],kind:`markdown`,...derivePageMeta(t,E)})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}else if(j.isFile()){if(s){let g=toPosix(relative(t,e));if(s.isPathIgnored(g))continue}let S=pathToDocName(D,t);if(isSystemDoc(S)||isConfigDoc(S))continue;g.set(S,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:e,inode:j.ino,aliases:[],kind:`file`})}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(j.isDirectory()){let e=contentRelativePath(t,D);if(s&&(!e||s.isDirExcluded(e)))continue;upsertFolderIndexEntry(S,t,D,j),await seedLastKnownHashes(D,t,s,g,S,w,E,O)}else if(j.isFile()&&isSupportedDocFile(k.name)){if(O.has(j.ino))continue;if(O.add(j.ino),s){let e=toPosix(relative(t,D));if(s.isExcluded(e))continue}try{let e=await readFile$1(D,`utf-8`);lastKnownHash.set(D,contentHash(e));let s=pathToDocName(D,t),S=extractDocExtension(D);if(S){let e=registerDocExtension(s,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(s,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:D,inode:j.ino,aliases:[],kind:`markdown`,...derivePageMeta(e,s)})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${D}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${D}:`,e)}}else if(j.isFile()){if(O.has(j.ino))continue;if(O.add(j.ino),s){let e=toPosix(relative(t,D));if(s.isPathIgnored(e))continue}let e=pathToDocName(D,t);if(isSystemDoc(e)||isConfigDoc(e))continue;g.set(e,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:D,inode:j.ino,aliases:[],kind:`file`})}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(!(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)){if(e.kind===`file-create`||e.kind===`file-update`||e.kind===`file-delete`){let s=e.relativePath;if(isSystemDoc(s)||isConfigDoc(s))return;if(e.kind===`file-delete`){let e=t.get(s);e&&e.kind===`file`&&t.delete(s);return}let g=t.get(s);if(g&&g.kind===`markdown`)return;t.set(s,{size:e.size,modified:new Date(e.modifiedTs).toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:e.inode||g?.inode||0,aliases:g?.aliases??[],kind:`file`});return}if(!isReservedForUserTree(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let s=e.docName,g=t.get(s),S=extractDocExtension(e.path);S&&registerDocExtension(s,S),t.set(s,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:g?.inode??0,aliases:g?.aliases??[],kind:`markdown`,...derivePageMeta(e.content,s)});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,s]of t){let t=s.aliases.indexOf(e.docName);if(t!==-1){s.aliases.splice(t,1);break}}break;case`rename`:{let s=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let g=extractDocExtension(e.newPath);g&&registerDocExtension(e.newDocName,g),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:s?.canonicalPath??e.newPath,inode:s?.inode??0,aliases:s?.aliases??[],kind:`markdown`,...derivePageMeta(e.content,e.newDocName)});break}default:assertNeverDiskEvent(e)}}}function updateFolderIndexFromRawEvents(e,t,s,g){let S=[],w=[];for(let E of e){let e=contentRelativePath(t,E.path);if(!e)continue;if(E.type===`delete`){removeFolderIndexEntries(g,e)&&S.push({kind:`folder-delete`,path:E.path,relativePath:e});continue}let D;try{D=lstatSync(E.path)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder lstat failed for ${E.path} (${t})`);continue}let O=null,k=E.path;if(D.isDirectory())O=D;else if(D.isSymbolicLink())try{if(k=realpathSync(E.path),!isWithinContentDir(k,t))continue;let e=statSync(k);e.isDirectory()&&(O=e)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder symlink resolve failed for ${E.path} (${t})`),O=null}if(!O||s?.isDirExcluded(e))continue;let j=g.has(e);upsertFolderIndexEntry(g,t,E.path,O,k),j||(S.push({kind:`folder-create`,path:E.path,relativePath:e}),scanForUntrackedSubfolders(k,t,s,g,S,w))}return{events:S,untrackedFiles:w}}function scanForUntrackedSubfolders(e,t,s,g,S,w){let E=[e];for(;E.length>0;){let e=E.shift();if(e===void 0)continue;let D;try{D=readdirSync(e,{withFileTypes:!0})}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] folder rescan readdir failed for ${e} (${s})`);continue}for(let O of D){if(O.isFile()){w.push(join(e,O.name));continue}if(!O.isDirectory())continue;let D=join(e,O.name),k=contentRelativePath(t,D);if(!k||s?.isDirExcluded(k))continue;let j;try{j=lstatSync(D)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder rescan lstat failed for ${D} (${t})`);continue}j.isDirectory()&&(g.has(k)||(upsertFolderIndexEntry(g,t,D,j),S.push({kind:`folder-create`,path:D,relativePath:k})),E.push(D))}}}async function handleRawEvents(e,t,s,g,S,w,E){let D=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),{events:O,untrackedFiles:k}=updateFolderIndexFromRawEvents(D,t,s,S),j=[];if(k.length>0){let e=new Set(D.map(e=>e.path)),s=new Set;for(let e of g.values())s.add(e.canonicalPath);j=k.filter(t=>!e.has(t)&&!lastKnownHash.has(t)&&!s.has(t)).filter(e=>!eventEscapesContentDir(e,t)).map(e=>({type:`create`,path:e})),j.length>0&&getLogger(`file-watcher`).debug({count:j.length,paths:j.map(e=>toPosix(relative(t,e.path)))},`[file-watcher] re-injecting rescued file creates from new-folder rescan`)}let F=j.length>0?D.concat(j):D,L=F.filter(e=>isSupportedDocFile(e.path)),B=F.filter(e=>isSupportedAssetFile(e.path,LINKABLE_ASSET_EXTENSIONS)),H=F.filter(e=>!isSupportedDocFile(e.path));if(L.length===0&&B.length===0&&O.length===0&&H.length===0)return;let q=L.length>0?await classifyEvents(L,t,s,E):[];for(let e of q){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let s=contentHash(e.content),g=e.path;try{g=realpathSync(e.path)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${s})`)}t=isSelfWrite(g,s)}else if(e.kind===`rename`){let s=contentHash(e.content),g=e.newPath;try{g=realpathSync(e.newPath)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${s})`)}t=isSelfWrite(g,s)}if(updateFileIndex(e,g),s&&!t)switch(e.kind){case`create`:s.incrementMdDir(dirname(e.docName));break;case`delete`:s.decrementMdDir(dirname(e.docName));break;case`rename`:s.decrementMdDir(dirname(e.oldDocName)),s.incrementMdDir(dirname(e.newDocName));break;case`update`:case`conflict`:break;default:assertNeverDiskEvent(e)}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let S=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(S),"disk.path.role":classifyFsPath(S)}},async()=>w(e))}for(let e of O)getLogger(`file-watcher`).debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1}),await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(e.path),"disk.path.role":classifyFsPath(e.path)}},async()=>w(e));for(let e of B){if(s){let g=toPosix(relative(t,e.path));if(s.isExcluded(g))continue}let g=toPosix(relative(t,e.path));await w(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:g}:{kind:`asset-create`,path:e.path,relativePath:g})}for(let e of H){let S=toPosix(relative(t,e.path));if(s?.isPathIgnored(S)||isSystemDoc(S)||isConfigDoc(S))continue;if(e.type===`delete`){let t={kind:`file-delete`,path:e.path,relativePath:S};updateFileIndex(t,g),await w(t);continue}let E;try{E=lstatSync(e.path),E.isSymbolicLink()&&(E=statSync(e.path))}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] file-event lstat failed for ${e.path} (${s})`);continue}if(!E.isFile())continue;let D=e.type===`create`?{kind:`file-create`,path:e.path,relativePath:S,size:E.size,modifiedTs:E.mtime.getTime(),inode:Number(E.ino)}:{kind:`file-update`,path:e.path,relativePath:S,size:E.size,modifiedTs:E.mtime.getTime(),inode:Number(E.ino)};updateFileIndex(D,g),await w(D)}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,s,g,S,w,E){let D;try{D=await import(`@parcel/watcher`)}catch(e){return getLogger(`file-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let O=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await D.subscribe(e,async(D,O)=>{if(D){console.error(`[file-watcher]`,D);return}try{await handleRawEvents(O.map(e=>({type:e.type,path:e.path})),e,t,s,g,S,w),E()}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},O)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,s,g,S,w,E){let{watch:D}=await import(`./chokidar-987bEGiR.mjs`),O=D(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(s,g)=>{let S=toPosix(relative(e,s));return S===``||S===`.`?!1:g?.isDirectory()?t.isDirExcluded(S):t.isExcluded(S)}:void 0});O.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let k=50,j=[],F=null;function L(D,O){j.push({type:D,path:O}),F||=setTimeout(()=>{let D=j;j=[],F=null,handleRawEvents(D,e,t,s,g,S,w).then(E).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return O.on(`add`,e=>L(`create`,e)),O.on(`change`,e=>L(`update`,e)),O.on(`unlink`,e=>L(`delete`,e)),O.on(`addDir`,e=>L(`create`,e)),O.on(`unlinkDir`,e=>L(`delete`,e)),{unsubscribe:()=>(F&&(clearTimeout(F),F=null,j=[]),O.close())}}async function startWatcher(e,t,s){let g;try{g=realpathSync(e)}catch{g=e}let S=new Map,w=new Map,E=new Map,D=new Map,O=0,k=null,j=-1,F=()=>{O++};await seedLastKnownHashes(g,g,s,S,w,E,D),F();let L=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),B,H;try{let e=await startParcelWatcher(g,s,S,w,t,E,F);e?(B=e,H=`parcel`):(B=await startChokidarWatcher(g,s,S,w,t,E,F),H=`chokidar`)}catch(e){throw clearInterval(L),e}let q=B.unsubscribe.bind(B);return getLogger(`file-watcher`).info({contentDir:g,backend:H},`watching for external .md changes`),{async unsubscribe(){return clearInterval(L),writeTracker.clear(),lastKnownHash.clear(),q()},getFileIndex(){return k&&j===O?k:(k=markdownIndexView(S),j=O,k)},getAllFilesIndex(){return S},getFileIndexGeneration(){return O},getFolderIndex(){return w},getAliasMap(){return E},getFolderAliasIndex(){return D},mutateFileIndex(e){updateFileIndex(e,S),F()},pruneFileIndexNowExcluded(){if(!s)return 0;let e=0;for(let[t,w]of S){let E=toPosix(relative(g,w.canonicalPath));(w.kind===`file`?s.isPathIgnored(E):s.isExcluded(E))&&(S.delete(t),e++)}return e>0&&F(),e},pruneFolderIndexNowExcluded(){if(!s)return 0;let e=0;for(let t of w.keys())s.isDirExcluded(t)&&(w.delete(t),e++);return e},async rescanFromDisk(){await seedLastKnownHashes(g,g,s,S,w,E,D),F()}}}async function reconcileFileIndexAfterFilterRebuild(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),s=e.pruneFolderIndexNowExcluded();return await e.rescanFromDisk(),{prunedFiles:t,prunedFolders:s}}const log$20=getLogger(`managed-artifact-persistence`);function homeFor(e){return e.homedirOverride??homedir()}function managedArtifactContributorAttribution(e){let t=parseManagedArtifactName(e);if(t===null)return null;if(t.kind===`skill`)return t.scope===`project`?{docKey:`${SKILL_CONTENT_ROOT}/${t.name}`,subject:`skill-edit: ${t.name}/SKILL.md`}:null;let s=t.folder.replace(/\/$/,``),g=`${s?`${s}/`:``}.ok/templates/${t.name}`;return{docKey:g,subject:`template-edit: ${g}.md`}}function managedArtifactTimelinePaths(e){let t=parseManagedArtifactName(e);if(!t)return{managed:!1};let s=managedArtifactContributorAttribution(e);if(!s)return{managed:!0,versioned:!1};let g=t.kind===`skill`?`${s.docKey}/SKILL.md`:`${s.docKey}.md`;return{managed:!0,versioned:!0,docKey:s.docKey,filePath:g}}function managedArtifactSkillsRoots(e){return[resolve(homeFor(e),`.ok`,`skills`)]}function managedArtifactAbsPath(e,t){let s=parseManagedArtifactName(e);if(s===null)throw Error(`managedArtifactAbsPath: not a managed-artifact doc name: ${e}`);if(s.kind===`template`)return templateAbsPath(s.folder,s.name,t,e);if(!SKILL_NAME_REGEX.test(s.name)||s.name.length>64)throw Error(`managedArtifactAbsPath: invalid skill name: ${JSON.stringify(s.name)}`);let g=resolve(s.scope===`global`?homeFor(t):t.projectDir,`.ok`,`skills`),S=resolve(g,s.name,`SKILL.md`);if(!S.startsWith(g+sep))throw Error(`managedArtifactAbsPath: path escape for ${e}`);return S}function normalizeTemplateFolder(e){return e.replace(/^\/+/,``).replace(/\/+$/,``)}function templateAbsPath(e,t,s,g){if(!TEMPLATE_NAME_REGEX.test(t)||t.length>64)throw Error(`managedArtifactAbsPath: invalid template name: ${JSON.stringify(t)}`);let S=normalizeTemplateFolder(e);if(S.split(`/`).includes(`..`))throw Error(`managedArtifactAbsPath: template folder escape for ${g}`);let w=resolve(s.projectDir),E=S?resolve(w,S):w;if(E!==w&&!E.startsWith(w+sep))throw Error(`managedArtifactAbsPath: template folder escape for ${g}`);let D=resolve(E,`.ok`,`templates`),O=resolve(D,`${t}.md`);if(!O.startsWith(D+sep))throw Error(`managedArtifactAbsPath: path escape for ${g}`);return O}function managedArtifactDocNameForPath(e,t){let s=resolve(e);if(s.endsWith(`${sep}SKILL.md`)){let e=[[resolve(homeFor(t),`.ok`,`skills`),`global`]];for(let[t,g]of e){if(!s.startsWith(t+sep))continue;let e=s.slice(t.length+1).split(sep);if(e.length!==2||e[1]!==`SKILL.md`)continue;let S=e[0];if(!(!SKILL_NAME_REGEX.test(S)||S.length>64))return`${MANAGED_ARTIFACT_PREFIX_SKILL}${g}/${S}`}return null}if(s.endsWith(`.md`)){let e=resolve(t.projectDir);if(s!==e&&!s.startsWith(e+sep))return null;let g=s===e?``:s.slice(e.length+1),S=`.ok${sep}templates${sep}`,w=g.indexOf(S);if(w<0||w>0&&g[w-1]!==sep)return null;let E=g.slice(w+S.length);if(E.includes(sep)||!E.endsWith(`.md`))return null;let D=E.slice(0,-3);if(!TEMPLATE_NAME_REGEX.test(D)||D.length>64)return null;let O=w===0?``:g.slice(0,w-1),k=O?O.split(sep).map(e=>encodeURIComponent(e)).join(`/`):``;return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${k?`${k}/`:``}${encodeURIComponent(D)}`}return null}function loadManagedArtifactDoc(e,t,s){let g=parseManagedArtifactName(t);if(g?.kind===`skill`&&g.scope===`project`||e.getXmlFragment(`default`).length>0)return;let S=managedArtifactAbsPath(t,s);if(!existsSync(S))return;let w;try{w=readFileSync(S,`utf-8`)}catch(e){log$20.warn({documentName:t,err:e.message},`load: could not read; seeding empty`);return}e.transact(()=>{applyDiskContentToDoc(e,w,void 0,t),e.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},FILE_WATCHER_ORIGIN),s.setReconciledBase(t,w),s.lkgCache.set(t,w)}async function storeManagedArtifactDoc(e,t,s,g){let S=parseManagedArtifactName(t);if(S?.kind===`skill`&&S.scope===`project`||s===FILE_WATCHER_ORIGIN)return`no-op`;let w=e.getText(`source`).toString(),E=g.lkgCache.get(t);if(w===E)return`no-op`;let D=managedArtifactAbsPath(t,g);try{return await tracedMkdir(resolve(D,`..`),{recursive:!0}),await withFileLock(`${D}.lock`,async()=>{if(existsSync(D)){let s=null;try{s=readFileSync(D,`utf-8`)}catch(e){e.code!==`ENOENT`&&log$20.warn({documentName:t,err:e.message},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),s=null}if(s!==null&&s!==E&&s!==w)return e.transact(()=>{applyDiskContentToDoc(e,s,void 0,t)},FILE_WATCHER_ORIGIN),g.setReconciledBase(t,s),g.lkgCache.set(t,s),`reconciled`}return await atomicWriteFile(D,w,{fs:tracedAtomicFs}),g.lkgCache.set(t,w),g.setReconciledBase(t,w),`persisted`})}catch(e){return e instanceof FileLockTimeoutError?(log$20.warn({documentName:t},`store: file lock timeout; skipping write`),`write-failed`):(log$20.warn({documentName:t,err:e.message},`store: write failed`),`write-failed`)}}function applyExternalManagedArtifactChange(e,t,s,g){if(!e)return`no-op`;let S=g.lkgCache.get(t);return S!==void 0&&S===s?`no-op`:(e.transact(()=>{applyDiskContentToDoc(e,s,void 0,t)},FILE_WATCHER_ORIGIN),g.setReconciledBase(t,s),g.lkgCache.set(t,s),`applied`)}const log$19=getLogger(`mermaid-persistence`),MERMAID_SOURCE_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`mermaid-source`}};function mermaidAbsPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let s=resolve(t,docNameToRelativePath(e));if(!isWithinDir(s,t))throw Error(`Invalid document name: ${e}`);return s}function replaceSource(e,t,s){let g=e.getText(`source`);e.transact(()=>{g.length>0&&g.delete(0,g.length),t.length>0&&g.insert(0,t),s&&e.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},MERMAID_SOURCE_ORIGIN)}function loadMermaidDoc(e,t,s){if(e.getText(`source`).length>0)return;let g=mermaidAbsPath(t,s.contentDir);if(!existsSync(g))return;let S;try{S=readFileSync(g,`utf-8`)}catch(e){log$19.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}replaceSource(e,S,!0),s.lkgCache.set(t,S)}async function storeMermaidDoc(e,t,s,g){if(s===MERMAID_SOURCE_ORIGIN)return`no-op`;let S=e.getText(`source`).toString(),w=g.lkgCache.get(t);if(S===w)return`no-op`;let E=mermaidAbsPath(t,g.contentDir);try{if(await tracedMkdir(resolve(E,`..`),{recursive:!0}),existsSync(E)){let s=null;try{s=readFileSync(E,`utf-8`)}catch(e){e.code!==`ENOENT`&&log$19.warn({documentName:t,err:e},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),s=null}if(s!==null&&s!==w&&s!==S)return replaceSource(e,s,!1),g.lkgCache.set(t,s),`reconciled`}return await atomicWriteFile(E,S,{fs:tracedAtomicFs}),g.lkgCache.set(t,S),`persisted`}catch(e){return log$19.warn({documentName:t,err:e},`store: write failed`),`write-failed`}}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
782
782
  `||e===` `||e===`\r`}function classifyDuplication(e,t){let s=normalizeBody(t);if(s.length===0)return{kind:`allow`,reason:`empty-base`};let g=normalizeBody(e);if(g===s)return{kind:`allow`,reason:`identical`};if(g.length<s.length*2)return{kind:`allow`,reason:`too-short`};let S=0,w=0;for(;S<g.length;){if(g.slice(S,S+s.length)!==s)return{kind:`allow`,reason:`not-integer-multiple`};for(S+=s.length,w++;S<g.length&&isWhitespace(g[S]??``);)S++}return w>=2?{kind:`block`,reason:`structural-duplication`,copies:w}:{kind:`allow`,reason:`single-copy`}}function withHiddenWindowsConsole(e){return{...e,windowsHide:!0}}let _liveEntriesGauge=null;function liveEntriesGauge(){return _liveEntriesGauge||=getMeter().createUpDownCounter(`rename.log_entries_total`,{description:`Live rename-log entry count after each append / GC pass`}),_liveEntriesGauge}let _gcDroppedCounter=null;function gcDroppedCounter(){return _gcDroppedCounter||=getMeter().createCounter(`rename.log_gc_dropped_total`,{description:`Cumulative count of rename-log entries dropped by reachability GC`}),_gcDroppedCounter}const RENAME_LOG_HARD_CAP_BYTES=5*1024*1024,RENAME_LOG_MAX_LINE_BYTES=4*1024,RENAME_LOG_FILENAME=`renames.jsonl`;function createEmptyIndex(){return{byTo:new Map,byFrom:new Map}}function renameLogPath(e){return resolve(e,RENAME_LOG_FILENAME)}function validateEntry(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||typeof t.from!=`string`||t.from.length===0||typeof t.to!=`string`||t.to.length===0||t.from===t.to||typeof t.at!=`string`||t.at.length===0||typeof t.commitSha!=`string`||t.commitSha!==``&&!/^[0-9a-f]{40}$/.test(t.commitSha)||typeof t.branch!=`string`||t.branch.length===0||typeof t.groupId!=`string`||t.groupId.length===0||t.kind!==`file`&&t.kind!==`folder`||t.actor===null||typeof t.actor!=`object`)return null;let s=t.actor;return typeof s.writerId!=`string`||s.writerId.length===0||typeof s.displayName!=`string`?null:{v:1,from:t.from,to:t.to,at:t.at,commitSha:t.commitSha,branch:t.branch,groupId:t.groupId,kind:t.kind,actor:{writerId:s.writerId,displayName:s.displayName}}}function removeFromByFrom(e,t){let s=e.byFrom.get(t.from);if(!s)return;let g=s.filter(e=>e!==t);g.length===0?e.byFrom.delete(t.from):e.byFrom.set(t.from,g)}function indexRemove(e,t){e.byTo.delete(t.to),removeFromByFrom(e,t)}function indexInsert(e,t){let s=e.byTo.get(t.to);s&&removeFromByFrom(e,s),e.byTo.set(t.to,t);let g=e.byFrom.get(t.from);g?g.push(t):e.byFrom.set(t.from,[t])}function loadRenameLogIndex(e){let t=createEmptyIndex(),s=renameLogPath(e);if(!existsSync(s))return t;let g;try{g=readFileSync(s,`utf-8`)}catch(e){return console.warn(`[rename-log] WARN: failed to read ${s}, treating as empty:`,e),t}if(g.length===0)return t;let S=g.split(`
783
783
  `),w=S[S.length-1];w!==``&&console.warn(`[rename-log] WARN: trailing line missing newline (${w.length} bytes); dropped`);let E=S.slice(0,-1);for(let e=0;e<E.length;e++){let s=E[e];if(s.length===0)continue;let g;try{g=JSON.parse(s)}catch(t){let g=s.slice(0,80),S=t.message;console.warn(`[rename-log] WARN: corrupt entry at line ${e+1} skipped (${S}): ${g}${s.length>80?`…`:``}`);continue}let S=validateEntry(g);if(!S){console.warn(`[rename-log] WARN: corrupt entry at line ${e+1} skipped`);continue}indexInsert(t,S)}return t.byTo.size>0&&liveEntriesGauge().add(t.byTo.size),t}function appendRenameLogEntry(e,t,s,g){let S=validateEntry(t);if(!S)throw Error(`[rename-log] refusing to append malformed entry`);let w=`${JSON.stringify(S)}\n`;if(Buffer.byteLength(w,`utf-8`)>RENAME_LOG_MAX_LINE_BYTES)throw Error(`[rename-log] entry exceeds max line size (${RENAME_LOG_MAX_LINE_BYTES} bytes)`);let E=renameLogPath(e),D=!1;if(existsSync(E))try{let e=statSync(E).size;e>5242880&&(D=!0,console.warn(`[rename-log] WARN: file size ${e} exceeds hard cap ${RENAME_LOG_HARD_CAP_BYTES}; forcing GC sweep`))}catch{}tracedAppendFileSync(E,w,{flag:`a`}),indexInsert(s,S),liveEntriesGauge().add(1),D&&g&&scheduleHardCapGc(g,s)}const gcPending=new Set;function scheduleHardCapGc(e,t){queueMicrotask(()=>{gcRenameLog(e,t).catch(e=>{console.warn(`[rename-log] WARN: hard-cap forced GC failed:`,e)})})}let _moduleIndex=null;function setRenameLogIndex(e,t){_moduleIndex={shadowDir:e,index:t}}function getOrLoadRenameLogIndex(e){if(_moduleIndex&&_moduleIndex.shadowDir===e)return _moduleIndex.index;let t=loadRenameLogIndex(e);return _moduleIndex={shadowDir:e,index:t},t}function serializeIndexToString(e){let t=[];for(let s of e.byTo.values())t.push(JSON.stringify(s));return t.length>0?`${t.join(`
784
784
  `)}\n`:``}function parseGitTimeoutMs(){let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4}function expandPredecessors(e,t,s){let g=[],S=new Set,w=e,E=0;for(;;){if(g.length>=100){console.warn(`[rename-log] WARN: predecessor chain depth exceeded 100 while expanding "${e}"; truncating`);break}if(S.has(w)){console.warn(`[rename-log] WARN: cycle detected at "${w}" while expanding predecessors of "${e}"; truncating`);break}S.add(w);let D=s.byTo.get(w);if(!D||D.branch!==t)break;if(D.commitSha===``){E+=1;break}g.push({path:D.from,renameCommit:D.commitSha}),w=D.from}return g.reverse(),g.push({path:e,renameCommit:null}),{chain:g,skipped:E}}function createAncestorShaSetCache(){return new Map}function createSeedsCache(){return new Map}async function buildSeeds(e,t,s,g){return withSpan(`rename.buildSeeds`,void 0,async S=>{if(g){let e=g.get(`${s}:${t}`);if(e)return S.setAttribute(`rename.seeds_count`,e.length),S.setAttribute(`rename.cache_hit`,!0),e}let w=shadowGit(e),E;try{E=(await w.raw(`show`,`-s`,`--format=%aI`,t)).trim()}catch(e){return console.warn(`[rename-log] WARN: buildSeeds: git show failed for rename commit ${t}; falling back to single-seed:`,e),S.setAttribute(`rename.seeds_count`,1),[t]}if(!E)return S.setAttribute(`rename.seeds_count`,1),[t];let D;try{D=await w.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(creatordate:iso8601-strict) %(objectname)`,`refs/checkpoints/${s}/`)}catch(e){return console.warn(`[rename-log] WARN: buildSeeds: for-each-ref failed for branch ${s}; falling back to single-seed:`,e),S.setAttribute(`rename.seeds_count`,1),[t]}let O=[t];for(let e of D.split(`
@@ -796,10 +796,10 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
796
796
  `).slice(0,4).join(`
797
797
  `)})})})},k=``,j=``,F=!1,L=!1,B=!1,H=0,q=()=>{j=g.toString(),F=!1},ee=e=>{k=e,q(),F=e!==``},J=e=>{k=e,j=e,F=!1},Y=e=>{k=e,F=!1},te=e=>{k=e,j=g.toString(),F=!0},ne=()=>stripFrontmatter(g.toString()).frontmatter,ae=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,oe=createDocCanonicalizer(S,{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,docName:e.docName}),se=``,ce=``,ue=!1,de=(e,t)=>{if(ue&&e===se&&t===ce)return!0;let s=isParseEquivalentBridge(e,t,oe);return s&&(se=e,ce=t,ue=!0),s},fe=(e,t,s)=>settlesSplitBrain(e,t,s)&&!de(e,t);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e),E=prependFrontmatter(ne(),t);de(g.toString(),E)?ee(E):J(E)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),ee(``)}let me,ge=5e3,_e=2e3,ve=new Map,ye=new Map,Ce=(t,s)=>{let S=e.docName??`__nodoc__`,w=Date.now(),E=ve.get(S);if(E!==void 0&&w-E.lastMs<5e3)E.suppressed+=1,incrementProducerGuardFiresSuppressed();else{let g=E?.suppressed??0;ve.set(S,{lastMs:w,suppressed:0}),incrementProducerGuardFires(),console.warn(JSON.stringify({event:`producer-guard-violation`,docName:e.docName??null,reason:t.reason,construct:s,appliedDegrades:t.appliedDegrades,suppressedSincePrevious:g,timestamp:new Date().toISOString()}))}let D=e.shadow?.();if(!D||!e.docName)return;let O=g.toString();if(ye.get(S)===O)return;ye.set(S,O);let k=e.getBranch?.()??`main`,j=e.contentRoot??``,F=e.docName;queueMicrotask(()=>{saveInMemoryCheckpoint(D,j,{kind:`producer-guard-loss`,docName:F,contents:O,label:`Before producer-guard content-loss @ ${new Date().toISOString()}`,branch:k,metadata:{construct:s}}).then(e=>{incrementProducerGuardCheckpointCreated(),console.warn(JSON.stringify({event:`producer-guard-checkpoint-created`,docName:F,sha:e,kind:`producer-guard-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{ye.get(S)===O&&ye.delete(S);let t=e instanceof Error?e:Error(String(e));console.warn(`[Server Observer A] Producer-guard checkpoint write failed:`,{name:t.name,message:t.message,stack:t.stack?.split(`
798
798
  `).slice(0,4).join(`
799
- `)})})})},we=(t,s)=>{if(s===me||(me=s,!fragmentContainsDangerSpace(t)))return;let g=comparePmStructural(t,S.parseWithFallback(s,ae));if(!(g.equivalent||g.reason!==`content-loss`)){if(shouldRethrowBridgeMergeLoss())throw new ProducerGuardViolationError({docName:e.docName,reason:g.reason,detail:g.detail});Ce(g,dangerSpaceLocator(t))}},Te=()=>{try{let L=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),q=g.toString()===j,Y=Date.now()-H>=2e3,te=q&&Y,ae=S.serialize(L,{skipFreshnessDerive:!te});te&&we(L,ae);let oe=prependFrontmatter(ne(),ae),se=g.toString(),ce=overMultipliedBodyLines(oe,se,8);if(ce.length>0&&findRaceDuplicatedSpans(s,t.clientID,ce)){J(oe),B=!0,D(`duplication-guard`),incrementObserverADuplicationRederives(),O(oe,ce.length),setActiveSpanAttributes({"observer.a.path":`gated-duplication-rederive`});return}if(F&&k===oe){fe(g.toString(),oe)?(J(oe),B=!0,D(`identity-gate`),setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged-rederive`})):setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged`});return}let ue=normalizeBridge(se),de=normalizeBridge(oe);if(ue===de){setActiveSpanAttributes({"observer.a.path":`gated-in-sync`}),ee(oe);return}let me=j,ge=se===j,_e=ge&&F&&j!==k&&ue!==normalizeBridge(k);setActiveSpanAttributes({"observer.a.path":ge?_e?`residual-merge`:`path-a`:`path-b`});let ve={mergedText:null},ye=performance.now(),Ce=ge&&_e?null:tryComputeMapDrivenSplice({currentText:se,lastSyncedXmlMd:j,json:L,mdManager:S,docName:e.docName});Ce&&setActiveSpanAttributes({"observer.a.path":`map-driven-splice`,"observer.a.splice.compute_ms":Math.round(performance.now()-ye)}),t.transact(()=>{if(Ce)applyMapDrivenSplice(g,Ce);else if(ge&&!_e)applyIncrementalDiff(g,se,oe);else{let t=ge?k:me,{boundary:s}=splitLeadingDocBoundary(se),S=e=>reattachLeadingDocBoundary(splitLeadingDocBoundary(e).text,s),w=e.mergeThreeWay??mergeThreeWay;try{let e=S(w(projectMergeBoundarySpace(t),projectMergeBoundarySpace(oe),projectMergeBoundarySpace(se)));applyFastDiff(g,se,e),ve.mergedText=e}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(E(e,me),shouldRethrowBridgeMergeLoss()))throw e;let t=S(e.info.result);applyFastDiff(g,se,t),ve.mergedText=t}}},OBSERVER_SYNC_ORIGIN),Ce&&incrementMapDrivenSpliceApplied(),ve.mergedText!==null&&!ge&&emitObserverAPathBFired(e.docName)&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!ge,mergeBytesChanged:Math.abs(ve.mergedText.length-se.length)}))),ve.mergedText!==null&&ge&&incrementObserverAResidualMergeRuns(),incrementServerObserverFire(`a`),ee(oe),fe(g.toString(),oe,de)&&(B=!0,D(`post-merge`))}catch(t){if(t instanceof BridgeMergeContentLossError||t instanceof ProducerGuardViolationError)throw t;incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,t);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e),E=prependFrontmatter(ne(),t);fe(g.toString(),E)?(te(E),B=!0,D(`error-recovery`)):ee(E)}catch(s){console.warn(`[Server Observer A] Baseline recovery also failed`,JSON.stringify({"doc.name":e.docName??null,originalError:t instanceof Error?t.message:String(t),recoveryError:s instanceof Error?s.message:String(s)})),k=``,j=``,F=!1}}},De=()=>{withSpanSync(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},Te)},je=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=ne();q(),Me=e}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),L=!0}return}L=!0}};if(s.length>0&&g.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(e),D=prependFrontmatter(ne(),E);t.transact(()=>{g.insert(0,D)},OBSERVER_SYNC_ORIGIN),ee(D)}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),ee(``)}let Me=ne(),Pe=()=>{try{let w=g.toString(),{frontmatter:E,body:D}=stripFrontmatter(w);if(normalizeBridge(j)===normalizeBridge(w)){Me!==E&&(recordFrontmatterEditSurface(`source-mode`),Me=E);return}let O=S.parseWithFallback(D,ae),k=e.schema.nodeFromJSON(O);t.transact(()=>{updateYFragment(t,s,k,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),Me!==E&&(recordFrontmatterEditSurface(`source-mode`),Me=E),incrementServerObserverFire(`b`);try{let t=S.serialize(O),s=prependFrontmatter(E,t);assertBridgeInvariant(g.toString(),s,{site:`observer-b`,docName:e.docName,canonicalizeBody:e=>e===D?t:oe(e)}),ee(s)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),ee(prependFrontmatter(E,D))}}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e);Y(prependFrontmatter(ne(),t))}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},Ie=()=>{withSpanSync(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},Pe)},Re=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=ne();q(),Me=e}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),B=!0}return}H=Date.now(),B=!0}},ze=(t,s)=>{withSpanSync(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!L&&!B){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(s.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){L=!1,B=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}let g=L;L&&(L=!1,e.onDispatch?.(`a`),De());let S=B;B&&(B=!1,e.onDispatch?.(`b`),Ie()),t.setAttribute(`observer.dispatch`,g&&S?`a-then-b`:g?`a`:S?`b`:`none`)})};s.observeDeep(je),g.observe(Re),t.on(`afterAllTransactions`,ze);let Be=attachQuiescenceTracker(t);return()=>{Be(),t.off(`afterAllTransactions`,ze),s.unobserveDeep(je),g.unobserve(Re)}}const log$17=getLogger(`persistence`);var DocumentOpenSizeLimitError=class extends Error{docName;size;limit;constructor(e,t,s=DOCUMENT_OPEN_BYTE_LIMIT){super(`Document "${e}" is ${formatFileSize(t)}; OpenKnowledge opens documents up to ${formatFileSize(s)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=s}};function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let s=e;if(s.source===`local`){let e=s.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(s.source===`connection`){let e=s.connection?.context;if(typeof e?.principalId==`string`){let s=e.principalId,g=t?.();return g&&g.id===s&&g.display_name&&g.display_email?{id:g.id,name:g.display_name,email:g.display_email}:{id:s,name:`Local User`,email:`${s}@openknowledge.local`}}return SERVICE_WRITER}return null}const ERRNO_FS_CODES=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function classifyDeferredStoreError(e){if(typeof e!=`object`||!e)return`unknown`;let t=e,s=typeof t.message==`string`?t.message:``;return s.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&ERRNO_FS_CODES.has(t.code)?s.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof BridgeInvariantViolationError?`serialize`:`unknown`}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let s=resolve(t,docNameToRelativePath(e));if(!isWithinDir(s,t))throw Error(`Invalid document name: ${e}`);return s}function isWithinContentDir(e,t){return isWithinDir(e,t)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}const inFlightFlushByDoc=new Map;function peekInFlightFlush(e){return inFlightFlushByDoc.get(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function toStoreFailure(e){let t;try{let s=e?.code;typeof s==`string`&&(t=s)}catch{}let s=`unknown store error`;try{s=e instanceof Error?e.message:String(e)}catch{}return{code:t,message:s}}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),s;try{s=realpathSync(t)}catch{s=t}let g=e?.projectDir??process.cwd(),S=e?.shadowRef,w=e?.contentRoot??(toPosix(relative(g,s))||`.`),E=e?.backlinkIndex,D=e?.getPrincipal,O=e?.onAgentCommit,k=e?.onFlushCommit,j=e?.onDiskFlush,F=e?.onConfigPersisted,L=e?.mdManager??mdManager,B=e?.ephemeral??!1,H={projectDir:g,contentDir:s,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected,ephemeral:B},q=new Map,ee={projectDir:g,homedirOverride:e?.configHomedirOverride,lkgCache:q,setReconciledBase,getReconciledBase},J={contentDir:s,lkgCache:new Map},Y=new Set,te=e?.applyDiskContentToDoc??applyDiskContentToDoc,ne=null,ae=8,oe=new Map,se=new Map,ce=new Set,ue=new Set,de=e?.gitEnabled??!0,fe=e?.commitDebounceMs??15e3,me=e?.wipRef??`refs/wip/main`,ge=e?.getCurrentBranch,_e=null,ve=0,ye=null,Ce=!1,we=null,Te=new Map;async function De(){We();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await je()).finally(()=>{Ue?.record((Date.now()-e)/1e3)})}async function je(){let e=S?.current;if(e){let t=swapContributors(),s=ge?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},g=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,w,g,s);ve=0,log$17.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`);try{backfillRenameLogCommitSha(e.gitDir,SERVICE_WRITER.id,t,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$17.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){ve++,incrementGitAutoSaveFailure(),log$17.error({err:e,attempt:ve},`[persistence] Shadow commit failed (attempt ${ve})`),ve>=3&&log$17.error({attempt:ve},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let g;try{g=await buildWipTree(e,w)}catch(e){restoreContributors(t),ve++,incrementGitAutoSaveFailure(),log$17.error({err:e,attempt:ve},`[persistence] Shadow WIP tree build failed (attempt ${ve})`);return}let S=!1;for(let[w,E]of t){let t={id:w,name:E.displayName,email:`${w}@openknowledge.local`},D=[...E.docs],j=E.actor,F=[...E.summaries],L=[...E.previousPaths],B={v:1,writer_id:w,principal:j?.principalId??null,agent_session:w.startsWith(`agent-`)?w.slice(6):null,agent_type:j?.agentType??null,client_name:j?.clientName??null,client_version:j?.clientVersion??null,label:j?.label??null,display_name:E.displayName,color_seed:E.colorSeed,docs:D,...F.length>0?{summaries:F}:{},...L.length>0?{previous_paths:L}:{}},H=`${composeCommitSubject(E.subjectOverride??formatWipSubject(D),F)}\n\n${formatOkActor(B)}`;try{let E=await commitWipFromTree(e,t,g,H,s);S=!0;try{k?.()}catch(e){log$17.warn({err:e},`[persistence] onFlushCommit callback failed (non-fatal)`)}log$17.info({sha:E.slice(0,8),writer:w,tree:g.slice(0,8)},`[persistence] Shadow WIP commit: ${E.slice(0,8)} on refs/wip/${w}`);try{backfillRenameLogCommitSha(e.gitDir,w,E,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$17.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}w.startsWith(`agent-`)&&O?.()}catch(e){restoreContributorEntry(w,E),incrementGitWriterCommitFailure(),log$17.error({err:e,writer:w},`[persistence] Per-writer shadow commit failed for ${w}`)}}S?ve=0:(ve++,incrementGitAutoSaveFailure(),ve>=3&&log$17.error({attempt:ve},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(g,`.git`),workTree:g}),s=resolve(g,`.git/index-wip`),E={GIT_INDEX_FILE:s};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(E).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$17.info({},`[persistence] Empty repo — starting with empty index`):log$17.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(E).raw(`add`,w);let e=(await t.env(E).raw(`write-tree`)).trim(),s=null;try{s=(await t.raw(`rev-parse`,me)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let g=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];s&&g.push(`-p`,s);let S=(await t.raw(...g)).trim();await t.raw(`update-ref`,me,S),ve=0,log$17.info({sha:S.slice(0,8),wipRef:me},`[persistence] Git commit: ${S.slice(0,8)} on ${me}`)}catch(e){ve++,incrementGitAutoSaveFailure(),log$17.error({err:e,attempt:ve},`[persistence] Git commit failed (attempt ${ve})`),ve>=3&&log$17.error({attempt:ve},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(s)}catch{}}}function Me(e){if(e<=0)return fe;let t=2**Math.min(e,5),s=Math.random()*.25*fe;return fe*t+s}function Pe(){de&&(isBatchInProgress()||(_e&&clearTimeout(_e),_e=setTimeout(()=>{if(_e=null,ye){Ce=!0;return}ye=De().finally(()=>{ye=null,Ce&&(Ce=!1,Pe())})},Me(ve))))}async function Ie(){_e&&(clearTimeout(_e),_e=null,ye||=De().finally(()=>{ye=null,Ce&&(Ce=!1,Pe())})),ye&&await ye}function Re(t,s){try{let{frontmatter:g,body:S}=stripFrontmatter(t),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:s}:void 0,E=L.parseWithFallback(S,w);return normalizeBridge(prependFrontmatter(g,L.serialize(E)))}catch(e){return log$17.debug({err:e,documentName:s},`[g8] ephemeral canonical baseline failed; falling through to write`),null}}function ze(t,s,g){try{let S=t.getXmlFragment(`default`),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:g}:void 0,E=mdManager.parseWithFallback(s,w),D=schema.nodeFromJSON(E);t.transact(()=>{updateYFragment(t,S,D,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN)}catch(e){incrementPersistenceReconciliationFailures(),log$17.warn({err:e,documentName:g},`[persistence] reconcileFragmentNow failed for ${g}`)}}let Be=null,Ve=null,Ue=null;function We(){if(Be)return;let e=getMeter();Be=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),Ve=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),Ue=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function Ge({document:t,documentName:g,lastTransactionOrigin:S}){We();let w=Date.now(),O;return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":g}},async()=>{let w=ue.delete(g),k=t.getMap(`lifecycle`).get(`status`);if(k===`deleted-upstream`||k===`renamed`||k===`conflict`){log$17.info({documentName:g,lifecycleStatus:k},`[persistence] Skipped store for ${g}: lifecycle=${k}`),oe.delete(g),Y.delete(g);return}if(!isDocQuiescent(t)){let e=oe.get(g)??0;if(e<8){let s=getMsSinceLastUserTx(t);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":g,wallClockMsSinceLastTransaction:s??null,deferCount:e})),incrementPersistenceSkipNonQuiescent(),oe.set(g,e+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":g,wallClockMsSinceLastTransaction:getMsSinceLastUserTx(t)??null,deferCount:e})),incrementPersistenceForceFlushDuringBurst()}let{sv:F,json:H}=captureDocSnapshotForPersistence(t),{frontmatter:q,body:ee}=stripFrontmatter(t.getText(`source`).toString()),J=prependFrontmatter(q,ee),ne;try{ne=assertBridgeInvariant(J,prependFrontmatter(q,L.serialize(H)),{site:`persistence`,docName:g,suppressDevThrow:!0,canonicalizeBody:createDocCanonicalizer(L,{resolveEmbed:e?.resolveEmbed,resolveSize:e?.resolveSize,docName:g})})}catch(e){incrementPersistenceSanityCheckSerializeFailures(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":g,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),log$17.warn({err:e,documentName:g},`[persistence] Sanity-check serialize failed for ${g}; proceeding with ytext bytes`),ne=!1}ne||ze(t,ee,g);let ae=getReconciledBase(g),de=normalizeBridge(J),fe=ae!==void 0&&de===normalizeBridge(ae);if(!fe&&B&&ae!==void 0){let e=Re(ae,g);e!==null&&de===e&&(fe=!0)}if(fe){contributorCount()>0&&Pe(),oe.delete(g);return}if(ae===void 0&&normalizeBridge(J)===``){log$17.warn({documentName:g},`[persistence] Skipped phantom write for ${g}: empty Y.Doc with no reconciled base`),oe.delete(g);return}let me=resolveWriterFromOrigin(S,D);if(me&&me.id!==SERVICE_WRITER.id&&(hasContributor(me.id)||recordContributor(g,me.id,me.name,me.id)),ae!==void 0){let e=classifyDuplication(J,ae);if(e.kind===`block`){if(Y.has(g)){log$17.warn({documentName:g},`[persistence] Tripwire breaker active — skipping duplicate store for ${g}`);return}let S=t.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":g,candidateBytes:J.length,baseBytes:ae.length,fragmentChildren:S,copies:e.copies,reason:e.reason}));try{let e=safeContentPath(g,s),S;if(existsSync(e)){let t=null;try{t=realpathSync(e)}catch(e){log$17.warn({err:e,documentName:g},`[persistence] Tripwire reset realpath failed for ${g}; using currentBase`)}if(t&&isWithinContentDir(t,s))try{S=readFileSync(t,`utf-8`)}catch(e){log$17.warn({err:e,documentName:g,canonical:t},`[persistence] Tripwire reset readFileSync failed for ${g}; using currentBase`),S=ae}else t&&console.warn(`[persistence] symlink-escape on tripwire reset: ${e} → ${t}, using currentBase`,{docName:g,originalPath:e,canonical:t,contentDir:s}),S=ae}else S=ae;t.transact(()=>{te(t,S)},FILE_WATCHER_ORIGIN),Y.delete(g)}catch(e){Y.add(g),log$17.error({err:e,documentName:g},`[persistence] Tripwire reset failed for ${g}`)}oe.delete(g);return}}O=normalizeBridge(J),inFlightFlushByDoc.set(g,O);let ge=safeContentPath(g,s);await tracedMkdir(dirname(ge),{recursive:!0});let _e;try{_e=await realpath(ge)}catch(e){let t=e.code;if(t===`ENOENT`){let e=!1;try{e=lstatSync(ge).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$17.warn({err:e,path:ge},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:g,reason:`broken-symlink`}),_e=ge}else if(t===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${ge}`),Error(`Symlink cycle detected at ${ge}`);else throw e}if(!isWithinContentDir(_e,s)){let e=`symlink-escape: ${ge} resolves to ${_e} outside ${s}`;throw console.error(`[persistence] ${e}`,{docName:g,originalPath:ge,canonical:_e,contentDir:s}),Error(e)}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_DIVERGENCE===g&&await tracedWriteFile(_e,`# NATIVE
799
+ `)})})})},we=(t,s)=>{if(s===me||(me=s,!fragmentContainsDangerSpace(t)))return;let g=comparePmStructural(t,S.parseWithFallback(s,ae));if(!(g.equivalent||g.reason!==`content-loss`)){if(shouldRethrowBridgeMergeLoss())throw new ProducerGuardViolationError({docName:e.docName,reason:g.reason,detail:g.detail});Ce(g,dangerSpaceLocator(t))}},Te=()=>{try{let L=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),q=g.toString()===j,Y=Date.now()-H>=2e3,te=q&&Y,ae=S.serialize(L,{skipFreshnessDerive:!te});te&&we(L,ae);let oe=prependFrontmatter(ne(),ae),se=g.toString(),ce=overMultipliedBodyLines(oe,se,8);if(ce.length>0&&findRaceDuplicatedSpans(s,t.clientID,ce)){J(oe),B=!0,D(`duplication-guard`),incrementObserverADuplicationRederives(),O(oe,ce.length),setActiveSpanAttributes({"observer.a.path":`gated-duplication-rederive`});return}if(F&&k===oe){fe(g.toString(),oe)?(J(oe),B=!0,D(`identity-gate`),setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged-rederive`})):setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged`});return}let ue=normalizeBridge(se),de=normalizeBridge(oe);if(ue===de){setActiveSpanAttributes({"observer.a.path":`gated-in-sync`}),ee(oe);return}let me=j,ge=se===j,_e=ge&&F&&j!==k&&ue!==normalizeBridge(k);setActiveSpanAttributes({"observer.a.path":ge?_e?`residual-merge`:`path-a`:`path-b`});let ve={mergedText:null},ye=performance.now(),Ce=ge&&_e?null:tryComputeMapDrivenSplice({currentText:se,lastSyncedXmlMd:j,json:L,mdManager:S,docName:e.docName});Ce&&setActiveSpanAttributes({"observer.a.path":`map-driven-splice`,"observer.a.splice.compute_ms":Math.round(performance.now()-ye)}),t.transact(()=>{if(Ce)applyMapDrivenSplice(g,Ce);else if(ge&&!_e)applyIncrementalDiff(g,se,oe);else{let t=ge?k:me,{boundary:s}=splitLeadingDocBoundary(se),S=e=>reattachLeadingDocBoundary(splitLeadingDocBoundary(e).text,s),w=e.mergeThreeWay??mergeThreeWay;try{let e=S(w(projectMergeBoundarySpace(t),projectMergeBoundarySpace(oe),projectMergeBoundarySpace(se)));applyFastDiff(g,se,e),ve.mergedText=e}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(E(e,me),shouldRethrowBridgeMergeLoss()))throw e;let t=S(e.info.result);applyFastDiff(g,se,t),ve.mergedText=t}}},OBSERVER_SYNC_ORIGIN),Ce&&incrementMapDrivenSpliceApplied(),ve.mergedText!==null&&!ge&&emitObserverAPathBFired(e.docName)&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!ge,mergeBytesChanged:Math.abs(ve.mergedText.length-se.length)}))),ve.mergedText!==null&&ge&&incrementObserverAResidualMergeRuns(),incrementServerObserverFire(`a`),ee(oe),fe(g.toString(),oe,de)&&(B=!0,D(`post-merge`))}catch(t){if(t instanceof BridgeMergeContentLossError||t instanceof ProducerGuardViolationError)throw t;incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,t);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e),E=prependFrontmatter(ne(),t);fe(g.toString(),E)?(te(E),B=!0,D(`error-recovery`)):ee(E)}catch(s){console.warn(`[Server Observer A] Baseline recovery also failed`,JSON.stringify({"doc.name":e.docName??null,originalError:t instanceof Error?t.message:String(t),recoveryError:s instanceof Error?s.message:String(s)})),k=``,j=``,F=!1}}},De=()=>{withSpanSync(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},Te)},je=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=ne();q(),Me=e}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),L=!0}return}L=!0}};if(s.length>0&&g.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(e),D=prependFrontmatter(ne(),E);t.transact(()=>{g.insert(0,D)},OBSERVER_SYNC_ORIGIN),ee(D)}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),ee(``)}let Me=ne(),Pe=()=>{try{let w=g.toString(),{frontmatter:E,body:D}=stripFrontmatter(w);if(normalizeBridge(j)===normalizeBridge(w)){Me!==E&&(recordFrontmatterEditSurface(`source-mode`),Me=E);return}let O=S.parseWithFallback(D,ae),k=e.schema.nodeFromJSON(O);t.transact(()=>{updateYFragment(t,s,k,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),Me!==E&&(recordFrontmatterEditSurface(`source-mode`),Me=E),incrementServerObserverFire(`b`);try{let t=S.serialize(O),s=prependFrontmatter(E,t);assertBridgeInvariant(g.toString(),s,{site:`observer-b`,docName:e.docName,canonicalizeBody:e=>e===D?t:oe(e)}),ee(s)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),ee(prependFrontmatter(E,D))}}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e);Y(prependFrontmatter(ne(),t))}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},Ie=()=>{withSpanSync(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},Pe)},Re=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=ne();q(),Me=e}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),B=!0}return}H=Date.now(),B=!0}},ze=(t,s)=>{withSpanSync(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!L&&!B){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(s.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){L=!1,B=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}let g=L;L&&(L=!1,e.onDispatch?.(`a`),De());let S=B;B&&(B=!1,e.onDispatch?.(`b`),Ie()),t.setAttribute(`observer.dispatch`,g&&S?`a-then-b`:g?`a`:S?`b`:`none`)})};s.observeDeep(je),g.observe(Re),t.on(`afterAllTransactions`,ze);let Be=attachQuiescenceTracker(t);return()=>{Be(),t.off(`afterAllTransactions`,ze),s.unobserveDeep(je),g.unobserve(Re)}}const log$18=getLogger(`persistence`);var DocumentOpenSizeLimitError=class extends Error{docName;size;limit;constructor(e,t,s=DOCUMENT_OPEN_BYTE_LIMIT){super(`Document "${e}" is ${formatFileSize(t)}; OpenKnowledge opens documents up to ${formatFileSize(s)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=s}};function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let s=e;if(s.source===`local`){let e=s.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(s.source===`connection`){let e=s.connection?.context;if(typeof e?.principalId==`string`){let s=e.principalId,g=t?.();return g&&g.id===s&&g.display_name&&g.display_email?{id:g.id,name:g.display_name,email:g.display_email}:{id:s,name:`Local User`,email:`${s}@openknowledge.local`}}return SERVICE_WRITER}return null}const ERRNO_FS_CODES=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function classifyDeferredStoreError(e){if(typeof e!=`object`||!e)return`unknown`;let t=e,s=typeof t.message==`string`?t.message:``;return s.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&ERRNO_FS_CODES.has(t.code)?s.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof BridgeInvariantViolationError?`serialize`:`unknown`}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let s=resolve(t,docNameToRelativePath(e));if(!isWithinDir(s,t))throw Error(`Invalid document name: ${e}`);return s}function isWithinContentDir(e,t){return isWithinDir(e,t)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}const inFlightFlushByDoc=new Map;function peekInFlightFlush(e){return inFlightFlushByDoc.get(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function toStoreFailure(e){let t;try{let s=e?.code;typeof s==`string`&&(t=s)}catch{}let s=`unknown store error`;try{s=e instanceof Error?e.message:String(e)}catch{}return{code:t,message:s}}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),s;try{s=realpathSync(t)}catch{s=t}let g=e?.projectDir??process.cwd(),S=e?.shadowRef,w=e?.contentRoot??(toPosix(relative(g,s))||`.`),E=e?.backlinkIndex,D=e?.getPrincipal,O=e?.onAgentCommit,k=e?.onFlushCommit,j=e?.onDiskFlush,F=e?.onConfigPersisted,L=e?.mdManager??mdManager,B=e?.ephemeral??!1,H={projectDir:g,contentDir:s,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected,ephemeral:B},q=new Map,ee={projectDir:g,homedirOverride:e?.configHomedirOverride,lkgCache:q,setReconciledBase,getReconciledBase},J={contentDir:s,lkgCache:new Map},Y=new Set,te=e?.applyDiskContentToDoc??applyDiskContentToDoc,ne=null,ae=8,oe=new Map,se=new Map,ce=new Set,ue=new Set,de=e?.gitEnabled??!0,fe=e?.commitDebounceMs??15e3,me=e?.wipRef??`refs/wip/main`,ge=e?.getCurrentBranch,_e=null,ve=0,ye=null,Ce=!1,we=null,Te=new Map;async function De(){We();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await je()).finally(()=>{Ue?.record((Date.now()-e)/1e3)})}async function je(){let e=S?.current;if(e){let t=swapContributors(),s=ge?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},g=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,w,g,s);ve=0,log$18.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`);try{backfillRenameLogCommitSha(e.gitDir,SERVICE_WRITER.id,t,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$18.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){ve++,incrementGitAutoSaveFailure(),log$18.error({err:e,attempt:ve},`[persistence] Shadow commit failed (attempt ${ve})`),ve>=3&&log$18.error({attempt:ve},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let g;try{g=await buildWipTree(e,w)}catch(e){restoreContributors(t),ve++,incrementGitAutoSaveFailure(),log$18.error({err:e,attempt:ve},`[persistence] Shadow WIP tree build failed (attempt ${ve})`);return}let S=!1;for(let[w,E]of t){let t={id:w,name:E.displayName,email:`${w}@openknowledge.local`},D=[...E.docs],j=E.actor,F=[...E.summaries],L=[...E.previousPaths],B={v:1,writer_id:w,principal:j?.principalId??null,agent_session:w.startsWith(`agent-`)?w.slice(6):null,agent_type:j?.agentType??null,client_name:j?.clientName??null,client_version:j?.clientVersion??null,label:j?.label??null,display_name:E.displayName,color_seed:E.colorSeed,docs:D,...F.length>0?{summaries:F}:{},...L.length>0?{previous_paths:L}:{}},H=`${composeCommitSubject(E.subjectOverride??formatWipSubject(D),F)}\n\n${formatOkActor(B)}`;try{let E=await commitWipFromTree(e,t,g,H,s);S=!0;try{k?.()}catch(e){log$18.warn({err:e},`[persistence] onFlushCommit callback failed (non-fatal)`)}log$18.info({sha:E.slice(0,8),writer:w,tree:g.slice(0,8)},`[persistence] Shadow WIP commit: ${E.slice(0,8)} on refs/wip/${w}`);try{backfillRenameLogCommitSha(e.gitDir,w,E,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$18.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}w.startsWith(`agent-`)&&O?.()}catch(e){restoreContributorEntry(w,E),incrementGitWriterCommitFailure(),log$18.error({err:e,writer:w},`[persistence] Per-writer shadow commit failed for ${w}`)}}S?ve=0:(ve++,incrementGitAutoSaveFailure(),ve>=3&&log$18.error({attempt:ve},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(g,`.git`),workTree:g}),s=resolve(g,`.git/index-wip`),E={GIT_INDEX_FILE:s};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(E).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$18.info({},`[persistence] Empty repo — starting with empty index`):log$18.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(E).raw(`add`,w);let e=(await t.env(E).raw(`write-tree`)).trim(),s=null;try{s=(await t.raw(`rev-parse`,me)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let g=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];s&&g.push(`-p`,s);let S=(await t.raw(...g)).trim();await t.raw(`update-ref`,me,S),ve=0,log$18.info({sha:S.slice(0,8),wipRef:me},`[persistence] Git commit: ${S.slice(0,8)} on ${me}`)}catch(e){ve++,incrementGitAutoSaveFailure(),log$18.error({err:e,attempt:ve},`[persistence] Git commit failed (attempt ${ve})`),ve>=3&&log$18.error({attempt:ve},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(s)}catch{}}}function Me(e){if(e<=0)return fe;let t=2**Math.min(e,5),s=Math.random()*.25*fe;return fe*t+s}function Pe(){de&&(isBatchInProgress()||(_e&&clearTimeout(_e),_e=setTimeout(()=>{if(_e=null,ye){Ce=!0;return}ye=De().finally(()=>{ye=null,Ce&&(Ce=!1,Pe())})},Me(ve))))}async function Ie(){_e&&(clearTimeout(_e),_e=null,ye||=De().finally(()=>{ye=null,Ce&&(Ce=!1,Pe())})),ye&&await ye}function Re(t,s){try{let{frontmatter:g,body:S}=stripFrontmatter(t),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:s}:void 0,E=L.parseWithFallback(S,w);return normalizeBridge(prependFrontmatter(g,L.serialize(E)))}catch(e){return log$18.debug({err:e,documentName:s},`[g8] ephemeral canonical baseline failed; falling through to write`),null}}function ze(t,s,g){try{let S=t.getXmlFragment(`default`),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:g}:void 0,E=mdManager.parseWithFallback(s,w),D=schema.nodeFromJSON(E);t.transact(()=>{updateYFragment(t,S,D,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN)}catch(e){incrementPersistenceReconciliationFailures(),log$18.warn({err:e,documentName:g},`[persistence] reconcileFragmentNow failed for ${g}`)}}let Be=null,Ve=null,Ue=null;function We(){if(Be)return;let e=getMeter();Be=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),Ve=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),Ue=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function Ge({document:t,documentName:g,lastTransactionOrigin:S}){We();let w=Date.now(),O;return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":g}},async()=>{let w=ue.delete(g),k=t.getMap(`lifecycle`).get(`status`);if(k===`deleted-upstream`||k===`renamed`||k===`conflict`){log$18.info({documentName:g,lifecycleStatus:k},`[persistence] Skipped store for ${g}: lifecycle=${k}`),oe.delete(g),Y.delete(g);return}if(!isDocQuiescent(t)){let e=oe.get(g)??0;if(e<8){let s=getMsSinceLastUserTx(t);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":g,wallClockMsSinceLastTransaction:s??null,deferCount:e})),incrementPersistenceSkipNonQuiescent(),oe.set(g,e+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":g,wallClockMsSinceLastTransaction:getMsSinceLastUserTx(t)??null,deferCount:e})),incrementPersistenceForceFlushDuringBurst()}let{sv:F,json:H}=captureDocSnapshotForPersistence(t),{frontmatter:q,body:ee}=stripFrontmatter(t.getText(`source`).toString()),J=prependFrontmatter(q,ee),ne;try{ne=assertBridgeInvariant(J,prependFrontmatter(q,L.serialize(H)),{site:`persistence`,docName:g,suppressDevThrow:!0,canonicalizeBody:createDocCanonicalizer(L,{resolveEmbed:e?.resolveEmbed,resolveSize:e?.resolveSize,docName:g})})}catch(e){incrementPersistenceSanityCheckSerializeFailures(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":g,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),log$18.warn({err:e,documentName:g},`[persistence] Sanity-check serialize failed for ${g}; proceeding with ytext bytes`),ne=!1}ne||ze(t,ee,g);let ae=getReconciledBase(g),de=normalizeBridge(J),fe=ae!==void 0&&de===normalizeBridge(ae);if(!fe&&B&&ae!==void 0){let e=Re(ae,g);e!==null&&de===e&&(fe=!0)}if(fe){contributorCount()>0&&Pe(),oe.delete(g);return}if(ae===void 0&&normalizeBridge(J)===``){log$18.warn({documentName:g},`[persistence] Skipped phantom write for ${g}: empty Y.Doc with no reconciled base`),oe.delete(g);return}let me=resolveWriterFromOrigin(S,D);if(me&&me.id!==SERVICE_WRITER.id&&(hasContributor(me.id)||recordContributor(g,me.id,me.name,me.id)),ae!==void 0){let e=classifyDuplication(J,ae);if(e.kind===`block`){if(Y.has(g)){log$18.warn({documentName:g},`[persistence] Tripwire breaker active — skipping duplicate store for ${g}`);return}let S=t.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":g,candidateBytes:J.length,baseBytes:ae.length,fragmentChildren:S,copies:e.copies,reason:e.reason}));try{let e=safeContentPath(g,s),S;if(existsSync(e)){let t=null;try{t=realpathSync(e)}catch(e){log$18.warn({err:e,documentName:g},`[persistence] Tripwire reset realpath failed for ${g}; using currentBase`)}if(t&&isWithinContentDir(t,s))try{S=readFileSync(t,`utf-8`)}catch(e){log$18.warn({err:e,documentName:g,canonical:t},`[persistence] Tripwire reset readFileSync failed for ${g}; using currentBase`),S=ae}else t&&console.warn(`[persistence] symlink-escape on tripwire reset: ${e} → ${t}, using currentBase`,{docName:g,originalPath:e,canonical:t,contentDir:s}),S=ae}else S=ae;t.transact(()=>{te(t,S)},FILE_WATCHER_ORIGIN),Y.delete(g)}catch(e){Y.add(g),log$18.error({err:e,documentName:g},`[persistence] Tripwire reset failed for ${g}`)}oe.delete(g);return}}O=normalizeBridge(J),inFlightFlushByDoc.set(g,O);let ge=safeContentPath(g,s);await tracedMkdir(dirname(ge),{recursive:!0});let _e;try{_e=await realpath(ge)}catch(e){let t=e.code;if(t===`ENOENT`){let e=!1;try{e=lstatSync(ge).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$18.warn({err:e,path:ge},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:g,reason:`broken-symlink`}),_e=ge}else if(t===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${ge}`),Error(`Symlink cycle detected at ${ge}`);else throw e}if(!isWithinContentDir(_e,s)){let e=`symlink-escape: ${ge} resolves to ${_e} outside ${s}`;throw console.error(`[persistence] ${e}`,{docName:g,originalPath:ge,canonical:_e,contentDir:s}),Error(e)}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_DIVERGENCE===g&&await tracedWriteFile(_e,`# NATIVE
800
800
 
801
801
  native-divergence-injected
802
- `,`utf-8`),w&&ae!==void 0){let e=null;try{existsSync(_e)&&(e=readFileSync(_e,`utf-8`))}catch(t){e=null,log$17.warn({err:t,documentName:g},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(e!==null&&normalizeBridge(e)!==normalizeBridge(ae)){let s=e;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":g,outcome:`reverted`,diskBytes:s.length,baseBytes:ae.length,candidateBytes:J.length}));try{t.transact(()=>{te(t,s)},FILE_WATCHER_ORIGIN)}catch(e){throw se.set(g,toStoreFailure(e)),oe.delete(g),e}setReconciledBase(g,s),ce.add(g),oe.delete(g);return}}e?.isRecentlyRemoved?.(g)&&(incrementPersistenceStoreRemovedDoc(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":g})));let ve=`${_e}.tmp.${crypto.randomUUID()}`;try{if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_FAULT===g){let e=Error(`OK_TEST_STORE_FAULT: simulated disk failure for ${g}`);throw e.code=`ENOSPC`,e}await tracedWriteFile(ve,J,`utf-8`),await tracedRename(ve,_e),registerWrite(_e,contentHash(J)),se.delete(g),incrementPersistenceDiskWrite();try{j?.(g,F,J,ae??null)}catch(e){log$17.warn({err:e,documentName:g},`[persistence] onDiskFlush callback failed for ${g}`)}}catch(e){try{tracedUnlinkSync(ve)}catch{}throw oe.delete(g),se.set(g,toStoreFailure(e)),log$17.error({err:e,documentName:g},`[persistence] Failed to save ${g}`),e}log$17.info({filePath:_e,bytes:J.length},`[persistence] Wrote ${_e} (${J.length} bytes)`),setReconciledBase(g,J),Y.delete(g),oe.delete(g),E&&(E.updateDocumentFromMarkdown(g,J),E.saveToDisk().catch(e=>{log$17.warn({err:e,documentName:g},`[backlinks] Failed to persist cache for ${g}`)})),setActiveSpanAttributes({"persistence.bytes":J.length}),Pe()}).finally(()=>{O!==void 0&&inFlightFlushByDoc.get(g)===O&&inFlightFlushByDoc.delete(g),Ve?.record((Date.now()-w)/1e3)})}function Ke({document:e,documentName:t,lastTransactionOrigin:s}){Te.set(t,{branch:getActiveBranch(),document:e,lastTransactionOrigin:s})}async function Xe(e=`within-branch`){return we?(ne=ne===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,we):(we=(async()=>{let t=e;for(;;){let e=[...Te.entries()];if(Te.clear(),t!==`discard-stale`){for(let[t,s]of e)if(s.branch===getActiveBranch())try{await Ge({document:s.document,documentName:t,lastTransactionOrigin:s.lastTransactionOrigin})}catch(e){let s=process.env.OK_TELEMETRY_VERBOSE===`1`,g=``;try{g=String(e?.message??``)}catch{g=``}let S=fnv1aDigest(g),w;try{w=classifyDeferredStoreError(e)}catch(e){let g=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":t,classifyErrorHash:fnv1aDigest(g),errorMessageHash:S,...s?{classifyErrorMessage:g}:{},timestamp:new Date().toISOString()})),w=`unknown`}incrementDeferredStoreFailures(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":t,errorClass:w,errorMessageHash:S,...s?{errorMessage:g}:{},timestamp:new Date().toISOString()})),log$17.error({err:e,documentName:t},`[persistence] Deferred store failed for ${t}`)}}let s=ne;if(ne=null,Te.size===0&&s===null)break;t=s??`within-branch`}})().finally(()=>{we=null}),we)}let $e={async onLoadDocument({document:t,documentName:g,context:S}){if(isSystemDoc(g))return;if(isConfigDoc(g)){loadConfigDoc(t,g,H);return}if(isManagedArtifactDoc(g)){loadManagedArtifactDoc(t,g,ee);return}if(isMermaidDoc(g)){loadMermaidDoc(t,g,J);return}We();let w=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":g}},async()=>{log$17.info({documentName:g,connections:t.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${g} (connections: ${t.getConnectionsCount?.()??`?`})`);let S=safeContentPath(g,s);if(!existsSync(S))return;let w=S;try{let e=realpathSync(S);if(!isWithinContentDir(e,s)){console.warn(`[persistence] symlink-escape on load: ${S} → ${e}, refusing`);return}w=e}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${S}, refusing`);return}}let E=statSync(w).size;if(E>524288)throw log$17.warn({documentName:g,fileSize:E,limit:DOCUMENT_OPEN_BYTE_LIMIT},`[persistence] Document exceeds open byte limit; refusing to load`),new DocumentOpenSizeLimitError(g,E);let D=readFileSync(S,`utf-8`),O=t.getXmlFragment(`default`);log$17.info({documentName:g,fragmentLength:O.length},`[persistence] onLoadDocument ${g}: fragment.length=${O.length} before update`),O.length===0?(t.transact(()=>{applyDiskContentToDoc(t,D,e?.resolveEmbed,g,e?.resolveSize),t.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},FILE_WATCHER_ORIGIN),log$17.info({filePath:S,children:O.length},`[persistence] Loaded ${S} into Y.Doc (${O.length} children)`),O.observeDeep(()=>{log$17.info({documentName:g,fragmentLength:O.length},`[persistence] MUTATION on ${g}: fragment.length=${O.length}`)})):log$17.info({documentName:g,children:O.length},`[persistence] Skipped load for ${g} — fragment already has ${O.length} children`),setReconciledBase(g,D)}).finally(()=>{Be?.record((Date.now()-w)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:s,lastContext:g}){if(!isSystemDoc(t)){if(isConfigDoc(t)){let g=await storeConfigDoc(e,t,s,H);if(g===`persisted`||g===`reconciled`)try{F?.(t)}catch(e){log$17.warn({err:e,documentName:t},`[persistence] onConfigPersisted callback failed`)}return}if(isManagedArtifactDoc(t)){if(await storeManagedArtifactDoc(e,t,s,ee)===`persisted`){let e=resolveWriterFromOrigin(s,D);if(e&&e.id!==SERVICE_WRITER.id&&!e.id.startsWith(`agent-`)){let s=managedArtifactContributorAttribution(t);s&&(recordContributor(s.docKey,e.id,e.name,e.id,s.subject),Pe())}}return}if(isMermaidDoc(t)){await storeMermaidDoc(e,t,s,J);return}if(isBatchInProgress()){Ke({document:e,documentName:t,lastTransactionOrigin:s});return}return Ge({document:e,documentName:t,lastTransactionOrigin:s})}}};async function nt(){ye&&await ye}async function rt(){if(ye){await ye;return}contributorCount()!==0&&(ye=De().finally(()=>{ye=null,Ce&&(Ce=!1,Pe())}),await ye)}function it(e){let t=se.get(e);return t&&se.delete(e),t??null}function at(e){return ce.has(e)?(ce.delete(e),!0):!1}function st(e){ue.add(e)}return{extension:$e,flushDeferredStores:Xe,flushPendingGitCommit:Ie,flushContributors:rt,waitForPendingCommits:nt,takeStoreFailure:it,takeStoreDivergence:at,markAgentWriteStore:st,configPersistenceCtx:H,managedArtifactCtx:ee}}const MARKDOWN_LINK_OR_IMAGE_RE=/!?\[[^\]\n]*(?:\][^[\]\n]*)?\]\((?:<([^>\n]+)>|([^)\s]+))(?:\s+['"][^'"]*['"])?\)/g,WIKI_LINK_OR_EMBED_RE=/!?\[\[([^[\]|#]+?)(?:#[^\]|]+?)?(?:\|[^\]]+?)?\]\]/g,HTML_LINK_ATTR_RE=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function isRemoteOrOpaqueHref(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function stripHrefDecorations(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),s=t.indexOf(`#`),g=s>=0?t.slice(0,s):t,S=g.indexOf(`?`);return S>=0?g.slice(0,S):g}function isLocalAssetReferenceHref(e){let t=stripHrefDecorations(e);return!t||isRemoteOrOpaqueHref(t)?!1:LINKABLE_ASSET_EXTENSIONS.has(extname(t).slice(1).toLowerCase())}function assetReferenceSignature(e){return e?[...new Set(extractLocalAssetHrefs(e).filter(isLocalAssetReferenceHref))].sort().join(`\0`):``}function assetReferencesChanged(e,t){return assetReferenceSignature(e)!==assetReferenceSignature(t)}function decodeHrefPath(e){let t=stripHrefDecorations(e);try{return decodeURI(t)}catch{return t}}function mediaKindForAssetPath(e){return mediaKindForSidebarAssetExtension(extname(e).slice(1).toLowerCase())}function errnoCode$1(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function collectHrefsFromLine(e,t){for(let s of e.matchAll(MARKDOWN_LINK_OR_IMAGE_RE)){let e=s[1]??s[2];e&&t.add(e)}for(let s of e.matchAll(WIKI_LINK_OR_EMBED_RE)){let e=s[1];e&&t.add(e)}for(let s of e.matchAll(HTML_LINK_ATTR_RE)){let e=s[1]??s[2]??s[3]??s[4];e&&t.add(e)}}function stripHtmlComments(e,t){let s=e,g=``;for(;s.length>0;){if(t.inComment){let e=s.indexOf(`-->`);if(e===-1)return g;s=s.slice(e+3),t.inComment=!1;continue}let e=s.indexOf(`<!--`);if(e===-1)return g+s;g+=s.slice(0,e),s=s.slice(e+4),t.inComment=!0}return g}function extractLocalAssetHrefs(e){let t=new Set,s=createCodeFenceTracker(),g={inComment:!1};for(let S of e.replaceAll(`\r
802
+ `,`utf-8`),w&&ae!==void 0){let e=null;try{existsSync(_e)&&(e=readFileSync(_e,`utf-8`))}catch(t){e=null,log$18.warn({err:t,documentName:g},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(e!==null&&normalizeBridge(e)!==normalizeBridge(ae)){let s=e;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":g,outcome:`reverted`,diskBytes:s.length,baseBytes:ae.length,candidateBytes:J.length}));try{t.transact(()=>{te(t,s)},FILE_WATCHER_ORIGIN)}catch(e){throw se.set(g,toStoreFailure(e)),oe.delete(g),e}setReconciledBase(g,s),ce.add(g),oe.delete(g);return}}e?.isRecentlyRemoved?.(g)&&(incrementPersistenceStoreRemovedDoc(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":g})));let ve=`${_e}.tmp.${crypto.randomUUID()}`;try{if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_FAULT===g){let e=Error(`OK_TEST_STORE_FAULT: simulated disk failure for ${g}`);throw e.code=`ENOSPC`,e}await tracedWriteFile(ve,J,`utf-8`),await tracedRename(ve,_e),registerWrite(_e,contentHash(J)),se.delete(g),incrementPersistenceDiskWrite();try{j?.(g,F,J,ae??null)}catch(e){log$18.warn({err:e,documentName:g},`[persistence] onDiskFlush callback failed for ${g}`)}}catch(e){try{tracedUnlinkSync(ve)}catch{}throw oe.delete(g),se.set(g,toStoreFailure(e)),log$18.error({err:e,documentName:g},`[persistence] Failed to save ${g}`),e}log$18.info({filePath:_e,bytes:J.length},`[persistence] Wrote ${_e} (${J.length} bytes)`),setReconciledBase(g,J),Y.delete(g),oe.delete(g),E&&(E.updateDocumentFromMarkdown(g,J),E.saveToDisk().catch(e=>{log$18.warn({err:e,documentName:g},`[backlinks] Failed to persist cache for ${g}`)})),setActiveSpanAttributes({"persistence.bytes":J.length}),Pe()}).finally(()=>{O!==void 0&&inFlightFlushByDoc.get(g)===O&&inFlightFlushByDoc.delete(g),Ve?.record((Date.now()-w)/1e3)})}function Ke({document:e,documentName:t,lastTransactionOrigin:s}){Te.set(t,{branch:getActiveBranch(),document:e,lastTransactionOrigin:s})}async function Xe(e=`within-branch`){return we?(ne=ne===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,we):(we=(async()=>{let t=e;for(;;){let e=[...Te.entries()];if(Te.clear(),t!==`discard-stale`){for(let[t,s]of e)if(s.branch===getActiveBranch())try{await Ge({document:s.document,documentName:t,lastTransactionOrigin:s.lastTransactionOrigin})}catch(e){let s=process.env.OK_TELEMETRY_VERBOSE===`1`,g=``;try{g=String(e?.message??``)}catch{g=``}let S=fnv1aDigest(g),w;try{w=classifyDeferredStoreError(e)}catch(e){let g=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":t,classifyErrorHash:fnv1aDigest(g),errorMessageHash:S,...s?{classifyErrorMessage:g}:{},timestamp:new Date().toISOString()})),w=`unknown`}incrementDeferredStoreFailures(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":t,errorClass:w,errorMessageHash:S,...s?{errorMessage:g}:{},timestamp:new Date().toISOString()})),log$18.error({err:e,documentName:t},`[persistence] Deferred store failed for ${t}`)}}let s=ne;if(ne=null,Te.size===0&&s===null)break;t=s??`within-branch`}})().finally(()=>{we=null}),we)}let $e={async onLoadDocument({document:t,documentName:g,context:S}){if(isSystemDoc(g))return;if(isConfigDoc(g)){loadConfigDoc(t,g,H);return}if(isManagedArtifactDoc(g)){loadManagedArtifactDoc(t,g,ee);return}if(isMermaidDoc(g)){loadMermaidDoc(t,g,J);return}We();let w=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":g}},async()=>{log$18.info({documentName:g,connections:t.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${g} (connections: ${t.getConnectionsCount?.()??`?`})`);let S=safeContentPath(g,s);if(!existsSync(S))return;let w=S;try{let e=realpathSync(S);if(!isWithinContentDir(e,s)){console.warn(`[persistence] symlink-escape on load: ${S} → ${e}, refusing`);return}w=e}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${S}, refusing`);return}}let E=statSync(w).size;if(E>524288)throw log$18.warn({documentName:g,fileSize:E,limit:DOCUMENT_OPEN_BYTE_LIMIT},`[persistence] Document exceeds open byte limit; refusing to load`),new DocumentOpenSizeLimitError(g,E);let D=readFileSync(S,`utf-8`),O=t.getXmlFragment(`default`);log$18.info({documentName:g,fragmentLength:O.length},`[persistence] onLoadDocument ${g}: fragment.length=${O.length} before update`),O.length===0?(t.transact(()=>{applyDiskContentToDoc(t,D,e?.resolveEmbed,g,e?.resolveSize),t.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},FILE_WATCHER_ORIGIN),log$18.info({filePath:S,children:O.length},`[persistence] Loaded ${S} into Y.Doc (${O.length} children)`),O.observeDeep(()=>{log$18.info({documentName:g,fragmentLength:O.length},`[persistence] MUTATION on ${g}: fragment.length=${O.length}`)})):log$18.info({documentName:g,children:O.length},`[persistence] Skipped load for ${g} — fragment already has ${O.length} children`),setReconciledBase(g,D)}).finally(()=>{Be?.record((Date.now()-w)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:s,lastContext:g}){if(!isSystemDoc(t)){if(isConfigDoc(t)){let g=await storeConfigDoc(e,t,s,H);if(g===`persisted`||g===`reconciled`)try{F?.(t)}catch(e){log$18.warn({err:e,documentName:t},`[persistence] onConfigPersisted callback failed`)}return}if(isManagedArtifactDoc(t)){if(await storeManagedArtifactDoc(e,t,s,ee)===`persisted`){let e=resolveWriterFromOrigin(s,D);if(e&&e.id!==SERVICE_WRITER.id&&!e.id.startsWith(`agent-`)){let s=managedArtifactContributorAttribution(t);s&&(recordContributor(s.docKey,e.id,e.name,e.id,s.subject),Pe())}}return}if(isMermaidDoc(t)){await storeMermaidDoc(e,t,s,J);return}if(isBatchInProgress()){Ke({document:e,documentName:t,lastTransactionOrigin:s});return}return Ge({document:e,documentName:t,lastTransactionOrigin:s})}}};async function nt(){ye&&await ye}async function rt(){if(ye){await ye;return}contributorCount()!==0&&(ye=De().finally(()=>{ye=null,Ce&&(Ce=!1,Pe())}),await ye)}function it(e){let t=se.get(e);return t&&se.delete(e),t??null}function at(e){return ce.has(e)?(ce.delete(e),!0):!1}function st(e){ue.add(e)}return{extension:$e,flushDeferredStores:Xe,flushPendingGitCommit:Ie,flushContributors:rt,waitForPendingCommits:nt,takeStoreFailure:it,takeStoreDivergence:at,markAgentWriteStore:st,configPersistenceCtx:H,managedArtifactCtx:ee}}const MARKDOWN_LINK_OR_IMAGE_RE=/!?\[[^\]\n]*(?:\][^[\]\n]*)?\]\((?:<([^>\n]+)>|([^)\s]+))(?:\s+['"][^'"]*['"])?\)/g,WIKI_LINK_OR_EMBED_RE=/!?\[\[([^[\]|#]+?)(?:#[^\]|]+?)?(?:\|[^\]]+?)?\]\]/g,HTML_LINK_ATTR_RE=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function isRemoteOrOpaqueHref(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function stripHrefDecorations(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),s=t.indexOf(`#`),g=s>=0?t.slice(0,s):t,S=g.indexOf(`?`);return S>=0?g.slice(0,S):g}function isLocalAssetReferenceHref(e){let t=stripHrefDecorations(e);return!t||isRemoteOrOpaqueHref(t)?!1:LINKABLE_ASSET_EXTENSIONS.has(extname(t).slice(1).toLowerCase())}function assetReferenceSignature(e){return e?[...new Set(extractLocalAssetHrefs(e).filter(isLocalAssetReferenceHref))].sort().join(`\0`):``}function assetReferencesChanged(e,t){return assetReferenceSignature(e)!==assetReferenceSignature(t)}function decodeHrefPath(e){let t=stripHrefDecorations(e);try{return decodeURI(t)}catch{return t}}function mediaKindForAssetPath(e){return mediaKindForSidebarAssetExtension(extname(e).slice(1).toLowerCase())}function errnoCode$1(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function collectHrefsFromLine(e,t){for(let s of e.matchAll(MARKDOWN_LINK_OR_IMAGE_RE)){let e=s[1]??s[2];e&&t.add(e)}for(let s of e.matchAll(WIKI_LINK_OR_EMBED_RE)){let e=s[1];e&&t.add(e)}for(let s of e.matchAll(HTML_LINK_ATTR_RE)){let e=s[1]??s[2]??s[3]??s[4];e&&t.add(e)}}function stripHtmlComments(e,t){let s=e,g=``;for(;s.length>0;){if(t.inComment){let e=s.indexOf(`-->`);if(e===-1)return g;s=s.slice(e+3),t.inComment=!1;continue}let e=s.indexOf(`<!--`);if(e===-1)return g+s;g+=s.slice(0,e),s=s.slice(e+4),t.inComment=!0}return g}function extractLocalAssetHrefs(e){let t=new Set,s=createCodeFenceTracker(),g={inComment:!1};for(let S of e.replaceAll(`\r
803
803
  `,`
804
804
  `).replaceAll(`\r`,`
805
805
  `).split(`
@@ -823,16 +823,16 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
823
823
  `}function buildWorkflowHandler(e,t,s,g){return async S=>{let w=typeof S.cwd==`string`?S.cwd:void 0,E=await resolveProjectConfigContext(t.resolveCwd,t.config,w);if(!E.ok)return textResult(`Error: ${E.error}`,!0);let D=S[s],O=typeof D==`string`?D:``;return textPlusStructured(`${buildWorkflowFrame(e)}${g(O,E.config.content.dir)}`,{previewUrl:null})}}async function resolveServerUrl(e,t){return typeof e==`function`?await e(t):e}async function resolveConfig(e,t){return typeof e==`function`?await e(t):e}async function resolveProjectConfigContext(e,t,s){let g;try{g=await e(s)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let S=s===void 0?g:resolve(s);try{let e=await resolveConfig(t,g);return{ok:!0,cwd:g,executionCwd:S,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function resolveProjectServerContext(e,t,s,g){let S=await resolveProjectConfigContext(e,t,g);if(!S.ok)return S;let{cwd:w,executionCwd:E,config:D}=S;try{return{ok:!0,cwd:w,executionCwd:E,config:D,url:await resolveServerUrl(s,w)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function okReservedPathRedirect(e){let t=e.replace(/^\/+/,``);return t!==`.ok`&&!t.startsWith(`.ok/`)?null:t.startsWith(`.ok/skills/`)?"Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes `.ok/skills/<name>/SKILL.md`. To author or improve a skill, use the `open-knowledge-write-skill` skill.":t.startsWith(`.ok/templates/`)?"Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.":"Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target."}function normalizeDocName(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let s=e,g=t;for(;g.endsWith(`.mdx`)||g.endsWith(`.md`);)s=s.slice(0,g.endsWith(`.mdx`)?-4:-3),g=s.toLowerCase();let S=validateDocName(s);return S.ok?{ok:!0,docName:s}:{ok:!1,error:`Error: "${e}" is invalid — ${S.reason}.`}}function normalizeResponse(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...s}=t;return{ok:!0,...s}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let s=t;if(typeof s.type==`string`&&typeof s.title==`string`){let{type:e,title:t,status:g,instance:S,detail:w,...E}=s;return{...E,ok:!1,error:t,type:e,...typeof g==`number`?{status:g}:{},...typeof S==`string`?{instance:S}:{},...typeof w==`string`?{detail:w}:{}}}let{ok:g,error:S,...w}=s,E=typeof S==`string`?S:typeof s.message==`string`?s.message:`Server returned HTTP ${e.status}`;return{...w,ok:!1,error:E}}async function httpGet(e,t){let s;try{s=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let g;try{g=await s.json()}catch(e){let t=e instanceof Error?e.message:String(e);return s.ok?{ok:!1,httpStatus:s.status,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,httpStatus:s.status,error:`Server returned HTTP ${s.status} with non-JSON body: ${t}`}}return{...normalizeResponse(s,g),httpStatus:s.status}}async function httpSend(e,t,s,g){let S;if(g!==void 0)try{S=JSON.stringify(g)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}let w;try{w=await fetch(`${t}${s}`,{method:e,headers:S===void 0?void 0:{"Content-Type":`application/json`},body:S,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let E;try{E=await w.json()}catch(e){let t=e instanceof Error?e.message:String(e);return w.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${w.status} with non-JSON body: ${t}`}}return normalizeResponse(w,E)}function httpPost(e,t,s){return httpSend(`POST`,e,t,s)}function httpPut(e,t,s){return httpSend(`PUT`,e,t,s)}function httpDelete(e,t){return httpSend(`DELETE`,e,t)}function parseRenameCollidingPairs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:s,to:g}=e;return typeof t==`string`&&typeof s==`string`&&typeof g==`string`?[{existing:t,incoming:s,to:g}]:[]}):[]}function readFolderFrontmatter(e,t){let s=nestedOkPath(e,t,`frontmatter.yml`);if(!existsSync(s))return{};let g=readFrontmatterYaml(s);return g==null?{}:coerceWellKnown(g)}function coerceWellKnown(e){let t={};for(let[s,g]of Object.entries(e))t[s]=g;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const warnedPaths=new Set;function readFrontmatterYaml(e){let t;try{t=readFileSync(e,`utf-8`)}catch{return null}let s;try{s=(0,import_dist$1.parse)(t)}catch(t){if(!warnedPaths.has(e)){warnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-folder-frontmatter] malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${s}`)}return null}return typeof s!=`object`||!s||Array.isArray(s)?null:(warnedPaths.delete(e),s)}function nestedOkPath(e,t,s){let g=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return g===``||g===`.`?join(e,`.ok`,s):join(e,g,`.ok`,s)}function parentFolderOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}const GIT_TIMEOUT_MS$2=5e3;function projectHasGitDir(e){try{return statSync(resolve(e,`.git`)).isDirectory()}catch{return!1}}function openProjectGit(e){return esm_default({baseDir:resolve(e),timeout:{block:GIT_TIMEOUT_MS$2}})}async function readProjectGitLog(e,t,s=5){if(!projectHasGitDir(e))return{commits:[],source:`git-absent`};let g=openProjectGit(e),S=``;try{S=await g.raw(`log`,`-${Math.max(1,s)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let w=[];for(let e of S.split(`
824
824
  `)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let s=e.indexOf(`|`,t+1);if(s<0)continue;let g=e.indexOf(`|`,s+1);g<0||w.push({hash:e.slice(0,t),date:e.slice(t+1,s),authorName:e.slice(s+1,g),subject:e.slice(g+1)})}return{commits:w,source:`git`}}const GIT_TIMEOUT_MS$1=5e3;async function currentProjectBranch(e){try{let t=(await esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS$1}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function openShadowGit(e,t){return esm_default({baseDir:t,timeout:{block:GIT_TIMEOUT_MS$1}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function writerIdFromRef(e,t){let s=getWipRefPattern(t);return e.startsWith(s)?e.slice(s.length):e}async function logOnRef(e,t,s,g,S){let w=``;try{w=await e.raw(`log`,t,`-${Math.max(1,S*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,s)}catch{return[]}let E=writerIdFromRef(t,g),D=parseWriterId(E),O=[];for(let e of w.split(``)){let t=e.trimStart();if(!t)continue;let[s=``,S=``,w=``,k=``,j=``]=t.split(`\0`),F=s.trim();F.length===40&&O.push({hash:F,date:S,writerName:w,message:k,contributors:readContributors(j),writerId:E,isAgent:D.isAgent,writerClassification:D.classification,branch:g})}return O}async function checkpointAncestryFallback(e,t,s,g,S){let w=``;try{w=(await e.raw(`for-each-ref`,`--sort=-creatordate`,`--count=1`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)).trim()}catch{return[]}if(!w)return[];let E=``;try{E=await e.raw(`log`,w,`-${Math.max(g*3,20)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,s)}catch{return[]}let D=[];for(let e of E.split(``)){if(D.length>=g)break;let s=e.trimStart();if(!s)continue;let[w=``,E=``,O=``,k=``,j=``]=s.split(`\0`),F=w.trim();if(F.length!==40||S.has(F)||k.startsWith(`checkpoint:`)||k.startsWith(`park:`)||k.startsWith(`import:`)||k.startsWith(`upstream:`))continue;let L=parseOkActor(j),B=L?.writer_id??``,H=parseWriterId(B);S.add(F),D.push({hash:F,date:E,writerName:L?.display_name??O,message:k,contributors:readContributors(j),writerId:B,isAgent:H.isAgent,writerClassification:H.classification,branch:t})}return D}async function readShadowLog(e,t,s=5){let g=getShadowRepoPath(e);if(!g)return{commits:[],source:`shadow-repo-absent`};let S=await currentProjectBranch(e);if(!S)return{commits:[],source:`shadow-repo`};let w=openShadowGit(g,resolve(e)),E=``;try{E=await w.raw(`for-each-ref`,getWipRefPattern(S),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let D=E.split(`
825
825
  `).map(e=>e.trim()).filter(Boolean),O=(D.length===0?[]:await Promise.all(D.map(e=>logOnRef(w,e,t,S,s)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s);if(O.length<s){let e=new Set(O.map(e=>e.hash)),g=await checkpointAncestryFallback(w,S,t,s-O.length,e);g.length>0&&(O=[...O,...g].sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s))}return{commits:O,source:`shadow-repo`}}function resolveTemplatesAvailable(e,t,s={}){let g=normalizeFolderPath(t),S=g===``?[]:g.split(`/`),w=new Set,E=[];collectFromFolder(e,g,`local`,w,E);for(let t=S.length-1;t>=1;t--)collectFromFolder(e,S.slice(0,t).join(`/`),`inherited`,w,E);return S.length>0&&collectFromFolder(e,``,`inherited`,w,E),E}function resolveProjectTemplates(e){let t=[],s=new Map,g=e=>{let t=s.get(e);return t||(t=new Set,s.set(e,t)),t},S=0,w=!1,E=[``];for(;E.length>0;){let s=E.shift()??``;if(S++>=PROJECT_TEMPLATE_SCAN_CAP){w=!0,console.warn(`[ok-templates] project scan hit the ${PROJECT_TEMPLATE_SCAN_CAP}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${E.length}.`);break}collectFromFolder(e,s,`local`,g(s),t);let D=s?join(e,s):e,O;try{O=readdirSync(D).sort()}catch(e){if(e?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(D)){templateMetaWarnedPaths.add(D);let t=e instanceof Error?e.message:String(e);console.warn(`[ok-templates] failed to read directory ${D} during project scan — skipped. Reason: ${t}`)}continue}for(let e of O){if(PROJECT_TEMPLATE_DIR_SKIP.has(e)||e.startsWith(`.`))continue;let t=join(D,e),g;try{g=statSync(t)}catch{continue}if(!g.isDirectory())continue;let S=s?posix.join(s,e):e;E.push(S)}}return{templates:t,truncated:w}}const PROJECT_TEMPLATE_SCAN_CAP=2e3,PROJECT_TEMPLATE_DIR_SKIP=new Set([`node_modules`,`dist`,`build`]);function collectFromFolder(e,t,s,g,S){let w=t?join(e,t,`.ok`,`templates`):join(e,`.ok`,`templates`);if(!existsSync(w))return;let E;try{E=readdirSync(w)}catch{return}for(let e of E){if(!e.endsWith(`.md`))continue;let E=e.slice(0,-3);if(g.has(E))continue;let D=join(w,e),O;try{O=statSync(D)}catch{continue}if(!O.isFile())continue;let k=readTemplateMeta(D),j={name:E,path:t?posix.join(t,`.ok`,`templates`,e):posix.join(`.ok`,`templates`,e),source_folder:t,scope:s};k.title!==void 0&&(j.title=k.title),k.description!==void 0&&(j.description=k.description),g.add(E),S.push(j)}}function normalizeFolderPath(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const templateMetaWarnedPaths=new Set;function readTemplateMeta(e){let t;try{t=readFileSync(e,`utf-8`)}catch(t){if(t?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] failed to read template at ${e} — metadata skipped. Reason: ${s}`)}return{}}let{identity:s}=parseTemplateFile(t);typeof s.title!=`string`&&!templateMetaWarnedPaths.has(e)&&(templateMetaWarnedPaths.add(e),console.warn(`[ok-templates] template at ${e} has no title — YAML may be malformed or the title is missing.`));let g={};return typeof s.title==`string`&&(g.title=s.title),typeof s.description==`string`&&(g.description=s.description),g}function parseFrontmatterRaw(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return null;try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i,HUB_MIN_INBOUND=5;function computeGraphRole(e,t){if(e===null||t===null)return null;let s=e,g=t;return s===0&&g===0?`orphan`:s>=HUB_MIN_INBOUND?`hub`:s>0&&g>0?`connector`:`leaf`}function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${s}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.backlinks??s.results??s.links;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e,s=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;s&&S.push({source:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let s=[...new Set(t)],g=[];for(let e=0;e<s.length;e+=BACKLINK_COUNT_CHUNK)g.push(s.slice(e,e+BACKLINK_COUNT_CHUNK));let S=await Promise.all(g.map(async t=>{let s=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return s.ok?s.counts??{}:null})),w=new Map,E=!1;for(let e of S)if(e){E=!0;for(let[t,s]of Object.entries(e))typeof s==`number`&&Number.isFinite(s)&&w.set(t,s)}return E?w:null}async function fetchForwardLinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.forwardLinks??s.links??s.results;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){S.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let s=typeof t.docName==`string`?t.docName:void 0;s&&S.push({kind:`doc`,docName:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}function liftOwnFrontmatter(e){let t=e??{};return{title:typeof t.title==`string`?t.title:void 0,description:typeof t.description==`string`?t.description:void 0,tags:Array.isArray(t.tags)?t.tags.filter(e=>typeof e==`string`):[],frontmatter:t}}async function enrichPath(e,t,s={}){let g=resolveWithinRoot(t.projectDir,e);if(!g.ok)throw Error(`enrichPath: ${g.reason}`);let S=g.rel,w=g.abs,E=t.historyDepth??5,D=s.includeRichFields===!0,O=readFrontmatter(w);if(!D){let e=liftOwnFrontmatter(await O);return{path:S,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null,graphRole:null}}let[k,j,F,L,B]=await Promise.all([O,fetchBacklinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),readShadowLog(t.projectDir,S,E).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,S,E).catch(()=>({commits:[],source:`git`}))]),H=liftOwnFrontmatter(k);return{path:S,title:H.title,description:H.description,tags:H.tags,frontmatter:H.frontmatter,backlinkCount:j?.length??null,backlinks:j,forwardLinkCount:F?.length??null,forwardLinks:F,history:L.commits,historySource:L.source,projectHistory:B.commits,projectHistorySource:B.source,graphRole:computeGraphRole(j?.length??null,F?.length??null)}}async function scanDirectory(e,t){let s={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},g=0,S=[{path:e,depth:0}];for(;S.length>0;){let e=S.shift();if(!e)break;if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}let w;try{w=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let E of w){if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}g++;let w=E.name;if(E.isDirectory()){if(DIR_SKIP.has(w)||w.startsWith(`.`))continue;e.depth===0&&s.childDirCount++,S.push({path:`${e.path}/${w}`,depth:e.depth+1})}else if(E.isFile()&&WIKI_EXT_RE.test(w)){s.recursiveMdCount++,e.depth===0&&s.directMdCount++;let g=`${e.path}/${w}`;try{let e=await stat$1(g);(!s.mostRecent||e.mtimeMs>s.mostRecent.mtimeMs)&&(s.mostRecent={absPath:g,relPath:relative(t,g).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return s}async function enrichDirectory(e,t){let s=resolveWithinRoot(t.projectDir,e);if(!s.ok)throw Error(`enrichDirectory: ${s.reason}`);let g=s.rel,S=s.abs,w=await scanDirectory(S,t.projectDir),E;if(w.mostRecent){let e=await readFrontmatter(w.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;E={path:w.mostRecent.relPath,title:t??basename(w.mostRecent.relPath),updatedAt:new Date(w.mostRecent.mtimeMs).toISOString()}}let D={path:g,type:`directory`,directMdCount:w.directMdCount,recursiveMdCount:w.recursiveMdCount,childDirCount:w.childDirCount,mostRecentMd:E,truncated:w.truncated},O=readFolderFrontmatter(t.projectDir,g);O.title!==void 0&&(D.title=O.title),O.description!==void 0&&(D.description=O.description),(O.tags?.length??0)>0&&(D.tags=O.tags);let k=resolveTemplatesAvailable(t.projectDir,g);return k.length>0&&(D.templates_available=k),D}async function enrichDirectoryRecursive(e,t,s){let g=await enrichDirectory(e,s);if(t<=1)return g;let S=g.path,w=resolve(s.projectDir,S),E;try{E=await readdir(w,{withFileTypes:!0})}catch{return g}let D=[];for(let e of E){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let g=await enrichDirectoryRecursive(S?`${S}/${e.name}`:e.name,t-1,s);D.push(g)}return D.length>0&&(g.subfolders=D),g}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function mergePatch(e,t){let s={...e};for(let[e,g]of Object.entries(t))if(g!==void 0){if(isEmpty$2(g)){delete s[e];continue}s[e]=g}return s}function isEmpty$2(e){return isFrontmatterValueEmpty(e)}function applyFolderFrontmatterPatch(e){if(!isAbsolute(e.anchorDir))return{ok:!1,error:{code:`BAD_CONTENT_DIR`,message:`anchorDir must be absolute`}};let t=resolve(e.anchorDir),s=e.folderRel.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(s.split(`/`).some(e=>e===`..`))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Folder path escapes the content directory: ${e.folderRel}`}};let g=s===``?t:resolve(t,s);if(g!==t&&!g.startsWith(t+sep))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder escapes the content directory: ${g}`}};let S=join(g,`.ok`),w=join(S,`frontmatter.yml`);try{let s=readExistingFrontmatter(w),g=Object.keys(e.patch).length===0?{}:mergePatch(s,e.patch);if(Object.keys(g).length===0)return existsSync(w)?(unlinkSync(w),autoCleanOkDir(S),{ok:!0,path:relPathOf$2(t,w),action:`deleted`}):{ok:!0,path:relPathOf$2(t,w),action:`noop`};mkdirSync(S,{recursive:!0});let E=(0,import_dist$1.stringify)(g),D=`${w}.tmp.${process.pid}.${Date.now()}`;return writeFileSync(D,E,`utf-8`),renameSync(D,w),{ok:!0,path:relPathOf$2(t,w),action:`written`}}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write folder frontmatter for "${s||`.`}": ${e.message}`}}}}function readExistingFrontmatter(e){if(!existsSync(e))return{};let t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:{...t}}function autoCleanOkDir(e){if(!existsSync(e))return;let t;try{t=readdirSync(e)}catch{return}if(t.length===0)try{rmdirSync(e)}catch{}}function relPathOf$2(e,t){return t.startsWith(e+sep)?t.slice(e.length+1).split(sep).join(`/`):t}const NAME_MAX=64,DESCRIPTION_MAX=1024,RESERVED_NAME_WORDS=[`anthropic`,`claude`],BODY_SOFT_MAX_LINES=500,SKILL_FILE=`SKILL.md`;function composeSkillContent(e){let t=validateName(e.name);if(!t.ok)return{ok:!1,error:t.error};let s=validateFrontmatter(e.frontmatter,e.name);if(!s.ok)return{ok:!1,error:s.error};let g=`---\n${serializeFrontmatter(e.frontmatter)}---\n${e.body}`,S=[],w=e.body.split(`
826
- `).length;return w>BODY_SOFT_MAX_LINES&&S.push(`SKILL.md body is ${w} lines — keep it under ${BODY_SOFT_MAX_LINES} for performance (every line is a recurring token cost). Move detail into one-level-deep references/.`),{ok:!0,content:g,warnings:S}}function applySkillWrite(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=composeSkillContent({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!s.ok)return{ok:!1,error:s.error};let{content:g,warnings:S}=s,{skillDir:w,filePath:E}=skillPaths(e.skillsRoot,e.name);try{mkdirSync(w,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create skill directory at ${relPathOf$1(e.skillsRoot,w)}: ${t.message}`}}}let D=!existsSync(E),O=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(O,g,`utf-8`),renameSync(O,E)}catch(t){try{unlinkSync(O)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill at ${relPathOf$1(e.skillsRoot,E)}: ${t.message}`}}}return{ok:!0,path:relPathOf$1(e.skillsRoot,E),created:D,warnings:S}}const BUNDLE_FILE_MAX_BYTES=256*1024;function resolveBundleFileAbs(e,t){if(typeof t!=`string`||t.length===0||t.includes(`\0`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path.`}};let s=t.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);if(s.length<2||s.some(e=>e===`..`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path: ${t}`}};if(s[0]!==`references`&&s[0]!==`scripts`)return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file must be under references/ or scripts/: ${t}`}};let g=join(e,...s);return g!==e&&!g.startsWith(e+sep)?{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file escapes the skill dir: ${t}`}}:{ok:!0,abs:g}}function countBundleFiles(e){let t=0,s=g=>{let S;try{S=readdirSync(g)}catch{return}for(let w of S){let S=join(g,w),E;try{E=statSync(S).isDirectory()}catch{continue}E?s(S):g===e&&w===SKILL_FILE||t++}};return s(e),t}function applySkillBundleFileWrite(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillDir:g,filePath:S}=skillPaths(e.skillsRoot,e.name);if(!existsSync(S))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill "${e.name}" — create it (write its SKILL.md) before adding bundle files.`}};let w=resolveBundleFileAbs(g,e.relPath);if(!w.ok)return{ok:!1,error:w.error};let{abs:E}=w,D=Buffer.byteLength(e.content,`utf-8`);if(D>262144)return{ok:!1,error:{code:`FILE_TOO_LARGE`,message:`Skill file ${e.relPath} is ${D} bytes — the per-file cap is ${BUNDLE_FILE_MAX_BYTES}.`}};let O=!existsSync(E);if(O&&countBundleFiles(g)>=50)return{ok:!1,error:{code:`TOO_MANY_FILES`,message:`Skill "${e.name}" already holds 50 bundle files (the cap) — delete one before adding another.`}};try{mkdirSync(join(E,`..`),{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create directory for ${e.relPath}: ${t.message}`}}}let k=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(k,e.content,`utf-8`),renameSync(k,E)}catch(t){try{unlinkSync(k)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill file ${e.relPath}: ${t.message}`}}}return{ok:!0,path:relPathOf$1(e.skillsRoot,E),created:O}}function applySkillBundleFileDelete(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillDir:g}=skillPaths(e.skillsRoot,e.name),S=resolveBundleFileAbs(g,e.relPath);if(!S.ok)return{ok:!1,error:S.error};let{abs:w}=S,E=existsSync(w);if(E){try{unlinkSync(w)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill file ${e.relPath}: ${t.message}`}}}let t=join(w,`..`);if(t!==g&&isEmpty$1(t))try{rmdirSync(t)}catch{}}return{ok:!0,path:relPathOf$1(e.skillsRoot,w),existed:E}}function applySkillDelete(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillsRoot:g}=t,{skillDir:S}=skillPaths(e.skillsRoot,e.name),w=existsSync(S);if(w)try{rmSync(S,{recursive:!0,force:!0})}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill at ${relPathOf$1(e.skillsRoot,S)}: ${t.message}`}}}return cleanEmptyDirs(g),{ok:!0,path:relPathOf$1(e.skillsRoot,S),existed:w}}async function applySkillMove(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.fromName);if(!s.ok)return{ok:!1,error:s.error};let g=validateName(e.toName);if(!g.ok)return{ok:!1,error:g.error};let S=skillPaths(e.skillsRoot,e.fromName),w=skillPaths(e.skillsRoot,e.toName);if(S.skillDir===w.skillDir)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same skill.`}};if(!existsSync(S.skillDir))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill at ${relPathOf$1(e.skillsRoot,S.skillDir)}.`}};if(existsSync(w.skillDir))return{ok:!1,error:{code:`SKILL_EXISTS`,message:`A skill already exists at ${relPathOf$1(e.skillsRoot,w.skillDir)}.`}};let E;try{E=await e.relocate(S.skillDir,w.skillDir)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move skill: ${e.message}`}}}return{ok:!0,fromPath:relPathOf$1(e.skillsRoot,S.skillDir),toPath:relPathOf$1(e.skillsRoot,w.skillDir),committed:E}}function validateBase(e){return isAbsolute(e)?{ok:!0,skillsRoot:e}:{ok:!1,error:{code:`BAD_SKILLS_ROOT`,message:`skillsRoot must be absolute`}}}function validateName(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name is required.`}}:e.length>NAME_MAX?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must be ≤${NAME_MAX} characters.`}}:SKILL_NAME_REGEX.test(e)?RESERVED_NAME_WORDS.some(t=>e.includes(t))?{ok:!1,error:{code:`RESERVED_NAME`,message:`Skill name may not contain reserved words (${RESERVED_NAME_WORDS.join(`, `)}).`}}:{ok:!0}:{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must match /^[a-z0-9-]+$/ (got: ${JSON.stringify(e)}). Lowercase letters, digits, hyphens — no slashes, dots, spaces, or uppercase.`}}}function validateFrontmatter(e,t){return!e||typeof e!=`object`?{ok:!1,error:{code:`BAD_FRONTMATTER`,message:`Skill frontmatter (name, description) is required.`}}:typeof e.name!=`string`||e.name.length===0?{ok:!1,error:{code:`SKILL_NAME_REQUIRED`,message:`Skill frontmatter.name is required.`}}:e.name===t?containsXmlTag(e.name)?{ok:!1,error:{code:`XML_TAG_IN_NAME`,message:"Skill frontmatter.name may not contain XML tags (`<...>`)."}}:typeof e.description!=`string`||e.description.length===0?{ok:!1,error:{code:`SKILL_DESCRIPTION_REQUIRED`,message:`Skill frontmatter.description is required — it is the primary triggering surface (when to use the skill).`}}:e.description.length>DESCRIPTION_MAX?{ok:!1,error:{code:`DESCRIPTION_TOO_LONG`,message:`Skill frontmatter.description must be ≤${DESCRIPTION_MAX} characters (got ${e.description.length}).`}}:containsXmlTag(e.description)?{ok:!1,error:{code:`XML_TAG_IN_DESCRIPTION`,message:"Skill frontmatter.description may not contain XML tags (`<...>`) — they break the Cowork parser and skill loader."}}:{ok:!0}:{ok:!1,error:{code:`NAME_DIR_MISMATCH`,message:`Skill frontmatter.name (${JSON.stringify(e.name)}) must equal the skill directory name (${JSON.stringify(t)}).`}}}function skillPaths(e,t){let s=join(e,t);return{skillDir:s,filePath:join(s,SKILL_FILE)}}function cleanEmptyDirs(e){if(existsSync(e)&&isEmpty$1(e))try{rmdirSync(e)}catch{}let t=normalize(join(e,`..`));if(t.endsWith(`${sep}.ok`)&&existsSync(t)&&isEmpty$1(t))try{rmdirSync(t)}catch{}}function relPathOf$1(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function serializeFrontmatter(e){return(0,import_dist$1.stringify)({name:e.name,description:e.description})}function isEmpty$1(e){try{return readdirSync(e).length===0}catch{return!1}}const SUBSTITUTION_ALLOWLIST=[`date`,`user`],TOKEN_PATTERN=/\{\{([^{}\n]+?)\}\}/g;function validateSubstitution(e){let t=[];for(let s of e.matchAll(TOKEN_PATTERN)){let e=(s[1]??``).trim();isAllowedToken(e)||t.push({token:e,offset:s.index??0})}return t}function applySubstitution(e,t){return e.replace(TOKEN_PATTERN,(e,s)=>{let g=s.trim();return isAllowedToken(g)?t[g]:e})}function isAllowedToken(e){return SUBSTITUTION_ALLOWLIST.includes(e)}function todayIsoUtc(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}const NAME_RE=TEMPLATE_NAME_REGEX;function composeTemplateContent(e){if(!NAME_RE.test(e.name))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(e.name)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let t=validateTitle(e.frontmatter.title);if(!t.ok)return{ok:!1,error:t.error};let s=validateSubstitutionAllowlist(e.body);if(!s.ok)return{ok:!1,error:s.error};let g=validateNoReservedDocKey(e.body);if(!g.ok)return{ok:!1,error:g.error};let S={};e.frontmatter.title!==void 0&&(S.title=e.frontmatter.title),e.frontmatter.description!==void 0&&(S.description=e.frontmatter.description),Array.isArray(e.frontmatter.tags)&&e.frontmatter.tags.length>0&&(S.tags=e.frontmatter.tags);let w=composeTemplateFile(S,e.body),E=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&E.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,content:w,warnings:E}}function applyTemplateWrite(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let s=composeTemplateContent({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!s.ok)return{ok:!1,error:s.error};let{content:g,warnings:S}=s,{templatesDir:w,filePath:E}=templatePaths(e.projectDir,t.folderRel,e.name);try{mkdirSync(w,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${relPathOf(e.projectDir,w)}: ${t.message}`}}}let D=!existsSync(E),O=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(O,g,`utf-8`),renameSync(O,E)}catch(t){try{unlinkSync(O)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${relPathOf(e.projectDir,E)}: ${t.message}`}}}return{ok:!0,path:relPathOf(e.projectDir,E),created:D,warnings:S}}function applyTemplateDelete(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:s,okDir:g,filePath:S}=templatePaths(e.projectDir,t.folderRel,e.name),w=existsSync(S);if(w)try{unlinkSync(S)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${relPathOf(e.projectDir,S)}: ${t.message}`}}}return{ok:!0,path:relPathOf(e.projectDir,S),existed:w,cleanedEmpty:cleanEmptyOkDirs(s,g)}}function cleanEmptyOkDirs(e,t){let s=!1,g=!1;if(existsSync(e)&&isEmpty(e))try{rmdirSync(e),s=!0}catch{}if(existsSync(t)&&isEmpty(t))try{rmdirSync(t),g=!0}catch{}return{templatesDir:s,okDir:g}}async function applyTemplateMove(e){let t=validateInputs(e.projectDir,e.fromFolder,e.fromName);if(!t.ok)return{ok:!1,error:t.error};let s=validateInputs(e.projectDir,e.toFolder,e.toName);if(!s.ok)return{ok:!1,error:s.error};let g=templatePaths(e.projectDir,t.folderRel,e.fromName),S=templatePaths(e.projectDir,s.folderRel,e.toName);if(g.filePath===S.filePath)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same template.`}};if(!existsSync(g.filePath))return{ok:!1,error:{code:`TEMPLATE_NOT_FOUND`,message:`No template at ${relPathOf(e.projectDir,g.filePath)}.`}};if(existsSync(S.filePath))return{ok:!1,error:{code:`TEMPLATE_EXISTS`,message:`A template already exists at ${relPathOf(e.projectDir,S.filePath)}.`}};try{mkdirSync(S.templatesDir,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create destination template directory at ${relPathOf(e.projectDir,S.templatesDir)}: ${t.message}`}}}let w;try{w=await e.relocate(g.filePath,S.filePath)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move template: ${e.message}`}}}let E=cleanEmptyOkDirs(g.templatesDir,g.okDir);return{ok:!0,fromPath:relPathOf(e.projectDir,g.filePath),toPath:relPathOf(e.projectDir,S.filePath),committed:w,cleanedEmpty:E}}function validateInputs(e,t,s){if(!isAbsolute(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!NAME_RE.test(s))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(s)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let g=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(g.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let S=g?resolve(e,g):e,w=resolve(e);return!S.startsWith(w+sep)&&S!==w?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${S}`}}:{ok:!0,folderRel:g}}function validateTitle(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function validateSubstitutionAllowlist(e){let t=validateSubstitution(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function templatePaths(e,t,s){let g=t?join(e,t,`.ok`):join(e,`.ok`),S=join(g,`templates`);return{okDir:g,templatesDir:S,filePath:join(S,`${s}.md`)}}function relPathOf(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function validateNoReservedDocKey(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return{ok:!0};let s=unwrapFrontmatterFences(t);return RegExp(`^template:`,`m`).test(s)?{ok:!1,error:{code:`TEMPLATE_RESERVED_KEY`,message:`Template starter content may not declare a top-level \`${TEMPLATE_IDENTITY_KEY}:\` frontmatter key — it is reserved for the template's identity.`}}:{ok:!0}}function isEmpty(e){try{return readdirSync(e).length===0}catch{return!1}}var RingBuffer=class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let s=1;s<=t;s++){let t=(this.writeIndex-s+this.capacity)%this.capacity,g=this.store[t];g!==void 0&&e.push(g)}return e}get size(){return this.filled?this.capacity:this.writeIndex}};const embedProbeRing=new RingBuffer(256);function recordEmbedProbe(e){embedProbeRing.push(e)}const CURSOR_UA_RE=UA_PATTERNS.cursor,CODEX_UA_RE=UA_PATTERNS.codex,CLAUDE_UA_RE=UA_PATTERNS[`claude-desktop`],CURSOR_REFERER_STRATEGY_LITERAL=`?strategy=C_iframe`,EMPTY_DETECTION={app:null,signals_fired:[]};function deriveDetection(e){if(!e)return{...EMPTY_DETECTION};let t=[],s=e.ua,g=e.referer,S=!!s&&CURSOR_UA_RE.test(s),w=!!g&&g.includes(CURSOR_REFERER_STRATEGY_LITERAL);if(S&&t.push(`cursor_ua_regex`),w&&t.push(`cursor_referer_strategy_iframe`),S||w)return{app:`cursor`,signals_fired:t};let E=!!s&&CODEX_UA_RE.test(s);if(E&&t.push(`codex_ua_regex`),E)return{app:`codex`,signals_fired:t};let D=!!s&&CLAUDE_UA_RE.test(s);return D&&t.push(`claude_ua_regex`),D?{app:`claude`,signals_fired:t}:{...EMPTY_DETECTION}}const log$16=getLogger(`embeddings`);let _tokens=null,_errors=null,_requestDuration=null,_queryTotal=null,_queryEmbedDuration=null;function tokensCounter(){return _tokens||=getMeter().createCounter(`ok.embeddings.tokens_total`,{description:`Embeddings tokens billed, by role. Bounded label: role ∈ {query, document}. Makes spend legible; never includes content.`}),_tokens}function errorsCounter(){return _errors||=getMeter().createCounter(`ok.embeddings.provider_errors_total`,{description:`Embeddings provider failures, by reason. Bounded label: reason ∈ {rate_limit, timeout, http_error, network, dims_mismatch, malformed_response}.`}),_errors}function requestDurationHist(){return _requestDuration||=getMeter().createHistogram(`ok.embeddings.request_duration_ms`,{description:`Wall-clock duration of one embeddings API request. Bounded label: role.`,unit:`ms`}),_requestDuration}function queryTotalCounter(){return _queryTotal||=getMeter().createCounter(`ok.search.semantic_query_total`,{description:`Semantic-requested searches, by outcome and caller surface. Bounded labels: outcome ∈ {applied, no_match, warming, incapable, provider_error}, source ∈ {omnibar, mcp, http}. The omnibar/mcp split separates interactive cost from agent cost.`}),_queryTotal}function queryEmbedDurationHist(){return _queryEmbedDuration||=getMeter().createHistogram(`ok.search.semantic_query_embed_ms`,{description:`Wall-clock latency of the per-query embed on the semantic search path.`,unit:`ms`}),_queryEmbedDuration}function recordEmbeddingTokens(e,t){t>0&&tokensCounter().add(t,{role:e})}function recordEmbeddingProviderError(e){errorsCounter().add(1,{reason:e})}function recordEmbeddingRequestDuration(e,t){requestDurationHist().record(Math.max(0,t),{role:e})}function recordSemanticQuery(e){queryTotalCounter().add(1,{outcome:e.outcome,source:e.source}),e.queryEmbedMs!==null&&queryEmbedDurationHist().record(Math.max(0,e.queryEmbedMs)),log$16.debug({outcome:e.outcome,source:e.source,capable:e.capable,embedded:e.embedded,total:e.total,coverage:e.total>0?e.embedded/e.total:0,queryEmbedMs:e.queryEmbedMs,vectorContributors:e.vectorContributors},`[search] semantic query`)}const DEFAULT_EMBEDDINGS_DIMENSIONS=1536,EMBEDDINGS_API_KEY_ENV=`OK_EMBEDDINGS_API_KEY`;var EmbeddingDimsMismatchError=class extends Error{name=`EmbeddingDimsMismatchError`;constructor(e,t){super(`embeddings provider returned ${t}-dim vectors, expected ${e}. Set search.semantic.dimensions to ${t} (or point at the right model).`),this.expected=e,this.got=t}},MalformedEmbeddingResponseError=class extends Error{name=`MalformedEmbeddingResponseError`;constructor(e,t){super(`embeddings response had ${t} vectors, expected ${e}`)}};function cosineSimilarity(e,t){let s=0,g=Math.min(e.length,t.length);for(let S=0;S<g;S++)s+=e[S]*t[S];return s}function normalizeInPlace(e){let t=0;for(let s=0;s<e.length;s++)t+=e[s]*e[s];if(t=Math.sqrt(t),t>0)for(let s=0;s<e.length;s++)e[s]/=t;return e}const DEFAULTS={maxBatchSize:96,maxBatchChars:96e3,docTimeoutMs:3e4,queryTimeoutMs:8e3,maxRetries:4,backoffBaseMs:500};function normalizeProviderId(e){try{let t=new URL(e),s=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${s}`}catch{return e.trim().replace(/\/+$/,``)}}function assertSafeEmbeddingsBaseUrl(e){let t=checkEmbeddingsBaseUrl(e);if(t===null)return;if(t===`invalid-url`)throw Error(`embeddings baseUrl is not a valid URL: ${e}`);let s=new URL(e);throw Error(`refusing to send the embeddings API key to a non-HTTPS endpoint (${s.protocol}//${s.host}); use https:// (http:// is allowed only for localhost)`)}const RETRYABLE_STATUS=new Set([408,409,429,500,502,503,504]);function defaultSleep$1(e){return new Promise(t=>setTimeout(t,e))}function createOpenAiEmbedder(e,t={}){let s=t.fetchImpl??fetch,g=t.sleep??defaultSleep$1,S=t.maxBatchSize??DEFAULTS.maxBatchSize,w=t.maxBatchChars??DEFAULTS.maxBatchChars,E=t.maxRetries??DEFAULTS.maxRetries,D=t.backoffBaseMs??DEFAULTS.backoffBaseMs,O=t.docTimeoutMs??DEFAULTS.docTimeoutMs,k=t.queryTimeoutMs??DEFAULTS.queryTimeoutMs;assertSafeEmbeddingsBaseUrl(e.baseUrl);let j=e.dimensions??1536,F=`${e.baseUrl.replace(/\/+$/,``)}/embeddings`;function L(e){let t=[],s=[],g=0;for(let E of e)s.length>0&&(s.length>=S||g+E.length>w)&&(t.push(s),s=[],g=0),s.push(E),g+=E.length;return s.length>0&&t.push(s),t}async function B(t,g,S,w){let E=new AbortController,D=setTimeout(()=>E.abort(),w),O=performance.now();try{let w=await s(F,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.apiKey}`},body:t,signal:E.signal});if(recordEmbeddingRequestDuration(S,performance.now()-O),!w.ok){await w.text().catch(()=>``);let e=w.status===429?`rate_limit`:`http_error`,t=Error(`embeddings request failed: HTTP ${w.status}`);return RETRYABLE_STATUS.has(w.status)?{kind:`retry`,reason:e,error:t}:{kind:`fatal`,reason:e,error:t}}let D=await w.json(),k=q(D,g,j);return recordEmbeddingTokens(S,D.usage?.total_tokens??0),{kind:`ok`,vectors:k}}catch(e){if(e instanceof EmbeddingDimsMismatchError)return{kind:`fatal`,reason:`dims_mismatch`,error:e};if(e instanceof MalformedEmbeddingResponseError)return{kind:`fatal`,reason:`malformed_response`,error:e};let t=e instanceof Error&&e.name===`AbortError`,s=e instanceof Error?e:Error(String(e));return{kind:`retry`,reason:t?`timeout`:`network`,error:s}}finally{clearTimeout(D)}}async function H(t,s){let S=s===`query`?k:O,w=s===`query`?`query`:`document`,j=JSON.stringify({model:e.model,input:t,encoding_format:`float`,...e.dimensions===void 0?{}:{dimensions:e.dimensions}}),F=0;for(;;){let e=await B(j,t.length,w,S);if(e.kind===`ok`)return e.vectors;if(recordEmbeddingProviderError(e.reason),e.kind===`fatal`||F>=E)throw e.error;F+=1;let s=D*2**(F-1);await g(Math.round(s/2+s/2*Math.random()))}}function q(e,t,s){let g=e.data;if(!Array.isArray(g)||g.length!==t)throw new MalformedEmbeddingResponseError(t,g?.length??0);let S=[...g].sort((e,t)=>(e.index??0)-(t.index??0)),w=[];for(let e of S){let g=e.embedding;if(!Array.isArray(g))throw new MalformedEmbeddingResponseError(t,0);if(g.length!==s)throw new EmbeddingDimsMismatchError(s,g.length);w.push(normalizeInPlace(Float32Array.from(g)))}return w}return{providerId:normalizeProviderId(e.baseUrl),modelId:e.model,dims:j,async embed(e,{role:t}){if(e.length===0)return[];let s=[];for(let g of L(e))s.push(...await H(g,t));return s}}}async function loadOpenAiEmbedder(e){let t=(e.keyStore?await e.keyStore.get().catch(()=>null):null)??process.env.OK_EMBEDDINGS_API_KEY??null;return t?createOpenAiEmbedder({...e.config,apiKey:t},e.options):null}const SECRETS_KEY_FIELD=`OPENAI_API_KEY`,LEGACY_KEY_FIELD=`embeddings`;function secretsFilePath(e){return join(e??homedir(),`.ok`,`secrets.yml`)}var FileEmbeddingsBackend=class{backend=`file`;secretsFile;constructor(e){this.secretsFile=e??secretsFilePath()}tightenPermsIfLoose(){let e;try{e=statSync(this.secretsFile).mode&511}catch{return}if(e&63)try{chmodSync(this.secretsFile,384),process.stderr.write(`[embeddings] ${this.secretsFile} was readable beyond your user account (mode ${e.toString(8)}); tightened to 600. It stores an API key.\n`)}catch(t){let s=t instanceof Error?t.message:`unknown error`;process.stderr.write(`[embeddings] ${this.secretsFile} is readable beyond your user account (mode ${e.toString(8)}) and could not be tightened (${s}); your API key remains exposed — run: chmod 600 ${this.secretsFile}\n`)}}read(){if(!existsSync(this.secretsFile))return{};this.tightenPermsIfLoose();try{return(0,import_dist$1.parse)(readFileSync(this.secretsFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[embeddings] Failed to parse ${this.secretsFile}: ${t}. Starting with empty secrets.\n`),{}}}write(e){let t=dirname(this.secretsFile);existsSync(t)||tracedMkdirSync(t,{recursive:!0,mode:448}),tracedWriteFileSync(this.secretsFile,(0,import_dist$1.stringify)(e),{mode:384}),chmodSync(this.secretsFile,384)}get(){let e=this.read(),t=e[SECRETS_KEY_FIELD]??e[LEGACY_KEY_FIELD];return Promise.resolve(typeof t==`string`&&t!==``?t:null)}set(e){let t=this.read();return delete t[LEGACY_KEY_FIELD],t[SECRETS_KEY_FIELD]=e,this.write(t),Promise.resolve()}clear(){let e=this.read();if(SECRETS_KEY_FIELD in e||LEGACY_KEY_FIELD in e)if(delete e[SECRETS_KEY_FIELD],delete e[LEGACY_KEY_FIELD],Object.keys(e).length===0)try{tracedUnlinkSync(this.secretsFile)}catch{}else this.write(e);return Promise.resolve()}};function createEmbeddingsSecretStore(e){return new FileEmbeddingsBackend(e)}function makeLazyEmbeddingsKeyStore(e){return new FileEmbeddingsBackend(e)}async function describeStoredEmbeddingsKey(e){return{file:await new FileEmbeddingsBackend(e).get()!=null}}async function clearEmbeddingsKeyFromAllBackends(e){let t=[],s=new FileEmbeddingsBackend(e);return await s.get()!=null&&(await s.clear(),t.push(`file`)),{touched:t}}function readProjectLocalSemanticConfig(e,t){let s=readConfigSafely({absPath:resolveConfigPath(`project-local`,e,t?.configHomedirOverride),sideline:!1,warn:t?.onWarn??(()=>{})}).value.search?.semantic;return{enabled:s?.enabled===!0,baseUrl:s?.baseUrl??`https://api.openai.com/v1`,model:s?.model??`text-embedding-3-small`,dimensions:s?.dimensions??void 0,similarityFloor:s?.similarityFloor??void 0}}const CHUNK_CONFIG_ID=`c8000-o400-m80`;function chunkDocument(e,t={}){let s=Math.max(1,t.targetChars??8e3),g=Math.max(0,Math.min(t.overlapChars??400,s-1)),S=t.maxChunks??80;if(e.trim().length===0)return[];if(e.length<=s)return[e.trim()];let w=[],E=0;for(;E<e.length&&w.length<S;){let t=Math.min(e.length,E+s);if(t<e.length){let g=Math.max(e.lastIndexOf(` `,t),e.lastIndexOf(`
827
- `,t));g>E+Math.floor(s/2)&&(t=g)}let S=e.slice(E,t).trim();if(S&&w.push(S),t>=e.length)break;let D=t-g;E=D>E?D:t}return w}const log$15=getLogger(`embeddings`),MANIFEST_SCHEMA_VERSION=1,VEC_SUBDIR=`vec`,MANIFEST_NAME=`manifest.json`;function hashContent(e){return createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function serializeVectors(e){let t=0;for(let s of e)t+=s.length;let s=new Float32Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function deserializeVectors(e,t){let s=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),g=new Float32Array(s);if(g.length%t!==0)throw Error(`vector blob length ${g.length} is not a multiple of dims ${t}`);let S=[];for(let e=0;e<g.length;e+=t)S.push(g.slice(e,e+t));return S}var VectorCache=class{cacheDir;vecDir;manifestPath;providerId;modelId;dims;chunkConfigId;entries=new Map;vectorsByHash=new Map;persistedHashes=new Set;dirty=!1;constructor(e){this.cacheDir=e.cacheDir,this.vecDir=e.cacheDir?join(e.cacheDir,VEC_SUBDIR):null,this.manifestPath=e.cacheDir?join(e.cacheDir,MANIFEST_NAME):null,this.providerId=e.providerId,this.modelId=e.modelId,this.dims=e.dims,this.chunkConfigId=e.chunkConfigId}async init(){if(!this.cacheDir||!this.manifestPath||!this.vecDir)return;let e=null;try{existsSync(this.manifestPath)&&(e=JSON.parse(await readFile$1(this.manifestPath,`utf-8`)))}catch(t){log$15.warn({err:t instanceof Error?t.message:String(t)},`[embeddings] unreadable cache manifest — rebuilding`),e=null}if(!(e!==null&&e.schemaVersion===MANIFEST_SCHEMA_VERSION&&e.providerId===this.providerId&&e.modelId===this.modelId&&e.dims===this.dims&&e.chunkConfigId===this.chunkConfigId)){e!==null&&log$15.info({hadModel:e.modelId,wantModel:this.modelId},`[embeddings] cache identity changed (provider/model/dims/chunking) — invalidating`),this.wipeDisk();return}if(e){for(let[t,s]of Object.entries(e.entries))if(s?.contentHash&&(this.entries.set(t,{contentHash:s.contentHash,mtimeMs:s.mtimeMs??0}),!this.vectorsByHash.has(s.contentHash)))try{let e=join(this.vecDir,`${s.contentHash}.bin`);if(existsSync(e)){let t=await readFile$1(e);this.vectorsByHash.set(s.contentHash,deserializeVectors(t,this.dims)),this.persistedHashes.add(s.contentHash)}}catch(e){log$15.warn({hash:s.contentHash,err:e instanceof Error?e.message:String(e)},`[embeddings] corrupt vector blob — will re-embed`)}}}isFresh(e,t){let s=this.entries.get(e);return s!==void 0&&s.mtimeMs===t&&this.vectorsByHash.has(s.contentHash)}link(e,t,s){if(!this.vectorsByHash.has(t))return!1;let g=this.entries.get(e);return(!g||g.contentHash!==t||g.mtimeMs!==s)&&(this.dirty=!0),this.entries.set(e,{contentHash:t,mtimeMs:s}),!0}store(e,t,s,g){this.vectorsByHash.set(t,g),this.entries.set(e,{contentHash:t,mtimeMs:s}),this.dirty=!0}getVectors(e){let t=this.entries.get(e);if(t)return this.vectorsByHash.get(t.contentHash)}get embeddedCount(){let e=0;for(let t of this.entries.values()){let s=this.vectorsByHash.get(t.contentHash);s&&s.length>0&&(e+=1)}return e}retain(e){for(let t of this.entries.keys())e.has(t)||(this.entries.delete(t),this.dirty=!0);let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of this.vectorsByHash.keys())t.has(e)||this.vectorsByHash.delete(e)}clearMemory(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.dirty=!1}async persist(){if(!(!this.cacheDir||!this.manifestPath||!this.vecDir)&&this.dirty)try{await tracedMkdir(this.vecDir,{recursive:!0});let e=new Set;for(let t of this.entries.values())e.add(t.contentHash);for(let t of e){if(this.persistedHashes.has(t))continue;let e=this.vectorsByHash.get(t);e&&(await tracedWriteFile(join(this.vecDir,`${t}.bin`),serializeVectors(e)),this.persistedHashes.add(t))}let t={schemaVersion:MANIFEST_SCHEMA_VERSION,providerId:this.providerId,modelId:this.modelId,dims:this.dims,chunkConfigId:this.chunkConfigId,entries:Object.fromEntries(this.entries)},s=`${this.manifestPath}.tmp`;await tracedWriteFile(s,JSON.stringify(t)),await tracedRename(s,this.manifestPath);for(let t of readdirSync(this.vecDir)){if(!t.endsWith(`.bin`))continue;let s=t.slice(0,-4);e.has(s)||(tracedUnlinkSync(join(this.vecDir,t)),this.persistedHashes.delete(s))}this.dirty=!1}catch(e){log$15.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to persist vector cache`)}}wipeDisk(){if(this.cacheDir)try{tracedRmSync(this.cacheDir,{recursive:!0,force:!0})}catch(e){log$15.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to wipe stale cache`)}}};const log$14=getLogger(`embeddings`);function errMsg(e){return e instanceof Error?e.message:String(e)}const EMBED_BATCH_CHUNK_LIMIT=96,MAX_CONSECUTIVE_EMBED_FAILURES=5;var SemanticSearchService=class{loadEmbedder;cacheDir;enabled;providerFingerprint;capable=!1;ready=!1;embedder=null;cache=null;warmPromise=null;embedChain=Promise.resolve();queuedDocs=null;constructor(e){this.loadEmbedder=e.loadEmbedder,this.cacheDir=e.cacheDir,this.enabled=e.enabled??!1,this.providerFingerprint=e.providerFingerprint??``}isEnabled(){return this.enabled}getStatus(){return{enabled:this.enabled,capable:this.capable,ready:this.ready,embeddedCount:this.cache?.embeddedCount??0}}applyConfig(e){e.providerFingerprint!==this.providerFingerprint&&(this.providerFingerprint=e.providerFingerprint,this.resetWarm()),e.enabled!==this.enabled&&(this.enabled=e.enabled,e.enabled||(this.cache?.clearMemory(),this.resetWarm()))}resetWarm(){this.warmPromise=null,this.ready=!1,this.capable=!1,this.embedder=null,this.cache=null}ensureWarm(){return!this.enabled||this.ready?Promise.resolve():(this.warmPromise||=this.warm(),this.warmPromise)}async warm(){try{let e=await this.loadEmbedder();if(!e){this.capable=!1,this.ready=!0,log$14.info({},`[embeddings] no embeddings key configured — semantic search degrades to lexical`);return}this.embedder=e,this.cache=new VectorCache({cacheDir:this.cacheDir,providerId:e.providerId,modelId:e.modelId,dims:e.dims,chunkConfigId:CHUNK_CONFIG_ID}),await this.cache.init(),this.capable=!0,this.ready=!0}catch(e){this.capable=!1,this.ready=!0,log$14.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] warm failed`)}}embedCorpus(e){return this.enabled?(this.queuedDocs=e,this.embedChain=this.embedChain.then(async()=>{let e=this.queuedDocs;if(e){this.queuedDocs=null;try{await this.runEmbedPass(e)}catch(e){log$14.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] embed pass failed`)}}}),this.embedChain):Promise.resolve()}async runEmbedPass(e){if(await this.ensureWarm(),!this.enabled||!this.embedder||!this.cache)return;let t=this.cache,s=this.embedder,g=e.filter(e=>e.kind===`page`),S=new Set(g.map(e=>e.id)),w=[];for(let e of g){if(!this.enabled)return;let s=e.modifiedTs;if(t.isFresh(e.id,s))continue;let g=hashContent(e.content);t.link(e.id,g,s)||w.push({doc:e,contentHash:g,chunks:chunkDocument(e.content)})}let E=0,D=(e,s)=>{t.store(e.doc.id,e.contentHash,e.doc.modifiedTs,s)},O=async e=>{let t=e.flatMap(e=>e.chunks);try{let g=t.length?await s.embed(t,{role:`document`}):[],S=0;for(let t of e)D(t,g.slice(S,S+t.chunks.length)),S+=t.chunks.length;return E=0,!0}catch(t){if(e.length===1)return log$14.warn({docId:e[0].doc.id,err:errMsg(t)},`[embeddings] failed to embed document`),E+=1,E<MAX_CONSECUTIVE_EMBED_FAILURES;for(let t of e){if(!this.enabled)return!1;try{D(t,t.chunks.length?await s.embed(t.chunks,{role:`document`}):[]),E=0}catch(e){if(log$14.warn({docId:t.doc.id,err:errMsg(e)},`[embeddings] failed to embed document`),E+=1,E>=MAX_CONSECUTIVE_EMBED_FAILURES)return!1}}return!0}},k=[],j=0;for(let e of w){if(!this.enabled)break;if(k.push(e),j+=Math.max(1,e.chunks.length),j>=EMBED_BATCH_CHUNK_LIMIT){let e=await O(k);if(k=[],j=0,!e)break}}k.length>0&&this.enabled&&await O(k),!(!this.enabled||this.cache!==t)&&(t.retain(S),await t.persist())}async queryScores(e,t){if(!this.enabled||!this.capable||!this.ready||!this.embedder||!this.cache||this.cache.embeddedCount===0)return null;let s=e.trim();if(!s)return null;let g;try{[g]=await this.embedder.embed([s],{role:`query`})}catch(e){return log$14.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] query embed failed — degrading to lexical`),null}if(!g)return null;let S=new Map;for(let e of t){let t=this.cache.getVectors(e.id);if(!t||t.length===0)continue;let s=-1/0;for(let e of t){let t=cosineSimilarity(g,e);t>s&&(s=t)}s>-1/0&&S.set(e.id,s)}return S}};const log$13=()=>getLogger(`http`);function successResponse(e,t,s,g,S={}){if(e.headersSent||e.writableEnded||e.destroyed){log$13().error({event:`api.success.double-write`,status:t,handler:S.handler},`successResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let w=s.safeParse(g);if(!w.success){log$13().error({event:`api.success.malformed-body`,issues:w.error.issues,bodyKeys:typeof g==`object`&&g?Object.keys(g):null,handler:S.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}let E;try{E=JSON.stringify(w.data)}catch(s){log$13().error({event:`api.success.unserializable-body`,bodyKeys:typeof w.data==`object`&&w.data!==null?Object.keys(w.data):null,handler:S.handler,originalStatus:t,err:s},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(E)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,s=e.now??Date.now,g=e.ttlMs??6e4;async function S(S){let w=t.get(S);if(w?.status===`resolved`&&w.expiresAt>s())return w.installed;if(w?.status===`inflight`)return w.promise;let E=(async()=>{try{let w=await e.probe(S);return t.set(S,{status:`resolved`,installed:w,expiresAt:s()+g}),w}catch{return t.set(S,{status:`resolved`,installed:!1,expiresAt:s()+g}),!1}})();return t.set(S,{status:`inflight`,promise:E}),E}async function w(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await S(e)]));return Object.fromEntries(e)}return{probeAll:w,probeWithCache:S}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let s=e.headers.origin;if(typeof s==`string`&&s.length>0)try{return isLoopbackHostname(new URL(s).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await s():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return s=>e===`darwin`?probeMacOs(s,t):e===`win32`?probeWindows(s,t):probeLinux(s,t)}function probeMacOs(e,t){let s=MACOS_APP_NAMES[e];function g(e){return new Promise(s=>{t(`osascript`,[`-e`,`id of app "${e}"`],withHiddenWindowsConsole({timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`}),(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}return(async()=>{for(let e of s)if(await g(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(s=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],withHiddenWindowsConsole({timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`}),e=>{s(!e)})})}function probeLinux(e,t){return new Promise(s=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],withHiddenWindowsConsole({timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`}),(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let s=[],g=0,S=AbortSignal.timeout(t.timeoutMs),w=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));S.addEventListener(`abort`,w,{once:!0});try{for await(let S of e){if(g+=S.length,g>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);s.push(S)}return Buffer.concat(s)}finally{S.removeEventListener(`abort`,w)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,s,g={}){let S=e.safeParse(t);if(S.success)return{ok:!0,value:S.data};let w=S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(s,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:g.handler,detail:w}),{ok:!1}}function withValidation(e,t,s={}){return async(g,S)=>{if(s.method!==void 0&&g.method!==s.method){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:s.handler,extraHeaders:{Allow:s.method}});return}if(s.preBodyGate!==void 0&&!s.preBodyGate(g,S)){!S.headersSent&&!S.writableEnded&&!S.destroyed&&errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(s.skipBodyParse){let w=validateBody(e,{},S,s);if(!w.ok)return;await t(g,S,w.value);return}let w;try{w=await readRequestBody(g)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(S,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(S,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s.handler,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s.handler,cause:e});return}let E;try{E=w.length===0?{}:JSON.parse(w.toString(`utf8`))}catch(e){errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:s.handler,cause:e});return}let D=validateBody(e,E,S,s);D.ok&&await t(g,S,D.value)}}const DETACHED_IGNORED_STDIO_OPTIONS={detached:!0,stdio:`ignore`,shell:!1};function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,s){return new Promise(g=>{let S=!1,w=e=>{S||(S=!0,g(e))},E=setTimeout(()=>w({ok:!1,reason:`timeout`}),s);try{let s=spawn(e,[...t],withHiddenWindowsConsole(DETACHED_IGNORED_STDIO_OPTIONS));s.once(`error`,e=>{clearTimeout(E),w(classifySpawnError(e))}),s.once(`spawn`,()=>{if(!S){try{s.unref()}catch{}clearTimeout(E),w({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(E),w(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let w=typeof S.path==`string`?S.path:``;if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(w,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let E=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!E){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let D=resolveCursorSpawnInvocation(E,w,s.platform),O=await(s.spawnDetached??spawnDetached)(D.exec,D.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(O.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(O.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(O.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let s of t){let t=s(e);try{return await access(t,constants$1.X_OK),t}catch(e){let s=e?.code;s!==`ENOENT`&&s!==`EACCES`&&s!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,s,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],withHiddenWindowsConsole({timeout:e,encoding:`utf-8`}),(e,s)=>{if(e){t(null);return}let g=s.split(/\r?\n/)[0]?.trim();t(g&&g.length>0?g:null)})})}function resolveCursorSpawnInvocation(e,t,s){return s===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:s===`win32`&&/\.(cmd|bat)$/i.test(e)?{exec:process.env.ComSpec||`cmd.exe`,args:[`/d`,`/c`,e,t]}:{exec:e,args:[t]}}function isPathWithinDir(e,t,s){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(s===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let g=s===`win32`?win32:posix;try{let S=g.resolve(e),w=g.resolve(t);if(s===`win32`){let e=g.parse(S).root.toLowerCase(),t=g.parse(w).root.toLowerCase();if(!e||!t||e!==t)return!1}if(S===w)return!0;let E=g.relative(w,S);return E===``||E===`.`?!0:!(E===`..`||E.startsWith(`..${g.sep}`)||s===`win32`&&(/^[a-zA-Z]:[\\/]/.test(E)||E.startsWith(`\\\\`))||s!==`win32`&&E.startsWith(`/`))}catch(e){return console.warn(`[spawn-cursor] unexpected path-resolution error:`,e),!1}}const HANDLER=`handoff`,HANDOFF_MAX_BODY_BYTES=4*1024,HANDOFF_BODY_READ_TIMEOUT_MS=5e3,SPAWN_TIMEOUT_MS$1=2e3,WHICH_TIMEOUT_MS=500,QUIT_SETTLE_MS=3e3,APP_BUNDLE_SETTLE_MS=5e3,CURSOR_SETTLE_MS=1500,RECIPES={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},TARGET_VALUES=Object.keys(RECIPES),HandoffRequestSchema=object$1({target:_enum(TARGET_VALUES),url:string().min(1).max(4096),workspacePath:string().optional()}),HandoffSuccessSchema=object$1({}).loose();function defaultSleep(e){return new Promise(t=>setTimeout(t,e))}async function handleHandoffDispatch(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:HANDOFF_MAX_BODY_BYTES,timeoutMs:HANDOFF_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER,cause:e});return}let w=HandoffRequestSchema.safeParse(S);if(!w.success){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:HANDLER});return}let{target:E,url:D,workspacePath:O}=w.data,k=RECIPES[E];if(!D.startsWith(k.urlScheme)){errorResponse(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${k.urlScheme} for target ${E}.`,{handler:HANDLER});return}let j=s.sleep??defaultSleep,F=s.spawnDetached??spawnDetached,L=s.isSchemeRegistered??createOsProbe(s.platform);if(k.type===`app-bundle`){if(s.platform===`darwin`){k.quitFirst&&(await F(`/usr/bin/osascript`,[`-e`,`tell application "${k.appName}" to quit`],SPAWN_TIMEOUT_MS$1).catch(()=>void 0),await j(QUIT_SETTLE_MS));let e=await F(`/usr/bin/open`,[`-a`,k.appName],SPAWN_TIMEOUT_MS$1);if(!e.ok){emitSpawnFailure(t,E,e.reason);return}await j(APP_BUNDLE_SETTLE_MS)}else if(!await L(k.probeScheme)){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:E}});return}let e=resolveUrlOpenInvocation(D,s.platform),g=await F(e.exec,e.args,SPAWN_TIMEOUT_MS$1);if(!g.ok){emitSpawnFailure(t,E,g.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER});return}if(!O){errorResponse(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:HANDLER});return}if(!isPathWithinDir(O,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER});return}let B=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!B){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let H=resolveCursorSpawnInvocation(B,O,s.platform),q=await F(H.exec,H.args,SPAWN_TIMEOUT_MS$1);if(!q.ok){emitSpawnFailure(t,E,q.reason);return}await j(CURSOR_SETTLE_MS);let ee=resolveUrlOpenInvocation(D,s.platform),J=await F(ee.exec,ee.args,SPAWN_TIMEOUT_MS$1);if(!J.ok){emitSpawnFailure(t,E,J.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}function resolveUrlOpenInvocation(e,t){return t===`darwin`?{exec:`/usr/bin/open`,args:[e]}:t===`win32`?{exec:`rundll32.exe`,args:[`url.dll,FileProtocolHandler`,e]}:{exec:`xdg-open`,args:[e]}}function emitSpawnFailure(e,t,s){switch(s){case`not-installed`:errorResponse(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:t}});return;case`timeout`:errorResponse(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:HANDLER,extensions:{target:t}});return;case`spawn-error`:errorResponse(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:HANDLER,extensions:{target:t}});return;default:assertNeverReason(s)}}function assertNeverReason(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let s=[],g=new Set,S=t=>{!t||g.has(t)||t!==e&&(g.add(t),s.push(t))},w=buildLowerDocNameIndex(t),E=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES)return s;let e=E===``?null:basename$1(E);if(e&&(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES))return s;if(E===``)break;E=parentFolder(E)}return s}function lookup$1(e,t,s){return e.has(s)?s:t.get(s.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let s of e.keys()){let e=s.toLowerCase();t.has(e)||t.set(e,s)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}const logger$4=getLogger(`installed-skills-marker`),TRACED_FS_ADAPTER={writeFile:(e,t,s)=>tracedWriteFile(e,t,s),rename:(e,t)=>tracedRename(e,t)};function installedSkillsPath(e){return join(e,...INSTALLED_SKILLS_REL)}const markerWriteChains=new Map;function withMarkerLock(e,t){let s=installedSkillsPath(e),g=(markerWriteChains.get(s)??Promise.resolve()).then(t,t);return markerWriteChains.set(s,g.then(()=>void 0,()=>void 0)),g}function readInstalledSkills(e){let t=installedSkillsPath(e);if(!existsSync(t))return emptyInstalledSkills();try{return parseInstalledSkills(readFileSync(t,`utf-8`))??emptyInstalledSkills()}catch(e){return logger$4.warn({err:e,path:t},`installed-skills marker unreadable`),emptyInstalledSkills()}}async function writeInstalledSkills(e,t){let s=InstalledSkillsSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid installed-skills marker: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=installedSkillsPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s.data,null,2)}\n`,{fs:TRACED_FS_ADAPTER})}async function recordSkillInstall(e,t,s){return withMarkerLock(e,async()=>{let g=readInstalledSkills(e);await writeInstalledSkills(e,{...g,skills:{...g.skills,[t]:s}})})}async function removeSkillInstall(e,t){return withMarkerLock(e,async()=>{let s=readInstalledSkills(e),g=s.skills[t]??null;if(g===null)return null;let{[t]:S,...w}=s.skills;return await writeInstalledSkills(e,{...s,skills:w}),g})}const log$12=getLogger(`mermaid-validator`),MAX_FENCE_BYTES=1e5,MAX_FENCE_LINES=2e3,MAX_FENCES_PARSED=20,TOTAL_PARSE_BUDGET_MS=2e3,MAX_WARNINGS=10,MAX_MESSAGE_CHARS=500,MAX_FIRST_LINE_CHARS=200;let initPromise=null;function extractMermaidFences(e){let t=[],s=e.split(`
826
+ `).length;return w>BODY_SOFT_MAX_LINES&&S.push(`SKILL.md body is ${w} lines — keep it under ${BODY_SOFT_MAX_LINES} for performance (every line is a recurring token cost). Move detail into one-level-deep references/.`),{ok:!0,content:g,warnings:S}}function applySkillWrite(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=composeSkillContent({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!s.ok)return{ok:!1,error:s.error};let{content:g,warnings:S}=s,{skillDir:w,filePath:E}=skillPaths(e.skillsRoot,e.name);try{mkdirSync(w,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create skill directory at ${relPathOf$1(e.skillsRoot,w)}: ${t.message}`}}}let D=!existsSync(E),O=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(O,g,`utf-8`),renameSync(O,E)}catch(t){try{unlinkSync(O)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill at ${relPathOf$1(e.skillsRoot,E)}: ${t.message}`}}}return{ok:!0,path:relPathOf$1(e.skillsRoot,E),created:D,warnings:S}}const BUNDLE_FILE_MAX_BYTES=256*1024;function resolveBundleFileAbs(e,t){if(typeof t!=`string`||t.length===0||t.includes(`\0`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path.`}};let s=t.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);if(s.length<2||s.some(e=>e===`..`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path: ${t}`}};if(s[0]!==`references`&&s[0]!==`scripts`)return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file must be under references/ or scripts/: ${t}`}};let g=join(e,...s);return g!==e&&!g.startsWith(e+sep)?{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file escapes the skill dir: ${t}`}}:{ok:!0,abs:g}}function countBundleFiles(e){let t=0,s=g=>{let S;try{S=readdirSync(g)}catch{return}for(let w of S){let S=join(g,w),E;try{E=statSync(S).isDirectory()}catch{continue}E?s(S):g===e&&w===SKILL_FILE||t++}};return s(e),t}function applySkillBundleFileWrite(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillDir:g,filePath:S}=skillPaths(e.skillsRoot,e.name);if(!existsSync(S))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill "${e.name}" — create it (write its SKILL.md) before adding bundle files.`}};let w=resolveBundleFileAbs(g,e.relPath);if(!w.ok)return{ok:!1,error:w.error};let{abs:E}=w,D=Buffer.byteLength(e.content,`utf-8`);if(D>262144)return{ok:!1,error:{code:`FILE_TOO_LARGE`,message:`Skill file ${e.relPath} is ${D} bytes — the per-file cap is ${BUNDLE_FILE_MAX_BYTES}.`}};let O=!existsSync(E);if(O&&countBundleFiles(g)>=50)return{ok:!1,error:{code:`TOO_MANY_FILES`,message:`Skill "${e.name}" already holds 50 bundle files (the cap) — delete one before adding another.`}};try{mkdirSync(join(E,`..`),{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create directory for ${e.relPath}: ${t.message}`}}}let k=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(k,e.content,`utf-8`),renameSync(k,E)}catch(t){try{unlinkSync(k)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill file ${e.relPath}: ${t.message}`}}}return{ok:!0,path:relPathOf$1(e.skillsRoot,E),created:O}}function applySkillBundleFileDelete(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillDir:g}=skillPaths(e.skillsRoot,e.name),S=resolveBundleFileAbs(g,e.relPath);if(!S.ok)return{ok:!1,error:S.error};let{abs:w}=S,E=existsSync(w);if(E){try{unlinkSync(w)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill file ${e.relPath}: ${t.message}`}}}let t=join(w,`..`);if(t!==g&&isEmpty$1(t))try{rmdirSync(t)}catch{}}return{ok:!0,path:relPathOf$1(e.skillsRoot,w),existed:E}}function applySkillDelete(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillsRoot:g}=t,{skillDir:S}=skillPaths(e.skillsRoot,e.name),w=existsSync(S);if(w)try{rmSync(S,{recursive:!0,force:!0})}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill at ${relPathOf$1(e.skillsRoot,S)}: ${t.message}`}}}return cleanEmptyDirs(g),{ok:!0,path:relPathOf$1(e.skillsRoot,S),existed:w}}async function applySkillMove(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.fromName);if(!s.ok)return{ok:!1,error:s.error};let g=validateName(e.toName);if(!g.ok)return{ok:!1,error:g.error};let S=skillPaths(e.skillsRoot,e.fromName),w=skillPaths(e.skillsRoot,e.toName);if(S.skillDir===w.skillDir)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same skill.`}};if(!existsSync(S.skillDir))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill at ${relPathOf$1(e.skillsRoot,S.skillDir)}.`}};if(existsSync(w.skillDir))return{ok:!1,error:{code:`SKILL_EXISTS`,message:`A skill already exists at ${relPathOf$1(e.skillsRoot,w.skillDir)}.`}};let E;try{E=await e.relocate(S.skillDir,w.skillDir)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move skill: ${e.message}`}}}return{ok:!0,fromPath:relPathOf$1(e.skillsRoot,S.skillDir),toPath:relPathOf$1(e.skillsRoot,w.skillDir),committed:E}}function validateBase(e){return isAbsolute(e)?{ok:!0,skillsRoot:e}:{ok:!1,error:{code:`BAD_SKILLS_ROOT`,message:`skillsRoot must be absolute`}}}function validateName(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name is required.`}}:e.length>NAME_MAX?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must be ≤${NAME_MAX} characters.`}}:SKILL_NAME_REGEX.test(e)?RESERVED_NAME_WORDS.some(t=>e.includes(t))?{ok:!1,error:{code:`RESERVED_NAME`,message:`Skill name may not contain reserved words (${RESERVED_NAME_WORDS.join(`, `)}).`}}:{ok:!0}:{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must match /^[a-z0-9-]+$/ (got: ${JSON.stringify(e)}). Lowercase letters, digits, hyphens — no slashes, dots, spaces, or uppercase.`}}}function validateFrontmatter(e,t){return!e||typeof e!=`object`?{ok:!1,error:{code:`BAD_FRONTMATTER`,message:`Skill frontmatter (name, description) is required.`}}:typeof e.name!=`string`||e.name.length===0?{ok:!1,error:{code:`SKILL_NAME_REQUIRED`,message:`Skill frontmatter.name is required.`}}:e.name===t?containsXmlTag(e.name)?{ok:!1,error:{code:`XML_TAG_IN_NAME`,message:"Skill frontmatter.name may not contain XML tags (`<...>`)."}}:typeof e.description!=`string`||e.description.length===0?{ok:!1,error:{code:`SKILL_DESCRIPTION_REQUIRED`,message:`Skill frontmatter.description is required — it is the primary triggering surface (when to use the skill).`}}:e.description.length>DESCRIPTION_MAX?{ok:!1,error:{code:`DESCRIPTION_TOO_LONG`,message:`Skill frontmatter.description must be ≤${DESCRIPTION_MAX} characters (got ${e.description.length}).`}}:containsXmlTag(e.description)?{ok:!1,error:{code:`XML_TAG_IN_DESCRIPTION`,message:"Skill frontmatter.description may not contain XML tags (`<...>`) — they break the Cowork parser and skill loader."}}:{ok:!0}:{ok:!1,error:{code:`NAME_DIR_MISMATCH`,message:`Skill frontmatter.name (${JSON.stringify(e.name)}) must equal the skill directory name (${JSON.stringify(t)}).`}}}function skillPaths(e,t){let s=join(e,t);return{skillDir:s,filePath:join(s,SKILL_FILE)}}function cleanEmptyDirs(e){if(existsSync(e)&&isEmpty$1(e))try{rmdirSync(e)}catch{}let t=normalize(join(e,`..`));if(t.endsWith(`${sep}.ok`)&&existsSync(t)&&isEmpty$1(t))try{rmdirSync(t)}catch{}}function relPathOf$1(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function serializeFrontmatter(e){return(0,import_dist$1.stringify)({name:e.name,description:e.description})}function isEmpty$1(e){try{return readdirSync(e).length===0}catch{return!1}}const SUBSTITUTION_ALLOWLIST=[`date`,`user`],TOKEN_PATTERN=/\{\{([^{}\n]+?)\}\}/g;function validateSubstitution(e){let t=[];for(let s of e.matchAll(TOKEN_PATTERN)){let e=(s[1]??``).trim();isAllowedToken(e)||t.push({token:e,offset:s.index??0})}return t}function applySubstitution(e,t){return e.replace(TOKEN_PATTERN,(e,s)=>{let g=s.trim();return isAllowedToken(g)?t[g]:e})}function isAllowedToken(e){return SUBSTITUTION_ALLOWLIST.includes(e)}function todayIsoUtc(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}const NAME_RE=TEMPLATE_NAME_REGEX;function composeTemplateContent(e){if(!NAME_RE.test(e.name))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(e.name)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let t=validateTitle(e.frontmatter.title);if(!t.ok)return{ok:!1,error:t.error};let s=validateSubstitutionAllowlist(e.body);if(!s.ok)return{ok:!1,error:s.error};let g=validateNoReservedDocKey(e.body);if(!g.ok)return{ok:!1,error:g.error};let S={};e.frontmatter.title!==void 0&&(S.title=e.frontmatter.title),e.frontmatter.description!==void 0&&(S.description=e.frontmatter.description),Array.isArray(e.frontmatter.tags)&&e.frontmatter.tags.length>0&&(S.tags=e.frontmatter.tags);let w=composeTemplateFile(S,e.body),E=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&E.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,content:w,warnings:E}}function applyTemplateWrite(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let s=composeTemplateContent({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!s.ok)return{ok:!1,error:s.error};let{content:g,warnings:S}=s,{templatesDir:w,filePath:E}=templatePaths(e.projectDir,t.folderRel,e.name);try{mkdirSync(w,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${relPathOf(e.projectDir,w)}: ${t.message}`}}}let D=!existsSync(E),O=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(O,g,`utf-8`),renameSync(O,E)}catch(t){try{unlinkSync(O)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${relPathOf(e.projectDir,E)}: ${t.message}`}}}return{ok:!0,path:relPathOf(e.projectDir,E),created:D,warnings:S}}function applyTemplateDelete(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:s,okDir:g,filePath:S}=templatePaths(e.projectDir,t.folderRel,e.name),w=existsSync(S);if(w)try{unlinkSync(S)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${relPathOf(e.projectDir,S)}: ${t.message}`}}}return{ok:!0,path:relPathOf(e.projectDir,S),existed:w,cleanedEmpty:cleanEmptyOkDirs(s,g)}}function cleanEmptyOkDirs(e,t){let s=!1,g=!1;if(existsSync(e)&&isEmpty(e))try{rmdirSync(e),s=!0}catch{}if(existsSync(t)&&isEmpty(t))try{rmdirSync(t),g=!0}catch{}return{templatesDir:s,okDir:g}}async function applyTemplateMove(e){let t=validateInputs(e.projectDir,e.fromFolder,e.fromName);if(!t.ok)return{ok:!1,error:t.error};let s=validateInputs(e.projectDir,e.toFolder,e.toName);if(!s.ok)return{ok:!1,error:s.error};let g=templatePaths(e.projectDir,t.folderRel,e.fromName),S=templatePaths(e.projectDir,s.folderRel,e.toName);if(g.filePath===S.filePath)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same template.`}};if(!existsSync(g.filePath))return{ok:!1,error:{code:`TEMPLATE_NOT_FOUND`,message:`No template at ${relPathOf(e.projectDir,g.filePath)}.`}};if(existsSync(S.filePath))return{ok:!1,error:{code:`TEMPLATE_EXISTS`,message:`A template already exists at ${relPathOf(e.projectDir,S.filePath)}.`}};try{mkdirSync(S.templatesDir,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create destination template directory at ${relPathOf(e.projectDir,S.templatesDir)}: ${t.message}`}}}let w;try{w=await e.relocate(g.filePath,S.filePath)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move template: ${e.message}`}}}let E=cleanEmptyOkDirs(g.templatesDir,g.okDir);return{ok:!0,fromPath:relPathOf(e.projectDir,g.filePath),toPath:relPathOf(e.projectDir,S.filePath),committed:w,cleanedEmpty:E}}function validateInputs(e,t,s){if(!isAbsolute(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!NAME_RE.test(s))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(s)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let g=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(g.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let S=g?resolve(e,g):e,w=resolve(e);return!S.startsWith(w+sep)&&S!==w?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${S}`}}:{ok:!0,folderRel:g}}function validateTitle(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function validateSubstitutionAllowlist(e){let t=validateSubstitution(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function templatePaths(e,t,s){let g=t?join(e,t,`.ok`):join(e,`.ok`),S=join(g,`templates`);return{okDir:g,templatesDir:S,filePath:join(S,`${s}.md`)}}function relPathOf(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function validateNoReservedDocKey(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return{ok:!0};let s=unwrapFrontmatterFences(t);return RegExp(`^template:`,`m`).test(s)?{ok:!1,error:{code:`TEMPLATE_RESERVED_KEY`,message:`Template starter content may not declare a top-level \`${TEMPLATE_IDENTITY_KEY}:\` frontmatter key — it is reserved for the template's identity.`}}:{ok:!0}}function isEmpty(e){try{return readdirSync(e).length===0}catch{return!1}}var RingBuffer=class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let s=1;s<=t;s++){let t=(this.writeIndex-s+this.capacity)%this.capacity,g=this.store[t];g!==void 0&&e.push(g)}return e}get size(){return this.filled?this.capacity:this.writeIndex}};const embedProbeRing=new RingBuffer(256);function recordEmbedProbe(e){embedProbeRing.push(e)}const CURSOR_UA_RE=UA_PATTERNS.cursor,CODEX_UA_RE=UA_PATTERNS.codex,CLAUDE_UA_RE=UA_PATTERNS[`claude-desktop`],CURSOR_REFERER_STRATEGY_LITERAL=`?strategy=C_iframe`,EMPTY_DETECTION={app:null,signals_fired:[]};function deriveDetection(e){if(!e)return{...EMPTY_DETECTION};let t=[],s=e.ua,g=e.referer,S=!!s&&CURSOR_UA_RE.test(s),w=!!g&&g.includes(CURSOR_REFERER_STRATEGY_LITERAL);if(S&&t.push(`cursor_ua_regex`),w&&t.push(`cursor_referer_strategy_iframe`),S||w)return{app:`cursor`,signals_fired:t};let E=!!s&&CODEX_UA_RE.test(s);if(E&&t.push(`codex_ua_regex`),E)return{app:`codex`,signals_fired:t};let D=!!s&&CLAUDE_UA_RE.test(s);return D&&t.push(`claude_ua_regex`),D?{app:`claude`,signals_fired:t}:{...EMPTY_DETECTION}}const log$17=getLogger(`embeddings`);let _tokens=null,_errors=null,_requestDuration=null,_queryTotal=null,_queryEmbedDuration=null;function tokensCounter(){return _tokens||=getMeter().createCounter(`ok.embeddings.tokens_total`,{description:`Embeddings tokens billed, by role. Bounded label: role ∈ {query, document}. Makes spend legible; never includes content.`}),_tokens}function errorsCounter(){return _errors||=getMeter().createCounter(`ok.embeddings.provider_errors_total`,{description:`Embeddings provider failures, by reason. Bounded label: reason ∈ {rate_limit, timeout, http_error, network, dims_mismatch, malformed_response}.`}),_errors}function requestDurationHist(){return _requestDuration||=getMeter().createHistogram(`ok.embeddings.request_duration_ms`,{description:`Wall-clock duration of one embeddings API request. Bounded label: role.`,unit:`ms`}),_requestDuration}function queryTotalCounter(){return _queryTotal||=getMeter().createCounter(`ok.search.semantic_query_total`,{description:`Semantic-requested searches, by outcome and caller surface. Bounded labels: outcome ∈ {applied, no_match, warming, incapable, provider_error}, source ∈ {omnibar, mcp, http}. The omnibar/mcp split separates interactive cost from agent cost.`}),_queryTotal}function queryEmbedDurationHist(){return _queryEmbedDuration||=getMeter().createHistogram(`ok.search.semantic_query_embed_ms`,{description:`Wall-clock latency of the per-query embed on the semantic search path.`,unit:`ms`}),_queryEmbedDuration}function recordEmbeddingTokens(e,t){t>0&&tokensCounter().add(t,{role:e})}function recordEmbeddingProviderError(e){errorsCounter().add(1,{reason:e})}function recordEmbeddingRequestDuration(e,t){requestDurationHist().record(Math.max(0,t),{role:e})}function recordSemanticQuery(e){queryTotalCounter().add(1,{outcome:e.outcome,source:e.source}),e.queryEmbedMs!==null&&queryEmbedDurationHist().record(Math.max(0,e.queryEmbedMs)),log$17.debug({outcome:e.outcome,source:e.source,capable:e.capable,embedded:e.embedded,total:e.total,coverage:e.total>0?e.embedded/e.total:0,queryEmbedMs:e.queryEmbedMs,vectorContributors:e.vectorContributors},`[search] semantic query`)}const DEFAULT_EMBEDDINGS_DIMENSIONS=1536,EMBEDDINGS_API_KEY_ENV=`OK_EMBEDDINGS_API_KEY`;var EmbeddingDimsMismatchError=class extends Error{name=`EmbeddingDimsMismatchError`;constructor(e,t){super(`embeddings provider returned ${t}-dim vectors, expected ${e}. Set search.semantic.dimensions to ${t} (or point at the right model).`),this.expected=e,this.got=t}},MalformedEmbeddingResponseError=class extends Error{name=`MalformedEmbeddingResponseError`;constructor(e,t){super(`embeddings response had ${t} vectors, expected ${e}`)}};function cosineSimilarity(e,t){let s=0,g=Math.min(e.length,t.length);for(let S=0;S<g;S++)s+=e[S]*t[S];return s}function normalizeInPlace(e){let t=0;for(let s=0;s<e.length;s++)t+=e[s]*e[s];if(t=Math.sqrt(t),t>0)for(let s=0;s<e.length;s++)e[s]/=t;return e}const DEFAULTS={maxBatchSize:96,maxBatchChars:96e3,docTimeoutMs:3e4,queryTimeoutMs:8e3,maxRetries:4,backoffBaseMs:500};function normalizeProviderId(e){try{let t=new URL(e),s=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${s}`}catch{return e.trim().replace(/\/+$/,``)}}function assertSafeEmbeddingsBaseUrl(e){let t=checkEmbeddingsBaseUrl(e);if(t===null)return;if(t===`invalid-url`)throw Error(`embeddings baseUrl is not a valid URL: ${e}`);let s=new URL(e);throw Error(`refusing to send the embeddings API key to a non-HTTPS endpoint (${s.protocol}//${s.host}); use https:// (http:// is allowed only for localhost)`)}const RETRYABLE_STATUS=new Set([408,409,429,500,502,503,504]);function defaultSleep$1(e){return new Promise(t=>setTimeout(t,e))}function createOpenAiEmbedder(e,t={}){let s=t.fetchImpl??fetch,g=t.sleep??defaultSleep$1,S=t.maxBatchSize??DEFAULTS.maxBatchSize,w=t.maxBatchChars??DEFAULTS.maxBatchChars,E=t.maxRetries??DEFAULTS.maxRetries,D=t.backoffBaseMs??DEFAULTS.backoffBaseMs,O=t.docTimeoutMs??DEFAULTS.docTimeoutMs,k=t.queryTimeoutMs??DEFAULTS.queryTimeoutMs;assertSafeEmbeddingsBaseUrl(e.baseUrl);let j=e.dimensions??1536,F=`${e.baseUrl.replace(/\/+$/,``)}/embeddings`;function L(e){let t=[],s=[],g=0;for(let E of e)s.length>0&&(s.length>=S||g+E.length>w)&&(t.push(s),s=[],g=0),s.push(E),g+=E.length;return s.length>0&&t.push(s),t}async function B(t,g,S,w){let E=new AbortController,D=setTimeout(()=>E.abort(),w),O=performance.now();try{let w=await s(F,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.apiKey}`},body:t,signal:E.signal});if(recordEmbeddingRequestDuration(S,performance.now()-O),!w.ok){await w.text().catch(()=>``);let e=w.status===429?`rate_limit`:`http_error`,t=Error(`embeddings request failed: HTTP ${w.status}`);return RETRYABLE_STATUS.has(w.status)?{kind:`retry`,reason:e,error:t}:{kind:`fatal`,reason:e,error:t}}let D=await w.json(),k=q(D,g,j);return recordEmbeddingTokens(S,D.usage?.total_tokens??0),{kind:`ok`,vectors:k}}catch(e){if(e instanceof EmbeddingDimsMismatchError)return{kind:`fatal`,reason:`dims_mismatch`,error:e};if(e instanceof MalformedEmbeddingResponseError)return{kind:`fatal`,reason:`malformed_response`,error:e};let t=e instanceof Error&&e.name===`AbortError`,s=e instanceof Error?e:Error(String(e));return{kind:`retry`,reason:t?`timeout`:`network`,error:s}}finally{clearTimeout(D)}}async function H(t,s){let S=s===`query`?k:O,w=s===`query`?`query`:`document`,j=JSON.stringify({model:e.model,input:t,encoding_format:`float`,...e.dimensions===void 0?{}:{dimensions:e.dimensions}}),F=0;for(;;){let e=await B(j,t.length,w,S);if(e.kind===`ok`)return e.vectors;if(recordEmbeddingProviderError(e.reason),e.kind===`fatal`||F>=E)throw e.error;F+=1;let s=D*2**(F-1);await g(Math.round(s/2+s/2*Math.random()))}}function q(e,t,s){let g=e.data;if(!Array.isArray(g)||g.length!==t)throw new MalformedEmbeddingResponseError(t,g?.length??0);let S=[...g].sort((e,t)=>(e.index??0)-(t.index??0)),w=[];for(let e of S){let g=e.embedding;if(!Array.isArray(g))throw new MalformedEmbeddingResponseError(t,0);if(g.length!==s)throw new EmbeddingDimsMismatchError(s,g.length);w.push(normalizeInPlace(Float32Array.from(g)))}return w}return{providerId:normalizeProviderId(e.baseUrl),modelId:e.model,dims:j,async embed(e,{role:t}){if(e.length===0)return[];let s=[];for(let g of L(e))s.push(...await H(g,t));return s}}}async function loadOpenAiEmbedder(e){let t=(e.keyStore?await e.keyStore.get().catch(()=>null):null)??process.env.OK_EMBEDDINGS_API_KEY??null;return t?createOpenAiEmbedder({...e.config,apiKey:t},e.options):null}const SECRETS_KEY_FIELD=`OPENAI_API_KEY`,LEGACY_KEY_FIELD=`embeddings`;function secretsFilePath(e){return join(e??homedir(),`.ok`,`secrets.yml`)}var FileEmbeddingsBackend=class{backend=`file`;secretsFile;constructor(e){this.secretsFile=e??secretsFilePath()}tightenPermsIfLoose(){let e;try{e=statSync(this.secretsFile).mode&511}catch{return}if(e&63)try{chmodSync(this.secretsFile,384),process.stderr.write(`[embeddings] ${this.secretsFile} was readable beyond your user account (mode ${e.toString(8)}); tightened to 600. It stores an API key.\n`)}catch(t){let s=t instanceof Error?t.message:`unknown error`;process.stderr.write(`[embeddings] ${this.secretsFile} is readable beyond your user account (mode ${e.toString(8)}) and could not be tightened (${s}); your API key remains exposed — run: chmod 600 ${this.secretsFile}\n`)}}read(){if(!existsSync(this.secretsFile))return{};this.tightenPermsIfLoose();try{return(0,import_dist$1.parse)(readFileSync(this.secretsFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[embeddings] Failed to parse ${this.secretsFile}: ${t}. Starting with empty secrets.\n`),{}}}write(e){let t=dirname(this.secretsFile);existsSync(t)||tracedMkdirSync(t,{recursive:!0,mode:448}),tracedWriteFileSync(this.secretsFile,(0,import_dist$1.stringify)(e),{mode:384}),chmodSync(this.secretsFile,384)}get(){let e=this.read(),t=e[SECRETS_KEY_FIELD]??e[LEGACY_KEY_FIELD];return Promise.resolve(typeof t==`string`&&t!==``?t:null)}set(e){let t=this.read();return delete t[LEGACY_KEY_FIELD],t[SECRETS_KEY_FIELD]=e,this.write(t),Promise.resolve()}clear(){let e=this.read();if(SECRETS_KEY_FIELD in e||LEGACY_KEY_FIELD in e)if(delete e[SECRETS_KEY_FIELD],delete e[LEGACY_KEY_FIELD],Object.keys(e).length===0)try{tracedUnlinkSync(this.secretsFile)}catch{}else this.write(e);return Promise.resolve()}};function createEmbeddingsSecretStore(e){return new FileEmbeddingsBackend(e)}function makeLazyEmbeddingsKeyStore(e){return new FileEmbeddingsBackend(e)}async function describeStoredEmbeddingsKey(e){return{file:await new FileEmbeddingsBackend(e).get()!=null}}async function clearEmbeddingsKeyFromAllBackends(e){let t=[],s=new FileEmbeddingsBackend(e);return await s.get()!=null&&(await s.clear(),t.push(`file`)),{touched:t}}function readProjectLocalSemanticConfig(e,t){let s=readConfigSafely({absPath:resolveConfigPath(`project-local`,e,t?.configHomedirOverride),sideline:!1,warn:t?.onWarn??(()=>{})}).value.search?.semantic;return{enabled:s?.enabled===!0,baseUrl:s?.baseUrl??`https://api.openai.com/v1`,model:s?.model??`text-embedding-3-small`,dimensions:s?.dimensions??void 0,similarityFloor:s?.similarityFloor??void 0}}const CHUNK_CONFIG_ID=`c8000-o400-m80`;function chunkDocument(e,t={}){let s=Math.max(1,t.targetChars??8e3),g=Math.max(0,Math.min(t.overlapChars??400,s-1)),S=t.maxChunks??80;if(e.trim().length===0)return[];if(e.length<=s)return[e.trim()];let w=[],E=0;for(;E<e.length&&w.length<S;){let t=Math.min(e.length,E+s);if(t<e.length){let g=Math.max(e.lastIndexOf(` `,t),e.lastIndexOf(`
827
+ `,t));g>E+Math.floor(s/2)&&(t=g)}let S=e.slice(E,t).trim();if(S&&w.push(S),t>=e.length)break;let D=t-g;E=D>E?D:t}return w}const log$16=getLogger(`embeddings`),MANIFEST_SCHEMA_VERSION$1=1,VEC_SUBDIR=`vec`,MANIFEST_NAME$1=`manifest.json`;function hashContent(e){return createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function serializeVectors(e){let t=0;for(let s of e)t+=s.length;let s=new Float32Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function deserializeVectors(e,t){let s=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),g=new Float32Array(s);if(g.length%t!==0)throw Error(`vector blob length ${g.length} is not a multiple of dims ${t}`);let S=[];for(let e=0;e<g.length;e+=t)S.push(g.slice(e,e+t));return S}var VectorCache=class{cacheDir;vecDir;manifestPath;providerId;modelId;dims;chunkConfigId;entries=new Map;vectorsByHash=new Map;persistedHashes=new Set;dirty=!1;constructor(e){this.cacheDir=e.cacheDir,this.vecDir=e.cacheDir?join(e.cacheDir,VEC_SUBDIR):null,this.manifestPath=e.cacheDir?join(e.cacheDir,MANIFEST_NAME$1):null,this.providerId=e.providerId,this.modelId=e.modelId,this.dims=e.dims,this.chunkConfigId=e.chunkConfigId}async init(){if(!this.cacheDir||!this.manifestPath||!this.vecDir)return;let e=null;try{existsSync(this.manifestPath)&&(e=JSON.parse(await readFile$1(this.manifestPath,`utf-8`)))}catch(t){log$16.warn({err:t instanceof Error?t.message:String(t)},`[embeddings] unreadable cache manifest — rebuilding`),e=null}if(!(e!==null&&e.schemaVersion===MANIFEST_SCHEMA_VERSION$1&&e.providerId===this.providerId&&e.modelId===this.modelId&&e.dims===this.dims&&e.chunkConfigId===this.chunkConfigId)){e!==null&&log$16.info({hadModel:e.modelId,wantModel:this.modelId},`[embeddings] cache identity changed (provider/model/dims/chunking) — invalidating`),this.wipeDisk();return}if(e){for(let[t,s]of Object.entries(e.entries))if(s?.contentHash&&(this.entries.set(t,{contentHash:s.contentHash,mtimeMs:s.mtimeMs??0}),!this.vectorsByHash.has(s.contentHash)))try{let e=join(this.vecDir,`${s.contentHash}.bin`);if(existsSync(e)){let t=await readFile$1(e);this.vectorsByHash.set(s.contentHash,deserializeVectors(t,this.dims)),this.persistedHashes.add(s.contentHash)}}catch(e){log$16.warn({hash:s.contentHash,err:e instanceof Error?e.message:String(e)},`[embeddings] corrupt vector blob — will re-embed`)}}}isFresh(e,t){let s=this.entries.get(e);return s!==void 0&&s.mtimeMs===t&&this.vectorsByHash.has(s.contentHash)}link(e,t,s){if(!this.vectorsByHash.has(t))return!1;let g=this.entries.get(e);return(!g||g.contentHash!==t||g.mtimeMs!==s)&&(this.dirty=!0),this.entries.set(e,{contentHash:t,mtimeMs:s}),!0}store(e,t,s,g){this.vectorsByHash.set(t,g),this.entries.set(e,{contentHash:t,mtimeMs:s}),this.dirty=!0}getVectors(e){let t=this.entries.get(e);if(t)return this.vectorsByHash.get(t.contentHash)}get embeddedCount(){let e=0;for(let t of this.entries.values()){let s=this.vectorsByHash.get(t.contentHash);s&&s.length>0&&(e+=1)}return e}retain(e){for(let t of this.entries.keys())e.has(t)||(this.entries.delete(t),this.dirty=!0);let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of this.vectorsByHash.keys())t.has(e)||this.vectorsByHash.delete(e)}clearMemory(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.dirty=!1}async persist(){if(!(!this.cacheDir||!this.manifestPath||!this.vecDir)&&this.dirty)try{await tracedMkdir(this.vecDir,{recursive:!0});let e=new Set;for(let t of this.entries.values())e.add(t.contentHash);for(let t of e){if(this.persistedHashes.has(t))continue;let e=this.vectorsByHash.get(t);e&&(await tracedWriteFile(join(this.vecDir,`${t}.bin`),serializeVectors(e)),this.persistedHashes.add(t))}let t={schemaVersion:MANIFEST_SCHEMA_VERSION$1,providerId:this.providerId,modelId:this.modelId,dims:this.dims,chunkConfigId:this.chunkConfigId,entries:Object.fromEntries(this.entries)},s=`${this.manifestPath}.tmp`;await tracedWriteFile(s,JSON.stringify(t)),await tracedRename(s,this.manifestPath);for(let t of readdirSync(this.vecDir)){if(!t.endsWith(`.bin`))continue;let s=t.slice(0,-4);e.has(s)||(tracedUnlinkSync(join(this.vecDir,t)),this.persistedHashes.delete(s))}this.dirty=!1}catch(e){log$16.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to persist vector cache`)}}wipeDisk(){if(this.cacheDir)try{tracedRmSync(this.cacheDir,{recursive:!0,force:!0})}catch(e){log$16.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to wipe stale cache`)}}};const log$15=getLogger(`embeddings`);function errMsg(e){return e instanceof Error?e.message:String(e)}const EMBED_BATCH_CHUNK_LIMIT=96,MAX_CONSECUTIVE_EMBED_FAILURES=5;var SemanticSearchService=class{loadEmbedder;cacheDir;enabled;providerFingerprint;capable=!1;ready=!1;embedder=null;cache=null;warmPromise=null;embedChain=Promise.resolve();queuedDocs=null;constructor(e){this.loadEmbedder=e.loadEmbedder,this.cacheDir=e.cacheDir,this.enabled=e.enabled??!1,this.providerFingerprint=e.providerFingerprint??``}isEnabled(){return this.enabled}getStatus(){return{enabled:this.enabled,capable:this.capable,ready:this.ready,embeddedCount:this.cache?.embeddedCount??0}}applyConfig(e){e.providerFingerprint!==this.providerFingerprint&&(this.providerFingerprint=e.providerFingerprint,this.resetWarm()),e.enabled!==this.enabled&&(this.enabled=e.enabled,e.enabled||(this.cache?.clearMemory(),this.resetWarm()))}resetWarm(){this.warmPromise=null,this.ready=!1,this.capable=!1,this.embedder=null,this.cache=null}ensureWarm(){return!this.enabled||this.ready?Promise.resolve():(this.warmPromise||=this.warm(),this.warmPromise)}async warm(){try{let e=await this.loadEmbedder();if(!e){this.capable=!1,this.ready=!0,log$15.info({},`[embeddings] no embeddings key configured — semantic search degrades to lexical`);return}this.embedder=e,this.cache=new VectorCache({cacheDir:this.cacheDir,providerId:e.providerId,modelId:e.modelId,dims:e.dims,chunkConfigId:CHUNK_CONFIG_ID}),await this.cache.init(),this.capable=!0,this.ready=!0}catch(e){this.capable=!1,this.ready=!0,log$15.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] warm failed`)}}embedCorpus(e){return this.enabled?(this.queuedDocs=e,this.embedChain=this.embedChain.then(async()=>{let e=this.queuedDocs;if(e){this.queuedDocs=null;try{await this.runEmbedPass(e)}catch(e){log$15.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] embed pass failed`)}}}),this.embedChain):Promise.resolve()}async runEmbedPass(e){if(await this.ensureWarm(),!this.enabled||!this.embedder||!this.cache)return;let t=this.cache,s=this.embedder,g=e.filter(e=>e.kind===`page`),S=new Set(g.map(e=>e.id)),w=[];for(let e of g){if(!this.enabled)return;let s=e.modifiedTs;if(t.isFresh(e.id,s))continue;let g=hashContent(e.content);t.link(e.id,g,s)||w.push({doc:e,contentHash:g,chunks:chunkDocument(e.content)})}let E=0,D=(e,s)=>{t.store(e.doc.id,e.contentHash,e.doc.modifiedTs,s)},O=async e=>{let t=e.flatMap(e=>e.chunks);try{let g=t.length?await s.embed(t,{role:`document`}):[],S=0;for(let t of e)D(t,g.slice(S,S+t.chunks.length)),S+=t.chunks.length;return E=0,!0}catch(t){if(e.length===1)return log$15.warn({docId:e[0].doc.id,err:errMsg(t)},`[embeddings] failed to embed document`),E+=1,E<MAX_CONSECUTIVE_EMBED_FAILURES;for(let t of e){if(!this.enabled)return!1;try{D(t,t.chunks.length?await s.embed(t.chunks,{role:`document`}):[]),E=0}catch(e){if(log$15.warn({docId:t.doc.id,err:errMsg(e)},`[embeddings] failed to embed document`),E+=1,E>=MAX_CONSECUTIVE_EMBED_FAILURES)return!1}}return!0}},k=[],j=0;for(let e of w){if(!this.enabled)break;if(k.push(e),j+=Math.max(1,e.chunks.length),j>=EMBED_BATCH_CHUNK_LIMIT){let e=await O(k);if(k=[],j=0,!e)break}}k.length>0&&this.enabled&&await O(k),!(!this.enabled||this.cache!==t)&&(t.retain(S),await t.persist())}async queryScores(e,t){if(!this.enabled||!this.capable||!this.ready||!this.embedder||!this.cache||this.cache.embeddedCount===0)return null;let s=e.trim();if(!s)return null;let g;try{[g]=await this.embedder.embed([s],{role:`query`})}catch(e){return log$15.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] query embed failed — degrading to lexical`),null}if(!g)return null;let S=new Map;for(let e of t){let t=this.cache.getVectors(e.id);if(!t||t.length===0)continue;let s=-1/0;for(let e of t){let t=cosineSimilarity(g,e);t>s&&(s=t)}s>-1/0&&S.set(e.id,s)}return S}};const log$14=()=>getLogger(`http`);function successResponse(e,t,s,g,S={}){if(e.headersSent||e.writableEnded||e.destroyed){log$14().error({event:`api.success.double-write`,status:t,handler:S.handler},`successResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let w=s.safeParse(g);if(!w.success){log$14().error({event:`api.success.malformed-body`,issues:w.error.issues,bodyKeys:typeof g==`object`&&g?Object.keys(g):null,handler:S.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}let E;try{E=JSON.stringify(w.data)}catch(s){log$14().error({event:`api.success.unserializable-body`,bodyKeys:typeof w.data==`object`&&w.data!==null?Object.keys(w.data):null,handler:S.handler,originalStatus:t,err:s},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(E)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,s=e.now??Date.now,g=e.ttlMs??6e4;async function S(S){let w=t.get(S);if(w?.status===`resolved`&&w.expiresAt>s())return w.installed;if(w?.status===`inflight`)return w.promise;let E=(async()=>{try{let w=await e.probe(S);return t.set(S,{status:`resolved`,installed:w,expiresAt:s()+g}),w}catch{return t.set(S,{status:`resolved`,installed:!1,expiresAt:s()+g}),!1}})();return t.set(S,{status:`inflight`,promise:E}),E}async function w(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await S(e)]));return Object.fromEntries(e)}return{probeAll:w,probeWithCache:S}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let s=e.headers.origin;if(typeof s==`string`&&s.length>0)try{return isLoopbackHostname(new URL(s).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await s():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return s=>e===`darwin`?probeMacOs(s,t):e===`win32`?probeWindows(s,t):probeLinux(s,t)}function probeMacOs(e,t){let s=MACOS_APP_NAMES[e];function g(e){return new Promise(s=>{t(`osascript`,[`-e`,`id of app "${e}"`],withHiddenWindowsConsole({timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`}),(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}return(async()=>{for(let e of s)if(await g(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(s=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],withHiddenWindowsConsole({timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`}),e=>{s(!e)})})}function probeLinux(e,t){return new Promise(s=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],withHiddenWindowsConsole({timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`}),(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let s=[],g=0,S=AbortSignal.timeout(t.timeoutMs),w=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));S.addEventListener(`abort`,w,{once:!0});try{for await(let S of e){if(g+=S.length,g>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);s.push(S)}return Buffer.concat(s)}finally{S.removeEventListener(`abort`,w)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,s,g={}){let S=e.safeParse(t);if(S.success)return{ok:!0,value:S.data};let w=S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(s,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:g.handler,detail:w}),{ok:!1}}function withValidation(e,t,s={}){return async(g,S)=>{if(s.method!==void 0&&g.method!==s.method){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:s.handler,extraHeaders:{Allow:s.method}});return}if(s.preBodyGate!==void 0&&!s.preBodyGate(g,S)){!S.headersSent&&!S.writableEnded&&!S.destroyed&&errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(s.skipBodyParse){let w=validateBody(e,{},S,s);if(!w.ok)return;await t(g,S,w.value);return}let w;try{w=await readRequestBody(g)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(S,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(S,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s.handler,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s.handler,cause:e});return}let E;try{E=w.length===0?{}:JSON.parse(w.toString(`utf8`))}catch(e){errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:s.handler,cause:e});return}let D=validateBody(e,E,S,s);D.ok&&await t(g,S,D.value)}}const DETACHED_IGNORED_STDIO_OPTIONS={detached:!0,stdio:`ignore`,shell:!1};function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,s){return new Promise(g=>{let S=!1,w=e=>{S||(S=!0,g(e))},E=setTimeout(()=>w({ok:!1,reason:`timeout`}),s);try{let s=spawn(e,[...t],withHiddenWindowsConsole(DETACHED_IGNORED_STDIO_OPTIONS));s.once(`error`,e=>{clearTimeout(E),w(classifySpawnError(e))}),s.once(`spawn`,()=>{if(!S){try{s.unref()}catch{}clearTimeout(E),w({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(E),w(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let w=typeof S.path==`string`?S.path:``;if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(w,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let E=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!E){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let D=resolveCursorSpawnInvocation(E,w,s.platform),O=await(s.spawnDetached??spawnDetached)(D.exec,D.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(O.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(O.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(O.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let s of t){let t=s(e);try{return await access(t,constants$1.X_OK),t}catch(e){let s=e?.code;s!==`ENOENT`&&s!==`EACCES`&&s!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,s,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],withHiddenWindowsConsole({timeout:e,encoding:`utf-8`}),(e,s)=>{if(e){t(null);return}let g=s.split(/\r?\n/)[0]?.trim();t(g&&g.length>0?g:null)})})}function resolveCursorSpawnInvocation(e,t,s){return s===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:s===`win32`&&/\.(cmd|bat)$/i.test(e)?{exec:process.env.ComSpec||`cmd.exe`,args:[`/d`,`/c`,e,t]}:{exec:e,args:[t]}}function isPathWithinDir(e,t,s){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(s===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let g=s===`win32`?win32:posix;try{let S=g.resolve(e),w=g.resolve(t);if(s===`win32`){let e=g.parse(S).root.toLowerCase(),t=g.parse(w).root.toLowerCase();if(!e||!t||e!==t)return!1}if(S===w)return!0;let E=g.relative(w,S);return E===``||E===`.`?!0:!(E===`..`||E.startsWith(`..${g.sep}`)||s===`win32`&&(/^[a-zA-Z]:[\\/]/.test(E)||E.startsWith(`\\\\`))||s!==`win32`&&E.startsWith(`/`))}catch(e){return console.warn(`[spawn-cursor] unexpected path-resolution error:`,e),!1}}const HANDLER=`handoff`,HANDOFF_MAX_BODY_BYTES=4*1024,HANDOFF_BODY_READ_TIMEOUT_MS=5e3,SPAWN_TIMEOUT_MS$1=2e3,WHICH_TIMEOUT_MS=500,QUIT_SETTLE_MS=3e3,APP_BUNDLE_SETTLE_MS=5e3,CURSOR_SETTLE_MS=1500,RECIPES={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},TARGET_VALUES=Object.keys(RECIPES),HandoffRequestSchema=object$1({target:_enum(TARGET_VALUES),url:string().min(1).max(4096),workspacePath:string().optional()}),HandoffSuccessSchema=object$1({}).loose();function defaultSleep(e){return new Promise(t=>setTimeout(t,e))}async function handleHandoffDispatch(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:HANDOFF_MAX_BODY_BYTES,timeoutMs:HANDOFF_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER,cause:e});return}let w=HandoffRequestSchema.safeParse(S);if(!w.success){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:HANDLER});return}let{target:E,url:D,workspacePath:O}=w.data,k=RECIPES[E];if(!D.startsWith(k.urlScheme)){errorResponse(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${k.urlScheme} for target ${E}.`,{handler:HANDLER});return}let j=s.sleep??defaultSleep,F=s.spawnDetached??spawnDetached,L=s.isSchemeRegistered??createOsProbe(s.platform);if(k.type===`app-bundle`){if(s.platform===`darwin`){k.quitFirst&&(await F(`/usr/bin/osascript`,[`-e`,`tell application "${k.appName}" to quit`],SPAWN_TIMEOUT_MS$1).catch(()=>void 0),await j(QUIT_SETTLE_MS));let e=await F(`/usr/bin/open`,[`-a`,k.appName],SPAWN_TIMEOUT_MS$1);if(!e.ok){emitSpawnFailure(t,E,e.reason);return}await j(APP_BUNDLE_SETTLE_MS)}else if(!await L(k.probeScheme)){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:E}});return}let e=resolveUrlOpenInvocation(D,s.platform),g=await F(e.exec,e.args,SPAWN_TIMEOUT_MS$1);if(!g.ok){emitSpawnFailure(t,E,g.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER});return}if(!O){errorResponse(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:HANDLER});return}if(!isPathWithinDir(O,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER});return}let B=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!B){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let H=resolveCursorSpawnInvocation(B,O,s.platform),q=await F(H.exec,H.args,SPAWN_TIMEOUT_MS$1);if(!q.ok){emitSpawnFailure(t,E,q.reason);return}await j(CURSOR_SETTLE_MS);let ee=resolveUrlOpenInvocation(D,s.platform),J=await F(ee.exec,ee.args,SPAWN_TIMEOUT_MS$1);if(!J.ok){emitSpawnFailure(t,E,J.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}function resolveUrlOpenInvocation(e,t){return t===`darwin`?{exec:`/usr/bin/open`,args:[e]}:t===`win32`?{exec:`rundll32.exe`,args:[`url.dll,FileProtocolHandler`,e]}:{exec:`xdg-open`,args:[e]}}function emitSpawnFailure(e,t,s){switch(s){case`not-installed`:errorResponse(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:t}});return;case`timeout`:errorResponse(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:HANDLER,extensions:{target:t}});return;case`spawn-error`:errorResponse(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:HANDLER,extensions:{target:t}});return;default:assertNeverReason(s)}}function assertNeverReason(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let s=[],g=new Set,S=t=>{!t||g.has(t)||t!==e&&(g.add(t),s.push(t))},w=buildLowerDocNameIndex(t),E=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(S(lookup$1$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES)return s;let e=E===``?null:basename$1(E);if(e&&(S(lookup$1$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES))return s;if(E===``)break;E=parentFolder(E)}return s}function lookup$1$1(e,t,s){return e.has(s)?s:t.get(s.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let s of e.keys()){let e=s.toLowerCase();t.has(e)||t.set(e,s)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}const logger$5=getLogger(`installed-skills-marker`),TRACED_FS_ADAPTER={writeFile:(e,t,s)=>tracedWriteFile(e,t,s),rename:(e,t)=>tracedRename(e,t)};function installedSkillsPath(e){return join(e,...INSTALLED_SKILLS_REL)}const markerWriteChains=new Map;function withMarkerLock(e,t){let s=installedSkillsPath(e),g=(markerWriteChains.get(s)??Promise.resolve()).then(t,t);return markerWriteChains.set(s,g.then(()=>void 0,()=>void 0)),g}function readInstalledSkills(e){let t=installedSkillsPath(e);if(!existsSync(t))return emptyInstalledSkills();try{return parseInstalledSkills(readFileSync(t,`utf-8`))??emptyInstalledSkills()}catch(e){return logger$5.warn({err:e,path:t},`installed-skills marker unreadable`),emptyInstalledSkills()}}async function writeInstalledSkills(e,t){let s=InstalledSkillsSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid installed-skills marker: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=installedSkillsPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s.data,null,2)}\n`,{fs:TRACED_FS_ADAPTER})}async function recordSkillInstall(e,t,s){return withMarkerLock(e,async()=>{let g=readInstalledSkills(e);await writeInstalledSkills(e,{...g,skills:{...g.skills,[t]:s}})})}async function removeSkillInstall(e,t){return withMarkerLock(e,async()=>{let s=readInstalledSkills(e),g=s.skills[t]??null;if(g===null)return null;let{[t]:S,...w}=s.skills;return await writeInstalledSkills(e,{...s,skills:w}),g})}const log$13=getLogger(`mermaid-validator`),MAX_FENCE_BYTES=1e5,MAX_FENCE_LINES=2e3,MAX_FENCES_PARSED=20,TOTAL_PARSE_BUDGET_MS=2e3,MAX_WARNINGS=10,MAX_MESSAGE_CHARS=500,MAX_FIRST_LINE_CHARS=200;let initPromise=null;function extractMermaidFences(e){let t=[],s=e.split(`
828
828
  `),g=e=>e.endsWith(`\r`)?e.slice(0,-1):e,S=0;for(;S<s.length;){let e=g(s[S]??``),w=e.match(/^ {0,3}(`{3,}|~{3,})[ \t]*([^\s`]*)/);if(!w){S++;continue}let E=w[1]??``,D=E[0]??"`";if(D==="`"&&e.slice(e.indexOf(E)+E.length).includes("`")){S++;continue}let O=w[2]??``,k=RegExp(`^ {0,3}\\${D}{${E.length},}[ \t]*$`),j=[],F=S+1;for(;F<s.length&&!k.test(g(s[F]??``));)j.push(s[F]??``),F++;if(O===`mermaid`){let e=j.join(`
829
829
  `),s=(j.find(e=>e.trim().length>0)?.trim()??``).slice(0,MAX_FIRST_LINE_CHARS);t.push({firstLine:s,body:e})}S=F+1}return t}async function initMermaid(){let{Window:e}=await import(`./lib-BLR9KuxL.mjs`),t=new e({url:`http://localhost/`}),s={window:t,document:t.document,navigator:t.navigator,location:t.location,DOMParser:t.DOMParser,Element:t.Element,Node:t.Node,SVGElement:t.SVGElement,HTMLElement:t.HTMLElement,MutationObserver:t.MutationObserver},g=new Map;try{for(let[e,t]of Object.entries(s))g.set(e,Object.getOwnPropertyDescriptor(globalThis,e)),Object.defineProperty(globalThis,e,{value:t,configurable:!0,writable:!0});let e=(await import(`./mermaid.core-DyEIpJO9.mjs`)).default;return e.initialize({startOnLoad:!1,securityLevel:`strict`,suppressErrorRendering:!0}),await e.parse(`graph LR
830
- A-->B`),e}finally{for(let[e,t]of g)t?Object.defineProperty(globalThis,e,t):delete globalThis[e]}}function getMermaid(e){return initPromise??=initMermaid().catch(t=>(log$12.warn({err:t,"doc.name":e},`mermaid validator unavailable — render validation disabled for this process`),null)),initPromise}function extractLineNumber(e){let t=e.match(/Parse error on line (\d+)/);if(!t?.[1])return;let s=Number(t[1]);return Number.isSafeInteger(s)&&s>0?s:void 0}async function validateMermaidFences(e,t){try{if(!e.includes(`mermaid`))return;let{body:s}=detectFmRegion(e),g=extractMermaidFences(s);if(g.length===0)return;let S=performance.now(),w=await getMermaid(t);if(w===null)return;let E=performance.now(),D=[],O=0;for(let e=0;e<g.length&&D.length<MAX_WARNINGS&&!(O>=MAX_FENCES_PARSED);e++){if(performance.now()-E>TOTAL_PARSE_BUDGET_MS){log$12.debug({"doc.name":t,skippedFrom:e+1,fences:g.length},`mermaid validation budget exceeded — remaining fences skipped`);break}let s=g[e];if(s!==void 0){if(s.body.length>MAX_FENCE_BYTES||s.body.split(`
831
- `).length>MAX_FENCE_LINES){log$12.debug({"doc.name":t,fenceIndex:e+1},`mermaid fence over validation caps — skipped`);continue}try{O++,await w.parse(s.body)}catch(g){if(g instanceof TypeError){log$12.debug({err:g,"doc.name":t,fenceIndex:e+1},`mermaid validation skipped fence — environment failure`);continue}let S=g instanceof Error?g.message:String(g),w=S.slice(0,MAX_MESSAGE_CHARS),E=extractLineNumber(S);D.push({kind:`mermaid-parse-error`,fenceIndex:e+1,fenceFirstLine:s.firstLine,message:w,...E===void 0?{}:{line:E}})}}}let k=Math.round(performance.now()-S);if(D.length===0){k>250&&log$12.debug({"doc.name":t,durationMs:k,fences:g.length},`mermaid validation slow (no warnings)`);return}return log$12.debug({"doc.name":t,count:D.length,durationMs:k},`mermaid render warnings emitted`),D}catch(e){log$12.warn({err:e,"doc.name":t},`mermaid validation errored unexpectedly — skipped`);return}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidSharePath(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,s,g){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(s)}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function buildGitHubTreeUrl(e,t,s,g){let S=`https://github.com/${e}/${t}/tree/${encodeURIComponent(s)}`;return g===``?S:`${S}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let s=t?.branchExists,g=t?.kind,S=t?.freshness;getLogger(`share`).info({action:`construct-url`,result:e,...s===void 0?{}:{branchExists:s},...g===void 0?{}:{kind:g},...S===void 0?{}:{freshness:S}},`share action`)}function truncateError(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}const FRESHNESS_PROBE_TIMEOUT_MS=5e3;async function computeShareFreshness(e,t,s,g){try{let{git:g}=createGitInstance(e,{timeoutMs:FRESHNESS_PROBE_TIMEOUT_MS}),S=`refs/remotes/origin/${t}`;await g.raw([`rev-parse`,`--verify`,S]);let w=s===``?`.`:s,[E,D,O]=await Promise.all([g.raw([`cat-file`,`-e`,`${S}:${s}`]).then(()=>!0).catch(()=>!1),g.raw([`diff`,`--name-only`,S,`--`,w]),g.raw([`status`,`--porcelain`,`--untracked-files=all`,`--`,w])]);return E?D.trim()!==``||O.trim()!==``?`stale`:`current`:`absent`}catch(e){let t=truncateError(e);getLogger(`share`).warn({action:`freshness-probe-failed`,kind:g,error:t},`[share] freshness probe failed; omitting freshness`);return}}const log$11=getLogger(`git-context`);function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let s;try{s=statSync(t)}catch{return null}if(s.isDirectory())return t;if(s.isFile()){let s;try{s=readFileSync(t,`utf-8`)}catch{return null}let g=/^gitdir:\s*(.+)$/m.exec(s.trim());if(!g)return null;let S=g[1].trim(),w=isAbsolute(S)?S:resolve(e,S);return existsSync(w)?w:null}return null}function resolveCommonDir(e){let t=join(e,`commondir`);if(!existsSync(t))return e;let s;try{s=readFileSync(t,`utf-8`).trim()}catch{return e}return s.length===0?e:isAbsolute(s)?s:resolve(e,s)}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(t,`HEAD`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=/^ref:\s*refs\/heads\/(.+)$/.exec(g.trim());return S?S[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),s=e.indexOf(`;`),g=-1;return t>=0&&s>=0?g=Math.min(t,s):t>=0?g=t:s>=0&&(g=s),(g===-1?e:e.slice(0,g)).trim()}function extractOriginUrl(e){let t=!1;for(let s of e.split(/\r?\n/)){let e=stripCommentAndTrim(s);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let g=/^url\s*=\s*(.+)$/.exec(e);if(!g)continue;let S=g[1].trim();if((S.startsWith(`"`)&&S.endsWith(`"`)||S.startsWith(`'`)&&S.endsWith(`'`))&&(S=S.slice(1,-1)),S.length>0)return S}return null}function normalizeGitHost(e){let t=e.toLowerCase().replace(/:\d+$/,``);return t===`www.github.com`?`github.com`:t}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let s=(e,t,s)=>{let g=normalizeGitHost(e);return KNOWN_NON_GITHUB_GIT_HOSTS.has(g)?null:{host:g,owner:t,repo:s}},g=/^https?:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return g||(g=/^ssh:\/\/(?:[\w.-]+@)?([\w.-]+)(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),g)||(g=/^[\w.-]+@([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),g)||(g=/^git:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),g)?s(g[1],g[2],g[3]):null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(resolveCommonDir(t),`config`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=extractOriginUrl(g);return S?{originUrl:S,github:parseGitHubOriginUrl(S)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);if(!t)return{kind:`no-remote`};if(t.github){let{host:e,owner:s,repo:g}=t.github;return{kind:`ok`,host:e,owner:s,repo:g}}return{kind:`non-github`}}function originGitHubHost(e){let t=readOriginGitHubRepo(e);return t.kind===`ok`?t.host:(log$11.debug({kind:t.kind},`[git-context] origin is not a GitHub host — falling back to github.com`),`github.com`)}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);if(!t)return null;if(t.github){let{host:e,owner:s,repo:g}=t.github;return{label:e===`github.com`?`${s}/${g}`:`${e}/${s}/${g}`,webUrl:`https://${e}/${s}/${g}`}}return{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),s=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(s)return`${s[1]}/${s[2]}`;let g=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return g?g[1]:t}function branchExistsOnOrigin(e,t){let s=resolveGitDir$1(e);if(!s)return!1;let g=resolveCommonDir(s);if(existsSync(join(g,`refs`,`remotes`,`origin`,t)))return!0;let S=join(g,`packed-refs`);if(!existsSync(S))return!1;let w;try{w=readFileSync(S,`utf-8`)}catch{return!1}let E=`refs/remotes/origin/${t}`;for(let e of w.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let s=t.split(/\s+/);if(s.length===2&&s[1]===E)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
830
+ A-->B`),e}finally{for(let[e,t]of g)t?Object.defineProperty(globalThis,e,t):delete globalThis[e]}}function getMermaid(e){return initPromise??=initMermaid().catch(t=>(log$13.warn({err:t,"doc.name":e},`mermaid validator unavailable — render validation disabled for this process`),null)),initPromise}function extractLineNumber(e){let t=e.match(/Parse error on line (\d+)/);if(!t?.[1])return;let s=Number(t[1]);return Number.isSafeInteger(s)&&s>0?s:void 0}async function validateMermaidFences(e,t){try{if(!e.includes(`mermaid`))return;let{body:s}=detectFmRegion(e),g=extractMermaidFences(s);if(g.length===0)return;let S=performance.now(),w=await getMermaid(t);if(w===null)return;let E=performance.now(),D=[],O=0;for(let e=0;e<g.length&&D.length<MAX_WARNINGS&&!(O>=MAX_FENCES_PARSED);e++){if(performance.now()-E>TOTAL_PARSE_BUDGET_MS){log$13.debug({"doc.name":t,skippedFrom:e+1,fences:g.length},`mermaid validation budget exceeded — remaining fences skipped`);break}let s=g[e];if(s!==void 0){if(s.body.length>MAX_FENCE_BYTES||s.body.split(`
831
+ `).length>MAX_FENCE_LINES){log$13.debug({"doc.name":t,fenceIndex:e+1},`mermaid fence over validation caps — skipped`);continue}try{O++,await w.parse(s.body)}catch(g){if(g instanceof TypeError){log$13.debug({err:g,"doc.name":t,fenceIndex:e+1},`mermaid validation skipped fence — environment failure`);continue}let S=g instanceof Error?g.message:String(g),w=S.slice(0,MAX_MESSAGE_CHARS),E=extractLineNumber(S);D.push({kind:`mermaid-parse-error`,fenceIndex:e+1,fenceFirstLine:s.firstLine,message:w,...E===void 0?{}:{line:E}})}}}let k=Math.round(performance.now()-S);if(D.length===0){k>250&&log$13.debug({"doc.name":t,durationMs:k,fences:g.length},`mermaid validation slow (no warnings)`);return}return log$13.debug({"doc.name":t,count:D.length,durationMs:k},`mermaid render warnings emitted`),D}catch(e){log$13.warn({err:e,"doc.name":t},`mermaid validation errored unexpectedly — skipped`);return}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidSharePath(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,s,g){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(s)}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function buildGitHubTreeUrl(e,t,s,g){let S=`https://github.com/${e}/${t}/tree/${encodeURIComponent(s)}`;return g===``?S:`${S}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let s=t?.branchExists,g=t?.kind,S=t?.freshness;getLogger(`share`).info({action:`construct-url`,result:e,...s===void 0?{}:{branchExists:s},...g===void 0?{}:{kind:g},...S===void 0?{}:{freshness:S}},`share action`)}function truncateError(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}const FRESHNESS_PROBE_TIMEOUT_MS=5e3;async function computeShareFreshness(e,t,s,g){try{let{git:g}=createGitInstance(e,{timeoutMs:FRESHNESS_PROBE_TIMEOUT_MS}),S=`refs/remotes/origin/${t}`;await g.raw([`rev-parse`,`--verify`,S]);let w=s===``?`.`:s,[E,D,O]=await Promise.all([g.raw([`cat-file`,`-e`,`${S}:${s}`]).then(()=>!0).catch(()=>!1),g.raw([`diff`,`--name-only`,S,`--`,w]),g.raw([`status`,`--porcelain`,`--untracked-files=all`,`--`,w])]);return E?D.trim()!==``||O.trim()!==``?`stale`:`current`:`absent`}catch(e){let t=truncateError(e);getLogger(`share`).warn({action:`freshness-probe-failed`,kind:g,error:t},`[share] freshness probe failed; omitting freshness`);return}}const log$12=getLogger(`git-context`);function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let s;try{s=statSync(t)}catch{return null}if(s.isDirectory())return t;if(s.isFile()){let s;try{s=readFileSync(t,`utf-8`)}catch{return null}let g=/^gitdir:\s*(.+)$/m.exec(s.trim());if(!g)return null;let S=g[1].trim(),w=isAbsolute(S)?S:resolve(e,S);return existsSync(w)?w:null}return null}function resolveCommonDir(e){let t=join(e,`commondir`);if(!existsSync(t))return e;let s;try{s=readFileSync(t,`utf-8`).trim()}catch{return e}return s.length===0?e:isAbsolute(s)?s:resolve(e,s)}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(t,`HEAD`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=/^ref:\s*refs\/heads\/(.+)$/.exec(g.trim());return S?S[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),s=e.indexOf(`;`),g=-1;return t>=0&&s>=0?g=Math.min(t,s):t>=0?g=t:s>=0&&(g=s),(g===-1?e:e.slice(0,g)).trim()}function extractOriginUrl(e){let t=!1;for(let s of e.split(/\r?\n/)){let e=stripCommentAndTrim(s);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let g=/^url\s*=\s*(.+)$/.exec(e);if(!g)continue;let S=g[1].trim();if((S.startsWith(`"`)&&S.endsWith(`"`)||S.startsWith(`'`)&&S.endsWith(`'`))&&(S=S.slice(1,-1)),S.length>0)return S}return null}function normalizeGitHost(e){let t=e.toLowerCase().replace(/:\d+$/,``);return t===`www.github.com`?`github.com`:t}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let s=(e,t,s)=>{let g=normalizeGitHost(e);return KNOWN_NON_GITHUB_GIT_HOSTS.has(g)?null:{host:g,owner:t,repo:s}},g=/^https?:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return g||(g=/^ssh:\/\/(?:[\w.-]+@)?([\w.-]+)(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),g)||(g=/^[\w.-]+@([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),g)||(g=/^git:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),g)?s(g[1],g[2],g[3]):null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(resolveCommonDir(t),`config`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=extractOriginUrl(g);return S?{originUrl:S,github:parseGitHubOriginUrl(S)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);if(!t)return{kind:`no-remote`};if(t.github){let{host:e,owner:s,repo:g}=t.github;return{kind:`ok`,host:e,owner:s,repo:g}}return{kind:`non-github`}}function originGitHubHost(e){let t=readOriginGitHubRepo(e);return t.kind===`ok`?t.host:(log$12.debug({kind:t.kind},`[git-context] origin is not a GitHub host — falling back to github.com`),`github.com`)}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);if(!t)return null;if(t.github){let{host:e,owner:s,repo:g}=t.github;return{label:e===`github.com`?`${s}/${g}`:`${e}/${s}/${g}`,webUrl:`https://${e}/${s}/${g}`}}return{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),s=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(s)return`${s[1]}/${s[2]}`;let g=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return g?g[1]:t}function branchExistsOnOrigin(e,t){let s=resolveGitDir$1(e);if(!s)return!1;let g=resolveCommonDir(s);if(existsSync(join(g,`refs`,`remotes`,`origin`,t)))return!0;let S=join(g,`packed-refs`);if(!existsSync(S))return!1;let w;try{w=readFileSync(S,`utf-8`)}catch{return!1}let E=`refs/remotes/origin/${t}`;for(let e of w.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let s=t.split(/\s+/);if(s.length===2&&s[1]===E)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
832
832
  `).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e--)try{let s=JSON.parse(t[e]);if(s&&typeof s==`object`&&!Array.isArray(s))return s}catch{}return null}function parseOwnersEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`owners`&&Array.isArray(e.owners)){let t=[];for(let s of e.owners){if(!s||typeof s!=`object`)continue;let e=s,g=typeof e.login==`string`?e.login:null,S=e.kind===`user`||e.kind===`org`?e.kind:null;if(g===null||S===null)continue;let w=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:g,kind:S,...w?{avatarUrl:w}:{}})}return{ok:!0,owners:t}}return e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function isOwnersErrorCode(e){return e===`auth-required`||e===`network`}function parseNameCheckEvent(e){return e===null?{ok:!1,error:`network`}:e.type===`name-check`&&typeof e.available==`boolean`?{ok:!0,available:e.available}:e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}const PUBLISH_ERROR_CODES=new Set([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);function isPublishErrorCode(e){return typeof e==`string`&&PUBLISH_ERROR_CODES.has(e)}function parsePublishEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`publish`){let t=typeof e.ownerLogin==`string`?e.ownerLogin:null,s=typeof e.repoName==`string`?e.repoName:null,g=typeof e.cloneUrl==`string`?e.cloneUrl:null,S=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&s!==null&&g!==null&&S!==null?{ok:!0,ownerLogin:t,repoName:s,cloneUrl:g,defaultBranch:S}:{ok:!1,error:`network`}}return e.type===`error`?{ok:!1,error:isPublishErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function emitSharePublishLog(e,t,s){getLogger(`share`).info({action:e,result:t,...s?.count===void 0?{}:{count:s.count},...s?.available===void 0?{}:{available:s.available}},`share action`)}function redactShareSubprocessStderr(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const SHARE_TARGET_STATUS_HANDLER_TAG=`share-target-status`,DEFAULT_FETCH_TIMEOUT_MS=15e3;function classifyDoc(e,t){for(let s of e)if(s.from===t){if(s.status.startsWith(`R`))return{verdict:`renamed`,renamedTo:s.to};if(s.status===`D`)return{verdict:`deleted`}}return{verdict:`deleted`}}function classifyFolder(e,t){let s=t.endsWith(`/`)?t:`${t}/`,g=new Set;for(let t of e){if(!t.from.startsWith(s)||!t.status.startsWith(`R`))continue;let e=t.from.slice(s.length);t.to.endsWith(`/${e}`)?g.add(t.to.slice(0,t.to.length-e.length-1)):g.add(`\0ambiguous`)}let S=g.size===1?[...g][0]:void 0;return S!==void 0&&S!==`\0ambiguous`?{verdict:`renamed`,renamedTo:S}:{verdict:`deleted`}}async function computeShareTargetStatus(e,t,s,g,S={}){let w=getLogger(`share`),E=e=>(w.info({action:`target-status`,verdict:e.verdict,kind:g},`target-status verdict`),e),{git:D}=createGitInstance(e,S.skipFetch?{}:{timeoutMs:S.fetchTimeoutMs??DEFAULT_FETCH_TIMEOUT_MS});if(!S.skipFetch)try{await D.raw([`fetch`,`origin`,t])}catch(e){return w.warn({action:`target-status`,kind:g,error:truncateError(e)},`target-status fetch failed`),E({verdict:`unknown`})}let O=`origin/${t}`;try{if(await D.raw([`cat-file`,`-e`,`${O}:${s}`]).then(()=>!0).catch(()=>!1)){let t=await D.raw([`cat-file`,`-e`,`HEAD:${s}`]).then(()=>!0).catch(()=>!1),g=existsSync(join(e,s));return E(t&&!g?{verdict:`changed-locally`}:{verdict:`on-origin`})}let t=(await D.raw([`log`,`-1`,`--format=%H`,O,`--`,s])).trim();if(t===``)return E({verdict:`never-on-branch`});let S=await listNameStatus(D,[`diff-tree`,`-M`,`-r`,`--no-commit-id`,`--name-status`,`${t}^1`,t]),w=g===`folder`?classifyFolder(S,s):classifyDoc(S,s);return w.verdict===`renamed`&&!await D.raw([`cat-file`,`-e`,`${O}:${w.renamedTo}`]).then(()=>!0).catch(()=>!1)?E({verdict:`deleted`}):E(w)}catch(e){return w.warn({action:`target-status`,kind:g,error:truncateError(e)},`target-status detection failed`),E({verdict:`unknown`})}}const BUNDLE_SKILL_NAME={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`},BUNDLE_IDS=Object.keys(BUNDLE_SKILL_NAME),BUNDLE_SCOPE={discovery:`user`,project:`project`,"write-skill":`user`},USER_GLOBAL_BUNDLE_IDS=BUNDLE_IDS.filter(e=>BUNDLE_SCOPE[e]===`user`);function bundleSkillMdPath(e){return`packages/server/assets/skills/${e}/SKILL.md`}const MAX_ZIP_BYTES=102400,DESKTOP_SKILLS_REL=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function resolveBundledSkillDir(e,t={}){let s=t.platform??process.platform,g=t.checkDesktop??!1,S=t.home??homedir(),w=[];g&&s===`darwin`&&(w.push(join(`/Applications`,DESKTOP_SKILLS_REL,e)),w.push(join(S,`Applications`,DESKTOP_SKILLS_REL,e))),w.push(fileURLToPath(new URL(`../dist/assets/skills/${e}`,import.meta.url))),w.push(fileURLToPath(new URL(`../assets/skills/${e}`,import.meta.url))),w.push(fileURLToPath(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of w)if(existsSync(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${w.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*walkFiles(e,t=e){let s=await readdir(e,{withFileTypes:!0});for(let g of s){let s=join(e,g.name);g.isDirectory()?yield*walkFiles(s,t):g.isFile()&&(yield relative(t,s))}}function computeWrapperFolderName(e,t=basename){return t(e)||`open-knowledge`}function toPosixZipPath(e,t=sep){return t===`/`?e:e.split(t).join(`/`)}async function zipDirectory(e,t,s=computeWrapperFolderName(e)){let g=new import_yazl.ZipFile;g.addEmptyDirectory(`${s}/`);let S=[];for await(let t of walkFiles(e))S.push(t);S.sort();for(let t of S){let S=join(e,t),w=`${s}/${toPosixZipPath(t)}`;g.addFile(S,w)}g.end(),await new Promise((e,s)=>{let S=createWriteStream(t);g.outputStream.pipe(S),S.on(`close`,()=>e()),S.on(`error`,s),g.outputStream.on(`error`,s)})}async function sha256OfFile(e){return new Promise((t,s)=>{let g=createHash(`sha256`),S=createReadStream(e);S.on(`data`,e=>g.update(e)),S.on(`end`,()=>t(g.digest(`hex`))),S.on(`error`,s)})}function extractMetadataVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let s=unwrapFrontmatterFences(t),g=s.search(/^metadata:/m);if(g<0)return;let S=s.slice(g).split(`
833
- `).slice(1);for(let e of S){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,s={}){let g=s.bundle??`project`,S=statSync(e).size;if(S>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${S} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let w=await sha256OfFile(e),E=await readFile$1(join(s.sourceDir??resolveBundledSkillDir(g,{checkDesktop:!1}),`SKILL.md`),`utf-8`),D=BUNDLE_SKILL_NAME[g];if(!RegExp(`^name:\\s+${D}$`,`m`).test(E.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${D}'. Check packages/server/assets/skills/${g}/SKILL.md frontmatter.`);let O=extractMetadataVersion(E);if(t!==void 0){if(!O)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${g}/SKILL.md.`);if(O!==t)throw Error(`SKILL.md metadata.version (${O}) does not match expected version (${t}).`)}return{size:S,sha256:w,skillVersion:O}}async function buildSkillZip(e={}){let t=e.bundle??`project`,s=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),g=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(s,g,BUNDLE_SKILL_NAME[t]);let{size:S,sha256:w,skillVersion:E}=await validateSkillZip(g,e.expectedSkillVersion,{bundle:t,sourceDir:s});return{outputPath:g,size:S,sha256:w,skillVersion:E}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let s=t?.homedir??(()=>process.env.HOME??``),g=t?.warn??((e,t)=>{console.warn(t,e)}),S=s();if(!S){g({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let w=join(S,...SKILL_INSTALL_EVENTS_FILE_REL),E=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(w),{recursive:!0})}catch(e){g({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(w,E,{flag:`a`,encoding:`utf-8`})}catch(e){g({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}async function withSkillStateWriteLock(e,t){let s=skillStateYamlPath(e);await tracedMkdir(dirname(s),{recursive:!0});try{return await withFileLock(`${s}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let s=skillStateYamlPath(e),g;try{g=await readFileAsync(s,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let S=(0,import_dist$1.parseDocument)(g);if(S.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:s,errors:S.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let w=SkillStateSchema.safeParse(S.toJSON());if(!w.success){let e=w.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:s,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:s,issues:w.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return w.data}async function writeSkillStateFile(e,t){let s=SkillStateSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid skill-state: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=skillStateYamlPath(e);await tracedMkdir(dirname(g),{recursive:!0});let S=(0,import_dist$1.parseDocument)(``);S.contents=S.createNode(s.data),await atomicWriteFile(g,S.toString(),{fs:tracedAtomicFs})}async function readTargetVersion(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.version??null}async function readTargetRecordedAt(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,s,g,S){if(!SKILL_STATE_VERSION_RE.test(s))throw Error(`Refusing to write invalid version string: ${s}`);await withSkillStateWriteLock(e,async()=>{let w=await readSkillStateFile(e,S)??emptySkillState(),E=new Date().toISOString(),D=w.targets[t],O=g===void 0?D?.surface??void 0:g,k=O===void 0?{version:s,recordedAt:E}:{version:s,recordedAt:E,surface:O};await writeSkillStateFile(e,{...w,targets:{...w.targets,[t]:k}})})}async function readBundleDecision(e,t,s){let g=(await readSkillStateFile(e,s).catch(()=>null))?.bundles?.[t];return typeof g?.enabled==`boolean`?g.enabled:null}async function writeBundleDecision(e,t,s,g){await withSkillStateWriteLock(e,async()=>{let S=await readSkillStateFile(e,g)??emptySkillState();await writeSkillStateFile(e,{...S,bundles:{...S.bundles,[t]:{enabled:s,decidedAt:new Date().toISOString()}}})})}async function readServerPackageVersion(){let e=await readFileAsync(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function readSkillInstallStateSnapshot(e,t){let[s,g]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:s,targets:g}}async function readAllTargets(e,t=DEFAULT_LOGGER){let s=null;try{s=await readSkillStateFile(e,t)}catch(g){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(g)},`non-ENOENT error reading skill-state.yml; treating as absent`),s=null}let g=SKILL_STATE_TARGETS.map(e=>{let t=s?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(g)}const LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$4=6e4;function centralSkillDir(e,t){return join(e,`.agents`,`skills`,t)}async function centralSkillExists(e,t){try{return(await stat$1(centralSkillDir(e,t))).isDirectory()}catch{return!1}}function quoteForWindowsShell(e){return/\s/.test(e)?`"${e.replaceAll(`"`,`\\"`)}"`:e}function runSpawn(e,t,s,g,S,w){return new Promise(E=>{let D,O=w===`win32`,k=O?s.map(quoteForWindowsShell):s;try{D=e(t,k,withHiddenWindowsConsole({env:g,stdio:[`ignore`,`pipe`,`pipe`],...O?{shell:!0}:{}}))}catch(e){E({kind:`spawn-error`,stderr:``,error:e});return}let j=``,F=!1,L=e=>{F||(F=!0,clearTimeout(B),E(e))};D.stderr?.on(`data`,e=>{j+=typeof e==`string`?e:e.toString(`utf-8`)}),D.on(`error`,e=>{L({kind:`spawn-error`,stderr:j,error:e})}),D.on(`exit`,e=>{L(e===0?{kind:`ok`,exitCode:e,stderr:j}:{kind:`nonzero`,exitCode:e,stderr:j})});let B=setTimeout(()=>{try{D.kill(`SIGTERM`)}catch{}L({kind:`timeout`,stderr:j})},S)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,s,g,S,w){if(!await anyLegacyUserSkillExists(e))return;let E=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],s,g,w);E.kind!==`ok`&&S.warn({event:`skill-install.legacy-remove-failed`,reason:E.kind,exitCode:E.exitCode,stderr:E.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}async function installUserSkill(e={}){let t=e.home??homedir(),s=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},g=e.spawn??spawn,S=e.timeoutMs??DEFAULT_TIMEOUT_MS$4,w=e.surface??`cli-npx-skills-add`,E=e.platform??process.platform,D=e.bundleId??`discovery`,O=BUNDLE_SKILL_NAME[D],k=async(e,g,S)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:w,target:`cli-hosts`,bundle:D,outcome:e,...g===void 0?{}:{version:g},...S===void 0?{}:{reason:S}},{homedir:()=>t,warn:s.warn})},j;try{j=await readServerPackageVersion()}catch(e){return s.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await k(`failed`,void 0,`version-read-failed`),`failed`}let F=await readTargetVersion(t,`cli-hosts`,s).catch(e=>(s.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(!e.force&&F!==null&&F===j){if(await centralSkillExists(t,O))return s.info?.({event:`skill-install.skip-current`,version:j},`OpenKnowledge skill already installed at current version; skipping.`),await k(`skip-current`,j),`skip-current`;s.info?.({event:`skill-install.reinstall-missing`,version:j,path:centralSkillDir(t,O)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let L;try{L=resolveBundledSkillDir(D,{checkDesktop:!1})}catch(e){return s.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),await k(`failed`,j,`bundled-asset-missing`),`failed`}let B={...process.env,HOME:t};await removeLegacyUserSkill(t,g,B,S,s,E);let H=await runSpawn(g,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,L,`--agent`,`*`,`-g`,`-y`,`--copy`],B,S,E);if(H.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,j,w,s)}catch(e){return s.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await k(`failed`,j,`sidecar-write-failed`),`failed`}return s.info?.({event:`skill-install.installed`,version:j},`OpenKnowledge skill installed to detected agent hosts.`),await k(`installed`,j),`installed`}return H.kind===`timeout`?(s.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:S,stderr:H.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`timeout`),`failed`):H.kind===`spawn-error`?(s.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(H.error),stderr:H.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`spawn-error`),`failed`):(s.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:H.exitCode,stderr:H.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`nonzero-exit:${H.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,s){let g=withHiddenWindowsConsole({detached:!0,stdio:`ignore`});try{return t===`darwin`?(s(`open`,[e],g).unref(),{ok:!0}):t===`win32`?(s(`cmd`,[`/c`,`start`,`""`,e],g).unref(),{ok:!0}):t===`linux`?(s(`xdg-open`,[e],g).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),s=resolve(e.out??defaultDownloadsPath(t)),g=e.platformName??platform(),S=e.spawnFn??spawn,w=e.logger,E=async(e,s,g)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...s===void 0?{}:{version:s},...g===void 0?{}:{reason:g}},{homedir:()=>t,warn:w?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){w?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let s=null,g=null;try{[s,g]=await Promise.all([readTargetVersion(t,`claude-cowork`,w),readTargetRecordedAt(t,`claude-cowork`,w)])}catch(e){w?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(s!==null&&s===e)return w?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await E(`skip-current`,e),{status:`skip-current`,skillVersion:e,...g===null?{}:{recordedAt:g}}}}try{await tracedMkdir(dirname(s),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let D;try{D=await buildSkillZip({outputPath:s,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let O={status:`built`,outputPath:D.outputPath,size:D.size,sha256:D.sha256,skillVersion:D.skillVersion};if(D.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,D.skillVersion,`server-build-and-open`,w)}catch(e){w?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:D.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await E(`built`,D.skillVersion),O;let k=invokeFileAssociation(D.outputPath,g,S);return k.ok?(await E(`installed`,D.skillVersion),{...O,status:`installed`}):(await E(`built`,D.skillVersion,`handoff-${k.reason}`),{...O,handoffError:{reason:k.reason,message:k.message}})}const logger$3=getLogger(`skill-management`),SKILL_MANAGEMENT_REL=[`.ok`,`local`,`skill-management.json`],SCHEMA_VERSION=1;function skillManagementPath(e){return join(e,...SKILL_MANAGEMENT_REL)}function readSkillManagement(e){let t=skillManagementPath(e);if(!existsSync(t))return null;try{let e=JSON.parse(readFileSync(t,`utf-8`));if(e&&typeof e==`object`&&typeof e.manageEditorSkills==`boolean`){let t=e;return{version:typeof t.version==`number`?t.version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:typeof t.decidedAt==`string`?t.decidedAt:void 0,surface:typeof t.surface==`string`?t.surface:void 0}}return logger$3.warn({path:t},`skill-management marker malformed — treating as unset`),null}catch(e){return logger$3.warn({err:e,path:t},`skill-management marker unreadable — treating as unset`),null}}async function writeSkillManagement(e,t){let s={version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:t.now??new Date().toISOString(),...t.surface?{surface:t.surface}:{}},g=skillManagementPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s,null,2)}\n`,{fs:tracedAtomicFs})}function isProjectSkillManaged(e,t=process.env){if(t.OK_RECLAIM_DISABLE===`1`)return!1;let s=t.OK_SKILL_MANAGE;return s===`1`||s===`true`?!0:s===`0`||s===`false`?!1:readSkillManagement(e)?.manageEditorSkills??!1}const MIN_GIT_VERSION=`2.31.0`,PROBE_TIMEOUT_MS$1=5e3;var GitNotAvailableError=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,s){super(buildMissingMessage(t),s),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},GitTooOldError=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,s,g,S,w){super(buildTooOldMessage(t,s,g,S),w),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=s,this.resolvedPath=g,this.guidance=S}};function detectGit(){let e=probeGit(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of fallbackPaths(process.platform)){if(!existsSync(e))continue;let t=probeGit(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new GitNotAvailableError(process.platform,buildGuidance(process.platform))}function assertGitAvailable(){let e=detectGit();if(compareSemver(e.version,`2.31.0`)<0)throw new GitTooOldError(process.platform,e.version,MIN_GIT_VERSION,e.resolvedPath,buildGuidance(process.platform));return e}function probeGit(e){let t=spawnSync(e,[`--version`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1,env:{...process.env,LANG:`C`,LC_ALL:`C`}}));if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let s=parseGitVersion(typeof t.stdout==`string`?t.stdout:``);return s===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:s,resolvedPath:e===`git`?resolveOnPath(`git`)??e:e}}function parseGitVersion(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const SAFE_COMMAND_NAME_RE=/^[a-zA-Z0-9_.-]+$/,resolveOnPathCache=new Map;function resolveOnPath(e){if(!SAFE_COMMAND_NAME_RE.test(e))return null;let t=resolveOnPathCache.get(e);if(t!==void 0)return t;let s;if(process.platform===`win32`){let t=spawnSync(`where`,[e],withHiddenWindowsConsole({encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1}));s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=spawnSync(`/bin/sh`,[`-c`,`command -v ${e}`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1}));s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return s!==null&&resolveOnPathCache.set(e,s),s}function fallbackPaths(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,join(homedir(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,join(homedir(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function buildGuidance(e){switch(e){case`darwin`:{let e=[];return hasBrew()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return hasWinget()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),hasScoop()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),hasChoco()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:linuxInstallOptions()}}}function linuxInstallOptions(){switch(detectLinuxFamily()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function detectLinuxFamily(e){let t=e;if(t===void 0)try{t=readFileSync(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let s=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return s.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:s.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:s.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:s.some(e=>/^opensuse/i.test(e))||s.includes(`suse`)?`opensuse`:s.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function hasCommand(e){return resolveOnPath(e)!==null}function hasBrew(){return hasCommand(`brew`)}function hasWinget(){return hasCommand(`winget`)}function hasScoop(){return hasCommand(`scoop`)}function hasChoco(){return hasCommand(`choco`)}function buildMissingMessage(e){let t=[];if(t.push(`OpenKnowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let s of e.options){let e=s.requiresAdmin?` (admin required)`:``;t.push(` • ${s.label}${e}`),t.push(` ${s.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run OpenKnowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
833
+ `).slice(1);for(let e of S){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,s={}){let g=s.bundle??`project`,S=statSync(e).size;if(S>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${S} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let w=await sha256OfFile(e),E=await readFile$1(join(s.sourceDir??resolveBundledSkillDir(g,{checkDesktop:!1}),`SKILL.md`),`utf-8`),D=BUNDLE_SKILL_NAME[g];if(!RegExp(`^name:\\s+${D}$`,`m`).test(E.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${D}'. Check packages/server/assets/skills/${g}/SKILL.md frontmatter.`);let O=extractMetadataVersion(E);if(t!==void 0){if(!O)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${g}/SKILL.md.`);if(O!==t)throw Error(`SKILL.md metadata.version (${O}) does not match expected version (${t}).`)}return{size:S,sha256:w,skillVersion:O}}async function buildSkillZip(e={}){let t=e.bundle??`project`,s=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),g=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(s,g,BUNDLE_SKILL_NAME[t]);let{size:S,sha256:w,skillVersion:E}=await validateSkillZip(g,e.expectedSkillVersion,{bundle:t,sourceDir:s});return{outputPath:g,size:S,sha256:w,skillVersion:E}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let s=t?.homedir??(()=>process.env.HOME??``),g=t?.warn??((e,t)=>{console.warn(t,e)}),S=s();if(!S){g({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let w=join(S,...SKILL_INSTALL_EVENTS_FILE_REL),E=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(w),{recursive:!0})}catch(e){g({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(w,E,{flag:`a`,encoding:`utf-8`})}catch(e){g({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}async function withSkillStateWriteLock(e,t){let s=skillStateYamlPath(e);await tracedMkdir(dirname(s),{recursive:!0});try{return await withFileLock(`${s}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let s=skillStateYamlPath(e),g;try{g=await readFileAsync(s,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let S=(0,import_dist$1.parseDocument)(g);if(S.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:s,errors:S.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let w=SkillStateSchema.safeParse(S.toJSON());if(!w.success){let e=w.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:s,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:s,issues:w.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return w.data}async function writeSkillStateFile(e,t){let s=SkillStateSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid skill-state: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=skillStateYamlPath(e);await tracedMkdir(dirname(g),{recursive:!0});let S=(0,import_dist$1.parseDocument)(``);S.contents=S.createNode(s.data),await atomicWriteFile(g,S.toString(),{fs:tracedAtomicFs})}async function readTargetVersion(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.version??null}async function readTargetRecordedAt(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,s,g,S){if(!SKILL_STATE_VERSION_RE.test(s))throw Error(`Refusing to write invalid version string: ${s}`);await withSkillStateWriteLock(e,async()=>{let w=await readSkillStateFile(e,S)??emptySkillState(),E=new Date().toISOString(),D=w.targets[t],O=g===void 0?D?.surface??void 0:g,k=O===void 0?{version:s,recordedAt:E}:{version:s,recordedAt:E,surface:O};await writeSkillStateFile(e,{...w,targets:{...w.targets,[t]:k}})})}async function readBundleDecision(e,t,s){let g=(await readSkillStateFile(e,s).catch(()=>null))?.bundles?.[t];return typeof g?.enabled==`boolean`?g.enabled:null}async function writeBundleDecision(e,t,s,g){await withSkillStateWriteLock(e,async()=>{let S=await readSkillStateFile(e,g)??emptySkillState();await writeSkillStateFile(e,{...S,bundles:{...S.bundles,[t]:{enabled:s,decidedAt:new Date().toISOString()}}})})}async function readServerPackageVersion(){let e=await readFileAsync(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function readSkillInstallStateSnapshot(e,t){let[s,g]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:s,targets:g}}async function readAllTargets(e,t=DEFAULT_LOGGER){let s=null;try{s=await readSkillStateFile(e,t)}catch(g){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(g)},`non-ENOENT error reading skill-state.yml; treating as absent`),s=null}let g=SKILL_STATE_TARGETS.map(e=>{let t=s?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(g)}const LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$5=6e4;function centralSkillDir(e,t){return join(e,`.agents`,`skills`,t)}async function centralSkillExists(e,t){try{return(await stat$1(centralSkillDir(e,t))).isDirectory()}catch{return!1}}function quoteForWindowsShell(e){return/\s/.test(e)?`"${e.replaceAll(`"`,`\\"`)}"`:e}function runSpawn(e,t,s,g,S,w){return new Promise(E=>{let D,O=w===`win32`,k=O?s.map(quoteForWindowsShell):s;try{D=e(t,k,withHiddenWindowsConsole({env:g,stdio:[`ignore`,`pipe`,`pipe`],...O?{shell:!0}:{}}))}catch(e){E({kind:`spawn-error`,stderr:``,error:e});return}let j=``,F=!1,L=e=>{F||(F=!0,clearTimeout(B),E(e))};D.stderr?.on(`data`,e=>{j+=typeof e==`string`?e:e.toString(`utf-8`)}),D.on(`error`,e=>{L({kind:`spawn-error`,stderr:j,error:e})}),D.on(`exit`,e=>{L(e===0?{kind:`ok`,exitCode:e,stderr:j}:{kind:`nonzero`,exitCode:e,stderr:j})});let B=setTimeout(()=>{try{D.kill(`SIGTERM`)}catch{}L({kind:`timeout`,stderr:j})},S)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,s,g,S,w){if(!await anyLegacyUserSkillExists(e))return;let E=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],s,g,w);E.kind!==`ok`&&S.warn({event:`skill-install.legacy-remove-failed`,reason:E.kind,exitCode:E.exitCode,stderr:E.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}async function installUserSkill(e={}){let t=e.home??homedir(),s=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},g=e.spawn??spawn,S=e.timeoutMs??DEFAULT_TIMEOUT_MS$5,w=e.surface??`cli-npx-skills-add`,E=e.platform??process.platform,D=e.bundleId??`discovery`,O=BUNDLE_SKILL_NAME[D],k=async(e,g,S)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:w,target:`cli-hosts`,bundle:D,outcome:e,...g===void 0?{}:{version:g},...S===void 0?{}:{reason:S}},{homedir:()=>t,warn:s.warn})},j;try{j=await readServerPackageVersion()}catch(e){return s.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await k(`failed`,void 0,`version-read-failed`),`failed`}let F=await readTargetVersion(t,`cli-hosts`,s).catch(e=>(s.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(!e.force&&F!==null&&F===j){if(await centralSkillExists(t,O))return s.info?.({event:`skill-install.skip-current`,version:j},`OpenKnowledge skill already installed at current version; skipping.`),await k(`skip-current`,j),`skip-current`;s.info?.({event:`skill-install.reinstall-missing`,version:j,path:centralSkillDir(t,O)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let L;try{L=resolveBundledSkillDir(D,{checkDesktop:!1})}catch(e){return s.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),await k(`failed`,j,`bundled-asset-missing`),`failed`}let B={...process.env,HOME:t};await removeLegacyUserSkill(t,g,B,S,s,E);let H=await runSpawn(g,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,L,`--agent`,`*`,`-g`,`-y`,`--copy`],B,S,E);if(H.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,j,w,s)}catch(e){return s.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await k(`failed`,j,`sidecar-write-failed`),`failed`}return s.info?.({event:`skill-install.installed`,version:j},`OpenKnowledge skill installed to detected agent hosts.`),await k(`installed`,j),`installed`}return H.kind===`timeout`?(s.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:S,stderr:H.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`timeout`),`failed`):H.kind===`spawn-error`?(s.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(H.error),stderr:H.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`spawn-error`),`failed`):(s.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:H.exitCode,stderr:H.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`nonzero-exit:${H.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,s){let g=withHiddenWindowsConsole({detached:!0,stdio:`ignore`});try{return t===`darwin`?(s(`open`,[e],g).unref(),{ok:!0}):t===`win32`?(s(`cmd`,[`/c`,`start`,`""`,e],g).unref(),{ok:!0}):t===`linux`?(s(`xdg-open`,[e],g).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),s=resolve(e.out??defaultDownloadsPath(t)),g=e.platformName??platform(),S=e.spawnFn??spawn,w=e.logger,E=async(e,s,g)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...s===void 0?{}:{version:s},...g===void 0?{}:{reason:g}},{homedir:()=>t,warn:w?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){w?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let s=null,g=null;try{[s,g]=await Promise.all([readTargetVersion(t,`claude-cowork`,w),readTargetRecordedAt(t,`claude-cowork`,w)])}catch(e){w?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(s!==null&&s===e)return w?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await E(`skip-current`,e),{status:`skip-current`,skillVersion:e,...g===null?{}:{recordedAt:g}}}}try{await tracedMkdir(dirname(s),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let D;try{D=await buildSkillZip({outputPath:s,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let O={status:`built`,outputPath:D.outputPath,size:D.size,sha256:D.sha256,skillVersion:D.skillVersion};if(D.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,D.skillVersion,`server-build-and-open`,w)}catch(e){w?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:D.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await E(`built`,D.skillVersion),O;let k=invokeFileAssociation(D.outputPath,g,S);return k.ok?(await E(`installed`,D.skillVersion),{...O,status:`installed`}):(await E(`built`,D.skillVersion,`handoff-${k.reason}`),{...O,handoffError:{reason:k.reason,message:k.message}})}const logger$4=getLogger(`skill-management`),SKILL_MANAGEMENT_REL=[`.ok`,`local`,`skill-management.json`],SCHEMA_VERSION=1;function skillManagementPath(e){return join(e,...SKILL_MANAGEMENT_REL)}function readSkillManagement(e){let t=skillManagementPath(e);if(!existsSync(t))return null;try{let e=JSON.parse(readFileSync(t,`utf-8`));if(e&&typeof e==`object`&&typeof e.manageEditorSkills==`boolean`){let t=e;return{version:typeof t.version==`number`?t.version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:typeof t.decidedAt==`string`?t.decidedAt:void 0,surface:typeof t.surface==`string`?t.surface:void 0}}return logger$4.warn({path:t},`skill-management marker malformed — treating as unset`),null}catch(e){return logger$4.warn({err:e,path:t},`skill-management marker unreadable — treating as unset`),null}}async function writeSkillManagement(e,t){let s={version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:t.now??new Date().toISOString(),...t.surface?{surface:t.surface}:{}},g=skillManagementPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s,null,2)}\n`,{fs:tracedAtomicFs})}function isProjectSkillManaged(e,t=process.env){if(t.OK_RECLAIM_DISABLE===`1`)return!1;let s=t.OK_SKILL_MANAGE;return s===`1`||s===`true`?!0:s===`0`||s===`false`?!1:readSkillManagement(e)?.manageEditorSkills??!1}const MIN_GIT_VERSION=`2.31.0`,PROBE_TIMEOUT_MS$1=5e3;var GitNotAvailableError=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,s){super(buildMissingMessage(t),s),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},GitTooOldError=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,s,g,S,w){super(buildTooOldMessage(t,s,g,S),w),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=s,this.resolvedPath=g,this.guidance=S}};function detectGit(){let e=probeGit(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of fallbackPaths(process.platform)){if(!existsSync(e))continue;let t=probeGit(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new GitNotAvailableError(process.platform,buildGuidance(process.platform))}function assertGitAvailable(){let e=detectGit();if(compareSemver(e.version,`2.31.0`)<0)throw new GitTooOldError(process.platform,e.version,MIN_GIT_VERSION,e.resolvedPath,buildGuidance(process.platform));return e}function probeGit(e){let t=spawnSync(e,[`--version`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1,env:{...process.env,LANG:`C`,LC_ALL:`C`}}));if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let s=parseGitVersion(typeof t.stdout==`string`?t.stdout:``);return s===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:s,resolvedPath:e===`git`?resolveOnPath(`git`)??e:e}}function parseGitVersion(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const SAFE_COMMAND_NAME_RE=/^[a-zA-Z0-9_.-]+$/,resolveOnPathCache=new Map;function resolveOnPath(e){if(!SAFE_COMMAND_NAME_RE.test(e))return null;let t=resolveOnPathCache.get(e);if(t!==void 0)return t;let s;if(process.platform===`win32`){let t=spawnSync(`where`,[e],withHiddenWindowsConsole({encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1}));s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=spawnSync(`/bin/sh`,[`-c`,`command -v ${e}`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1}));s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return s!==null&&resolveOnPathCache.set(e,s),s}function fallbackPaths(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,join(homedir(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,join(homedir(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function buildGuidance(e){switch(e){case`darwin`:{let e=[];return hasBrew()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return hasWinget()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),hasScoop()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),hasChoco()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:linuxInstallOptions()}}}function linuxInstallOptions(){switch(detectLinuxFamily()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function detectLinuxFamily(e){let t=e;if(t===void 0)try{t=readFileSync(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let s=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return s.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:s.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:s.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:s.some(e=>/^opensuse/i.test(e))||s.includes(`suse`)?`opensuse`:s.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function hasCommand(e){return resolveOnPath(e)!==null}function hasBrew(){return hasCommand(`brew`)}function hasWinget(){return hasCommand(`winget`)}function hasScoop(){return hasCommand(`scoop`)}function hasChoco(){return hasCommand(`choco`)}function buildMissingMessage(e){let t=[];if(t.push(`OpenKnowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let s of e.options){let e=s.requiresAdmin?` (admin required)`:``;t.push(` • ${s.label}${e}`),t.push(` ${s.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run OpenKnowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
834
834
  `)}function buildTooOldMessage(e,t,s,g){let S=[];if(S.push(`OpenKnowledge requires ${g.product} ${t} or newer (detected ${e} at ${s}).`),S.push(``),g.options.length>0){S.push(`Update ${g.product}:`);for(let e of g.options){let t=e.requiresAdmin?` (admin required)`:``;S.push(` • ${e.label}${t}`),S.push(` ${e.command}`)}S.push(``)}return S.push(`Or download from: ${g.url}`),S.push(``),S.push(`After updating, re-run OpenKnowledge.`),S.push("Run `ok diagnose health --check git` to verify your installation."),S.join(`
835
- `)}function compareSemver(e,t){let s=e.split(`.`).map(e=>Number.parseInt(e,10)||0),g=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=s[e]??0,S=g[e]??0;if(t!==S)return t-S}return 0}function resolvedHosts(e){let t=PROJECT_SKILL_EDITOR_IDS;return e.filter(e=>t.includes(e))}const RESERVED_SKILL_PREFIX=`open-knowledge`,PACK_SKILL_PREFIX=`open-knowledge-pack-`,SHIPPED_SKILL_NAME=`open-knowledge`,FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,CONFLICT_MARKER_RES=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function parseFrontmatter(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]??``);return e&&typeof e==`object`&&!Array.isArray(e)?e:null}catch{return null}}function validateSkillForInstall(e,t,s){let g=[],S=join(e,`SKILL.md`),w=existsSync(join(e,`scripts`))&&statSync(join(e,`scripts`)).isDirectory(),E=t.startsWith(RESERVED_SKILL_PREFIX)&&!t.startsWith(`open-knowledge-pack-`);if(!s?.allowReservedName&&E&&g.push(`"${t}" uses the reserved \`${RESERVED_SKILL_PREFIX}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!existsSync(S))return g.push(`No SKILL.md found at ${e}.`),{ok:g.length===0,errors:g,hasScripts:w};let D;try{D=readFileSync(S,`utf-8`)}catch(e){return g.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:g,hasScripts:w}}CONFLICT_MARKER_RES.some(e=>e.test(D))&&g.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let O=parseFrontmatter(D);if(O===null)g.push("SKILL.md has no valid `---` frontmatter block (name + description required).");else{let e=O.name,s=O.description;typeof e!=`string`||e.length===0?g.push(`SKILL.md frontmatter.name is missing or empty.`):e!==t&&g.push(`SKILL.md frontmatter.name ("${e}") must equal the skill directory ("${t}").`),(typeof s!=`string`||s.length===0)&&g.push(`SKILL.md frontmatter.description is missing or empty.`),(typeof e==`string`&&containsXmlTag(e)||typeof s==`string`&&containsXmlTag(s))&&g.push("SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.")}return{ok:g.length===0,errors:g,hasScripts:w}}function detectProjectConfiguredTargets(e){return PROJECT_SKILL_EDITOR_IDS.filter(t=>{let s=EDITOR_PROJECT_CONFIG_PATH[t];return s!==null&&existsSync(resolve(e,s))})}function resolveSkillTargets(e,t){if(t&&t.length>0){let e=new Set(PROJECT_SKILL_EDITOR_IDS);return t.filter(t=>e.has(t))}return detectProjectConfiguredTargets(e)}function skillHostDir(e,t,s){let g=EDITOR_PROJECT_SKILL_ROOT[t];return g===null?null:resolve(e,g,s)}function hostSkillsRootEscapes(e,t){if(!existsSync(t))return!1;try{let s=relative(realpathSync(e),realpathSync(t));return s.startsWith(`..`)||isAbsolute(s)}catch{return!0}}function skillLinkTarget(e,t,s){let g=resolve(s),S=relative(resolve(e),g);return S!==``&&!S.startsWith(`..`)&&!isAbsolute(S)?relative(t,g):g}function projectSkill(e,t,s,g){let S=[];for(let w of g){let g=skillHostDir(s,w,t);if(g===null)continue;let E=dirname(g);hostSkillsRootEscapes(s,E)||(tracedRmSync(g,{recursive:!0,force:!0}),tracedMkdirSync(E,{recursive:!0}),tracedSymlinkSync(skillLinkTarget(s,E,e),g,`dir`),S.push(w))}return S}function reverseProjectSkill(e,t,s){let g=[];for(let S of s){let s=skillHostDir(t,S,e);if(s===null)continue;let w=!1;try{lstatSync(s),w=!0}catch{w=!1}w&&(tracedRmSync(s,{recursive:!0,force:!0}),g.push(S))}return g}function projectBundleSkill(e,t){let s;try{s=resolveBundledSkillDir(`project`,{checkDesktop:!0})}catch{return[]}let g=[];for(let S of t){let t=skillHostDir(e,S,SHIPPED_SKILL_NAME);t!==null&&(hostSkillsRootEscapes(e,dirname(t))||(tracedRmSync(t,{recursive:!0,force:!0}),tracedCpSync(s,t,{recursive:!0}),g.push(S)))}return g}function reverseBundleSkill(e,t){return reverseProjectSkill(SHIPPED_SKILL_NAME,e,t)}const MAX_BUNDLED_FILE_BYTES=256*1024;function listSkillFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listSkillFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function readSkillBundledFiles(e){if(!existsSync(e))return[];let t=[];for(let s of listSkillFiles(e)){if(s===`SKILL.md`)continue;let g=null;try{let t=readFileSync(join(e,s));t.length<=MAX_BUNDLED_FILE_BYTES&&!t.includes(0)&&(g=t.toString(`utf-8`))}catch(e){if(e?.code!==`ENOENT`)throw e;g=null}t.push({path:s,text:g})}return t}function isPackSkillName(e){return e.startsWith(PACK_SKILL_PREFIX)}function packIdFromSkillName(e){return isPackSkillName(e)?e.slice(20):null}function readSkillVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let{map:s}=parseFrontmatterYaml(unwrapFrontmatterFences(t)),g=s?.version;return typeof g==`string`&&g.trim()!==``?g:void 0}function bundledPackSkillDir(e){let t=packIdFromSkillName(e);if(t===null)return null;try{return resolveBundledSkillDir(`packs/${t}`,{checkDesktop:!1})}catch{return null}}function bundledPackVersion(e){let t=bundledPackSkillDir(e);if(t!==null)try{return readSkillVersion(readFileSync(join(t,`SKILL.md`),`utf-8`))}catch{return}}function readBundledPackSkill(e){let t=bundledPackSkillDir(e);if(t===null)return null;let s;try{s=readFileSync(join(t,`SKILL.md`),`utf-8`)}catch{return null}return{content:s,version:readSkillVersion(s)}}function packUpdateAvailable(e,t){return e===void 0?!0:compareSemver(t,e)>0}function computePackUpdateStatus(e,t){let s=bundledPackVersion(e);return s===void 0?{}:{bundledVersion:s,updateAvailable:packUpdateAvailable(t,s)}}const logger$2=getLogger(`skill-reconcile`),SHIPPED_BUNDLE_NAMES=new Set([`open-knowledge`,`open-knowledge-discovery`]);function detectionRoots(){let e=[];for(let t of PROJECT_SKILL_EDITOR_IDS){let s=EDITOR_PROJECT_SKILL_ROOT[t];s!==null&&e.push({rel:s,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function relativeLinkTarget(e,t){let s=relative(e,resolve(t));return isAbsolute(s)?resolve(t):s}const DIRS_EQUAL_MAX_BYTES=1048576;function dirsEqual(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES||!readFileSync(D).equals(readFileSync(O)))return!1}return!0}function parseSkillManifest(e){let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{fm:g,body:s}}function skillManifestsSame(e,t){let s=parseSkillManifest(e),g=parseSkillManifest(t);if(s.body!==g.body)return!1;for(let e of Object.keys(s.fm))if(e in g.fm&&JSON.stringify(s.fm[e])!==JSON.stringify(g.fm[e]))return!1;return!0}function sameSkillModuloFrontmatter(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES)return!1;let k=readFileSync(D),j=readFileSync(O);if(!k.equals(j)&&(E!==`SKILL.md`||!skillManifestsSame(k.toString(`utf8`),j.toString(`utf8`))))return!1}return!0}function listFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function moveDir(e,t){tracedMkdirSync(dirname(t),{recursive:!0});try{tracedRenameSync(e,t)}catch(s){if(!(s instanceof Error)||s.code!==`EXDEV`)throw s;tracedCpSync(e,t,{recursive:!0}),tracedRmSync(e,{recursive:!0,force:!0})}}function linkInto(e,t,s){tracedRmSync(t,{recursive:!0,force:!0}),tracedMkdirSync(e,{recursive:!0}),tracedSymlinkSync(relativeLinkTarget(e,s),t,`dir`)}function pointsAtSource(e,t){try{let s=readlinkSync(e);return resolve(isAbsolute(s)?s:resolve(dirname(e),s))===resolve(t)}catch{return!1}}function countImportableEditorSkills(e){let{projectDir:t,skillsRoot:s}=e,g=new Set;for(let{rel:e}of detectionRoots()){let S=resolve(t,e);if(!existsSync(S)||hostSkillsRootEscapes(t,S))continue;let w;try{w=readdirSync(S)}catch(e){logger$2.warn({hostRoot:S,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of w){if(SHIPPED_BUNDLE_NAMES.has(e)||!SKILL_NAME_REGEX.test(e))continue;let t=join(S,e),w;try{w=lstatSync(t)}catch{continue}if(w.isSymbolicLink()||!w.isDirectory())continue;let E=resolve(s,e);existsSync(E)&&(dirsEqual(t,E)||sameSkillModuloFrontmatter(t,E))||g.add(e)}}return g.size}async function reconcileSkillInstalls(e){let{projectDir:t,skillsRoot:s}=e,g={healed:[],adopted:[],replaced:[],collided:[],orphansRemoved:[],skipped:[]},S=isProjectSkillManaged(t),w=new Map,E=(e,t)=>{if(t===null)return;let s=w.get(e)??new Set;s.add(t),w.set(e,s)};for(let{rel:e,editor:w}of detectionRoots()){let D=resolve(t,e);if(!existsSync(D)||hostSkillsRootEscapes(t,D))continue;let O;try{O=readdirSync(D)}catch(e){logger$2.warn({hostRoot:D,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of O){if(SHIPPED_BUNDLE_NAMES.has(e))continue;let t=join(D,e),O=resolve(s,e),k=existsSync(O);try{let j=lstatSync(t);if(j.isSymbolicLink()){if(pointsAtSource(t,O)&&k)continue;k?(linkInto(D,t,O),g.healed.push({name:e,editor:w})):(tracedRmSync(t,{recursive:!0,force:!0}),g.orphansRemoved.push({name:e,editor:w}));continue}if(!j.isDirectory())continue;if(!SKILL_NAME_REGEX.test(e)){logger$2.warn({skill:e,editor:w},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(k&&(dirsEqual(t,O)||sameSkillModuloFrontmatter(t,O))){linkInto(D,t,O),g.replaced.push({name:e,editor:w}),E(e,w);continue}if(!S){g.skipped.push({name:e,editor:w});continue}if(!k)moveDir(t,O),linkInto(D,t,O),g.adopted.push({name:e,editor:w}),E(e,w);else{let S=`${e}-${w??`agents`}`,O=resolve(s,S);if(existsSync(O)){logger$2.warn({skill:e,editor:w,suffixed:S},`collision: suffixed slot already occupied — skipping (manual resolution needed)`);continue}moveDir(t,O),linkInto(D,join(D,S),O),g.collided.push({name:e,editor:w}),E(S,w)}}catch(t){logger$2.warn({err:t,skill:e,editor:w},`reconcile skipped one skill entry after error`)}}}if(w.size>0){let e=readInstalledSkills(t);for(let[g,S]of w){let w=resolve(s,g);if(!existsSync(w))continue;let E=e.skills[g],D=Array.from(new Set([...E?.hosts??[],...S]));try{await recordSkillInstall(t,g,{hosts:D,scope:E?.scope??`project`,scripts:E?.scripts??validateSkillForInstall(w,g).hasScripts,installedAt:E?.installedAt??new Date().toISOString()})}catch(e){logger$2.warn({err:e,skill:g},`reconcile marker update failed (non-fatal)`)}}}return g}const logger$1=getLogger(`skill-reproject`),SKILL_SURFACE_EDITORS=PROJECT_SKILL_EDITOR_IDS;async function reprojectAllManagedSkills(e){let{projectDir:t,skillsRoot:s,targets:g}=e,S=new Set(g),w=readInstalledSkills(t),E=[];for(let[e,D]of Object.entries(w.skills)){if(D.scope!==`project`)continue;let w=resolvedHosts(D.hosts);try{let O=resolve(s,e),k=!existsSync(O),j=k?null:validateSkillForInstall(O,e);if(k||!j?.ok){!k&&j&&!j.ok&&logger$1.warn({skill:e,errors:j.errors},`managed skill failed validation — left un-projected; fix SKILL.md (e.g. frontmatter.name must equal the folder name)`),reverseProjectSkill(e,t,w),await recordSkillInstall(t,e,{...D,hosts:[]}),E.push({name:e,hosts:[]});continue}let F=w.filter(e=>!S.has(e));F.length>0&&reverseProjectSkill(e,t,F);let L=projectSkill(O,e,t,g);await recordSkillInstall(t,e,{...D,hosts:L}),E.push({name:e,hosts:L})}catch(t){logger$1.warn({err:t,skill:e},`reproject skipped one skill after error`)}}return reverseBundleSkill(t,SKILL_SURFACE_EDITORS.filter(e=>!S.has(e))),{reprojected:E,bundleHosts:projectBundleSkill(t,g)}}const logger=getLogger(`skill-targets-store`);function skillTargetsPath(e){return join(e,...SKILL_TARGETS_REL)}function readSkillTargets(e){let t=skillTargetsPath(e);if(!existsSync(t))return null;try{let e=parseSkillTargets(readFileSync(t,`utf-8`));return e?e.targets:null}catch(e){return logger.warn({err:e,path:t},`skill-targets store unreadable`),null}}async function writeSkillTargets(e,t){let s=Array.from(new Set(t)),g=SkillTargetsSchema.safeParse({schema:1,targets:s});if(!g.success)throw Error(`Refusing to write invalid skill-targets: ${g.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let S=skillTargetsPath(e);await tracedMkdir(dirname(S),{recursive:!0}),await atomicWriteFile(S,`${JSON.stringify(g.data,null,2)}\n`,{fs:tracedAtomicFs})}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e,t){releaseProcessLock({lockName:`ui`,lockDir:e,...t})}function markUiLockDraining(e){markProcessLockDraining({lockName:`ui`,lockDir:e})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function uploadStatusFor(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return assertNeverProblemType(e)}}function classifyUploadErrno(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function uploadTitleFor(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return assertNeverProblemType(e)}}const log$10=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,s){this.hash.update(e),this.bytes+=e.length,s(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(getLocalDir(e),`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,s){let g=extname(s),S=s.slice(0,s.length-g.length),w=[s,...Array.from({length:99},(e,t)=>`${S}-${t+1}${g}`)];for(let s of w){let g=resolve(t,s);try{tracedLinkSync(e,g);try{tracedUnlinkSync(e)}catch{}return s}catch(t){let s=t.code;if(s===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw s===`ENOSPC`||s===`EDQUOT`?new UploadWriteError(`urn:ok:error:storage-full`,t):s===`EROFS`||s===`EACCES`||s===`EPERM`?new UploadWriteError(`urn:ok:error:storage-readonly`,t):new UploadWriteError(`urn:ok:error:storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`urn:ok:error:collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let s=tmpUploadDir(e),g={scanned:0,deleted:0,errors:0};if(!existsSync(s))return g;let S;try{S=readdirSync(s)}catch(e){return log$10.warn({err:e,dir:s},`[upload-tempfile-sweep] readdir failed`),g.errors++,g}let w=Date.now()-t;for(let e of S){if(!e.startsWith(`upload-`))continue;g.scanned++;let t=resolve(s,e);try{if(statSync(t).mtimeMs>=w)continue;tracedUnlinkSync(t),g.deleted++}catch(e){log$10.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),g.errors++}}return(g.deleted>0||g.errors>0)&&log$10.info({dir:s,scanned:g.scanned,deleted:g.deleted,errors:g.errors},`[upload-tempfile-sweep] swept ${g.deleted}/${g.scanned} (errors: ${g.errors})`),g}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,length:s.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let s=0;for(;e[t+s]==="`";)s++;if(s===0)return null;let g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S++;continue}let t=0;for(;e[S+t]==="`";)t++;if(t===s)return{nextIndex:S+s};S+=t}return{nextIndex:g}}function readWikiLink$2(e,t){let s=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!s)return null;let g=s[1]?.trim(),S=s[2]?.trim()||null,w=s[3]?.trim()||null;return g?{target:g,alias:w,anchor:S,nextIndex:t+s[0].length}:null}function readWikiLinkOrEmbed(e,t){if(e[t]===`!`&&e[t+1]===`[`&&e[t+2]===`[`){let s=readWikiLink$2(e,t+1);return s?{...s,embed:!0}:null}if(e[t]===`[`&&e[t+1]===`[`){let s=readWikiLink$2(e,t);return s?{...s,embed:!1}:null}return null}function readMarkdownLink$2(e,t){let s=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!s)return null;let g=s[2]??``;return{text:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,titleSuffix:s[3]??``,nextIndex:t+s[0].length}}function readImageRef(e,t){let s=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!s)return null;let g=s[2]??``;return{alt:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,titleSuffix:s[3]??``,nextIndex:t+s[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),s=[];for(let e=0;e<t.length;e+=2)s.push({line:t[e]??``,ending:t[e+1]??``});return s}function rewriteWikiLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$2(e,w);if(E){E.target===t?(g+=`[[${s}${E.anchor?`#${E.anchor}`:``}${E.alias?`|${E.alias}`:``}]]`,S++):g+=e.slice(w,E.nextIndex),w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function recomputeRelativeImageHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w;if(O.startsWith(`/`)||O.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(O))return null;let k=posix.dirname(t),j=posix.dirname(s);if(k===j)return null;let F=k===`.`?`/`:`/${k}/`,L=posix.resolve(F,O).slice(1),B=posix.relative(j===`.`?``:j,L);return B||=posix.basename(L),O.startsWith(`./`)&&!B.startsWith(`./`)&&!B.startsWith(`../`)&&(B=`./${B}`),`${B}${D}${S}`}function decodeHrefForAssetResolution(e){try{return decodeURI(e)}catch{return e}}function splitHrefPathAndSuffix(e){let t=e.indexOf(`#`),s=t>=0?e.slice(t):``,g=t>=0?e.slice(0,t):e,S=g.indexOf(`?`),w=S>=0?g.slice(S):``;return{pathPart:S>=0?g.slice(0,S):g,suffix:`${w}${s}`}}function buildAssetHrefFromSource(e,t,s,g={}){let S=g.encodePath??!0,w=e=>S?encodeURI(e):e,{pathPart:E,suffix:D}=splitHrefPathAndSuffix(e);if(E.startsWith(`/`))return`/${w(s)}${D}`;let O=posix.dirname(t),k=posix.relative(O===`.`?``:O,s);return k||=posix.basename(s),E.startsWith(`./`)&&!k.startsWith(`./`)&&!k.startsWith(`../`)&&(k=`./${k}`),`${w(k)}${D}`}function rewriteAssetHrefForRename(e,t,s,g,S={}){return resolveAssetProjectPath(decodeHrefForAssetResolution(e),t)===s?buildAssetHrefFromSource(e,t,g,S):null}function recomputeRelativeMarkdownHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w,k=O.startsWith(`/`),j=posix.dirname(t),F=k?`/${s}`:posix.relative(j===`.`?``:j,s);return F||=posix.basename(s),O.endsWith(`.mdx`)?F+=`.mdx`:O.endsWith(`.md`)&&(F+=`.md`),!k&&O.startsWith(`./`)&&!F.startsWith(`./`)&&!F.startsWith(`../`)&&(F=`./${F}`),`${F}${D}${S}`}function rewriteMarkdownLinksInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=t===s&&s!==g?recomputeRelativeImageHref(D.href,s,g):null;if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`![${D.alt}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){if(resolveInternalHref(D.href,t)?.docName===s){let e=recomputeRelativeMarkdownHref(D.href,t,g),s=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${e}>`:e;S+=`[${D.text}](${s}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}function renderWikiLinkOrEmbed(e,t){return`${e.embed?`!`:``}[[${t}${e.anchor?`#${e.anchor}`:``}${e.alias?`|${e.alias}`:``}]]`}const HTML_ASSET_ATTR_RE=/(\s(?:href|src)\s*=\s*)(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function rewriteHtmlAssetAttrsInTag(e,t,s,g){let S=0;return{markdown:e.replace(HTML_ASSET_ATTR_RE,(e,w,E,D,O,k)=>{let j=E??D??O??k;if(typeof j!=`string`)return e;let F=rewriteAssetHrefForRename(j,t,s,g);return F===null?e:(S++,E===void 0?D===void 0?O===void 0?`${w}${F}`:`${w}“${F}”`:`${w}'${F}'`:`${w}"${F}"`)}),rewrites:S}}function rewriteAssetReferencesInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}let D=readWikiLinkOrEmbed(e,E);if(D){let O=rewriteAssetHrefForRename(D.target,t,s,g,{encodePath:!1});O===null?S+=e.slice(E,D.nextIndex):(S+=renderWikiLinkOrEmbed(D,O),w++),E=D.nextIndex;continue}if(e.startsWith(`<!--`,E)){let t=e.indexOf(`-->`,E+4);if(t===-1){S+=e.slice(E);break}S+=e.slice(E,t+3),E=t+3;continue}if(e[E]===`<`){let D=e.indexOf(`>`,E+1);if(D!==-1){let O=rewriteHtmlAssetAttrsInTag(e.slice(E,D+1),t,s,g);if(O.rewrites>0){S+=O.markdown,w+=O.rewrites,E=D+1;continue}}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`![${D.alt}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`[${D.text}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,s){let g=``,S=0,w=0;for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`<`){let E=new RegExp(MIRROR_TAG_RE.source),D=e.slice(w),O=E.exec(D);if(O&&O.index===0){let[e,E]=O,D=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),k=E.replace(D,(e,g,w,E)=>E===t?(S++,`${g}${w}${s}${w}`):e);g+=`<Mirror${k}/>`,w+=e.length;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteMirrorSrcForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteMirrorSrcInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteWikiLinksForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteWikiLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteMarkdownLinksForDocumentRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteMarkdownLinksInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteAssetReferencesForRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteAssetReferencesInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteOutboundMarkdownLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let t=readWikiLink$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`!`&&e[w+1]===`[`){let t=readImageRef(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`){let E=readMarkdownLink$2(e,w);if(E){let D=resolveInternalHref(E.href,t);if(D!==null){let t=recomputeRelativeMarkdownHref(E.href,s,D.docName);if(t!==E.href){let e=E.hrefRaw.startsWith(`<`)&&E.hrefRaw.endsWith(`>`)?`<${t}>`:t;g+=`[${E.text}](${e}${E.titleSuffix})`,S++}else g+=e.slice(w,E.nextIndex)}else g+=e.slice(w,E.nextIndex);w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,s){if(posix.dirname(t)===posix.dirname(s))return{markdown:e,rewrites:0};let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteOutboundMarkdownLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e,t=`${e} does not exist`){super(t),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e,t=`Source path is not a ${e}`){super(t),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},ManagedRenameInvalidRequestError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameInvalidRequestError`}},ManagedRenameReservedPathError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameReservedPathError`}},SymlinkEscapeError=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},BacklinkIndexRequiredError=class extends Error{constructor(){super(`Managed rename requires backlink index support`),this.name=`BacklinkIndexRequiredError`}},ManagedRenameSnapshotMissingError=class extends Error{docName;constructor(e){super(`Cannot snapshot missing document: ${e}`),this.name=`ManagedRenameSnapshotMissingError`,this.docName=e}},ManagedRenameMissingDocumentError=class extends Error{docName;constructor(e){super(`Cannot rename missing document: ${e}`),this.name=`ManagedRenameMissingDocumentError`,this.docName=e}};function buildRenameMap(e){let t=new Map,s=[];for(let{from:g,to:S}of e){for(let[e,w]of t)e!==g&&w===S&&s.push({existing:e,incoming:g,to:S});t.set(g,S)}if(s.length>0)throw new ManagedRenameCollisionError(s);return t}function rewriteSupportedLinksForRename(e,t,s,g){let{frontmatter:S,body:w}=stripFrontmatter(e),E=rewriteWikiLinksForDocumentRename(w,s,g),D=rewriteMarkdownLinksForDocumentRename(E.markdown,t,s,g),O=rewriteMirrorSrcForDocumentRename(D.markdown,s,g);return{markdown:prependFrontmatter(S,O.markdown),rewrites:E.rewrites+D.rewrites+O.rewrites}}function applyRenameMap(e,t,s){let g=e,S=0,w,E=[];for(let[e,g]of s)e!==g&&(e===t?w=g:E.push([e,g]));if(w!==void 0){let e=rewriteSupportedLinksForRename(g,t,t,w);g=e.markdown,S+=e.rewrites;let{frontmatter:s,body:E}=stripFrontmatter(g),D=rewriteOutboundMarkdownLinksForSourceMove(E,t,w);g=prependFrontmatter(s,D.markdown),S+=D.rewrites}let D=w??t,O=new Map;for(let[e,t]of E){let s=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,w=rewriteSupportedLinksForRename(g,D,e,s);w.rewrites>0&&(g=w.markdown,S+=w.rewrites,O.set(s,t))}for(let[e,t]of O)g=rewriteSupportedLinksForRename(g,D,e,t).markdown;return{markdown:g,rewrites:S}}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState$1(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function parseSkillBundleDocAnyScope(e){let t=parseProjectSkillBundleDoc(e);if(t)return{name:t.name,kind:t.kind,skillDocName:skillLiveDocName(`project`,t.name)};let s=parseGlobalSkillBundleDoc(e);return s?{name:s.name,kind:s.kind,skillDocName:skillLiveDocName(`global`,s.name)}:null}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,s){if(!normalizeSnippet$1(e))return null;let g=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
835
+ `)}function compareSemver(e,t){let s=e.split(`.`).map(e=>Number.parseInt(e,10)||0),g=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=s[e]??0,S=g[e]??0;if(t!==S)return t-S}return 0}function resolvedHosts(e){let t=PROJECT_SKILL_EDITOR_IDS;return e.filter(e=>t.includes(e))}const RESERVED_SKILL_PREFIX=`open-knowledge`,PACK_SKILL_PREFIX=`open-knowledge-pack-`,SHIPPED_SKILL_NAME=`open-knowledge`,FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,CONFLICT_MARKER_RES=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function parseFrontmatter(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]??``);return e&&typeof e==`object`&&!Array.isArray(e)?e:null}catch{return null}}function validateSkillForInstall(e,t,s){let g=[],S=join(e,`SKILL.md`),w=existsSync(join(e,`scripts`))&&statSync(join(e,`scripts`)).isDirectory(),E=t.startsWith(RESERVED_SKILL_PREFIX)&&!t.startsWith(`open-knowledge-pack-`);if(!s?.allowReservedName&&E&&g.push(`"${t}" uses the reserved \`${RESERVED_SKILL_PREFIX}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!existsSync(S))return g.push(`No SKILL.md found at ${e}.`),{ok:g.length===0,errors:g,hasScripts:w};let D;try{D=readFileSync(S,`utf-8`)}catch(e){return g.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:g,hasScripts:w}}CONFLICT_MARKER_RES.some(e=>e.test(D))&&g.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let O=parseFrontmatter(D);if(O===null)g.push("SKILL.md has no valid `---` frontmatter block (name + description required).");else{let e=O.name,s=O.description;typeof e!=`string`||e.length===0?g.push(`SKILL.md frontmatter.name is missing or empty.`):e!==t&&g.push(`SKILL.md frontmatter.name ("${e}") must equal the skill directory ("${t}").`),(typeof s!=`string`||s.length===0)&&g.push(`SKILL.md frontmatter.description is missing or empty.`),(typeof e==`string`&&containsXmlTag(e)||typeof s==`string`&&containsXmlTag(s))&&g.push("SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.")}return{ok:g.length===0,errors:g,hasScripts:w}}function detectProjectConfiguredTargets(e){return PROJECT_SKILL_EDITOR_IDS.filter(t=>{let s=EDITOR_PROJECT_CONFIG_PATH[t];return s!==null&&existsSync(resolve(e,s))})}function resolveSkillTargets(e,t){if(t&&t.length>0){let e=new Set(PROJECT_SKILL_EDITOR_IDS);return t.filter(t=>e.has(t))}return detectProjectConfiguredTargets(e)}function skillHostDir(e,t,s){let g=EDITOR_PROJECT_SKILL_ROOT[t];return g===null?null:resolve(e,g,s)}function hostSkillsRootEscapes(e,t){if(!existsSync(t))return!1;try{let s=relative(realpathSync(e),realpathSync(t));return s.startsWith(`..`)||isAbsolute(s)}catch{return!0}}function skillLinkTarget(e,t,s){let g=resolve(s),S=relative(resolve(e),g);return S!==``&&!S.startsWith(`..`)&&!isAbsolute(S)?relative(t,g):g}function projectSkill(e,t,s,g){let S=[];for(let w of g){let g=skillHostDir(s,w,t);if(g===null)continue;let E=dirname(g);hostSkillsRootEscapes(s,E)||(tracedRmSync(g,{recursive:!0,force:!0}),tracedMkdirSync(E,{recursive:!0}),tracedSymlinkSync(skillLinkTarget(s,E,e),g,`dir`),S.push(w))}return S}function reverseProjectSkill(e,t,s){let g=[];for(let S of s){let s=skillHostDir(t,S,e);if(s===null)continue;let w=!1;try{lstatSync(s),w=!0}catch{w=!1}w&&(tracedRmSync(s,{recursive:!0,force:!0}),g.push(S))}return g}function projectBundleSkill(e,t){let s;try{s=resolveBundledSkillDir(`project`,{checkDesktop:!0})}catch{return[]}let g=[];for(let S of t){let t=skillHostDir(e,S,SHIPPED_SKILL_NAME);t!==null&&(hostSkillsRootEscapes(e,dirname(t))||(tracedRmSync(t,{recursive:!0,force:!0}),tracedCpSync(s,t,{recursive:!0}),g.push(S)))}return g}function reverseBundleSkill(e,t){return reverseProjectSkill(SHIPPED_SKILL_NAME,e,t)}const MAX_BUNDLED_FILE_BYTES=256*1024;function listSkillFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listSkillFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function readSkillBundledFiles(e){if(!existsSync(e))return[];let t=[];for(let s of listSkillFiles(e)){if(s===`SKILL.md`)continue;let g=null;try{let t=readFileSync(join(e,s));t.length<=MAX_BUNDLED_FILE_BYTES&&!t.includes(0)&&(g=t.toString(`utf-8`))}catch(e){if(e?.code!==`ENOENT`)throw e;g=null}t.push({path:s,text:g})}return t}function isPackSkillName(e){return e.startsWith(PACK_SKILL_PREFIX)}function packIdFromSkillName(e){return isPackSkillName(e)?e.slice(20):null}function readSkillVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let{map:s}=parseFrontmatterYaml(unwrapFrontmatterFences(t)),g=s?.version;return typeof g==`string`&&g.trim()!==``?g:void 0}function bundledPackSkillDir(e){let t=packIdFromSkillName(e);if(t===null)return null;try{return resolveBundledSkillDir(`packs/${t}`,{checkDesktop:!1})}catch{return null}}function bundledPackVersion(e){let t=bundledPackSkillDir(e);if(t!==null)try{return readSkillVersion(readFileSync(join(t,`SKILL.md`),`utf-8`))}catch{return}}function readBundledPackSkill(e){let t=bundledPackSkillDir(e);if(t===null)return null;let s;try{s=readFileSync(join(t,`SKILL.md`),`utf-8`)}catch{return null}return{content:s,version:readSkillVersion(s)}}function packUpdateAvailable(e,t){return e===void 0?!0:compareSemver(t,e)>0}function computePackUpdateStatus(e,t){let s=bundledPackVersion(e);return s===void 0?{}:{bundledVersion:s,updateAvailable:packUpdateAvailable(t,s)}}const logger$3=getLogger(`skill-reconcile`),SHIPPED_BUNDLE_NAMES=new Set([`open-knowledge`,`open-knowledge-discovery`]);function detectionRoots(){let e=[];for(let t of PROJECT_SKILL_EDITOR_IDS){let s=EDITOR_PROJECT_SKILL_ROOT[t];s!==null&&e.push({rel:s,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function relativeLinkTarget(e,t){let s=relative(e,resolve(t));return isAbsolute(s)?resolve(t):s}const DIRS_EQUAL_MAX_BYTES=1048576;function dirsEqual(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES||!readFileSync(D).equals(readFileSync(O)))return!1}return!0}function parseSkillManifest(e){let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{fm:g,body:s}}function skillManifestsSame(e,t){let s=parseSkillManifest(e),g=parseSkillManifest(t);if(s.body!==g.body)return!1;for(let e of Object.keys(s.fm))if(e in g.fm&&JSON.stringify(s.fm[e])!==JSON.stringify(g.fm[e]))return!1;return!0}function sameSkillModuloFrontmatter(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES)return!1;let k=readFileSync(D),j=readFileSync(O);if(!k.equals(j)&&(E!==`SKILL.md`||!skillManifestsSame(k.toString(`utf8`),j.toString(`utf8`))))return!1}return!0}function listFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function moveDir(e,t){tracedMkdirSync(dirname(t),{recursive:!0});try{tracedRenameSync(e,t)}catch(s){if(!(s instanceof Error)||s.code!==`EXDEV`)throw s;tracedCpSync(e,t,{recursive:!0}),tracedRmSync(e,{recursive:!0,force:!0})}}function linkInto(e,t,s){tracedRmSync(t,{recursive:!0,force:!0}),tracedMkdirSync(e,{recursive:!0}),tracedSymlinkSync(relativeLinkTarget(e,s),t,`dir`)}function pointsAtSource(e,t){try{let s=readlinkSync(e);return resolve(isAbsolute(s)?s:resolve(dirname(e),s))===resolve(t)}catch{return!1}}function countImportableEditorSkills(e){let{projectDir:t,skillsRoot:s}=e,g=new Set;for(let{rel:e}of detectionRoots()){let S=resolve(t,e);if(!existsSync(S)||hostSkillsRootEscapes(t,S))continue;let w;try{w=readdirSync(S)}catch(e){logger$3.warn({hostRoot:S,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of w){if(SHIPPED_BUNDLE_NAMES.has(e)||!SKILL_NAME_REGEX.test(e))continue;let t=join(S,e),w;try{w=lstatSync(t)}catch{continue}if(w.isSymbolicLink()||!w.isDirectory())continue;let E=resolve(s,e);existsSync(E)&&(dirsEqual(t,E)||sameSkillModuloFrontmatter(t,E))||g.add(e)}}return g.size}async function reconcileSkillInstalls(e){let{projectDir:t,skillsRoot:s}=e,g={healed:[],adopted:[],replaced:[],collided:[],orphansRemoved:[],skipped:[]},S=isProjectSkillManaged(t),w=new Map,E=(e,t)=>{if(t===null)return;let s=w.get(e)??new Set;s.add(t),w.set(e,s)};for(let{rel:e,editor:w}of detectionRoots()){let D=resolve(t,e);if(!existsSync(D)||hostSkillsRootEscapes(t,D))continue;let O;try{O=readdirSync(D)}catch(e){logger$3.warn({hostRoot:D,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of O){if(SHIPPED_BUNDLE_NAMES.has(e))continue;let t=join(D,e),O=resolve(s,e),k=existsSync(O);try{let j=lstatSync(t);if(j.isSymbolicLink()){if(pointsAtSource(t,O)&&k)continue;k?(linkInto(D,t,O),g.healed.push({name:e,editor:w})):(tracedRmSync(t,{recursive:!0,force:!0}),g.orphansRemoved.push({name:e,editor:w}));continue}if(!j.isDirectory())continue;if(!SKILL_NAME_REGEX.test(e)){logger$3.warn({skill:e,editor:w},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(k&&(dirsEqual(t,O)||sameSkillModuloFrontmatter(t,O))){linkInto(D,t,O),g.replaced.push({name:e,editor:w}),E(e,w);continue}if(!S){g.skipped.push({name:e,editor:w});continue}if(!k)moveDir(t,O),linkInto(D,t,O),g.adopted.push({name:e,editor:w}),E(e,w);else{let S=`${e}-${w??`agents`}`,O=resolve(s,S);if(existsSync(O)){logger$3.warn({skill:e,editor:w,suffixed:S},`collision: suffixed slot already occupied — skipping (manual resolution needed)`);continue}moveDir(t,O),linkInto(D,join(D,S),O),g.collided.push({name:e,editor:w}),E(S,w)}}catch(t){logger$3.warn({err:t,skill:e,editor:w},`reconcile skipped one skill entry after error`)}}}if(w.size>0){let e=readInstalledSkills(t);for(let[g,S]of w){let w=resolve(s,g);if(!existsSync(w))continue;let E=e.skills[g],D=Array.from(new Set([...E?.hosts??[],...S]));try{await recordSkillInstall(t,g,{hosts:D,scope:E?.scope??`project`,scripts:E?.scripts??validateSkillForInstall(w,g).hasScripts,installedAt:E?.installedAt??new Date().toISOString()})}catch(e){logger$3.warn({err:e,skill:g},`reconcile marker update failed (non-fatal)`)}}}return g}const logger$2=getLogger(`skill-reproject`),SKILL_SURFACE_EDITORS=PROJECT_SKILL_EDITOR_IDS;async function reprojectAllManagedSkills(e){let{projectDir:t,skillsRoot:s,targets:g}=e,S=new Set(g),w=readInstalledSkills(t),E=[];for(let[e,D]of Object.entries(w.skills)){if(D.scope!==`project`)continue;let w=resolvedHosts(D.hosts);try{let O=resolve(s,e),k=!existsSync(O),j=k?null:validateSkillForInstall(O,e);if(k||!j?.ok){!k&&j&&!j.ok&&logger$2.warn({skill:e,errors:j.errors},`managed skill failed validation — left un-projected; fix SKILL.md (e.g. frontmatter.name must equal the folder name)`),reverseProjectSkill(e,t,w),await recordSkillInstall(t,e,{...D,hosts:[]}),E.push({name:e,hosts:[]});continue}let F=w.filter(e=>!S.has(e));F.length>0&&reverseProjectSkill(e,t,F);let L=projectSkill(O,e,t,g);await recordSkillInstall(t,e,{...D,hosts:L}),E.push({name:e,hosts:L})}catch(t){logger$2.warn({err:t,skill:e},`reproject skipped one skill after error`)}}return reverseBundleSkill(t,SKILL_SURFACE_EDITORS.filter(e=>!S.has(e))),{reprojected:E,bundleHosts:projectBundleSkill(t,g)}}const logger$1=getLogger(`skill-targets-store`);function skillTargetsPath(e){return join(e,...SKILL_TARGETS_REL)}function readSkillTargets(e){let t=skillTargetsPath(e);if(!existsSync(t))return null;try{let e=parseSkillTargets(readFileSync(t,`utf-8`));return e?e.targets:null}catch(e){return logger$1.warn({err:e,path:t},`skill-targets store unreadable`),null}}async function writeSkillTargets(e,t){let s=Array.from(new Set(t)),g=SkillTargetsSchema.safeParse({schema:1,targets:s});if(!g.success)throw Error(`Refusing to write invalid skill-targets: ${g.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let S=skillTargetsPath(e);await tracedMkdir(dirname(S),{recursive:!0}),await atomicWriteFile(S,`${JSON.stringify(g.data,null,2)}\n`,{fs:tracedAtomicFs})}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e,t){releaseProcessLock({lockName:`ui`,lockDir:e,...t})}function markUiLockDraining(e){markProcessLockDraining({lockName:`ui`,lockDir:e})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function uploadStatusFor(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return assertNeverProblemType(e)}}function classifyUploadErrno(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function uploadTitleFor(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return assertNeverProblemType(e)}}const log$11=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,s){this.hash.update(e),this.bytes+=e.length,s(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(getLocalDir(e),`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,s){let g=extname(s),S=s.slice(0,s.length-g.length),w=[s,...Array.from({length:99},(e,t)=>`${S}-${t+1}${g}`)];for(let s of w){let g=resolve(t,s);try{tracedLinkSync(e,g);try{tracedUnlinkSync(e)}catch{}return s}catch(t){let s=t.code;if(s===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw s===`ENOSPC`||s===`EDQUOT`?new UploadWriteError(`urn:ok:error:storage-full`,t):s===`EROFS`||s===`EACCES`||s===`EPERM`?new UploadWriteError(`urn:ok:error:storage-readonly`,t):new UploadWriteError(`urn:ok:error:storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`urn:ok:error:collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let s=tmpUploadDir(e),g={scanned:0,deleted:0,errors:0};if(!existsSync(s))return g;let S;try{S=readdirSync(s)}catch(e){return log$11.warn({err:e,dir:s},`[upload-tempfile-sweep] readdir failed`),g.errors++,g}let w=Date.now()-t;for(let e of S){if(!e.startsWith(`upload-`))continue;g.scanned++;let t=resolve(s,e);try{if(statSync(t).mtimeMs>=w)continue;tracedUnlinkSync(t),g.deleted++}catch(e){log$11.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),g.errors++}}return(g.deleted>0||g.errors>0)&&log$11.info({dir:s,scanned:g.scanned,deleted:g.deleted,errors:g.errors},`[upload-tempfile-sweep] swept ${g.deleted}/${g.scanned} (errors: ${g.errors})`),g}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,length:s.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let s=0;for(;e[t+s]==="`";)s++;if(s===0)return null;let g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S++;continue}let t=0;for(;e[S+t]==="`";)t++;if(t===s)return{nextIndex:S+s};S+=t}return{nextIndex:g}}function readWikiLink$2(e,t){let s=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!s)return null;let g=s[1]?.trim(),S=s[2]?.trim()||null,w=s[3]?.trim()||null;return g?{target:g,alias:w,anchor:S,nextIndex:t+s[0].length}:null}function readWikiLinkOrEmbed(e,t){if(e[t]===`!`&&e[t+1]===`[`&&e[t+2]===`[`){let s=readWikiLink$2(e,t+1);return s?{...s,embed:!0}:null}if(e[t]===`[`&&e[t+1]===`[`){let s=readWikiLink$2(e,t);return s?{...s,embed:!1}:null}return null}function readMarkdownLink$2(e,t){let s=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!s)return null;let g=s[2]??``;return{text:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,titleSuffix:s[3]??``,nextIndex:t+s[0].length}}function readImageRef(e,t){let s=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!s)return null;let g=s[2]??``;return{alt:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,titleSuffix:s[3]??``,nextIndex:t+s[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),s=[];for(let e=0;e<t.length;e+=2)s.push({line:t[e]??``,ending:t[e+1]??``});return s}function rewriteWikiLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$2(e,w);if(E){E.target===t?(g+=`[[${s}${E.anchor?`#${E.anchor}`:``}${E.alias?`|${E.alias}`:``}]]`,S++):g+=e.slice(w,E.nextIndex),w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function recomputeRelativeImageHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w;if(O.startsWith(`/`)||O.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(O))return null;let k=posix.dirname(t),j=posix.dirname(s);if(k===j)return null;let F=k===`.`?`/`:`/${k}/`,L=posix.resolve(F,O).slice(1),B=posix.relative(j===`.`?``:j,L);return B||=posix.basename(L),O.startsWith(`./`)&&!B.startsWith(`./`)&&!B.startsWith(`../`)&&(B=`./${B}`),`${B}${D}${S}`}function decodeHrefForAssetResolution(e){try{return decodeURI(e)}catch{return e}}function splitHrefPathAndSuffix(e){let t=e.indexOf(`#`),s=t>=0?e.slice(t):``,g=t>=0?e.slice(0,t):e,S=g.indexOf(`?`),w=S>=0?g.slice(S):``;return{pathPart:S>=0?g.slice(0,S):g,suffix:`${w}${s}`}}function buildAssetHrefFromSource(e,t,s,g={}){let S=g.encodePath??!0,w=e=>S?encodeURI(e):e,{pathPart:E,suffix:D}=splitHrefPathAndSuffix(e);if(E.startsWith(`/`))return`/${w(s)}${D}`;let O=posix.dirname(t),k=posix.relative(O===`.`?``:O,s);return k||=posix.basename(s),E.startsWith(`./`)&&!k.startsWith(`./`)&&!k.startsWith(`../`)&&(k=`./${k}`),`${w(k)}${D}`}function rewriteAssetHrefForRename(e,t,s,g,S={}){return resolveAssetProjectPath(decodeHrefForAssetResolution(e),t)===s?buildAssetHrefFromSource(e,t,g,S):null}function recomputeRelativeMarkdownHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w,k=O.startsWith(`/`),j=posix.dirname(t),F=k?`/${s}`:posix.relative(j===`.`?``:j,s);return F||=posix.basename(s),O.endsWith(`.mdx`)?F+=`.mdx`:O.endsWith(`.md`)&&(F+=`.md`),!k&&O.startsWith(`./`)&&!F.startsWith(`./`)&&!F.startsWith(`../`)&&(F=`./${F}`),`${F}${D}${S}`}function rewriteMarkdownLinksInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=t===s&&s!==g?recomputeRelativeImageHref(D.href,s,g):null;if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`![${D.alt}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){if(resolveInternalHref(D.href,t)?.docName===s){let e=recomputeRelativeMarkdownHref(D.href,t,g),s=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${e}>`:e;S+=`[${D.text}](${s}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}function renderWikiLinkOrEmbed(e,t){return`${e.embed?`!`:``}[[${t}${e.anchor?`#${e.anchor}`:``}${e.alias?`|${e.alias}`:``}]]`}const HTML_ASSET_ATTR_RE=/(\s(?:href|src)\s*=\s*)(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function rewriteHtmlAssetAttrsInTag(e,t,s,g){let S=0;return{markdown:e.replace(HTML_ASSET_ATTR_RE,(e,w,E,D,O,k)=>{let j=E??D??O??k;if(typeof j!=`string`)return e;let F=rewriteAssetHrefForRename(j,t,s,g);return F===null?e:(S++,E===void 0?D===void 0?O===void 0?`${w}${F}`:`${w}“${F}”`:`${w}'${F}'`:`${w}"${F}"`)}),rewrites:S}}function rewriteAssetReferencesInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}let D=readWikiLinkOrEmbed(e,E);if(D){let O=rewriteAssetHrefForRename(D.target,t,s,g,{encodePath:!1});O===null?S+=e.slice(E,D.nextIndex):(S+=renderWikiLinkOrEmbed(D,O),w++),E=D.nextIndex;continue}if(e.startsWith(`<!--`,E)){let t=e.indexOf(`-->`,E+4);if(t===-1){S+=e.slice(E);break}S+=e.slice(E,t+3),E=t+3;continue}if(e[E]===`<`){let D=e.indexOf(`>`,E+1);if(D!==-1){let O=rewriteHtmlAssetAttrsInTag(e.slice(E,D+1),t,s,g);if(O.rewrites>0){S+=O.markdown,w+=O.rewrites,E=D+1;continue}}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`![${D.alt}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`[${D.text}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,s){let g=``,S=0,w=0;for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`<`){let E=new RegExp(MIRROR_TAG_RE.source),D=e.slice(w),O=E.exec(D);if(O&&O.index===0){let[e,E]=O,D=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),k=E.replace(D,(e,g,w,E)=>E===t?(S++,`${g}${w}${s}${w}`):e);g+=`<Mirror${k}/>`,w+=e.length;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteMirrorSrcForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteMirrorSrcInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteWikiLinksForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteWikiLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteMarkdownLinksForDocumentRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteMarkdownLinksInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteAssetReferencesForRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteAssetReferencesInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteOutboundMarkdownLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let t=readWikiLink$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`!`&&e[w+1]===`[`){let t=readImageRef(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`){let E=readMarkdownLink$2(e,w);if(E){let D=resolveInternalHref(E.href,t);if(D!==null){let t=recomputeRelativeMarkdownHref(E.href,s,D.docName);if(t!==E.href){let e=E.hrefRaw.startsWith(`<`)&&E.hrefRaw.endsWith(`>`)?`<${t}>`:t;g+=`[${E.text}](${e}${E.titleSuffix})`,S++}else g+=e.slice(w,E.nextIndex)}else g+=e.slice(w,E.nextIndex);w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,s){if(posix.dirname(t)===posix.dirname(s))return{markdown:e,rewrites:0};let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteOutboundMarkdownLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e,t=`${e} does not exist`){super(t),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e,t=`Source path is not a ${e}`){super(t),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},ManagedRenameInvalidRequestError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameInvalidRequestError`}},ManagedRenameReservedPathError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameReservedPathError`}},SymlinkEscapeError=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},BacklinkIndexRequiredError=class extends Error{constructor(){super(`Managed rename requires backlink index support`),this.name=`BacklinkIndexRequiredError`}},ManagedRenameSnapshotMissingError=class extends Error{docName;constructor(e){super(`Cannot snapshot missing document: ${e}`),this.name=`ManagedRenameSnapshotMissingError`,this.docName=e}},ManagedRenameMissingDocumentError=class extends Error{docName;constructor(e){super(`Cannot rename missing document: ${e}`),this.name=`ManagedRenameMissingDocumentError`,this.docName=e}};function buildRenameMap(e){let t=new Map,s=[];for(let{from:g,to:S}of e){for(let[e,w]of t)e!==g&&w===S&&s.push({existing:e,incoming:g,to:S});t.set(g,S)}if(s.length>0)throw new ManagedRenameCollisionError(s);return t}function rewriteSupportedLinksForRename(e,t,s,g){let{frontmatter:S,body:w}=stripFrontmatter(e),E=rewriteWikiLinksForDocumentRename(w,s,g),D=rewriteMarkdownLinksForDocumentRename(E.markdown,t,s,g),O=rewriteMirrorSrcForDocumentRename(D.markdown,s,g);return{markdown:prependFrontmatter(S,O.markdown),rewrites:E.rewrites+D.rewrites+O.rewrites}}function applyRenameMap(e,t,s){let g=e,S=0,w,E=[];for(let[e,g]of s)e!==g&&(e===t?w=g:E.push([e,g]));if(w!==void 0){let e=rewriteSupportedLinksForRename(g,t,t,w);g=e.markdown,S+=e.rewrites;let{frontmatter:s,body:E}=stripFrontmatter(g),D=rewriteOutboundMarkdownLinksForSourceMove(E,t,w);g=prependFrontmatter(s,D.markdown),S+=D.rewrites}let D=w??t,O=new Map;for(let[e,t]of E){let s=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,w=rewriteSupportedLinksForRename(g,D,e,s);w.rewrites>0&&(g=w.markdown,S+=w.rewrites,O.set(s,t))}for(let[e,t]of O)g=rewriteSupportedLinksForRename(g,D,e,t).markdown;return{markdown:g,rewrites:S}}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState$1(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function parseSkillBundleDocAnyScope(e){let t=parseProjectSkillBundleDoc(e);if(t)return{name:t.name,kind:t.kind,skillDocName:skillLiveDocName(`project`,t.name)};let s=parseGlobalSkillBundleDoc(e);return s?{name:s.name,kind:s.kind,skillDocName:skillLiveDocName(`global`,s.name)}:null}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,s){if(!normalizeSnippet$1(e))return null;let g=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
836
836
  `,t-1)),S=[e.indexOf(`.`,s),e.indexOf(`?`,s),e.indexOf(`!`,s),e.indexOf(`
837
837
  `,s)].filter(e=>e>=0),w=g>=0?g+1:Math.max(0,t-60),E=S.length>0?Math.min(...S)+1:Math.min(e.length,s+60),D=w>0?`…`:``,O=E<e.length?`…`:``,k=normalizeSnippet$1(e.slice(w,E));return k?`${D}${k}${O}`:null}function matchFence$1(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,length:s.length}}function isFenceClose$1(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$1(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$1(e,t){let s=0;for(;e[t+s]==="`";)s++;if(s===0)return null;let g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S++;continue}let t=0;for(;e[S+t]==="`";)t++;if(t===s)return{text:e.slice(g,S),nextIndex:S+s};S+=t}return{text:e.slice(t,g),nextIndex:g}}function readWikiLink$1(e,t){WIKI_LINK_RE$1.lastIndex=t;let s=WIKI_LINK_RE$1.exec(e);if(!s)return null;let g=s[1]?.trim(),S=s[2]?.trim()||null,w=s[3]?.trim()||null;return g?{target:g,alias:w,anchor:S,nextIndex:t+s[0].length}:null}function extractWikiLinksFromLine(e,t){let s=``,g=[],S=leadingMarkdownPrefixLength$1(e);for(;S<e.length;){if(e[S]===`\\`&&S+1<e.length){s+=e[S+1],S+=2;continue}if(e[S]==="`"){let t=readInlineCode$1(e,S);if(t){s+=t.text,S=t.nextIndex;continue}}if(e[S]===`[`&&e[S+1]===`[`){let w=readWikiLink$1(e,S);if(w){let e=getWikiLinkText(w),E=s.length;s+=e;let D=classifyWikiLinkTarget(w.target,w.anchor);if(D?.kind===`doc`){let s=resolveSkillBundleWikiTarget(w.target,t)??D.docName;g.push({target:s,anchor:D.anchor,start:E,end:E+e.length})}S=w.nextIndex;continue}}s+=e[S],S++}return{text:s,occurrences:g}}function extractExternalWikiLinksFromLine(e){let t=``,s=[],g=leadingMarkdownPrefixLength$1(e);for(;g<e.length;){if(e[g]===`\\`&&g+1<e.length){t+=e[g+1],g+=2;continue}if(e[g]==="`"){let s=readInlineCode$1(e,g);if(s){t+=s.text,g=s.nextIndex;continue}}if(e[g]===`[`&&e[g+1]===`[`){let S=readWikiLink$1(e,g);if(S){let e=getWikiLinkText(S),w=t.length;t+=e;let E=classifyWikiLinkTarget(S.target,S.anchor);E?.kind===`external`&&s.push({url:E.url,label:e,start:w,end:w+e.length}),g=S.nextIndex;continue}}t+=e[g],g++}return{text:t,occurrences:s}}function normalizeMarkdownHref$1(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function readMarkdownLink$1(e,t){MD_LINK_RE$1.lastIndex=t;let s=MD_LINK_RE$1.exec(e);return s?{text:s[1]??``,href:normalizeMarkdownHref$1(s[2]??``),nextIndex:t+s[0].length}:null}function extractMarkdownLinksFromLine(e,t){let s=``,g=[],S=leadingMarkdownPrefixLength$1(e);for(;S<e.length;){if(e[S]===`\\`&&S+1<e.length){s+=e[S+1],S+=2;continue}if(e[S]==="`"){let t=readInlineCode$1(e,S);if(t){s+=t.text,S=t.nextIndex;continue}}if(e[S]===`[`&&e[S+1]===`[`){let t=readWikiLink$1(e,S);if(t){s+=getWikiLinkText(t),S=t.nextIndex;continue}}if(e[S]===`[`&&e[S-1]!==`!`){let w=readMarkdownLink$1(e,S);if(w){let e=classifyMarkdownHref(w.href,t);if(e?.kind===`doc`){let t=s.length;s+=w.text,g.push({target:e.docName,anchor:e.anchor,start:t,end:t+w.text.length})}else s+=w.text;S=w.nextIndex;continue}}s+=e[S],S++}return{text:s,occurrences:g}}function extractExternalMarkdownLinksFromLine(e,t){let s=``,g=[],S=leadingMarkdownPrefixLength$1(e);for(;S<e.length;){if(e[S]===`\\`&&S+1<e.length){s+=e[S+1],S+=2;continue}if(e[S]==="`"){let t=readInlineCode$1(e,S);if(t){s+=t.text,S=t.nextIndex;continue}}if(e[S]===`[`&&e[S+1]===`[`){let t=readWikiLink$1(e,S);if(t){s+=getWikiLinkText(t),S=t.nextIndex;continue}}if(e[S]===`[`&&e[S-1]!==`!`){let w=readMarkdownLink$1(e,S);if(w){let e=classifyMarkdownHref(w.href,t);if(s+=w.text,e?.kind===`external`){let t=s.length-w.text.length;g.push({url:e.url,label:w.text||null,start:t,end:t+w.text.length})}S=w.nextIndex;continue}}s+=e[S],S++}return{text:s,occurrences:g}}function extractMarkdownLinksFromMarkdown(e,t){let s=e.replaceAll(`\r
838
838
  `,`
@@ -954,7 +954,7 @@ last-spawn-error.log
954
954
  # !keep.md # re-include a file .gitignore excluded
955
955
  `,ROOT_GITIGNORE_TEMPLATE=`# Seeded by OpenKnowledge when this project was created. Edit freely.
956
956
  .DS_Store
957
- `;function initContent(e,t){let s=resolve(e,`.ok`),g=[],S=[],w=[];assertNotSymlink(s,`.ok/`),tracedMkdirSync(s,{recursive:!0});let E=ensureGitignoreEntries(join(s,`.gitignore`),OK_GITIGNORE_CONTENT);return E===`created`?g.push(`.gitignore`):E===`updated`?S.push(`.gitignore`):w.push(`.gitignore`),writeIfMissing(join(s,`config.yml`),buildConfigYmlContent(t?.packageVersion??`0.0.0`,{contentDir:t?.contentDir}),`.ok/config.yml`)?g.push(CONFIG_FILENAME):w.push(CONFIG_FILENAME),writeIfMissing(join(e,`.okignore`),OK_OKIGNORE_TEMPLATE,`.okignore`)?g.push(`.okignore`):w.push(`.okignore`),{created:g,updated:S,skipped:w}}function writeRootGitignoreForNewRepo(e){return writeIfMissing(join(e,`.gitignore`),ROOT_GITIGNORE_TEMPLATE,`.gitignore`)?`created`:`skipped`}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function ancestorChainHasSymlink(e,t){let s=dirname(e);for(;s!==t&&s!==dirname(s);){let e;try{e=lstatSync(s)}catch(e){let t=e.code;return console.warn(`[local-op-security] ancestorChainHasSymlink: lstat failed on ${s} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return console.warn(`[local-op-security] ancestorChainHasSymlink: symlink detected at ${s}`),!0;s=dirname(s)}return!1}function isPathWithinHome(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let s;try{s=realpathSync(t)}catch(e){let s=e.code;return console.warn(`[local-op-security] realpath failed on home dir ${t} (${s??`unknown`}); rejecting all paths`),!1}let g=resolve(expandTilde(e)),S=[],w=g;for(;;){let e=null;try{e=lstatSync(w)}catch(e){let t=e.code;if(t!==`ENOENT`)return console.warn(`[local-op-security] lstat error at ${w} (${t??`unknown`}); rejecting`),!1}if(e!==null){let g;try{g=realpathSync(w)}catch(s){let S=s.code;if(e.isSymbolicLink())return console.warn(`[local-op-security] realpath failed on symlink leaf at ${w} (${S??`unknown`}); rejecting`),!1;if(S===`EPERM`||S===`EACCES`){if(ancestorChainHasSymlink(w,t))return console.warn(`[local-op-security] EPERM accept-branch refused at ${w}: symlinked ancestor in chain; rejecting`),!1;console.warn(`[local-op-security] realpath denied on non-symlink leaf at ${w} (${S??`unknown`}); trusting lexical path (TCC-class)`),g=w}else return console.warn(`[local-op-security] realpath failed on non-symlink leaf at ${w} (${S??`unknown`}); rejecting`),!1}let E=S.length===0?g:join(g,...S),D=relative(s,E);return D===``||!D.startsWith(`..`)&&!isAbsolute(D)}let g=dirname(w);if(g===w)return!1;S.unshift(basename(w)),w=g}}function isSafeLocalPath(e){return isPathWithinHome(e,homedir())}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,s){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:s.handler}),!1):(errorResponse(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:s.handler}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}const SUBPROCESS_PIPE_STDIO_OPTIONS={stdio:[`ignore`,`pipe`,`pipe`]};function runSubprocess(e){let[t,...s]=e.cliArgs;if(!t)return{done:Promise.resolve({code:-1,stderr:`no command provided`,timedOut:!1,cancelled:!1}),cancel:()=>{}};let g=[...s,...e.trailingArgs],S=!1,w=!1,E=``,D=[],O={...process.env};e.extraPathDirs&&e.extraPathDirs.length>0&&(O.PATH=[...e.extraPathDirs,process.env.PATH??``].filter(Boolean).join(delimiter));let k=spawn(t,g,withHiddenWindowsConsole({...SUBPROCESS_PIPE_STDIO_OPTIONS,cwd:e.cwd,env:O})),j=setTimeout(()=>{S=!0,k.kill(`SIGTERM`)},e.timeoutMs),F=t=>{if(!t.trim())return;let s=null;try{let e=JSON.parse(t);s=e&&typeof e==`object`?e:null}catch{s=null}e.onLine({raw:t,parsed:s})};return k.stdout.on(`data`,e=>{E+=e.toString(`utf-8`);let t=E.split(`
957
+ `;function initContent(e,t){let s=resolve(e,`.ok`),g=[],S=[],w=[];assertNotSymlink(s,`.ok/`),tracedMkdirSync(s,{recursive:!0});let E=ensureGitignoreEntries(join(s,`.gitignore`),OK_GITIGNORE_CONTENT);return E===`created`?g.push(`.gitignore`):E===`updated`?S.push(`.gitignore`):w.push(`.gitignore`),writeIfMissing(join(s,`config.yml`),buildConfigYmlContent(t?.packageVersion??`0.0.0`,{contentDir:t?.contentDir}),`.ok/config.yml`)?g.push(CONFIG_FILENAME):w.push(CONFIG_FILENAME),writeIfMissing(join(e,`.okignore`),OK_OKIGNORE_TEMPLATE,`.okignore`)?g.push(`.okignore`):w.push(`.okignore`),{created:g,updated:S,skipped:w}}function writeRootGitignoreForNewRepo(e){return writeIfMissing(join(e,`.gitignore`),ROOT_GITIGNORE_TEMPLATE,`.gitignore`)?`created`:`skipped`}function parseIpLiteral(e){let t=e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;try{if(import_ipaddr.default.IPv4.isValid(t))return import_ipaddr.default.IPv4.parse(t);if(import_ipaddr.default.IPv6.isValid(t))return import_ipaddr.default.IPv6.parse(t)}catch{return null}return null}function isPublicUnicastIp(e){let t=parseIpLiteral(e);return t!==null&&t.range()===`unicast`}function classifyHost(e){let t=parseIpLiteral(e);return t===null?{kind:`hostname`}:{kind:`ip-literal`,allowed:t.range()===`unicast`,canonical:t.toString(),family:t.kind()===`ipv6`?6:4}}const logger=getLogger(`link-preview.guarded-fetch`),USER_AGENT=`OpenKnowledge-LinkPreview/1.x`,defaultResolve=async e=>(await lookup(e,{all:!0,family:0})).map(e=>({address:e.address,family:e.family===6?6:4}));function buildSanitizedUrl(e,t){let s=e.port?`:${e.port}`:``;return`${e.protocol}//${t}${s}${e.pathname}${e.search}`}async function admit(e,t,s){let g;try{g=new URL(e)}catch{return{ok:!1,reason:`fetch-error`}}if(g.protocol!==`http:`&&g.protocol!==`https:`)return{ok:!1,reason:`bad-scheme`};let S=classifyHost(g.hostname);if(S.kind===`ip-literal`){if(!S.allowed)return{ok:!1,reason:`private-ip`};let e=S.family===6?`[${S.canonical}]`:S.canonical;return{ok:!0,target:{requestUrl:buildSanitizedUrl(g,e),pinnedAddress:void 0,serverName:void 0,logicalUrl:g.toString()}}}let w;try{w=await t(g.hostname)}catch{return{ok:!1,reason:`dns-failure`}}if(w.length===0)return{ok:!1,reason:`dns-failure`};for(let e of w)if(!s(e.address))return{ok:!1,reason:`private-ip`};let E=w[0];return{ok:!0,target:{requestUrl:buildSanitizedUrl(g,g.hostname),pinnedAddress:{address:E.address,family:E.family===6||E.address.includes(`:`)?6:4},serverName:g.hostname,logicalUrl:g.toString()}}}function pinnedLookup(e){return(t,s,g)=>{s.all?g(null,[{address:e.address,family:e.family}]):g(null,e.address,e.family)}}function isRedirectStatus(e){return e===301||e===302||e===303||e===307||e===308}function parseMimeType(e){return e?(e.split(`;`,1)[0]??``).trim().toLowerCase():``}function classifyFetchError(e,t){return t.aborted||e instanceof Error&&(e.name===`TimeoutError`||e.name===`AbortError`)?`timeout`:`fetch-error`}function discardMessage(e){try{e.destroy()}catch{}}function issueRequest(e,t){return new Promise(s=>{let g=!1,S=e=>{g||(g=!0,s(e))},w=e.requestUrl.startsWith(`https:`),E={method:`GET`,agent:!1,signal:t,headers:{"User-Agent":USER_AGENT,Accept:`text/html`,"Accept-Encoding":`identity`}};e.pinnedAddress&&(E.lookup=pinnedLookup(e.pinnedAddress)),w&&e.serverName&&(E.servername=e.serverName);try{let s=(w?request$1:request)(e.requestUrl,E,e=>{e.on(`error`,()=>{}),S({ok:!0,response:e})});s.on(`error`,e=>S({ok:!1,reason:classifyFetchError(e,t)})),s.end()}catch(e){S({ok:!1,reason:classifyFetchError(e,t)})}})}function makeDecompressor(e){return e===``||e===`identity`?`identity`:e===`gzip`||e===`x-gzip`?createGunzip():e===`deflate`?createInflate():e===`br`?createBrotliDecompress():null}function readCappedBody(e,t,s){let g=makeDecompressor((e.headers[`content-encoding`]??``).trim().toLowerCase());if(g===null)return discardMessage(e),Promise.resolve({ok:!1,reason:`fetch-error`});let S=g===`identity`?e:e.pipe(g);return new Promise(g=>{let w=[],E=0,D=!1,O=()=>{s.removeEventListener(`abort`,j),discardMessage(e),S!==e&&S.destroy()},k=e=>{D||(D=!0,O(),g(e))},j=()=>k({ok:!1,reason:`timeout`});s.addEventListener(`abort`,j,{once:!0}),S!==e&&e.on(`error`,e=>k({ok:!1,reason:classifyFetchError(e,s)})),S.on(`data`,e=>{if(E+=e.byteLength,E>t){k({ok:!1,reason:`oversized`});return}w.push(e)}),S.on(`end`,()=>k({ok:!0,body:new Uint8Array(Buffer.concat(w))})),S.on(`error`,e=>k({ok:!1,reason:classifyFetchError(e,s)}))})}function rejectWith(e){return logger.debug({reason:e},`link-preview guarded fetch rejected`),{ok:!1,reason:e}}async function guardedFetch(e,t={}){let s=t.allowContentType??(e=>e===`text/html`),g=t.maxBytes??524288,S=t.timeoutMs??5e3,w=t.maxRedirects??3,E=t.resolve??defaultResolve,D=t.isAddressAllowed??isPublicUnicastIp,O=AbortSignal.timeout(S),k=e,j=0;for(;;){let e=await admit(k,E,D);if(!e.ok)return rejectWith(e.reason);let{target:t}=e,S=await issueRequest(t,O);if(!S.ok)return rejectWith(S.reason);let F=S.response;if(isRedirectStatus(F.statusCode??0)){let e=F.headers.location;if(discardMessage(F),e===void 0)return rejectWith(`fetch-error`);if(j>=w)return rejectWith(`redirect-limit`);j+=1;try{k=new URL(e,t.logicalUrl).toString()}catch{return rejectWith(`fetch-error`)}continue}let L=parseMimeType(F.headers[`content-type`]);if(!s(L))return discardMessage(F),rejectWith(`non-html`);let B=await readCappedBody(F,g,O);return B.ok?{ok:!0,body:B.body,contentType:L,finalUrl:t.logicalUrl}:rejectWith(B.reason)}}const MAX_TITLE=200,MAX_DESCRIPTION=500,MAX_SITE_NAME=100,NAMED_ENTITIES={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,copy:`©`,reg:`®`,trade:`™`,mdash:`—`,ndash:`–`,hellip:`…`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`};function decodeCodePoint(e){return!Number.isInteger(e)||e<0||e>1114111||e>=55296&&e<=57343?null:String.fromCodePoint(e)}function decodeHtmlEntities(e){return e.replace(/&(#[xX][0-9a-fA-F]+|#\d+|[a-zA-Z][a-zA-Z0-9]*);/g,(e,t)=>{if(t.startsWith(`#`)){let s=t[1]===`x`||t[1]===`X`;return decodeCodePoint(Number.parseInt(t.slice(s?2:1),s?16:10))??e}return NAMED_ENTITIES[t.toLowerCase()]??e})}function isFormatControl(e){return e===1564||e>=8203&&e<=8207||e===8232||e===8233||e>=8234&&e<=8238||e>=8288&&e<=8292||e>=8294&&e<=8297||e===65279}function isControl(e){return e<=31||e>=127&&e<=159}function stripUnsafeChars(e){let t=``;for(let s of e){let e=s.codePointAt(0)??0;isFormatControl(e)||(t+=isControl(e)?` `:s)}return t}function truncate(e,t){let s=Array.from(e);return s.length<=t?e:`${s.slice(0,t-1).join(``).trimEnd()}…`}function sanitizeText(e,t){return truncate(stripUnsafeChars(decodeHtmlEntities(e)).replace(/\s+/g,` `).trim(),t)}function relTokens(e){return e.trim().toLowerCase().split(/\s+/)}function asciiLowerCase(e){return e.replace(/[A-Z]+/g,e=>e.toLowerCase())}function isWhitespaceCode(e){return e===32||e===9||e===10||e===12||e===13}const RAW_TEXT_TAGS=new Set([`script`,`style`,`template`,`textarea`,`iframe`,`xmp`,`noembed`,`noframes`,`plaintext`]);function readTagName(e,t){let s=t;for(;s<e.length;){let t=e.charCodeAt(s);if(!(t>=97&&t<=122||t>=48&&t<=57||t===45))break;s++}return{name:e.slice(t,s),end:s}}function scanAttributes(e,t,s,g){let S=t.length,w=s;for(;w<S;){let s=t.charCodeAt(w);if(isWhitespaceCode(s)||s===47){w++;continue}if(s===62)return w+1;let E=w;for(;w<S&&(s=t.charCodeAt(w),!(isWhitespaceCode(s)||s===61||s===62||s===47));)w++;let D=t.slice(E,w);for(;w<S&&isWhitespaceCode(t.charCodeAt(w));)w++;let O=``;if(w<S&&t.charCodeAt(w)===61){for(w++;w<S&&isWhitespaceCode(t.charCodeAt(w));)w++;if(w<S){let g=t.charCodeAt(w);if(g===34||g===39){w++;let s=t.indexOf(g===34?`"`:`'`,w);O=e.slice(w,s===-1?S:s),w=s===-1?S:s+1}else{let g=w;for(;w<S&&(s=t.charCodeAt(w),!(isWhitespaceCode(s)||s===62));)w++;O=e.slice(g,w)}}}g&&D&&!g.has(D)&&g.set(D,O)}return S}function findCloseTag(e,t,s){let g=`</${t}`,S=s;for(;S<e.length;){let t=e.indexOf(g,S);if(t===-1)return null;let s=t+g.length,w=s<e.length?e.charCodeAt(s):-1;if(w===62||w===47||w===-1||isWhitespaceCode(w)){let g=e.indexOf(`>`,s);return{textEnd:t,end:g===-1?e.length:g+1}}S=t+1}return null}function extractHtmlMetadata(e){let t=``,s=new Map,g;try{let S=asciiLowerCase(e),w=S.length,E=0;for(;E<w;){let D=S.indexOf(`<`,E);if(D===-1)break;let O=D+1<w?S.charCodeAt(D+1):-1;if(O===33){if(S.startsWith(`<!--`,D)){let e=S.indexOf(`-->`,D+2);if(e===-1)break;E=e+3}else{let e=S.indexOf(`>`,D+2);if(e===-1)break;E=e+1}continue}if(O===63){let e=S.indexOf(`>`,D+2);if(e===-1)break;E=e+1;continue}if(O===47){let{name:e,end:t}=readTagName(S,D+2);if(e===`head`)break;let s=S.indexOf(`>`,t);if(s===-1)break;E=s+1;continue}if(!(O>=97&&O<=122)){E=D+1;continue}let{name:k,end:j}=readTagName(S,D+1);if(k===`body`)break;if(k===`title`){let s=scanAttributes(e,S,j,null),g=findCloseTag(S,`title`,s);if(g===null){t+=e.slice(s);break}t+=e.slice(s,g.textEnd),E=g.end;continue}if(RAW_TEXT_TAGS.has(k)){let t=findCloseTag(S,k,scanAttributes(e,S,j,null));if(t===null)break;E=t.end;continue}if(k===`meta`){let t=new Map;E=scanAttributes(e,S,j,t);let g=t.get(`content`);if(g){let e=t.get(`property`),S=t.get(`name`);e?s.set(e.toLowerCase(),g):S&&s.set(S.toLowerCase(),g)}continue}if(k===`link`){let t=new Map;if(E=scanAttributes(e,S,j,t),g===void 0){let e=t.get(`href`),s=t.get(`rel`);e&&s&&relTokens(s).includes(`icon`)&&(g=e)}continue}E=scanAttributes(e,S,j,null)}}catch{}let S=sanitizeText(s.get(`og:title`)??t,MAX_TITLE),w=sanitizeText(s.get(`og:description`)??s.get(`description`)??``,MAX_DESCRIPTION),E=sanitizeText(s.get(`og:site_name`)??``,MAX_SITE_NAME),D={};return S&&(D.title=S),w&&(D.description=w),E&&(D.siteName=E),g&&(D.faviconHref=g),D}function deriveDomain(e){let t;try{t=new URL(e).hostname}catch{return e}return t.startsWith(`www.`)&&t.slice(4).includes(`.`)&&(t=t.slice(4)),t}const FAVICON_MAX_BYTES=100*1024,FAVICON_TIMEOUT_MS=2500;function sniffImageMime(e){let t=e;return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?`image/png`:t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?`image/jpeg`:t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70&&t[3]===56&&(t[4]===55||t[4]===57)&&t[5]===97?`image/gif`:t.length>=2&&t[0]===66&&t[1]===77?`image/bmp`:t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?`image/webp`:t.length>=4&&t[0]===0&&t[1]===0&&t[2]===1&&t[3]===0?`image/x-icon`:null}function isImageContentType(e){return e.startsWith(`image/`)}function resolveFaviconUrl(e,t){try{return new URL(e??`/favicon.ico`,t).toString()}catch{return null}}async function fetchFavicon(e,t){let s=await t(e,{allowContentType:isImageContentType,maxBytes:FAVICON_MAX_BYTES,timeoutMs:FAVICON_TIMEOUT_MS});if(!s.ok)return;let g=sniffImageMime(s.body);if(g)return`data:${g};base64,${Buffer.from(s.body).toString(`base64`)}`}async function buildLinkPreviewMetadata(e){let t=extractHtmlMetadata(e.html),s=resolveFaviconUrl(t.faviconHref,e.finalUrl),g=s?await fetchFavicon(s,e.fetch??guardedFetch):void 0;return{domain:deriveDomain(e.requestUrl),...t.title===void 0?{}:{title:t.title},...t.description===void 0?{}:{description:t.description},...t.siteName===void 0?{}:{siteName:t.siteName},...g===void 0?{}:{faviconDataUri:g}}}const log$10=getLogger(`link-preview.cache`),MANIFEST_SCHEMA_VERSION=1,META_SUBDIR=`meta`,MANIFEST_NAME=`manifest.json`,DEFAULT_SUCCESS_TTL_MS=10080*60*1e3,DEFAULT_NEGATIVE_TTL_MS=3600*1e3,DEFAULT_MAX_ENTRIES=256;function normalizePreviewUrl(e){try{let t=new URL(e);return t.hash=``,t.username=``,t.password=``,t.toString()}catch{return null}}function hashKey(e){return createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}var LinkPreviewCache=class{cacheDir;metaDir;manifestPath;maxEntries;successTtlMs;negativeTtlMs;now;entries=new Map;payloads=new Map;persistedKeys=new Set;inFlight=new Map;dirty=!1;persisting=!1;persistPending=!1;constructor(e){this.cacheDir=e.cacheDir,this.metaDir=e.cacheDir?join(e.cacheDir,META_SUBDIR):null,this.manifestPath=e.cacheDir?join(e.cacheDir,MANIFEST_NAME):null,this.maxEntries=e.maxEntries??DEFAULT_MAX_ENTRIES,this.successTtlMs=e.successTtlMs??DEFAULT_SUCCESS_TTL_MS,this.negativeTtlMs=e.negativeTtlMs??DEFAULT_NEGATIVE_TTL_MS,this.now=e.now??Date.now}async init(){if(!this.cacheDir||!this.manifestPath||!this.metaDir)return;let e=null;try{existsSync(this.manifestPath)&&(e=JSON.parse(await readFile$1(this.manifestPath,`utf-8`)))}catch(e){log$10.warn({err:e instanceof Error?e.message:String(e)},`[link-preview] unreadable cache manifest — starting empty`);return}if(!e||e.schemaVersion!==MANIFEST_SCHEMA_VERSION||!e.entries)return;let t=this.now();for(let[s,g]of Object.entries(e.entries))if(!(!g||g.status!==`ok`&&g.status!==`negative`)&&!(typeof g.expiresAt!=`number`||t>=g.expiresAt)){if(g.status===`ok`){let e=await this.readBlob(s);if(!e)continue;this.payloads.set(s,e),this.persistedKeys.add(s)}this.entries.set(s,g)}}async load(e,t){let s=normalizePreviewUrl(e);if(s===null)return t();let g=this.getFresh(s);if(g)return g;let S=this.inFlight.get(s);if(S)return S;let w=(async()=>{let e=await t();return this.record(s,e),e})().finally(()=>{this.inFlight.delete(s)});return this.inFlight.set(s,w),w}getFresh(e){let t=this.entries.get(e);if(!t)return;if(this.now()>=t.expiresAt){this.drop(e),this.dirty=!0;return}if(this.entries.delete(e),this.entries.set(e,t),t.status===`negative`)return{ok:!1,reason:t.reason??`error`};let s=this.payloads.get(e);if(!s){this.drop(e),this.dirty=!0;return}return{ok:!0,metadata:s}}record(e,t){let s=this.now();this.persistedKeys.delete(e),this.entries.delete(e),this.payloads.delete(e),t.ok?(this.entries.set(e,{status:`ok`,fetchedAt:s,expiresAt:s+this.successTtlMs}),this.payloads.set(e,t.metadata)):this.entries.set(e,{status:`negative`,fetchedAt:s,expiresAt:s+this.negativeTtlMs,reason:t.reason}),this.dirty=!0,this.evict()}evict(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.drop(e),this.dirty=!0}}drop(e){this.entries.delete(e),this.payloads.delete(e),this.persistedKeys.delete(e)}async persist(){if(this.cacheDir){if(this.persisting){this.persistPending=!0;return}this.persisting=!0;try{do this.persistPending=!1,await this.writeToDisk();while(this.persistPending&&this.dirty)}finally{this.persisting=!1}}}async writeToDisk(){if(!(!this.cacheDir||!this.manifestPath||!this.metaDir)&&this.dirty)try{await tracedMkdir(this.metaDir,{recursive:!0});let e=new Set;for(let[t,s]of this.entries){if(s.status!==`ok`||(e.add(hashKey(t)),this.persistedKeys.has(t)))continue;let g=this.payloads.get(t);g&&(await tracedWriteFile(join(this.metaDir,`${hashKey(t)}.json`),JSON.stringify(g)),this.persistedKeys.add(t))}let t={schemaVersion:MANIFEST_SCHEMA_VERSION,entries:Object.fromEntries(this.entries)},s=`${this.manifestPath}.tmp`;await tracedWriteFile(s,JSON.stringify(t)),await tracedRename(s,this.manifestPath);for(let t of readdirSync(this.metaDir)){if(!t.endsWith(`.json`))continue;let s=t.slice(0,-5);e.has(s)||tracedUnlinkSync(join(this.metaDir,t))}this.dirty=!1}catch(e){log$10.warn({err:e instanceof Error?e.message:String(e)},`[link-preview] failed to persist cache`)}}clearMemory(){this.entries.clear(),this.payloads.clear(),this.persistedKeys.clear(),this.inFlight.clear(),this.dirty=!1}async wipe(){if(this.clearMemory(),this.cacheDir)try{tracedRmSync(this.cacheDir,{recursive:!0,force:!0})}catch(e){log$10.warn({err:e instanceof Error?e.message:String(e)},`[link-preview] failed to wipe cache`)}}get size(){return this.entries.size}async readBlob(e){if(!this.metaDir)return null;let t=join(this.metaDir,`${hashKey(e)}.json`);try{if(!existsSync(t))return null;let e=LinkPreviewMetadataSchema.safeParse(JSON.parse(await readFile$1(t,`utf-8`)));return e.success?e.data:null}catch(e){return log$10.warn({err:e instanceof Error?e.message:String(e)},`[link-preview] unreadable cache blob — treating as miss`),null}}};function isLoopbackHttpOrigin(e){if(!e||e===`null`)return!1;let t;try{t=new URL(e)}catch{return!1}if(t.protocol!==`http:`&&t.protocol!==`https:`)return!1;let s=t.hostname;return s===`localhost`||s===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(s)}function isJsonContentType(e){return e?e.split(`;`,1)[0]?.trim().toLowerCase()===`application/json`:!1}function classifyLinkPreviewRequest(e){return isLoopbackHttpOrigin(e.origin)?isJsonContentType(e.contentType)?{ok:!0}:{ok:!1,reason:`content-type`}:{ok:!1,reason:`origin`}}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function ancestorChainHasSymlink(e,t){let s=dirname(e);for(;s!==t&&s!==dirname(s);){let e;try{e=lstatSync(s)}catch(e){let t=e.code;return console.warn(`[local-op-security] ancestorChainHasSymlink: lstat failed on ${s} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return console.warn(`[local-op-security] ancestorChainHasSymlink: symlink detected at ${s}`),!0;s=dirname(s)}return!1}function isPathWithinHome(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let s;try{s=realpathSync(t)}catch(e){let s=e.code;return console.warn(`[local-op-security] realpath failed on home dir ${t} (${s??`unknown`}); rejecting all paths`),!1}let g=resolve(expandTilde(e)),S=[],w=g;for(;;){let e=null;try{e=lstatSync(w)}catch(e){let t=e.code;if(t!==`ENOENT`)return console.warn(`[local-op-security] lstat error at ${w} (${t??`unknown`}); rejecting`),!1}if(e!==null){let g;try{g=realpathSync(w)}catch(s){let S=s.code;if(e.isSymbolicLink())return console.warn(`[local-op-security] realpath failed on symlink leaf at ${w} (${S??`unknown`}); rejecting`),!1;if(S===`EPERM`||S===`EACCES`){if(ancestorChainHasSymlink(w,t))return console.warn(`[local-op-security] EPERM accept-branch refused at ${w}: symlinked ancestor in chain; rejecting`),!1;console.warn(`[local-op-security] realpath denied on non-symlink leaf at ${w} (${S??`unknown`}); trusting lexical path (TCC-class)`),g=w}else return console.warn(`[local-op-security] realpath failed on non-symlink leaf at ${w} (${S??`unknown`}); rejecting`),!1}let E=S.length===0?g:join(g,...S),D=relative(s,E);return D===``||!D.startsWith(`..`)&&!isAbsolute(D)}let g=dirname(w);if(g===w)return!1;S.unshift(basename(w)),w=g}}function isSafeLocalPath(e){return isPathWithinHome(e,homedir())}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,s){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:s.handler}),!1):(errorResponse(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:s.handler}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}const SUBPROCESS_PIPE_STDIO_OPTIONS={stdio:[`ignore`,`pipe`,`pipe`]};function runSubprocess(e){let[t,...s]=e.cliArgs;if(!t)return{done:Promise.resolve({code:-1,stderr:`no command provided`,timedOut:!1,cancelled:!1}),cancel:()=>{}};let g=[...s,...e.trailingArgs],S=!1,w=!1,E=``,D=[],O={...process.env};e.extraPathDirs&&e.extraPathDirs.length>0&&(O.PATH=[...e.extraPathDirs,process.env.PATH??``].filter(Boolean).join(delimiter));let k=spawn(t,g,withHiddenWindowsConsole({...SUBPROCESS_PIPE_STDIO_OPTIONS,cwd:e.cwd,env:O})),j=setTimeout(()=>{S=!0,k.kill(`SIGTERM`)},e.timeoutMs),F=t=>{if(!t.trim())return;let s=null;try{let e=JSON.parse(t);s=e&&typeof e==`object`?e:null}catch{s=null}e.onLine({raw:t,parsed:s})};return k.stdout.on(`data`,e=>{E+=e.toString(`utf-8`);let t=E.split(`
958
958
  `);E=t.pop()??``;for(let e of t)F(e)}),k.stderr.on(`data`,t=>{D.push(t),e.onStderr?.(t)}),{done:new Promise(e=>{k.on(`close`,t=>{clearTimeout(j),E.trim()&&F(E),E=``,e({code:t,stderr:Buffer.concat(D).toString(`utf-8`).trim(),timedOut:S,cancelled:w})}),k.on(`error`,t=>{clearTimeout(j),D.push(Buffer.from(t.message,`utf-8`)),e({code:-1,stderr:Buffer.concat(D).toString(`utf-8`).trim(),timedOut:S,cancelled:w})})}),cancel:()=>{if(!w&&(w=!0,!k.killed))try{k.kill(`SIGTERM`)}catch{}}}}const DEFAULT_TIMEOUT_MS$3=600*1e3;function asAuthEvent(e){let t=e.type;return t===`verification`?typeof e.user_code==`string`&&typeof e.verification_uri==`string`&&typeof e.expires_in==`number`?{type:`verification`,user_code:e.user_code,verification_uri:e.verification_uri,expires_in:e.expires_in}:null:t===`complete`?{type:`complete`,host:typeof e.host==`string`?e.host:``,login:typeof e.login==`string`?e.login:``,name:typeof e.name==`string`?e.name:void 0,email:typeof e.email==`string`?e.email:void 0,avatarUrl:typeof e.avatarUrl==`string`?e.avatarUrl:void 0}:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function runDeviceFlowSubprocess(e){let t=e.host??`github.com`,s=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,g=!1,S=runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`login`,`--json`,`--host`,t],timeoutMs:s,onLine:({parsed:t})=>{if(!t)return;let s=asAuthEvent(t);s&&((s.type===`complete`||s.type===`error`)&&(g=!0),e.onEvent(s))}});return{done:S.done.then(s=>{g||(s.code===0?e.onEvent({type:`complete`,host:t,login:``}):e.onEvent({type:`error`,message:s.timedOut?`Sign-in timed out`:`auth login exited with code ${s.code??-1}`}))}),cancel:S.cancel}}const DEFAULT_TIMEOUT_MS$2=3e4;async function runAuthStatusSubprocess(e){let t=e.host??`github.com`,s=[],g=await runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`status`,`--json`,`--host`,t],timeoutMs:e.timeoutMs??DEFAULT_TIMEOUT_MS$2,onLine:({parsed:e})=>{e&&s.push(e)}}).done;for(let e=s.length-1;e>=0;e--){let g=s[e];if(g.type!==`status`)continue;let S=typeof g.host==`string`?g.host:t;if(g.authenticated===!0&&typeof g.login==`string`){let e=g.tier===`A`||g.tier===`B`||g.tier===`C`?g.tier:void 0;return{authenticated:!0,host:S,login:g.login,tier:e,name:typeof g.name==`string`?g.name:void 0,email:typeof g.email==`string`?g.email:void 0}}return{authenticated:!1,host:S,error:typeof g.error==`string`?g.error:void 0}}return{authenticated:!1,host:t,error:g.timedOut?`auth status timed out`:g.code===0?void 0:g.stderr||`auth status exited with code ${g.code??-1}`}}async function runAuthReposSubprocess(e){let t=e.host??`github.com`,s=[],g=await runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`repos`,`--json`,`--host`,t],timeoutMs:e.timeoutMs??DEFAULT_TIMEOUT_MS$2,onLine:({parsed:e})=>{e&&s.push(e)}}).done;if(g.timedOut)return{ok:!1,error:`auth repos timed out`};if(g.code!==0)return{ok:!1,error:g.stderr||`auth repos exited with code ${g.code??-1}`};for(let e=s.length-1;e>=0;e--){let g=s[e];if(g.type!==`repos`||!Array.isArray(g.repos))continue;let S=[];for(let e of g.repos){if(!e||typeof e!=`object`)continue;let t=e;typeof t.full_name!=`string`||typeof t.clone_url!=`string`||S.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private===!0})}return{ok:!0,host:typeof g.host==`string`?g.host:t,repos:S}}return{ok:!1,error:`auth repos returned no data`}}const GENERIC_TITLE=`Clone subprocess reported an error.`,MAX_DETAIL_LEN=500;function classifyCloneError(e){let t=redactShareSubprocessStderr(e).trim().slice(0,MAX_DETAIL_LEN);return t.length===0?{title:GENERIC_TITLE,detail:``}:/repository not found|returned error:\s*404/i.test(t)?{title:`Can't access this repository. It may be private, or you may not have access.`,detail:t}:/permission denied|access denied|returned error:\s*403/i.test(t)?{title:`You don't have access to this repository.`,detail:t}:/authentication failed/i.test(t)?{title:`GitHub authentication failed. Try signing in again.`,detail:t}:{title:GENERIC_TITLE,detail:t}}const GIT_PREFLIGHT_FAIL_SPAN_NAME=`ok.preflight.git.fail`;function emitPreflightFailureSpan(e){let t=e instanceof GitTooOldError?`too_old`:`not_available`,s=e instanceof GitTooOldError?e.detected:``;withSpanSync(GIT_PREFLIGHT_FAIL_SPAN_NAME,{attributes:{"ok.platform":e.platform,"ok.preflight.git.reason":t,"ok.preflight.git.detected_version":s}},()=>{})}const log$9=getLogger(`clone-flow`),DEFAULT_TIMEOUT_MS$1=600*1e3;function validateCloneInputs(e,t){return isAllowedGitUrl(e)?isSafeLocalPath(t)?{ok:!0}:{ok:!1,reason:`invalid-dir`}:{ok:!1,reason:`invalid-url`}}function asRawCloneEvent(e){let t=e.type;return t===`progress`?typeof e.phase==`string`&&typeof e.pct==`number`?{type:`progress`,phase:e.phase,pct:e.pct}:null:t===`complete`?typeof e.dir==`string`?{type:`complete`,dir:e.dir}:null:t===`branch-fallback`?typeof e.branch==`string`&&e.branch.length>0?{type:`branch-fallback`,branch:e.branch}:null:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function runCloneSubprocess(e){let t=expandTilde(e.dir),s=e.timeoutMs??DEFAULT_TIMEOUT_MS$1,g;try{g=assertGitAvailable()}catch(t){t instanceof GitNotAvailableError||t instanceof GitTooOldError?(emitPreflightFailureSpan(t),log$9.warn({event:`git_preflight_fail`,platform:t.platform,reason:t instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:t instanceof GitTooOldError?t.detected:``},t instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log$9.error({event:`clone_preflight_unexpected_error`,err:t},`unexpected error during clone preflight`);let s=t instanceof Error?t.message:String(t);return{done:Promise.resolve().then(()=>{e.onEvent({type:`error`,message:s})}),cancel:()=>{}}}let S=isAbsolute(g.resolvedPath)?[dirname(g.resolvedPath)]:[],w=!1,E=typeof e.branch==`string`&&e.branch.length>0?[`-b`,e.branch]:[],D=runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`clone`,`--json`,...E,e.url,t],extraPathDirs:S,timeoutMs:s,onLine:({parsed:t})=>{if(!t)return;let s=asRawCloneEvent(t);s&&((s.type===`complete`||s.type===`error`)&&(w=!0),e.onEvent(s))}});return{done:D.done.then(s=>{if(!w){if(s.timedOut){e.onEvent({type:`error`,message:`Clone timed out after 10 minutes`});return}if(s.code!==0){let t=s.stderr?` — ${s.stderr}`:``;e.onEvent({type:`error`,message:`Clone process exited with code ${s.code??-1}${t}`});return}e.onEvent({type:`complete`,dir:t})}}),cancel:D.cancel}}function isLoopbackAddress(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function isAllowedWorkspaceHostHeader(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let s=e.slice(1,t),g=e.slice(t+1);return g!==``&&!/^:\d+$/.test(g)?!1:s===`::1`}let t=e.lastIndexOf(`:`),s=t>=0?e.slice(0,t):e,g=t>=0?e.slice(t+1):null;return g!==null&&!/^\d+$/.test(g)?!1:!!(s===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(s))}const MANAGED_RENAME_JOURNAL_FILENAME=`managed-rename.json`;function journalDir(e){return getLocalDir(e)}function managedRenameJournalPath(e){return resolve(journalDir(e),MANAGED_RENAME_JOURNAL_FILENAME)}function createManagedRenameRecoveryJournal(e){let t={version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:e.affectedDocs,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots};return e.pathSnapshots&&e.pathSnapshots.length>0&&(t.pathSnapshots=e.pathSnapshots),e.cleanupPaths&&e.cleanupPaths.length>0&&(t.cleanupPaths=e.cleanupPaths),t}function isManagedRenameSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function isManagedRenamePathSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.path==`string`&&typeof t.content==`string`}function isManagedRenameCleanupPath(e){return typeof e==`string`&&e.length>0}function isManagedRenameAffectedDoc(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.from==`string`&&typeof t.to==`string`}function parseV2(e){if(typeof e.fromPath!=`string`||e.fromPath.length===0)throw Error(`Managed rename journal v2 is missing fromPath`);if(typeof e.toPath!=`string`||e.toPath.length===0)throw Error(`Managed rename journal v2 is missing toPath`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v2 is missing createdAt`);let t=e.affectedDocs,s=e.pathSnapshots,g=e.cleanupPaths,S=Array.isArray(s)&&s.length>0,w=Array.isArray(g)&&g.length>0;if(!Array.isArray(t)||!t.every(isManagedRenameAffectedDoc)||t.length===0&&!S&&!w)throw Error(`Managed rename journal v2 has invalid affectedDocs`);if(!Array.isArray(e.snapshots)||t.length>0&&e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v2 has invalid snapshots`);if(s!==void 0&&(!Array.isArray(s)||!s.every(isManagedRenamePathSnapshot)))throw Error(`Managed rename journal v2 has invalid pathSnapshots`);if(g!==void 0&&(!Array.isArray(g)||!g.every(isManagedRenameCleanupPath)))throw Error(`Managed rename journal v2 has invalid cleanupPaths`);for(let s of t)if(!e.snapshots.some(e=>e.docName===s.from))throw Error(`Managed rename journal v2 is missing snapshot for affected doc: ${s.from}`);return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:t,createdAt:e.createdAt,snapshots:e.snapshots,...S?{pathSnapshots:s}:{},...w?{cleanupPaths:g}:{}}}function parseV1(e){if(typeof e.sourceDocName!=`string`||e.sourceDocName.length===0)throw Error(`Managed rename journal v1 is missing sourceDocName`);if(typeof e.destinationDocName!=`string`||e.destinationDocName.length===0)throw Error(`Managed rename journal v1 is missing destinationDocName`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v1 is missing createdAt`);if(!Array.isArray(e.snapshots)||e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v1 has invalid snapshots`);if(!e.snapshots.some(t=>t.docName===e.sourceDocName))throw Error(`Managed rename journal v1 must include the source document snapshot`);return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt,snapshots:e.snapshots}}function parseManagedRenameRecoveryJournal(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version===2)return parseV2(t);if(t.version===1)return parseV1(t);throw Error(`Unsupported managed rename journal version: ${String(t.version)}`)}function readManagedRenameJournal(e){let t=managedRenameJournalPath(e);if(!existsSync(t))return null;try{let e=readFileSync(t,`utf-8`);return parseManagedRenameRecoveryJournal(JSON.parse(e))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function writeManagedRenameJournal(e,t){let s=managedRenameJournalPath(e);tracedMkdirSync(dirname(s),{recursive:!0});let g=`${s}.tmp`;tracedWriteFileSync(g,JSON.stringify(t,null,2),`utf-8`),tracedRenameSync(g,s)}function clearManagedRenameJournal(e){tracedRmSync(managedRenameJournalPath(e),{force:!0})}async function withManagedRenameRecovery(e,t,s){writeManagedRenameJournal(e,t);let g=await s();return clearManagedRenameJournal(e),g}function destinationsToCleanV1(e){return[e.destinationDocName]}function destinationsToCleanV2(e){return e.affectedDocs.map(e=>e.to)}function resolveRecoveryPath(e,t){let s=resolve(e),g=resolve(s,t);if(t.includes(`\0`)||g===s||!g.startsWith(`${s}${sep}`))throw Error(`Invalid recovery path: ${t}`);return g}function pruneEmptyAncestors(e,t){let s=resolve(t),g=`${s}${sep}`,S=dirname(e);for(;S.startsWith(g)&&S!==s;){let e;try{e=readdirSync(S)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot read ${S}:`,e);return}if(e.length>0)return;try{tracedRmdirSync(S)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot rmdir ${S}:`,e);return}S=dirname(S)}}function recoverPendingManagedRename(e,t=e){let s=readManagedRenameJournal(t);if(!s)return{recovered:!1,journal:null,restoredDocNames:[]};let g=new Set,S=new Set,w=[];for(let t of s.snapshots)try{let s=safeContentPath(t.docName,e);tracedMkdirSync(dirname(s),{recursive:!0}),tracedWriteFileSync(s,t.content,`utf-8`),g.add(t.docName)}catch(e){w.push({docName:t.docName,cause:e}),console.warn(`[managed-rename] Failed to restore ${t.docName}:`,e)}if(w.length>0){let e=w.map(e=>e.docName).join(`, `);console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${e})`);let t=w.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to restore: ${e}`)}if(s.version===2){let t=[];for(let g of s.pathSnapshots??[])try{let t=resolveRecoveryPath(e,g.path);tracedMkdirSync(dirname(t),{recursive:!0}),tracedWriteFileSync(t,g.content,`utf-8`),S.add(g.path)}catch(e){t.push({path:g.path,cause:e}),console.warn(`[managed-rename] Failed to restore path ${g.path}:`,e)}if(t.length>0){let e=t.map(e=>e.path).join(`, `);console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${e})`);let s=t.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(s,`Managed rename recovery incomplete; failed to restore paths: ${e}`)}}let E=s.version===2?destinationsToCleanV2(s):destinationsToCleanV1(s),D=[];for(let t of E){if(g.has(t))continue;let s=safeContentPath(t,e);try{tracedRmSync(s,{force:!0}),pruneEmptyAncestors(s,e)}catch(e){existsSync(s)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t}:`,e),D.push({destination:t,cause:e})}}if(s.version===2)for(let t of s.cleanupPaths??[]){if(S.has(t))continue;let s=null;try{s=resolveRecoveryPath(e,t),tracedRmSync(s,{force:!0}),pruneEmptyAncestors(s,e)}catch(e){s&&existsSync(s)&&console.warn(`[managed-rename] Both source and destination paths exist after partial recovery for ${t}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination path ${t}:`,e),D.push({destination:t,cause:e})}}if(D.length>0){let e=D.map(e=>e.destination).join(`, `),t=D.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to clean destinations: ${e}`)}return clearManagedRenameJournal(t),{recovered:!0,journal:s,restoredDocNames:[...g].sort((e,t)=>e.localeCompare(t))}}const PROJECT_SKILL_EDITOR_LABELS={claude:`Claude Code`,cursor:`Cursor`,codex:`Codex`},PLATFORM_SKILL_NAME=BUNDLE_SKILL_NAME.project;function resolvePackSkillSource(e){let t;try{t=resolveBundledSkillDir(`packs/${e}`,{checkDesktop:!0})}catch{return null}return{name:`open-knowledge-pack-${e}`,sourceDir:t}}async function installPackSkill(e,t){let s=resolvePackSkillSource(t);if(!s)return[];let{name:g,sourceDir:S}=s,w=join(e,`.ok`,`skills`,g);if(!existsSync(join(w,`SKILL.md`)))try{tracedRmSync(w,{recursive:!0,force:!0}),tracedMkdirSync(join(e,`.ok`,`skills`),{recursive:!0}),tracedCpSync(S,w,{recursive:!0})}catch(e){return getLogger(`seed`).warn({err:e,packId:t,okSkillDir:w},`pack skill source authoring failed — skill not installed`),[]}let E=projectSkill(w,g,e,PROJECT_SKILL_EDITOR_IDS.filter(t=>{let s=EDITOR_PROJECT_SKILL_ROOT[t];return s===null?!1:existsSync(join(e,s,PLATFORM_SKILL_NAME,`SKILL.md`))})),D=E.map(e=>PROJECT_SKILL_EDITOR_LABELS[e]??e);if(E.length>0)try{await recordSkillInstall(e,g,{hosts:E,scope:`project`,scripts:existsSync(join(w,`scripts`)),installedAt:new Date().toISOString()})}catch{}return D}var SeedPrerequisiteError=class extends Error{constructor(e){super(e),this.name=`SeedPrerequisiteError`}},SeedRootDirError=class extends Error{constructor(e){super(e),this.name=`SeedRootDirError`}};function assertEntryPathInProject(e,t){if(typeof t!=`string`||t===``)throw new SeedRootDirError(`entry path must be a non-empty string, got: ${typeof t}`);if(t.includes(`\0`))throw new SeedRootDirError(`entry path must not contain null bytes`);if(isAbsolute(t))throw new SeedRootDirError(`entry path must be relative, got: ${t}`);if(t.split(/[/\\]/).some(e=>e===`..`))throw new SeedRootDirError(`entry path must not contain '..' segments, got: ${t}`);let s=resolve(e),g=resolve(s,t);if(g!==s&&!g.startsWith(s+sep))throw new SeedRootDirError(`entry path must resolve inside the project directory, got: ${t}`);return assertNoSymlinkEscape$1(g,s),g}function assertNoSymlinkEscape$1(e,t){let s;try{s=realpathSync(t)}catch{return}let g=e;for(;;){if(existsSync(g)){let t;try{t=realpathSync(g)}catch(t){throw t.code===`ELOOP`?new SeedRootDirError(`entry path traverses a symlink cycle: ${e}`):t}if(t!==s&&!t.startsWith(s+sep))throw new SeedRootDirError(`entry path resolves outside the project directory via symlink: ${e}`);return}let t=dirname(g);if(t===g)throw new SeedRootDirError(`entry path has no existing ancestor inside the project directory: ${e}`);g=t}}const DEFAULT_PACK_ID=`knowledge-base`,KNOWLEDGE_BASE_FOLDERS=[{path:`external-sources`,title:`External Sources`,uiSummary:`The original sources, saved word-for-word.`,description:"Raw sources saved verbatim — the fetched text of URLs, extracted PDFs, and copied files, each with the original URL and access date in frontmatter. Produced by `ingest`. Immutable after capture; no analysis here (that goes in `research/`).",tags:[`source`,`immutable`,`layer-ingest`],starterTemplate:`clip`},{path:`research`,title:`Research`,uiSummary:`Your work-in-progress take on what the sources mean.`,description:"Provisional analysis that synthesizes the external sources. Every claim cites a doc in `external-sources/`; `status: provisional`. Promoted to `articles/` via `consolidate` once the findings are stable.",tags:[`research`,`provisional`,`layer-research`],starterTemplate:`research-log`},{path:`articles`,title:`Articles`,uiSummary:`The finished, trusted version you can rely on.`,description:"Canonical knowledge, committed after a team decision. The source of truth for the domain; carries a `supersedes:` chain back to the `research/` docs it replaces.",tags:[`article`,`canonical`,`layer-consolidate`],starterTemplate:`article`}],KNOWLEDGE_BASE_TEMPLATES={clip:`---
959
959
  template:
960
960
  title: External Source
@@ -1946,12 +1946,12 @@ Change history for this knowledge base, newest entry first. Add a dated entry (\
1946
1946
  `).filter(Boolean);ce.push(...e)}catch{}if(ue&&ce.length===0)try{let e=(await oe.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/main/`)).trim().split(`
1947
1947
  `).filter(Boolean);ce.push(...e)}catch{}if(ce.length===0&&se.length===0&&de.length===0)return EMPTY;let fe=[...se,...de],me=[];if(fe.length>0){let t=parseGitLogOutput(await oe.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...fe)).map(e=>({...e,type:`checkpoint`}));if(ne&&(t=await filterEntriesByChain(e,t,O,S,ee,ae,Y)),ue&&se.length>0&&de.length>0){let e=new Set(se),s=t.filter(t=>e.has(t.sha)),g=t.filter(t=>!e.has(t.sha)),S=s.reduce((e,t)=>{let s=new Date(t.timestamp).getTime();return s<e?s:e},1/0);me=[...s,...g.filter(e=>new Date(e.timestamp).getTime()<S)]}else me=t}let ge=[...ce];for(let e of fe)ge.push(e);let _e=[];if(ge.length>0&&(_e=parseGitLogOutput(await oe.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(D),...ge,...ne?[`--`,ne]:[])),_e.length>=D&&(k=!0),J))for(let t=0;t<O.length-1;t++){let s=O[t];if(s.renameCommit!==null)try{let t=await buildSeeds(e,s.renameCommit,S,Y);if(t.length===0)continue;let g=ee(s.path),w=parseGitLogOutput(await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(D)],t,g));w.length>=D&&(k=!0),_e=[..._e,...w]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${s.path}); skipping:`,e)}}let ve=[...me,..._e],ye=new Set,Ce=[];for(let e of ve)ye.has(e.sha)||(ye.add(e.sha),Ce.push(e));let we=Ce;Ce.length>0&&O.length>0&&(we=filterEntriesByOkActorDocs(Ce,O,await Promise.all(O.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,S,Y);return s.length===0?new Set:buildAncestorShaSet(e,s,S,ae)})))),we.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let Te=we;Te=Te.filter(e=>e.type!==`park`),H||(Te=Te.filter(e=>e.checkpoint?.kind!==`auto-consolidation`)),F.length>0&&(Te=Te.filter(e=>F.includes(e.type))),L.length>0&&(Te=Te.filter(e=>matchesAuthor(e,L))),B.length>0&&(Te=Te.filter(e=>!matchesAuthor(e,B)));let De=Te.length,je=Te.slice(E,E+w),Me=je.map(({rawBody:e,...t})=>t);return j(ge.length,Ce.length),{entries:Me,total:De,hasMore:k&&je.length>0||E+w<De}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),j(0,0,!0),EMPTY}}async function getFolderTimeline(e,t,s=`.`,g){if(!existsSync(e.workTree)||!existsSync(e.gitDir)||t.includes(`..`)||t.includes(`\0`))return EMPTY;let S=g?.branch??`main`,w=Math.max(1,g?.limit??50),E=Math.max(0,g?.offset??0),D=s===`.`?``:s.replace(/^\.\//,``),O=t.replace(/^\.?\/+/,``).replace(/\/+$/,``),k=[D,O,`.ok`].filter(Boolean).join(`/`),j=shadowGit(e);try{let e=[];for(let t of[`refs/wip/${S}/`,`refs/checkpoints/${S}/`])try{let s=(await j.raw(`for-each-ref`,`--format=%(refname)`,t)).trim().split(`
1948
1948
  `).filter(Boolean);e.push(...s)}catch{}if(e.length===0)return EMPTY;let t=historyWalkCap(E,w),s=parseGitLogOutput(await j.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(t),...e,`--`,k)),g=s.length>=t,D=O?`${O}/.ok/`:`.ok/`,F=new Set,L=[];for(let e of s){if(F.has(e.sha)||!isFolderArtifactSubject(e.message)||!e.contributors.some(e=>e.docs.some(e=>e.startsWith(D))))continue;F.add(e.sha);let{rawBody:t,...s}=e;L.push(s)}let B=L.length,H=L.slice(E,E+w);return{entries:H,total:B,hasMore:g&&H.length>0||E+w<B}}catch(e){return console.warn(`[timeline] getFolderTimeline failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),_hintEmittedCounter}let _agentPatchFmTouchCounter=null;function agentPatchFmTouchCounter(){return _agentPatchFmTouchCounter||=getMeter().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:`Count of agent-patch calls whose find string targets the frontmatter region. Measures incidence during the soft-deprecation window before agent-patch FM-intersecting calls are enforced as 400. Bounded label: result ∈ {rejected, pre_deprecation_passthrough}.`}),_agentPatchFmTouchCounter}function findLooksLikeFrontmatter(e){return!!(/(^|\n)---(\s|\n|$)/.test(e)||/^\s*[\w-]+:\s+\S/.test(e))}let _renameAttributionCounter=null;function renameAttributionCounter(){return _renameAttributionCounter||=getMeter().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),_renameAttributionCounter}let _agentWriteGateFiredCounter=null;function agentWriteGateFiredCounter(){return _agentWriteGateFiredCounter||=getMeter().createCounter(`ok.agent_write.gate_fired_total`,{description:`Count of agent writes that ran the Site A content-divergence gate (denominator for the divergence rate). Bounded label: handler ∈ {agent-write-md, agent-patch, rollback}.`}),_agentWriteGateFiredCounter}let _agentWriteContentDivergenceCounter=null;function agentWriteContentDivergenceCounter(){return _agentWriteContentDivergenceCounter||=getMeter().createCounter(`ok.agent_write.content_divergence_total`,{description:`Count of agent writes whose converged Y.Text diverged from the composed intent (numerator for the divergence rate). Bounded labels: handler ∈ {agent-write-md, agent-patch, rollback}, divergence_type.`}),_agentWriteContentDivergenceCounter}let _searchCorpusTruncatedCounter=null;function searchCorpusTruncatedCounter(){return _searchCorpusTruncatedCounter||=getMeter().createCounter(`ok.search.corpus_truncated_total`,{description:`Count of search-corpus rebuilds where the name-only file tier hit OK_SEARCH_MAX_ENTRIES and dropped deepest-tail paths. One increment per truncated build; non-truncated builds do not increment.`}),_searchCorpusTruncatedCounter}function recordContentDivergenceGate(e,t){agentWriteGateFiredCounter().add(1,{handler:e}),t!==void 0&&agentWriteContentDivergenceCounter().add(1,{handler:e,divergence_type:t.divergenceType})}function resumeSyncOnAuthEvent(e,t){e.type===`complete`&&t?.()?.notifyCredentialsChanged().catch(()=>{})}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$7=getLogger(`api`);function ytextHasConflictMarkers(e){return/^<{7} /m.test(e)&&/^={7}$/m.test(e)&&/^>{7} /m.test(e)}function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let s=t===`.`?``:t.replace(/^\.\//,``),g=managedArtifactTimelinePaths(e);if(g.managed&&g.versioned)return{path:s?`${s}/${g.filePath}`:g.filePath};let S=getDocExtension(e);return{path:s?`${s}/${e}${S}`:`${e}${S}`}}const GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i,SAFE_FILENAME_CHARS=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,STRIP_ON_SIGHT=/[/\\\x00-\x1f\x7f]/g;function sanitizeFilename(e){let t=e.replace(STRIP_ON_SIGHT,``);if(t=t.replace(SAFE_FILENAME_CHARS,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let s=255,g=new TextEncoder;if(g.encode(t).length>255){let e=t.lastIndexOf(`.`),s=e>=0?t.slice(e):``,S=e>=0?t.slice(0,e):t;for(;g.encode(S+s).length>255&&S.length>0;)S=S.slice(0,-1);t=(S||`upload`)+s,g.encode(t).length>255&&(t=`upload`)}return t}function resolveUploadDestDir(e,t,s){let g=t.trim();return g===``||g===`./`?resolve(s,dirname(e)):g===`/`?s:g.startsWith(`./`)?resolve(s,dirname(e),g.slice(2)):resolve(s,g)}function readTempFileHead(e,t){let s=openSync(e,`r`);try{let e=Buffer.alloc(t),g=readSync(s,e,0,t,0);return e.subarray(0,g)}finally{closeSync(s)}}const MAX_DEDUP_SCAN_CANDIDATES=1e3;async function streamingHashFile(e){let t=createHash(`sha256`);return await pipeline(createReadStream(e),t),t.digest(`hex`)}async function findDuplicateAsset(e,t,s){let g;try{g=await readdir(e)}catch{return null}let S=getLogger(`upload`),w=0;for(let E of g){let g=extname(E).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(g))continue;let D=resolve(e,E),O;try{O=await stat$1(D)}catch{continue}if(!O.isFile()||O.size!==s)continue;if(w++,w>MAX_DEDUP_SCAN_CANDIDATES)return S.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:MAX_DEDUP_SCAN_CANDIDATES,expectedSize:s},`[upload-dedup] candidate scan exceeded ${MAX_DEDUP_SCAN_CANDIDATES} same-size siblings — degrading to no-dedup for this upload`),null;let k;try{k=await streamingHashFile(D)}catch(e){let t=e.code;t!==`ENOENT`&&S.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:E},`[upload-dedup] skipped candidate — read failed`);continue}if(k===t)return E}return null}function readUploadBody(e,t){return new Promise((s,g)=>{let S;try{S=(0,import_lib.default)({headers:e.headers,limits:{files:1,fields:10,fieldSize:2*1024}})}catch(e){g(new UploadWriteError(`urn:ok:error:malformed-upload`,e));return}let w=!1,E=`upload`,D=``,O=``,k=``,j,F,L=!1,B=(e,t)=>{if(!w){if(w=!0,j)try{unlinkSync(j)}catch{}g(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},H=classifyUploadErrno;S.on(`field`,(e,t)=>{e===`parentDocName`&&(O=t),e===`placement`&&(k=t)}),S.on(`file`,(e,g,S)=>{L=!0,E=S.filename||`upload`,D=S.mimeType||``;let q;try{q=mintTempUploadPath(t)}catch(e){B(H(e),e),g.resume();return}j=q;let ee=new HashingPassThrough;pipeline(g,ee,createWriteStream(q)).then(()=>{w||(w=!0,s({filename:E,mimeType:D,parentDocName:O,placement:k,tempPath:q,sha:ee.digest(),byteLength:ee.byteLength()}))}).catch(e=>{F=e,B(H(e),e)})}),S.on(`error`,e=>{B(`urn:ok:error:malformed-upload`,e)}),S.on(`close`,()=>{w||F||L||(w=!0,s({filename:``,mimeType:``,parentDocName:O,placement:k,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{w||F||e.complete||B(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(S)})}function safeSubdir(e,t){let s=resolve(e,t);if(!isWithinDir(s,e))throw Error(`Invalid directory: ${t}`);return s}function synthesizeShowAllAssetExt(e){let t=extname(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}const DEFAULT_SHOWALL_MAX_ENTRIES=5e4;function getShowAllMaxEntries(){let e=process.env.OK_SHOWALL_MAX_ENTRIES;if(e===void 0)return DEFAULT_SHOWALL_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SHOWALL_MAX_ENTRIES}const DEFAULT_SEARCH_MAX_ENTRIES=5e4;function getSearchMaxEntries(){let e=process.env.OK_SEARCH_MAX_ENTRIES;if(e===void 0)return DEFAULT_SEARCH_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SEARCH_MAX_ENTRIES}let showAllWalkInvocations=0,showAllWalkAborts=0;function __getShowAllWalkStatsForTesting(){return{invocations:showAllWalkInvocations,aborts:showAllWalkAborts}}function __resetShowAllWalkStatsForTesting(){showAllWalkInvocations=0,showAllWalkAborts=0}function showAllWantsNdjson(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}async function*streamShowAllEntries(e){let{contentDir:t,contentFilter:s,dirFilter:g,maxEntries:S,signal:w,showOk:E}=e,D=e.maxDepth??1/0,O={bypassFilters:!0,showOk:E};showAllWalkInvocations+=1;let k=0,j=!1,F=!1,L=e=>g?e===g||e.startsWith(`${g}/`):!0,B;try{B=await realpath(t)}catch{B=t}let H=e=>isWithinDir(e,B),q=async(e,t,g)=>{let S=new Map;for(let t of e){if(!t.isFile()&&!t.isSymbolicLink()||!isSupportedDocFile(t.name))continue;let e=stripDocExtension(g?`${g}/${t.name}`:t.name);S.set(e,(S.get(e)??0)+1)}let w=new Set([...S].filter(([,e])=>e>1).map(([e])=>e));if(w.size===0)return new Map;let E=new Map;for(let S of e){if(!S.isFile()&&!S.isSymbolicLink()||!isSupportedDocFile(S.name))continue;let e=g?`${g}/${S.name}`:S.name,D=stripDocExtension(e);if(w.has(D)&&!s.isExcluded(e,{bypassFilters:!0})&&L(e)){if(S.isSymbolicLink()){let e=join(t,S.name),s;try{s=await realpath(e)}catch{continue}if(!H(s))continue;let g;try{g=await stat$1(s)}catch{continue}if(!g.isFile())continue}else try{await stat$1(join(t,S.name))}catch{continue}E.set(D,(E.get(D)??0)+1)}}return E},ee=(e,t)=>{let s=stripDocExtension(e);return(t.get(s)??0)>1?e:s};async function J(e,t){let g;try{g=await readdir(e,{withFileTypes:!0})}catch(t){return console.warn(`[document-list][showAll] probe readdir failed for ${e}:`,t),!1}for(let S of g){let g=t?`${t}/${S.name}`:S.name;if(S.isDirectory()){if(s.isDirExcluded(g,O))continue;try{if(!H(await realpath(join(e,S.name))))continue}catch(t){console.warn(`[document-list][showAll] probe realpath failed for ${e}/${S.name}:`,t);continue}return!0}if(S.isFile()&&!s.isExcluded(g,O))return!0}return!1}async function*Y(e,g,E){let B=[{absDir:e,relDir:g,depth:E}];for(let e=0;e<B.length;e++){if(w?.aborted){F=!0;return}let{absDir:g,relDir:E,depth:Y}=B[e],te;try{te=await readdir(g,{withFileTypes:!0})}catch(e){console.warn(`[document-list][showAll] readdir failed for ${g}:`,e);continue}let ne=await q(te,g,E);for(let e of te){if(w?.aborted){F=!0;return}if(k>=S){j=!0;return}let q=E?`${E}/${e.name}`:e.name;if(e.isDirectory()){if(s.isDirExcluded(q,O))continue;let t=join(g,e.name),S;try{S=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!H(S)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${S}`);continue}if(L(q)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}k+=1;let s=Y>=D?await J(t,q):void 0;yield{kind:`folder`,path:q,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...s===void 0?{}:{hasChildren:s}}}Y<D&&B.push({absDir:t,relDir:q,depth:Y+1});continue}if(e.isSymbolicLink()){let S=join(g,e.name),w;try{w=await realpath(S)}catch(e){console.warn(`[document-list][showAll] symlink realpath failed for ${S}:`,e);continue}if(!H(w)){console.warn(`[document-list][showAll] refusing symlink-escape ${S} -> ${w}`);continue}let E;try{E=await stat$1(w)}catch(e){console.warn(`[document-list][showAll] symlink target stat failed for ${S}:`,e);continue}let D=toPosix(relative(t,w));if(E.isDirectory()){if(s.isDirExcluded(q,O)||!L(q))continue;k+=1,yield{kind:`folder`,path:q,size:0,modified:E.mtime.toISOString(),docExt:`.md`,isSymlink:!0,canonicalDocName:D,targetPath:D,hasChildren:await J(w,q)};continue}if(!E.isFile()||s.isExcluded(q,O)||!L(q))continue;if(k+=1,isSupportedDocFile(e.name))yield{kind:`document`,docName:ee(q,ne),docExt:extname(e.name),size:E.size,modified:E.mtime.toISOString(),isSymlink:!0,canonicalDocName:D.replace(/\.(md|mdx)$/i,``),targetPath:D};else{let t=synthesizeShowAllAssetExt(e.name);yield{kind:`asset`,docName:q,docExt:t,path:q,assetExt:t,mediaKind:mediaKindForSidebarAssetExtension(t),referencedBy:[],size:E.size,modified:E.mtime.toISOString(),isSymlink:!0,canonicalDocName:null,targetPath:D}}continue}if(!e.isFile()||s.isExcluded(q,O)||!L(q))continue;let te=null;try{te=await stat$1(join(g,e.name))}catch(t){console.warn(`[document-list][showAll] stat failed for ${g}/${e.name}:`,t);continue}if(isSupportedDocFile(e.name)){let t=ee(q,ne),s=extname(e.name);k+=1,yield{kind:`document`,docName:t,docExt:s,size:te.size,modified:te.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let ae=synthesizeShowAllAssetExt(e.name),oe=mediaKindForSidebarAssetExtension(ae);k+=1,yield{kind:`asset`,docName:q,docExt:ae,path:q,assetExt:ae,mediaKind:oe,referencedBy:[],size:te.size,modified:te.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}}return yield*Y(g?join(t,g):t,g??``,1),F&&(showAllWalkAborts+=1),{truncated:j}}async function walkContentDirForShowAll(e){let{documents:t,...s}=e,g=streamShowAllEntries(s),S=await g.next();for(;!S.done;)t.push(S.value),S=await g.next();return S.value}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function isReservedProjectStatePath(e){return e.split(`/`).some(e=>{let t=e.toLowerCase();return t===`.ok`||t===`.git`})}function isReservedSyntheticFolderPath(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function listAffectedDocNames(e,t,s){let g=[...e.keys()].filter(e=>t===`file`?e===s:e===s||e.startsWith(`${s}/`));return g.sort((e,t)=>e.localeCompare(t)),g}function remapDocNameForRename(e,t,s,g){return t===`file`||e===s?g:`${g}${e.slice(s.length)}`}function requireNonEmptyDocName(e,t,s){return e!==void 0&&e.length>0?e:(errorResponse(t,400,`urn:ok:error:invalid-request`,"`docName` must be a non-empty document name.",{handler:s}),null)}function assertNoSymlinkEscape(e,t){let s;try{s=realpathSync(t)}catch(e){throw e.code===`ENOENT`?new SymlinkEscapeError(`content directory does not exist`):e}let g=e;for(;;)try{if(!isWithinContentDir(realpathSync(g),s))throw new SymlinkEscapeError(`path resolves outside content directory`);return}catch(e){let s=e.code;if(s===`ELOOP`)throw new SymlinkEscapeError(`symlink cycle in path`);if(s!==`ENOENT`)throw e;let S=dirname(g);if(S===g||S!==t&&!S.startsWith(`${t}${sep}`))throw e;g=S}}function resolveContentEntryPath(e,t,s){if(!isValidRelativeContentPath(s))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,t===`file`?docNameToRelativePath(s):s);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function splitContentPath(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function joinContentPath(e,t){return e?`${e}/${t}`:t}function duplicateBasename(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}var DuplicateNameExhaustedError=class extends Error{constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};function isAlreadyExistsError(e){let t=e.code;return t===`EEXIST`||t===`ERR_FS_CP_EEXIST`}function classifyDuplicatePathFilesystemProblem(e){let t=e.code;return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function docNameExistsWithAnySupportedExtension(e,t){return isSupportedDocFile(t)?existsSync(resolve(e,t)):SUPPORTED_DOC_EXTENSIONS.some(s=>existsSync(resolve(e,`${t}${s}`)))}function hasSameStemDocumentSibling(e,t){if(!isSupportedDocFile(t))return!1;let s=stripDocExtension(t),g=extname(t).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.some(t=>t.toLowerCase()===g?!1:existsSync(resolve(e,`${s}${t}`)))}function docNameForFileOperationPath(e,t){let s=stripDocExtension(t);return isSupportedDocFile(t)&&hasSameStemDocumentSibling(e,t)?t:s}function resolveDuplicateDocPath(e,t,s){if(!isValidRelativeContentPath(t))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,`${t}${s}`);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function nextAvailableDuplicateDocName(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!docNameExistsWithAnySupportedExtension(e,S))return{docName:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function nextAvailableDuplicateFolderPath(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!existsSync(resolveContentEntryPath(e,`folder`,S)))return{folderPath:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function collectMarkdownCopies(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[];function S(t,s){for(let w of readdirSync(t,{withFileTypes:!0})){let E=resolve(t,w.name),D=s?`${s}/${w.name}`:w.name;if(w.isDirectory()){S(E,D);continue}!w.isFile()||!isSupportedDocFile(D)||g.push({docName:docNameForFileOperationPath(e,D),fullPath:E,content:readFileSync(E,`utf-8`)})}}return S(s,t),g.sort((e,t)=>e.docName.localeCompare(t.docName)),g}function collectFolderPaths(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[t];function S(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){if(!s.isDirectory())continue;let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;g.push(E),S(w,E)}}return S(s,t),g.sort((e,t)=>e.localeCompare(t)),g}function probeAndRegisterSourceFileExtension(e,t){if(!isValidRelativeContentPath(t))return;let s=resolve(e);if(isSupportedDocFile(t)){let e=stripDocExtension(t);for(let t of SUPPORTED_DOC_EXTENSIONS){let g=resolve(s,`${e}${t}`);g!==s&&!g.startsWith(`${s}${sep}`)||existsSync(g)&&registerDocExtension(e,t)}let g=resolve(s,t);g!==s&&g.startsWith(`${s}${sep}`)&&existsSync(g)&&registerDocExtension(e,extname(t));return}for(let e of SUPPORTED_DOC_EXTENSIONS){let g=resolve(s,`${t}${e}`);if(!(g!==s&&!g.startsWith(`${s}${sep}`))&&existsSync(g)){registerDocExtension(t,e);return}}}function toGitRelativePath(e,t){let s=resolve(e),g=resolve(t);return g!==s&&!g.startsWith(`${s}${sep}`)?null:relative(s,g).split(sep).join(`/`)}function stringsDifferOnlyByCase(e,t){return e!==t&&e.toLowerCase()===t.toLowerCase()}function pathsDifferOnlyByCase(e,t){return stringsDifferOnlyByCase(resolve(e),resolve(t))}function isCaseOnlySelfCollision(e,t){if(!pathsDifferOnlyByCase(e,t)||!existsSync(e)||!existsSync(t))return!1;try{let s=statSync(e),g=statSync(t);return s.dev===g.dev&&s.ino===g.ino}catch{return!1}}function createCaseOnlyRenameTempPath(e){let t=dirname(e);for(let e=0;e<10;e+=1){let e=resolve(t,`.ok-case-rename-${randomUUID()}`);if(!existsSync(e))return e}throw Error(`Unable to allocate temporary path for case-only rename`)}function writeFileIfContentDiffers(e,t){(existsSync(e)?readFileSync(e,`utf-8`):null)!==t&&tracedWriteFileSync(e,t,`utf-8`)}function renamePathOnDisk(e,t){if(tracedMkdirSync(dirname(t),{recursive:!0}),!pathsDifferOnlyByCase(e,t)){tracedRenameSync(e,t);return}let s=createCaseOnlyRenameTempPath(e);tracedRenameSync(e,s);try{tracedRenameSync(s,t)}catch(t){try{let t=existsSync(s),g=existsSync(e);t&&!g?tracedRenameSync(s,e):console.warn(`[renamePathOnDisk] skipped case-only rollback due to unexpected state:`,{tempExists:t,sourceExists:g})}catch(e){console.warn(`[renamePathOnDisk] failed to roll back temporary case-only rename:`,e)}throw t}}async function renameTrackedPathInGit(e,t,s){if(!e)return!1;let g=toGitRelativePath(e,t),S=toGitRelativePath(e,s);return!g||!S?!1:await withParentLock(async()=>{let w=esm_default({baseDir:e,timeout:{block:15e3}}),E=``;try{E=(await w.raw(`ls-files`,`--`,g)).trim()}catch(e){return console.warn(`[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:`,e),!1}if(!E)return!1;mkdirSync(dirname(s),{recursive:!0});let D=!1;try{if(pathsDifferOnlyByCase(t,s)){let s=toGitRelativePath(e,createCaseOnlyRenameTempPath(t));if(!s)return!1;await w.raw(`mv`,`--`,g,s);try{await w.raw(`mv`,`--`,s,S)}catch(e){try{await w.raw(`mv`,`--`,s,g)}catch(e){console.warn(`[renameTrackedPathInGit] case-only git rename failed and rollback also failed; git index and disk may have diverged:`,e),D=!0}throw e}}else await w.raw(`mv`,`--`,g,S);return!0}catch(e){if(D)throw e;return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}const workspaceSearchCaches=new Map;function extractHeadings(e){let{body:t}=stripFrontmatter(e),s=[],g=new Map,S=createCodeFenceTracker();for(let e of t.split(`
1949
- `)){if(S(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),S=getHeadingSlug(e,g);S&&s.push({level:t[1].length,text:e,slug:S})}}return s}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function applyDiskEventToLiveAllFilesIndex(e,t){let s=t();s instanceof Map&&updateFileIndex(e,s)}function createApiExtension(e){let{hocuspocus:t,sessionManager:s,contentDir:g,serverInstanceId:S,getFileIndex:w,getAttachmentFolderPath:E,getAllFilesIndex:D=w,mutateFileIndex:O=e=>applyDiskEventToLiveAllFilesIndex(e,D),getFileIndexGeneration:k,getFolderIndex:j,onReferencedAssetsCacheInvalidator:F,getAliasMap:L,getFolderAliasIndex:B,rescanFiles:H,enableTestRoutes:q=!1,shadowRef:ee,flushGitCommit:J,flushContributors:Y,takeStoreFailure:te,takeStoreDivergence:ne,markAgentWriteStore:ae,getCurrentBranch:oe,getDiskAckSVs:se,contentRoot:ce,backlinkIndex:ue,tagIndex:de,signalChannel:fe,agentFocusBroadcaster:me,agentPresenceBroadcaster:ge,onAgentWrite:_e,getSyncEngine:ve,localOpCliArgs:ye=[`open-knowledge`],projectDir:Ce,getPrincipal:we,homeDirOverride:Te,contentFilter:De,installedAgentsProbe:je,forceUnloadDocument:Me,ready:Pe,recentlyRemovedDocs:Ie,serializeDoc:Re,evictManagedArtifactLkg:ze,semanticSearch:Be,getSemanticSimilarityFloor:Ve,embeddingsSecretsFile:Ue,ephemeral:We=!1}=e,Ge=createConcurrencyGuard(),Ke=new Map,Xe=createSingleFlight(),$e=null;function nt(){let e=j?.();return e instanceof Map?e:null}function rt(e){let t=nt();if(t)try{upsertFolderIndexEntry(t,g,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function it(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)rt(resolve(g,t.slice(0,e).join(`/`)))}function at(e){let t=nt();t&&removeFolderIndexEntries(t,e)}function st(e,t){let s=nt();if(!s)return;let S=[];for(let[g,w]of s.entries()){if(g!==e&&!g.startsWith(`${e}/`))continue;s.delete(g);let E=g.slice(e.length);S.push([`${t}${E}`,w])}if(S.length===0){let e=resolveContentEntryPath(g,`folder`,t);existsSync(e)&&rt(e);return}for(let[e,t]of S)s.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(g,e)})}function vt(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
1950
- `)}function St(){$e=null}F?.(St);let Tt=createInstalledAgentsProbe({probe:je??createOsProbe(process.platform)});function Et(e){if(isManagedArtifactDocName(e))try{return managedArtifactAbsPath(e,{projectDir:Ce??g,homedirOverride:Te})}catch{return null}if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,docNameToRelativePath(e));return isWithinDir(s,t)?s:null}function jt(e){let t=Et(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Mt(e,t){return t.has(e)?jt(e):e}let Ft={cluster:void 0,category:void 0,tags:void 0};function It(e){try{let s=t.documents.get(e);if(s){let e=readFmMap(s.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,s=typeof e.category==`string`?e.category:void 0,g;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);g=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(g=[e.tags]);return{cluster:t,category:s,tags:g}}}}catch{}try{let t=Et(e);if(!t||!existsSync(t))return Ft;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):Ft}catch{return Ft}}function Lt(e,t){return t.has(e)?It(e):Ft}function Rt(e){if(ue)try{if(ue.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$7.debug({docName:e,elapsedMs:g,candidateCount:s.length},`[orphan-hint] findHubCandidates slow`),s.length===0?void 0:[{type:`orphan`,parentCandidates:s,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${s.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function zt(e){return L?.().get(e)??e}function Bt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Vt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Ht(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>J?.()).catch(e=>{log$7.warn({err:e},`[${s}] post-write flush failed`)})}async function Ut(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ae?.(e),await t.debouncer.executeNow(s));let g=te?.(e)??null;return g?{kind:`failure`,failure:g}:ne?.(e)?{kind:`divergence`}:null}function Wt(e,t,s){let g=classifyUploadErrno({code:t.code});errorResponse(e,uploadStatusFor(g),g,`Write applied in memory but failed to persist to disk (${t.code??`unknown error`}): ${t.message}. The content was NOT saved and will be lost if the server restarts.`,{handler:s})}function Xt(e,t){errorResponse(e,409,`urn:ok:error:disk-divergence`,`The document changed on disk after your edit was prepared; your edit was NOT applied, to avoid overwriting the newer on-disk content. Re-read the document and retry.`,{handler:t})}function Zt(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},hint:e.mergeOutcome===`merged`?'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.':'An out-of-band edit was reconciled into this document before your edit was applied on top; the document now reflects that edit plus yours. Re-read it (e.g. `exec("cat <path>")`) to see the combined result before continuing.'}}function $t(e){if(!De)return!1;let t=docNameToRelativePath(e);return De.isExcluded(t)}function en(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let s=resolve(t===`global`?fu:g,`.ok`,`skills`);for(let g of yu(s,t).skills)e.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${t}/${g.name}`)}for(let t of resolveProjectTemplates(resolve(g)).templates)e.add(mu(t.source_folder,t.name))}catch(e){log$7.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of ue?.getIndexedDocNames()??[])e.has(t)||$t(t)||e.add(t);return e}let tn=e=>existsSync(resolve(g,e));function rn(e,t){$t(e)||O?.({kind:w().has(e)?`update`:`create`,path:resolveContentEntryPath(g,`file`,e),docName:e,content:t})}function sn(){let e=Promise.resolve();return async function(t){let s=e,g=()=>{};e=new Promise(e=>{g=e}),await s;try{return await t()}finally{g()}}}let jr=sn(),Mr=e=>e.endsWith(`.`)?e:`${e}.`;function zr(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Mr(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Mr(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Mr(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Mr(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Mr(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Mr(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Mr(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function Br(e,g){let S=new Map;for(let s of e){let e=t.documents.get(s);e&&S.set(s,e.getText(`source`).toString())}for(let s of e){let e=t.documents.get(s);e&&e.getMap(`lifecycle`).set(`status`,g)}for(let t of e)await s.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let s of e){let e=t.documents.get(s);deleteReconciledBase(s),ze?.(s),e&&(t.closeConnections(s),await(Me??t.unloadDocument.bind(t))(e))}return S}function Vr(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&writeFileIfContentDiffers(e,w);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&&registerWrite(e,contentHash(E))}}function Hr(e,t){return e.map(e=>{let s=t.get(e);if(typeof s==`string`)return{docName:e,content:s};let S=safeContentPath(e,g);if(!existsSync(S))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(S,`utf-8`)}})}function Ur(e){let s=t.documents.get(e);if(s)return s.getText(`source`).toString();let S=resolveContentEntryPath(g,`file`,e);return existsSync(S)?readFileSync(S,`utf-8`):null}function Wr(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),writeFileIfContentDiffers(s,t),registerWrite(s,contentHash(t)),setReconciledBase(e,t),O?.({kind:`update`,path:s,docName:e,content:t})}function Gr(e,s,g=[]){let S=t.documents.get(e);if(!S)throw Error(`Document is not loaded: ${e}`);let w={markdown:``,rewrites:0};return S.transact(()=>{w=qr(S.getText(`source`).toString(),e,s.get(e)??e,s,g),w.rewrites!==0&&composeAndWriteRawBody(S,w.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),w}function Kr(e,t,s){let g=e,S=0;for(let{fromPath:e,toPath:w}of s){let s=rewriteAssetReferencesForRename(g,t,e,w);g=s.markdown,S+=s.rewrites}return{markdown:g,rewrites:S}}function qr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=Kr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Jr(e,s){let g=t.documents.get(e);if(!g)throw Error(`Document is not loaded: ${e}`);let S={markdown:``,rewrites:0};return g.transact(()=>{S=Kr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Yr(e){let t=[];if(e.length===0)return t;let s=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let g of s){let s=Ur(g);if(typeof s!=`string`)continue;let S=Kr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Xr(e){let s=ve?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=docNameToRelativePath(s),w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Zr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Jr(S.docName,s):S;e.rewrites!==0&&(Wr(S.docName,e.markdown),ue?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Qr(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),s=t===-1?``:e.slice(0,t),S=t===-1?e:e.slice(t+1),w=s?resolveContentEntryPath(g,`folder`,s):g,E;try{E=readdirSync(w,{withFileTypes:!0})}catch(t){let s=t.code;if(s===`ENOENT`||s===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let D=E.filter(e=>e.isFile()&&e.name.startsWith(`${S}.`)).map(e=>s?`${s}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function Gi(e){let t=[];try{if(!statSync(e).isDirectory())return t}catch(e){let s=e.code;if(s===`ENOENT`||s===`ENOTDIR`)return t;throw e}function s(e){for(let S of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,S.name),E=relative(g,w).split(sep).join(`/`);if(isReservedProjectStatePath(E))continue;if(S.isDirectory()){if(De?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||De?.isExcluded(E))continue;let D=docNameForFileOperationPath(g,E);registerDocExtension(stripDocExtension(E),extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Ki(e,t,s){let S=[];function w(e){for(let E of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,E.name),O=relative(g,D).split(sep).join(`/`);if(!isReservedProjectStatePath(O)){if(E.isDirectory()){if(De?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||De?.isExcluded(O)||(O===t?S.push({fromPath:O,toPath:s}):O.startsWith(`${t}/`)&&S.push({fromPath:O,toPath:`${s}${O.slice(t.length)}`}))}}}return w(e),S.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),S}async function Ji(e,t){return jr(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ue)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(S))throw new ManagedRenameInvalidRequestError(`Destination asset is excluded by the project content config.`);let w=resolveContentEntryPath(g,`folder`,e),E=resolveContentEntryPath(g,`folder`,S);if(w===E)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,S))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(w))throw new ManagedRenameSourceNotFoundError(`asset`,`Asset does not exist.`);if(existsSync(E))throw new ManagedRenameDestinationExistsError;if(!statSync(w).isFile())throw new ManagedRenameSourceTypeMismatchError(`asset`,`Source path is not an asset file.`);let D=[{fromPath:e,toPath:S}],O=Yr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Xr(O.map(e=>e.docName)),await renameTrackedPathInGit(Ce,w,E)||renamePathOnDisk(w,E);let k=Zr(O,D);return ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),fe?.(`files`),k.length>0&&(fe?.(`backlinks`),fe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Yi(e,s){return jr(async()=>withSpan(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async S=>{if(!ue)throw new BacklinkIndexRequiredError;if(!isSupportedDocFile(e)||isSupportedDocFile(s))throw new ManagedRenameInvalidRequestError(`Document-to-file rename requires a markdown source and non-markdown destination.`);let w=stripDocExtension(e);if(isSystemDoc(w)||isConfigDoc(w))throw new ManagedRenameReservedPathError(`Reserved document names cannot be renamed.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(s))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(s))throw new ManagedRenameInvalidRequestError(`Destination file is excluded by the project content config.`);let E=resolveContentEntryPath(g,`folder`,e),D=resolveContentEntryPath(g,`folder`,s);if(E===D)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,s))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(E))throw new ManagedRenameSourceNotFoundError(`file`);if(existsSync(D))throw new ManagedRenameDestinationExistsError;if(!statSync(E).isFile())throw new ManagedRenameSourceTypeMismatchError(`file`,`Source path is not a document file.`);let k=ve?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]),F=t.documents.get(w);if(F!==void 0&&isDocInConflict(F)||j.has(e))throw new DocInConflictError({file:e});let L=[{fromPath:e,toPath:s}],B=Yr(L).filter(e=>e.docName!==w);S.setAttribute(`rename.rewrite_candidates`,B.length),Xr(B.map(e=>e.docName)),reconcileDiskBeforeAgentWrite(t,w,g),Ie&&!isSystemDoc(w)&&!isConfigDoc(w)&&Ie.setDeleted(w);let H=(await Br([w],`renamed`)).get(w),q=typeof H==`string`?H:readFileSync(E,`utf-8`),ee=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[{from:w,to:w}],snapshots:[{docName:w,content:q}],cleanupPaths:[s]}),J=[];return await withManagedRenameRecovery(Ce??g,ee,async()=>{writeFileIfContentDiffers(E,q),registerWrite(E,contentHash(q)),await renameTrackedPathInGit(Ce,E,D)||renamePathOnDisk(E,D),ue.deleteDocument(w),forgetDocExtension(w),O?.({kind:`delete`,path:E,docName:w});let t=statSync(D);O?.({kind:`file-create`,path:D,relativePath:s,size:t.size,modifiedTs:t.mtimeMs,inode:t.ino}),J=Zr(B,L),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist document-to-file rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),J.length>0&&(fe?.(`backlinks`),fe?.(`graph`))}),J.sort((e,t)=>e.docName.localeCompare(t.docName)),S.setAttribute(`rename.rewrite_count`,J.length),{renamedAssets:L,rewrittenDocs:J}}))}async function Xi(e,s,S,E){return jr(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ue)throw new BacklinkIndexRequiredError;let k=resolveContentEntryPath(g,S,e),j=resolveContentEntryPath(g,S,s);if(k===j)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(k))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(j)&&!isCaseOnlySelfCollision(k,j))throw new ManagedRenameDestinationExistsError;let F=statSync(k);if(S===`file`&&!F.isFile()||S===`folder`&&!F.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Ki(k,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[docNameForFileOperationPath(g,e)]:Gi(k)).map(t=>({from:t,to:S===`file`?docNameForFileOperationPath(g,s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Yr(L);Xr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(Ce,k,j)||renamePathOnDisk(k,j),st(e,s),fe?.(`files`)),g.push(...Zr(t,L)),g.length>0&&(ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`backlinks`),fe?.(`graph`)),g.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:L,rewrittenDocs:g}}let H=buildRenameMap(B),q=B.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),J=new Set;for(let{from:e}of B)for(let t of ue.getBacklinks(e))H.has(t.source)||J.add(t.source);let Y=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ne=new Set,ae=new Set,se=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){se.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Ur(e);typeof s==`string`?(te.set(e,s),H.has(e)||ne.add(e)):H.has(e)||se.push(e)}if(L.length>0){let e=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=te.get(t)??Ur(t);typeof e==`string`&&qr(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),ae.add(t),H.has(t)||ne.add(t))}}Xr(ae);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ce=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Hr([...te.keys()],te)}),de=[],me=[...ne].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(Ce??g,ce,async()=>{for(let e of se)ue.deleteDocument(e);for(let e of me){let s=t.documents.get(e)?Gr(e,H,L):qr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Wr(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ue.updateDocumentFromMarkdown(e,s.markdown)}if(Ie)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(Ie.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let w=resolveContentEntryPath(g,S,e),D=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(Ce,w,D)||renamePathOnDisk(w,D),S===`folder`&&st(e,s);let k=await Br([...H.keys()],`renamed`);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(ee?.current){let e=ee.current,t=B.filter(({from:e,to:t})=>stripDocExtension(e)!==stripDocExtension(t));t.length>0&&withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},s=>{let g=randomUUID(),w=new Date().toISOString(),D=oe?.()??`main`,O=getOrLoadRenameLogIndex(e.gitDir),k=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},j=0;for(let{from:s,to:F}of t){let t={v:1,from:s,to:F,at:w,commitSha:``,branch:D,groupId:g,kind:S,actor:k};appendRenameLogEntry(e.gitDir,t,O,e),j+=1,E?.actor?recordContributor(F,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(s,F),E.actor.actorMetadata,void 0,[{from:s,to:F}]):recordContributor(F,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(s,F),void 0,void 0,[{from:s,to:F}])}s.setAttribute(`rename.entries_appended`,j)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=isSupportedDocFile(e)?extname(e):getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let F=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of F){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),w=qr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Vr([{fromDocName:e,toDocName:t}],new Map([[e,w.markdown]])),setReconciledBase(t,w.markdown),O?.({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:w.markdown}),ue.renameDocument(e,t,w.markdown),w.rewrites>0&&de.push({docName:t,rewrites:w.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),fe?.(`backlinks`),fe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Qi(e){let t=parseAgentBodyFields(e),s=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:s,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??s,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function Ra(e){return{principalId:we?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function eo(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function to(e){return{value:e.value}}function so(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function _s(e,t,s,g){if(s.length!==0)switch(e.kind){case`agent`:{let g=e.summary.kind===`value`,S=g?e.summary:normalizeSummary(t),w=eo(S),E=g||!w.response?w.response:to(w.response);for(let t=0;t<s.length;t++){let{docName:g,subject:S}=s[t];recordContributor(g,e.writerId,e.displayName,e.colorSeed,S,e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),so(S,!g);for(let{docName:e}of s)Ht(e,`rename-path`);return E}case`principal`:{let t=eo(e.summary);for(let g=0;g<s.length;g++){let{docName:S,subject:w}=s[g];recordContributor(S,e.writerId,e.displayName,e.colorSeed,w,e.actor,g===0?t.stored:void 0)}so(e.summary,!1);for(let{docName:e}of s)Ht(e,`rename-path`);return t.response}case`anonymous`:g.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${g.context}: ${String(t.kind)}`)}}}function xs(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`skill`?`${S}.ok/skills/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function Cs(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=eo(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Ts(e){if(Y)try{await Y()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let Ds=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Qi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write`});return}let H=normalizeSummary(E.summary),q=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),J=new Date().toISOString(),Y=typeof E.content==`string`?E.content:`Hello from the agent! ${J}`,{response:te,stored:ne}=eo(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:t,color:s,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(q.dc.document.getText(`source`),O,j,F),q.dc.document.transact(()=>{applyAgentMarkdownWrite(q.dc.document,`${Y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),q.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${Y.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,Ra({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),so(H)}finally{ge?.touchMode(O,`idle`)}let ae=await Ut(D);if(ae?.kind===`failure`){Wt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Xt(w,`agent-write`);return}Ht(D,`agent-write`),_e?.();let oe=Zt(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...te?{summary:te}:{},...oe?{warning:oe,warnings:[oe]}:{}},{handler:`agent-write`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Os=withValidation(AgentWriteMdRequestSchema,async(S,w,E)=>{try{let S=E.position??`append`,D=requireNonEmptyDocName(E.docName,w,`agent-write-md`);if(D===null)return;let O=zt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Qi(E);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`agent-write-md`});return}E.extension!==void 0&&!docNameExistsWithAnySupportedExtension(g,O)&&registerDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=eo(q),Y=await s.getSession(O,k,{displayName:j,colorSeed:F,clientName:L}),te=reconcileDiskBeforeAgentWrite(t,O,g,e.resolveEmbed),ne=new Date().toISOString(),ae;try{let t=iconFromClientName(L),s=AGENT_ICON_COLORS[t]??colorFromSeed(F??k);ge?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),k,F,L),Y.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(Y.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),Y.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),ae!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:S,intendedBytes:ae.intendedBytes,actualBytes:ae.actualBytes,byteDelta:ae.byteDelta,"agent.id":k,"agent.client_name":L})),recordContentDivergenceGate(`agent-write-md`,ae),recordContributor(O,k,j,F,void 0,Ra({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),so(q)}finally{ge?.touchMode(k,`idle`)}let oe=await Ut(O);if(oe?.kind===`failure`){Wt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Xt(w,`agent-write-md`);return}Ht(O,`agent-write-md`),me?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),_e?.();let se=Rt(O),ce=Y.dc.document.getText(`source`).toString();rn(O,ce);let ue=await validateMermaidFences(ce,O),de=en();de.add(O);let fe=computeBrokenOutboundLinks(ce,O,de,tn),ve=Bt(O),ye=Vt();ye===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let Ce=Zt(te),we=ae===void 0?void 0:toContentDivergenceWarning(ae),Te=[...we?[we]:[],...Ce?[Ce]:[],...ue??[]];successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:ve,systemSubscriberCount:ye,...se?{hints:se}:{},...ee?{summary:ee}:{},...we?{warning:we}:Ce?{warning:Ce}:{},...Te.length>0?{warnings:Te}:{},brokenLinks:fe},{handler:`agent-write-md`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write-md`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write-md`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),ks=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Qi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let H=E.patch??{},q=Object.keys(H),ee=normalizeSummary(E.summary),{response:J,stored:Y}=eo(ee),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,se=!1,ce=!1,ue=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:e,color:t,currentDoc:D,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":D,"frontmatter_patch.keys":q.length}},()=>{te.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(te.dc.document.getText(`source`).toString()),s=applyPatchToFm(e,H);if(!s.ok){oe=s.error;return}for(let e of Object.keys(H))ue.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
1949
+ `)){if(S(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),S=getHeadingSlug(e,g);S&&s.push({level:t[1].length,text:e,slug:S})}}return s}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function applyDiskEventToLiveAllFilesIndex(e,t){let s=t();s instanceof Map&&updateFileIndex(e,s)}function createApiExtension(e){let{hocuspocus:t,sessionManager:s,contentDir:g,serverInstanceId:S,getFileIndex:w,getAttachmentFolderPath:E,getAllFilesIndex:D=w,mutateFileIndex:O=e=>applyDiskEventToLiveAllFilesIndex(e,D),getFileIndexGeneration:k,getFolderIndex:j,onReferencedAssetsCacheInvalidator:F,getAliasMap:L,getFolderAliasIndex:B,rescanFiles:H,enableTestRoutes:q=!1,shadowRef:ee,flushGitCommit:J,flushContributors:Y,takeStoreFailure:te,takeStoreDivergence:ne,markAgentWriteStore:ae,getCurrentBranch:oe,getDiskAckSVs:se,contentRoot:ce,backlinkIndex:ue,tagIndex:de,signalChannel:fe,agentFocusBroadcaster:me,agentPresenceBroadcaster:ge,onAgentWrite:_e,getSyncEngine:ve,localOpCliArgs:ye=[`open-knowledge`],projectDir:Ce,getPrincipal:we,homeDirOverride:Te,contentFilter:De,installedAgentsProbe:je,forceUnloadDocument:Me,ready:Pe,recentlyRemovedDocs:Ie,serializeDoc:Re,evictManagedArtifactLkg:ze,semanticSearch:Be,getSemanticSimilarityFloor:Ve,embeddingsSecretsFile:Ue,ephemeral:We=!1,linkPreviewFetch:Ge,getLinkPreviewsEnabled:Ke}=e,Xe=createConcurrencyGuard(),$e=new Map,nt=createSingleFlight(),rt=null;function it(){let e=j?.();return e instanceof Map?e:null}function at(e){let t=it();if(t)try{upsertFolderIndexEntry(t,g,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function st(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)at(resolve(g,t.slice(0,e).join(`/`)))}function vt(e){let t=it();t&&removeFolderIndexEntries(t,e)}function St(e,t){let s=it();if(!s)return;let S=[];for(let[g,w]of s.entries()){if(g!==e&&!g.startsWith(`${e}/`))continue;s.delete(g);let E=g.slice(e.length);S.push([`${t}${E}`,w])}if(S.length===0){let e=resolveContentEntryPath(g,`folder`,t);existsSync(e)&&at(e);return}for(let[e,t]of S)s.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(g,e)})}function Tt(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
1950
+ `)}function Et(){rt=null}F?.(Et);let jt=createInstalledAgentsProbe({probe:je??createOsProbe(process.platform)});function Mt(e){if(isManagedArtifactDocName(e))try{return managedArtifactAbsPath(e,{projectDir:Ce??g,homedirOverride:Te})}catch{return null}if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,docNameToRelativePath(e));return isWithinDir(s,t)?s:null}function Ft(e){let t=Mt(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function It(e,t){return t.has(e)?Ft(e):e}let Lt={cluster:void 0,category:void 0,tags:void 0};function Rt(e){try{let s=t.documents.get(e);if(s){let e=readFmMap(s.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,s=typeof e.category==`string`?e.category:void 0,g;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);g=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(g=[e.tags]);return{cluster:t,category:s,tags:g}}}}catch{}try{let t=Mt(e);if(!t||!existsSync(t))return Lt;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):Lt}catch{return Lt}}function zt(e,t){return t.has(e)?Rt(e):Lt}function Bt(e){if(ue)try{if(ue.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$7.debug({docName:e,elapsedMs:g,candidateCount:s.length},`[orphan-hint] findHubCandidates slow`),s.length===0?void 0:[{type:`orphan`,parentCandidates:s,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${s.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function Vt(e){return L?.().get(e)??e}function Ht(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Ut(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Wt(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>J?.()).catch(e=>{log$7.warn({err:e},`[${s}] post-write flush failed`)})}async function Xt(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ae?.(e),await t.debouncer.executeNow(s));let g=te?.(e)??null;return g?{kind:`failure`,failure:g}:ne?.(e)?{kind:`divergence`}:null}function Zt(e,t,s){let g=classifyUploadErrno({code:t.code});errorResponse(e,uploadStatusFor(g),g,`Write applied in memory but failed to persist to disk (${t.code??`unknown error`}): ${t.message}. The content was NOT saved and will be lost if the server restarts.`,{handler:s})}function $t(e,t){errorResponse(e,409,`urn:ok:error:disk-divergence`,`The document changed on disk after your edit was prepared; your edit was NOT applied, to avoid overwriting the newer on-disk content. Re-read the document and retry.`,{handler:t})}function en(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},hint:e.mergeOutcome===`merged`?'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.':'An out-of-band edit was reconciled into this document before your edit was applied on top; the document now reflects that edit plus yours. Re-read it (e.g. `exec("cat <path>")`) to see the combined result before continuing.'}}function tn(e){if(!De)return!1;let t=docNameToRelativePath(e);return De.isExcluded(t)}function rn(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let s=resolve(t===`global`?mu:g,`.ok`,`skills`);for(let g of xu(s,t).skills)e.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${t}/${g.name}`)}for(let t of resolveProjectTemplates(resolve(g)).templates)e.add(gu(t.source_folder,t.name))}catch(e){log$7.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of ue?.getIndexedDocNames()??[])e.has(t)||tn(t)||e.add(t);return e}let sn=e=>existsSync(resolve(g,e));function jr(e,t){tn(e)||O?.({kind:w().has(e)?`update`:`create`,path:resolveContentEntryPath(g,`file`,e),docName:e,content:t})}function Mr(){let e=Promise.resolve();return async function(t){let s=e,g=()=>{};e=new Promise(e=>{g=e}),await s;try{return await t()}finally{g()}}}let zr=Mr(),Br=e=>e.endsWith(`.`)?e:`${e}.`;function Vr(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Br(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Br(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Br(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Br(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Br(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Br(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Br(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function Hr(e,g){let S=new Map;for(let s of e){let e=t.documents.get(s);e&&S.set(s,e.getText(`source`).toString())}for(let s of e){let e=t.documents.get(s);e&&e.getMap(`lifecycle`).set(`status`,g)}for(let t of e)await s.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let s of e){let e=t.documents.get(s);deleteReconciledBase(s),ze?.(s),e&&(t.closeConnections(s),await(Me??t.unloadDocument.bind(t))(e))}return S}function Ur(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&writeFileIfContentDiffers(e,w);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&&registerWrite(e,contentHash(E))}}function Wr(e,t){return e.map(e=>{let s=t.get(e);if(typeof s==`string`)return{docName:e,content:s};let S=safeContentPath(e,g);if(!existsSync(S))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(S,`utf-8`)}})}function Gr(e){let s=t.documents.get(e);if(s)return s.getText(`source`).toString();let S=resolveContentEntryPath(g,`file`,e);return existsSync(S)?readFileSync(S,`utf-8`):null}function Kr(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),writeFileIfContentDiffers(s,t),registerWrite(s,contentHash(t)),setReconciledBase(e,t),O?.({kind:`update`,path:s,docName:e,content:t})}function qr(e,s,g=[]){let S=t.documents.get(e);if(!S)throw Error(`Document is not loaded: ${e}`);let w={markdown:``,rewrites:0};return S.transact(()=>{w=Yr(S.getText(`source`).toString(),e,s.get(e)??e,s,g),w.rewrites!==0&&composeAndWriteRawBody(S,w.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),w}function Jr(e,t,s){let g=e,S=0;for(let{fromPath:e,toPath:w}of s){let s=rewriteAssetReferencesForRename(g,t,e,w);g=s.markdown,S+=s.rewrites}return{markdown:g,rewrites:S}}function Yr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=Jr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Xr(e,s){let g=t.documents.get(e);if(!g)throw Error(`Document is not loaded: ${e}`);let S={markdown:``,rewrites:0};return g.transact(()=>{S=Jr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Zr(e){let t=[];if(e.length===0)return t;let s=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let g of s){let s=Gr(g);if(typeof s!=`string`)continue;let S=Jr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Qr(e){let s=ve?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=docNameToRelativePath(s),w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Gi(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Xr(S.docName,s):S;e.rewrites!==0&&(Kr(S.docName,e.markdown),ue?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Ki(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),s=t===-1?``:e.slice(0,t),S=t===-1?e:e.slice(t+1),w=s?resolveContentEntryPath(g,`folder`,s):g,E;try{E=readdirSync(w,{withFileTypes:!0})}catch(t){let s=t.code;if(s===`ENOENT`||s===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let D=E.filter(e=>e.isFile()&&e.name.startsWith(`${S}.`)).map(e=>s?`${s}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function Ji(e){let t=[];try{if(!statSync(e).isDirectory())return t}catch(e){let s=e.code;if(s===`ENOENT`||s===`ENOTDIR`)return t;throw e}function s(e){for(let S of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,S.name),E=relative(g,w).split(sep).join(`/`);if(isReservedProjectStatePath(E))continue;if(S.isDirectory()){if(De?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||De?.isExcluded(E))continue;let D=docNameForFileOperationPath(g,E);registerDocExtension(stripDocExtension(E),extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Yi(e,t,s){let S=[];function w(e){for(let E of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,E.name),O=relative(g,D).split(sep).join(`/`);if(!isReservedProjectStatePath(O)){if(E.isDirectory()){if(De?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||De?.isExcluded(O)||(O===t?S.push({fromPath:O,toPath:s}):O.startsWith(`${t}/`)&&S.push({fromPath:O,toPath:`${s}${O.slice(t.length)}`}))}}}return w(e),S.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),S}async function Xi(e,t){return zr(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ue)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(S))throw new ManagedRenameInvalidRequestError(`Destination asset is excluded by the project content config.`);let w=resolveContentEntryPath(g,`folder`,e),E=resolveContentEntryPath(g,`folder`,S);if(w===E)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,S))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(w))throw new ManagedRenameSourceNotFoundError(`asset`,`Asset does not exist.`);if(existsSync(E))throw new ManagedRenameDestinationExistsError;if(!statSync(w).isFile())throw new ManagedRenameSourceTypeMismatchError(`asset`,`Source path is not an asset file.`);let D=[{fromPath:e,toPath:S}],O=Zr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Qr(O.map(e=>e.docName)),await renameTrackedPathInGit(Ce,w,E)||renamePathOnDisk(w,E);let k=Gi(O,D);return ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),fe?.(`files`),k.length>0&&(fe?.(`backlinks`),fe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Qi(e,s){return zr(async()=>withSpan(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async S=>{if(!ue)throw new BacklinkIndexRequiredError;if(!isSupportedDocFile(e)||isSupportedDocFile(s))throw new ManagedRenameInvalidRequestError(`Document-to-file rename requires a markdown source and non-markdown destination.`);let w=stripDocExtension(e);if(isSystemDoc(w)||isConfigDoc(w))throw new ManagedRenameReservedPathError(`Reserved document names cannot be renamed.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(s))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(s))throw new ManagedRenameInvalidRequestError(`Destination file is excluded by the project content config.`);let E=resolveContentEntryPath(g,`folder`,e),D=resolveContentEntryPath(g,`folder`,s);if(E===D)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,s))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(E))throw new ManagedRenameSourceNotFoundError(`file`);if(existsSync(D))throw new ManagedRenameDestinationExistsError;if(!statSync(E).isFile())throw new ManagedRenameSourceTypeMismatchError(`file`,`Source path is not a document file.`);let k=ve?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]),F=t.documents.get(w);if(F!==void 0&&isDocInConflict(F)||j.has(e))throw new DocInConflictError({file:e});let L=[{fromPath:e,toPath:s}],B=Zr(L).filter(e=>e.docName!==w);S.setAttribute(`rename.rewrite_candidates`,B.length),Qr(B.map(e=>e.docName)),reconcileDiskBeforeAgentWrite(t,w,g),Ie&&!isSystemDoc(w)&&!isConfigDoc(w)&&Ie.setDeleted(w);let H=(await Hr([w],`renamed`)).get(w),q=typeof H==`string`?H:readFileSync(E,`utf-8`),ee=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[{from:w,to:w}],snapshots:[{docName:w,content:q}],cleanupPaths:[s]}),J=[];return await withManagedRenameRecovery(Ce??g,ee,async()=>{writeFileIfContentDiffers(E,q),registerWrite(E,contentHash(q)),await renameTrackedPathInGit(Ce,E,D)||renamePathOnDisk(E,D),ue.deleteDocument(w),forgetDocExtension(w),O?.({kind:`delete`,path:E,docName:w});let t=statSync(D);O?.({kind:`file-create`,path:D,relativePath:s,size:t.size,modifiedTs:t.mtimeMs,inode:t.ino}),J=Gi(B,L),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist document-to-file rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),J.length>0&&(fe?.(`backlinks`),fe?.(`graph`))}),J.sort((e,t)=>e.docName.localeCompare(t.docName)),S.setAttribute(`rename.rewrite_count`,J.length),{renamedAssets:L,rewrittenDocs:J}}))}async function Ra(e,s,S,E){return zr(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ue)throw new BacklinkIndexRequiredError;let k=resolveContentEntryPath(g,S,e),j=resolveContentEntryPath(g,S,s);if(k===j)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(k))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(j)&&!isCaseOnlySelfCollision(k,j))throw new ManagedRenameDestinationExistsError;let F=statSync(k);if(S===`file`&&!F.isFile()||S===`folder`&&!F.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Yi(k,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[docNameForFileOperationPath(g,e)]:Ji(k)).map(t=>({from:t,to:S===`file`?docNameForFileOperationPath(g,s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Zr(L);Qr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(Ce,k,j)||renamePathOnDisk(k,j),St(e,s),fe?.(`files`)),g.push(...Gi(t,L)),g.length>0&&(ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`backlinks`),fe?.(`graph`)),g.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:L,rewrittenDocs:g}}let H=buildRenameMap(B),q=B.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),J=new Set;for(let{from:e}of B)for(let t of ue.getBacklinks(e))H.has(t.source)||J.add(t.source);let Y=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ne=new Set,ae=new Set,se=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){se.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Gr(e);typeof s==`string`?(te.set(e,s),H.has(e)||ne.add(e)):H.has(e)||se.push(e)}if(L.length>0){let e=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=te.get(t)??Gr(t);typeof e==`string`&&Yr(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),ae.add(t),H.has(t)||ne.add(t))}}Qr(ae);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ce=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Wr([...te.keys()],te)}),de=[],me=[...ne].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(Ce??g,ce,async()=>{for(let e of se)ue.deleteDocument(e);for(let e of me){let s=t.documents.get(e)?qr(e,H,L):Yr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Kr(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ue.updateDocumentFromMarkdown(e,s.markdown)}if(Ie)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(Ie.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let w=resolveContentEntryPath(g,S,e),D=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(Ce,w,D)||renamePathOnDisk(w,D),S===`folder`&&St(e,s);let k=await Hr([...H.keys()],`renamed`);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(ee?.current){let e=ee.current,t=B.filter(({from:e,to:t})=>stripDocExtension(e)!==stripDocExtension(t));t.length>0&&withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},s=>{let g=randomUUID(),w=new Date().toISOString(),D=oe?.()??`main`,O=getOrLoadRenameLogIndex(e.gitDir),k=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},j=0;for(let{from:s,to:F}of t){let t={v:1,from:s,to:F,at:w,commitSha:``,branch:D,groupId:g,kind:S,actor:k};appendRenameLogEntry(e.gitDir,t,O,e),j+=1,E?.actor?recordContributor(F,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(s,F),E.actor.actorMetadata,void 0,[{from:s,to:F}]):recordContributor(F,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(s,F),void 0,void 0,[{from:s,to:F}])}s.setAttribute(`rename.entries_appended`,j)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=isSupportedDocFile(e)?extname(e):getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let F=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of F){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),w=Yr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Ur([{fromDocName:e,toDocName:t}],new Map([[e,w.markdown]])),setReconciledBase(t,w.markdown),O?.({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:w.markdown}),ue.renameDocument(e,t,w.markdown),w.rewrites>0&&de.push({docName:t,rewrites:w.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),fe?.(`backlinks`),fe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function eo(e){let t=parseAgentBodyFields(e),s=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:s,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??s,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function to(e){return{principalId:we?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function so(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function _s(e){return{value:e.value}}function xs(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Cs(e,t,s,g){if(s.length!==0)switch(e.kind){case`agent`:{let g=e.summary.kind===`value`,S=g?e.summary:normalizeSummary(t),w=so(S),E=g||!w.response?w.response:_s(w.response);for(let t=0;t<s.length;t++){let{docName:g,subject:S}=s[t];recordContributor(g,e.writerId,e.displayName,e.colorSeed,S,e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),xs(S,!g);for(let{docName:e}of s)Wt(e,`rename-path`);return E}case`principal`:{let t=so(e.summary);for(let g=0;g<s.length;g++){let{docName:S,subject:w}=s[g];recordContributor(S,e.writerId,e.displayName,e.colorSeed,w,e.actor,g===0?t.stored:void 0)}xs(e.summary,!1);for(let{docName:e}of s)Wt(e,`rename-path`);return t.response}case`anonymous`:g.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${g.context}: ${String(t.kind)}`)}}}function Ts(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`skill`?`${S}.ok/skills/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function Ds(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=so(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Os(e){if(Y)try{await Y()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let ks=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=Vt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=eo(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write`});return}let H=normalizeSummary(E.summary),q=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),J=new Date().toISOString(),Y=typeof E.content==`string`?E.content:`Hello from the agent! ${J}`,{response:te,stored:ne}=so(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:t,color:s,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(q.dc.document.getText(`source`),O,j,F),q.dc.document.transact(()=>{applyAgentMarkdownWrite(q.dc.document,`${Y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),q.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${Y.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,to({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),xs(H)}finally{ge?.touchMode(O,`idle`)}let ae=await Xt(D);if(ae?.kind===`failure`){Zt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){$t(w,`agent-write`);return}Wt(D,`agent-write`),_e?.();let oe=en(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...te?{summary:te}:{},...oe?{warning:oe,warnings:[oe]}:{}},{handler:`agent-write`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Ms=withValidation(AgentWriteMdRequestSchema,async(S,w,E)=>{try{let S=E.position??`append`,D=requireNonEmptyDocName(E.docName,w,`agent-write-md`);if(D===null)return;let O=Vt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=eo(E);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`agent-write-md`});return}E.extension!==void 0&&!docNameExistsWithAnySupportedExtension(g,O)&&registerDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=so(q),Y=await s.getSession(O,k,{displayName:j,colorSeed:F,clientName:L}),te=reconcileDiskBeforeAgentWrite(t,O,g,e.resolveEmbed),ne=new Date().toISOString(),ae;try{let t=iconFromClientName(L),s=AGENT_ICON_COLORS[t]??colorFromSeed(F??k);ge?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),k,F,L),Y.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(Y.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),Y.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),ae!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:S,intendedBytes:ae.intendedBytes,actualBytes:ae.actualBytes,byteDelta:ae.byteDelta,"agent.id":k,"agent.client_name":L})),recordContentDivergenceGate(`agent-write-md`,ae),recordContributor(O,k,j,F,void 0,to({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),xs(q)}finally{ge?.touchMode(k,`idle`)}let oe=await Xt(O);if(oe?.kind===`failure`){Zt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){$t(w,`agent-write-md`);return}Wt(O,`agent-write-md`),me?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),_e?.();let se=Bt(O),ce=Y.dc.document.getText(`source`).toString();jr(O,ce);let ue=await validateMermaidFences(ce,O),de=rn();de.add(O);let fe=computeBrokenOutboundLinks(ce,O,de,sn),ve=Ht(O),ye=Ut();ye===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let Ce=en(te),we=ae===void 0?void 0:toContentDivergenceWarning(ae),Te=[...we?[we]:[],...Ce?[Ce]:[],...ue??[]];successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:ve,systemSubscriberCount:ye,...se?{hints:se}:{},...ee?{summary:ee}:{},...we?{warning:we}:Ce?{warning:Ce}:{},...Te.length>0?{warnings:Te}:{},brokenLinks:fe},{handler:`agent-write-md`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write-md`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write-md`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),Ns=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=Vt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=eo(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let H=E.patch??{},q=Object.keys(H),ee=normalizeSummary(E.summary),{response:J,stored:Y}=so(ee),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,se=!1,ce=!1,ue=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:e,color:t,currentDoc:D,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":D,"frontmatter_patch.keys":q.length}},()=>{te.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(te.dc.document.getText(`source`).toString()),s=applyPatchToFm(e,H);if(!s.ok){oe=s.error;return}for(let e of Object.keys(H))ue.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
1951
1951
  `),S=s.nextFenced+(g?`
1952
- `:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),ce=!0}se=!0},te.origin)})}finally{ge?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]:oe.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(se&&ue.length>0){if(recordContributor(D,O,k,j,void 0,Ra({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),so(ee),ce){let e=await Ut(D);if(e?.kind===`failure`){Wt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Xt(w,`frontmatter-patch`);return}}Ht(D,`frontmatter-patch`)}me?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),_e?.();let de=Bt(D),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Zt(ne);rn(D,te.dc.document.getText(`source`).toString());let ye=en();ye.add(D);let Ce=computeBrokenOutboundLinks(te.dc.document.getText(`source`).toString(),D,ye,tn);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:de,systemSubscriberCount:fe,appliedKeys:ue,...J?{summary:J}:{},...ve?{warning:ve,warnings:[ve]}:{},brokenLinks:Ce},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ms(e){let t=e.getMap(`lifecycle`),s=t.get(`status`);if(typeof s!=`string`||s.length===0)return null;let g=t.get(`reason`);return{status:s,reason:typeof g==`string`?g:``}}let Ns=withValidation(EmptyRequestSchema,async(e,s)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(S)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let w=zt(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`document-read`});return}let E=t.documents.get(w);if(E){successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:E.getText(`source`).toString(),lifecycle:Ms(E)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(g,`file`,w))){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document not found: ${w}.`,{handler:`document-read`});return}let D=await t.openDirectConnection(w);try{let e=D.document;if(!e){errorResponse(s,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:e.getText(`source`).toString(),lifecycle:Ms(e)},{handler:`document-read`})}finally{await D.disconnect()}}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Ps=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=s.searchParams.get(`dir`),E=s.searchParams.get(`showAll`)===`true`,O=s.searchParams.get(`showOk`)===`true`,k=s.searchParams.get(`depth`)===`1`?1:1/0;if(S)try{safeSubdir(g,S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(E&&De&&showAllWantsNdjson(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let s=createStreamingErrorWriter(t,`document-list`),w=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let s=()=>{t.off(`drain`,s),t.off(`close`,s),e()};t.once(`drain`,s),t.once(`close`,s)})};try{let t=getShowAllMaxEntries(),s=streamShowAllEntries({contentDir:g,contentFilter:De,dirFilter:S,maxEntries:t,maxDepth:k,showOk:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:j}=D.value;j&&log$7.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:j,count:E})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?s(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):log$7.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(E&&De){let e=`showAll:${k===1?`d1:`:``}${O?`ok:`:``}${S??``}`,s=Ke.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:De,dirFilter:S,documents:e,maxEntries:s,maxDepth:k,showOk:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$7.info({handler:`document-list`,maxEntries:s,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:w}})();s={promise:w,controller:t,waiters:0};let E=s;Ke.set(e,E),w.finally(()=>{Ke.get(e)===E&&Ke.delete(e)})}let w=s;w.waiters+=1;let E=!1,D=()=>{t.writableEnded||E||(E=!0,--w.waiters,w.waiters<=0&&(w.controller.abort(),Ke.get(e)===w&&Ke.delete(e)))};t.on(`close`,D);try{let{documents:e,truncated:s}=await w.promise;if(E)return;successResponse(t,200,DocumentListSuccessSchema,s?{documents:e,truncated:s}:{documents:e},{handler:`document-list`})}catch(e){if(E)return;errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,D)}return}let F=w(),L=D(),H=j?.()??new Map,q=[];for(let[e,t]of H)S&&!e.startsWith(`${S}/`)&&e!==S||q.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let ee=[];try{let e=vt(F);$e?.signature!==e&&($e={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:F,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:De?e=>De.isPathIgnored(e):void 0})}),ee=$e?.assets??[]}catch(e){$e=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let J=new Set;for(let e of ee)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||(J.add(e.path),q.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of L){if(t.kind===`markdown`){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);q.push({kind:`document`,docName:e,docExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let w of t.aliases){if(S&&!w.startsWith(`${S}/`)&&w!==S)continue;let E=toPosix(relative(g,t.canonicalPath));q.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}continue}if((!S||e===S||e.startsWith(`${S}/`))&&!J.has(e)){let s=synthesizeShowAllAssetExt(e);q.push({kind:`file`,docName:e,path:e,docExt:`.${s}`,assetExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let s of t.aliases){if(!(!S||s===S||s.startsWith(`${S}/`))||J.has(s))continue;let w=toPosix(relative(g,t.canonicalPath)),E=synthesizeShowAllAssetExt(s);q.push({kind:`file`,docName:s,path:s,docExt:`.${E}`,assetExt:E,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:w})}}let Y=B?.()??new Map;if(Y.size>0){let e=e=>!S||e===S||e.startsWith(`${S}/`),t=new Map;for(let[e,s]of Y){let g=t.get(s);g?g.push(e):t.set(s,[e])}for(let[s,S]of t){let t=H.get(s),w=t?toPosix(relative(g,t.canonicalPath)):s;for(let g of S)e(g)&&q.push({kind:`folder`,path:g,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:w})}let s=(s,g)=>{for(let S=s.indexOf(`/`);S!==-1;S=s.indexOf(`/`,S+1)){let w=t.get(s.slice(0,S));if(!w)continue;let E=s.slice(S);for(let t of w){let s=`${t}${E}`;e(s)&&g(s)}}};for(let[e,t]of H)s(e,s=>{q.push({kind:`folder`,path:s,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:toPosix(relative(g,t.canonicalPath))})});for(let[e,t]of L)s(e,s=>{let S=toPosix(relative(g,t.canonicalPath));if(t.kind===`markdown`)q.push({kind:`document`,docName:s,docExt:getDocExtension(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S});else{let g=synthesizeShowAllAssetExt(s);q.push({kind:`file`,docName:s,path:s,docExt:`.${g}`,assetExt:g,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S})}})}q.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),successResponse(t,200,DocumentListSuccessSchema,{documents:q},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Is=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:s,backlinks:ue.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:jt(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Ls=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let g={};for(let e of s.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(g[t]=ue.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:g},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let g=en();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ue.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Mt(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`docName`);if(g&&!isSafeDocName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let S=s.searchParams.get(`degrees`);if(S&&!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let w,E;if(S&&g){let e=Number.parseInt(S,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:w,links:E}=ue.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ue.getLinkGraph());let D=en();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=Lt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Mt(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ue.getOrphans([...w().keys()],s).map(e=>({docName:e,title:jt(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),g=s?Number.parseInt(s,10):20,S=Number.isFinite(g)&&g>0?g:20,w=en();successResponse(t,200,HubsSuccessSchema,{hubs:ue.getHubs(S).map(e=>({docName:e.docName,title:Mt(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(s.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let g=s.length?[...new Set(s.map(e=>zt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ue.getDeadLinks(en(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:jt(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),ic=withValidation(AgentPatchRequestSchema,async(S,w,E)=>{try{let{find:S,replace:D,offset:O}=E,k=requireNonEmptyDocName(E.docName,w,`agent-patch`);if(k===null)return;let j=zt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Qi(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,se=!1,ce;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ge?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){se=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));ce=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),ce!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:ce.intendedBytes,actualBytes:ce.actualBytes,byteDelta:ce.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!se){let{stored:e}=eo(J);recordContributor(j,F,L,B,void 0,Ra({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),so(J),recordContentDivergenceGate(`agent-patch`,ce)}}finally{ge?.touchMode(F,`idle`)}if(oe){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ae){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(se){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ue=await Ut(j);if(ue?.kind===`failure`){Wt(w,ue.failure,`agent-patch`);return}if(ue?.kind===`divergence`){Xt(w,`agent-patch`);return}Ht(j,`agent-patch`),me?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),_e?.();let de=Bt(j),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=eo(J),ye=Y.dc.document.getText(`source`).toString();rn(j,ye);let Ce=await validateMermaidFences(ye,j),we=en();we.add(j);let Te=computeBrokenOutboundLinks(ye,j,we,tn),De=Zt(te),je=ce===void 0?void 0:toContentDivergenceWarning(ce),Me=[...je?[je]:[],...De?[De]:[],...Ce??[]];successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:de,systemSubscriberCount:fe,...ve?{summary:ve}:{},...je?{warning:je}:De?{warning:De}:{},...Me.length>0?{warnings:Me}:{},brokenLinks:Te},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),ac=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=zt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Qi(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(g,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:L}=S,B=S.scope===`session`||S.scope===`file`?`session`:`last`;if(!s.hasSession(w,L)){errorResponse(g,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let H=await s.getSession(w,L),q=!1;try{let t=iconFromClientName(k),s=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);ge?.setPresence(E,{displayName:D,icon:t,color:s,currentDoc:w,mode:`writing`,ts:Date.now()}),q=applyAgentUndo(H,B,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:w}:void 0),q&&recordContributor(w,L,D,O,void 0,Ra({clientName:k,clientVersion:j,label:F}))}finally{ge?.touchMode(E,`idle`)}if(q){let e=await Ut(w);if(e?.kind===`failure`){Wt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Xt(g,`agent-undo`);return}Ht(w,`agent-undo`)}me?.setFocus(L,{agentName:L,currentDoc:w,writeKind:`undo`,ts:Date.now()}),successResponse(g,200,AgentUndoSuccessSchema,{docName:w,scope:B,undone:q},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(g,e,`agent-undo`);return}log$7.error({err:e},`[agent-undo] handler failed`),errorResponse(g,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),oc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(g===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(s,g),{handler:`agent-activity`})}catch(e){log$7.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),sc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=validateAgentId(g.searchParams.get(`agentId`)),w=g.searchParams.get(`docName`),E=g.searchParams.get(`stackIndex`);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!w||w.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let D=zt(w);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!E||Number.isNaN(Number(E))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let O=Number(E);if(!Number.isInteger(O)||O<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let k=s.getLiveSession(D,S);if(!k){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let j=k.um;if(O>=j.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${O} out of range (stack has ${j.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let F=j.undoStack[O];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(F,k.dc.document.getText(`source`),D),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$7.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{await J?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$7.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),lc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=zt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$7.error({err:e,docName:E},`[test-reset] safeContentPath rejected docName`),errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(E),t.closeConnections(E);let O=`onStoreDocument-${E}`;t.debouncer.isDebounced(O)&&await t.debouncer.executeNow(O);let k=t.documents.get(E);if(k&&await(Me??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ue&&(ue.deleteDocument(E),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),w.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(g,`.okignore`),s=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(s){let e=s.getText(`source`);e.length>0&&s.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),De&&await De.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`files`),successResponse(S,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ue.rebuildFromDisk(),await ue.ingestGlobalSkillBundles([resolve(fu,`.ok`,`skills`)]),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!H){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await H(),fe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),fc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Qi(s),E=ee?.current;if(!E){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let D=/^[a-zA-Z0-9_-]+$/,O=[],k=!1;if(Array.isArray(s.writers))try{O=s.writers.map(e=>{let t=e.id??`unknown`;if(!D.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let j=oe?.()??`main`;if(O.length===0)if(e!==void 0)O=[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}];else{let e=(await enumerateWipChains(E,j)).filter(e=>!e.isPark);O=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[SERVICE_WRITER],k=!0}let F=ce??`.`,L=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),B=await saveVersion(E,F,O,j,L.kind===`value`?L.value:void 0,k?{includeUpstream:!1}:void 0);getLogger(`history`).info({checkpointRef:B.checkpointRef},`checkpoint`);try{await gcRenameLog(E,getOrLoadRenameLogIndex(E.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:B.checkpointRef},{handler:`save-version`})}catch(e){log$7.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),pc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=ee?.current;if(!s){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`docName`)??``,w=g.searchParams.get(`folder`),E=g.searchParams.get(`branch`)??oe?.()??`main`;if(!S&&w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(E.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(w!==null&&!S){let e=Kl(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0),j=`folder\0${E}\0${e.folderRel}\0${D}\0${k}`,{promise:F,coalesced:L}=Xe.run(j,()=>getFolderTimeline(s,e.folderRel,ce??`.`,{branch:E,limit:D,offset:k}));L&&recordTimelineCoalesced(`folder`),successResponse(t,200,HistorySuccessSchema,{...await F},{handler:`history`});return}let D=ce??`.`,O=safeDocPath(S,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history`});return}let k=Number(g.searchParams.get(`limit`)??`50`),j=Number(g.searchParams.get(`offset`)??`0`),F=Math.min(200,Number.isFinite(k)?k:50),L=Number.isFinite(j)?j:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=g.searchParams.get(`includeAutoCheckpoints`)===`true`,Y=`doc\0${E}\0${S}\0${F}\0${L}\0${B??``}\0${H??``}\0${q??``}\0${J?`1`:`0`}`,te=Date.now();try{let{promise:e,coalesced:g}=Xe.run(Y,()=>getDocumentHistory(s,{docName:S,branch:E,limit:F,offset:L,type:B,author:H,excludeAuthor:q,includeAutoCheckpoints:J},D));g&&recordTimelineCoalesced(`doc`);let w=await e,O=Date.now()-te;getLogger(`timeline`).info({docName:S,entries:w.entries.length,durationMs:O},`query`),successResponse(t,200,HistorySuccessSchema,{...w},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function mc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let g=ee?.current;if(!g){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,w=ce??`.`,E=safeDocPath(S,w);if(`error`in E){errorResponse(t,400,`urn:ok:error:invalid-request`,E.error,{handler:`history-version`});return}let D=shadowGit(g),O=oe?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(g,S,s,O,getOrLoadRenameLogIndex(g.gitDir),e=>{let t=safeDocPath(e,w);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let E=await D.raw(`show`,`${s}:${e}`),[k=``,j=``]=(await D.raw(`log`,`-1`,`--format=%aI%x00%an`,s)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:s,content:E,timestamp:k,author:j},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let hc=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,we);if(w.kind===`invalid-summary`){errorResponse(g,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let E=t.documents.get(S.docName);if(E&&isDocInConflict(E)){respondDocInConflict(g,new DocInConflictError({file:docNameToRelativePath(S.docName)}),`rollback`);return}let D=ee?.current;if(!D){errorResponse(g,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:O,commitSha:k}=S,j=ce??`.`,F=safeDocPath(O,j);if(`error`in F){errorResponse(g,400,`urn:ok:error:invalid-request`,F.error,{handler:`rollback`});return}let L=shadowGit(D),B=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,oe?.()??`main`,s,e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path},S);if(E===null){errorResponse(g,404,`urn:ok:error:doc-not-found`,`Commit ${k.slice(0,7)} does not contain document ${O} at any known historical path.`,{handler:`rollback`});return}let F=await L.raw(`show`,`${k}:${E}`),H=new Date().toISOString();await safetyCheckpoint(D,j,{action:`rollback`,context:{docName:O,targetSha:k}});let q=t.documents.get(O);if(!q){errorResponse(g,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,J;q.transact(()=>{replaceRawBody(q,F,ee),J=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),J!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:J.intendedBytes,actualBytes:J.actualBytes,byteDelta:J.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,J);let Y;switch(w.kind){case`agent`:{let e=k.slice(0,8),t=w.summary.kind===`value`,s=t?w.summary:normalizeSummary(`Restored to ${e}`),g=eo(s);Y=t||!g.response?g.response:to(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),so(s,!t);break}case`principal`:{let e=eo(w.summary);Y=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),so(w.summary,!1);break}case`anonymous`:log$7.debug({docName:O,commitSha:k.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(w.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:w.kind});let te=await Ut(O);if(te?.kind===`failure`){Wt(g,te.failure,`rollback`);return}if(te?.kind===`divergence`){Xt(g,`rollback`);return}Ht(O,`rollback`);let ne=Date.now()-B;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ne},`rollback`),w.kind===`agent`&&me?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()});let ae=J===void 0?void 0:toContentDivergenceWarning(J);successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:H,...Y?{summary:Y}:{},...ae?{warning:ae,warnings:[ae]}:{}},{handler:`rollback`})}catch(e){errorResponse(g,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),gc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$7.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),_c=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$7.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),vc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.(),g=getBootTimings();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s},...g===void 0?{}:{boot:g}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function yc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let s=we?.()??null;if(!s){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,s,{handler:`principal`})}async function bc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=ge?.getPresenceMap()??{},s=Date.now(),g={};for(let[t,S]of Object.entries(e))s-S.ts<2e4&&(g[t]=S);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:g},{handler:`metrics-agent-presence`})}catch(e){log$7.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function xc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function Sc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let s=resolve(g),S=s,w=!0;try{S=realpathSync(s)}catch(e){let g=e?.code;if(g===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:s}),w=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:s,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:g??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:S,pathSeparator:sep,symlinkResolved:w},{handler:`workspace`})}let Cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(De?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$7.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:s,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),wc=1048576,Tc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let S=realpathSync(g),w=resolve(S,s),E;try{E=realpathSync(w)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(E,S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let D;try{D=statSync(E)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!D.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(S,E)!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(D.size>wc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${wc}-byte text-viewer cap.`,{handler:`asset-text`});return}let O=(await readFile$1(E)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(O)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Ec=1440*60*1e3,Dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(ee.current.gitDir,`rescue`);if(existsSync(g))try{let t=readdirSync(g).filter(e=>isSupportedDocFile(e));for(let S of t){let t=resolve(g,S),w=statSync(t);if(e-w.mtimeMs>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$7.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=oe?.()??`main`,t=await listRescueCheckpoints(ee.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$7.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,s,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),Oc=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let S=s.path;if(!isSupportedDocFile(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(S.includes(`..`)||S.startsWith(`/`)||S.includes(`\0`)||S.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let w=resolve(g),E=resolve(w,S);if(!isWithinDir(E,w)){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let D=stripDocExtension(S);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`});return}if(isReservedProjectStatePath(S)||isManagedArtifactDocName(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let k=typeof s.template==`string`?s.template.trim():``,j=``,F;if(k.length>0){if(!/^[A-Za-z0-9_-]+$/.test(k)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let s=S.includes(`/`)?S.slice(0,S.lastIndexOf(`/`)):``,g=resolveTemplatesAvailable(w,s),E=g.find(e=>e.name===k);if(!E){let e=g.length===0?`(none)`:g.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${k}" does not resolve for folder "${s||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let D=resolve(w,E.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${E.path}.`,{handler:`create-page`,cause:e});return}let L=instantiateDoc(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=E.scope}mkdirSync(dirname(E),{recursive:!0});try{writeFileSync(E,j,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let L=stripDocExtension(S);switch(Ie?.delete(L),De&&De.incrementMdDir(dirname(L)),registerWrite(E,contentHash(j)),e.kind){case`agent`:case`principal`:recordContributor(L,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}O?.({kind:`create`,path:E,docName:L,content:j}),ue&&(ue.updateDocumentFromMarkdown(L,j),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),F!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:k,templateScope:F,docName:L})),successResponse(t,200,CreatePageSuccessSchema,{docName:L},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),kc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=s.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(isReservedProjectStatePath(e)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(De?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let S=resolveContentEntryPath(g,`folder`,e);if(existsSync(S)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(S,{recursive:!0}),it(e),fe?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Ac=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:w}=S,E=S.path,D=w===`file`?stripDocExtension(E):E;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(isReservedProjectStatePath(E)||w===`file`&&(isSystemDoc(D)||isConfigDoc(D))||w===`folder`&&isReservedSyntheticFolderPath(E)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}w===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=resolveContentEntryPath(g,w,E);if(!existsSync(k)){if(w===`file`){let e=resolveContentEntryPath(g,`folder`,E);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${w} does not exist.`,{handler:`duplicate-path`});return}let j=statSync(k);if(w===`file`&&!j.isFile()||w===`folder`&&!j.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let F=w===`file`?[docNameForFileOperationPath(g,E)]:Gi(resolveContentEntryPath(g,`folder`,E)),L=ve?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let e of F){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=B.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let H,q=[];if(w===`file`){let e=extname(k);if(H=nextAvailableDuplicateDocName(g,D).docName,isSystemDoc(H)||isConfigDoc(H)||De?.isExcluded(`${H}${e}`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(g,H,e),S=readFileSync(k,`utf-8`),w=dirname(t),E=existsSync(w);try{tracedMkdirSync(w,{recursive:!0}),tracedWriteFileSync(t,S,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!E)try{tracedRmdirSync(w)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:w,err:e})}throw e}let j=!1;try{registerDocExtension(H,e),Ie?.delete(H),De&&(De.incrementMdDir(dirname(H)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:H,content:S}),ue?.updateDocumentFromMarkdown(H,S),q=[H]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(H),De&&j&&De.decrementMdDir(dirname(H)),O?.({kind:`delete`,path:t,docName:H}),e}}else{if(H=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.isDirExcluded(H)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(g,`folder`,H);try{tracedCpSync(k,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(g,H))it(e);let e=collectMarkdownCopies(g,H);q=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(stripDocExtension(t.docName),e),Ie?.delete(t.docName),De&&De.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),O?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),ue?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of q)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ue&&q.length>0&&(ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:w,path:H,duplicatedDocNames:q},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(s,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),jc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s||s.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let g=Et(s);if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(g)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:s,headings:extractHeadings(readFileSync(g,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Mc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:w,fromPath:E,toPath:D}=S;if(!isValidRelativeContentPath(E)||!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(w===`file`&&(isSystemDoc(E)||isSystemDoc(D)||isConfigDoc(E)||isConfigDoc(D))){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(isReservedProjectStatePath(E)||isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let O=w===`asset`&&isSupportedDocFile(E)&&isSupportedDocFile(D)?`file`:w;if(O===`asset`){let t;try{t=isSupportedDocFile(E)&&!isSupportedDocFile(D)?await Yi(E,D):await Ji(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=zr(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&St();let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=_s(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$7.debug({kind:`asset`,fromPath:E,toPath:D,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...g?{summary:g}:{}},{handler:`rename-path`});return}O===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=O===`file`?[docNameForFileOperationPath(g,E)]:Gi(resolveContentEntryPath(g,`folder`,E)),j=ve?.(),F=new Set(j?j.getConflicts().map(e=>e.file):[]);for(let e of k){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=F.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(De){let e=isSupportedDocFile(E)?extname(E):getDocExtension(E);if(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${e}`):De.isDirExcluded(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let L=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,B;try{B=await Xi(E,D,O,L?{actor:L}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Mr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(B.renamed.length===0&&B.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}B.renamedAssets.length>0&&St();let H,q=B.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(q.length>0&&(H=_s(e,`Renamed ${E} → ${D}`,q.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$7.debug({kind:w,fromPath:E,toPath:D,affectedDocs:B.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:B.renamed,renamedAssets:B.renamedAssets,rewrittenDocs:B.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=zr(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Nc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Qi(S);let{kind:e,path:w}=S;if(!isValidRelativeContentPath(w)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let E=e===`asset`?Qr(w):{path:w,ambiguous:!1};if(E.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let D=E.path,k=e===`asset`&&isSupportedDocFile(D)?`file`:e;if(k===`file`&&probeAndRegisterSourceFileExtension(g,D),isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let j=k===`asset`?resolveContentEntryPath(g,`folder`,D):resolveContentEntryPath(g,k,D);if(!existsSync(j)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${k} does not exist.`,{handler:`delete-path`});return}let F=statSync(j);if(k===`file`&&!F.isFile()||k===`asset`&&!F.isFile()||k===`folder`&&!F.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${k}.`,{handler:`delete-path`});return}let L=k===`asset`?[]:k===`file`?[docNameForFileOperationPath(g,D)]:Gi(resolveContentEntryPath(g,`folder`,D)),B=ve?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=H.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Br(L,`deleted-upstream`),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));k===`file`||k===`asset`?tracedUnlinkSync(j):(tracedRmSync(j,{recursive:!0,force:!1}),at(D)),St();for(let e of L)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});fe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:L},{handler:`delete-path`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Pc=withValidation(TrashCleanupRequestSchema,async(e,t,s)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":s.kind,"ok.cleanup.path":normalizeFsPath(s.path),"ok.cleanup.path.role":classifyFsPath(s.path)}},async()=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:S}=s;if(!isValidRelativeContentPath(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let E=e===`asset`&&isSupportedDocFile(S)?`file`:e,D=stripDocExtension(S);E===`file`&&probeAndRegisterSourceFileExtension(g,S);let k=E===`folder`&&isReservedSyntheticFolderPath(S);if(E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||k||isReservedProjectStatePath(S)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(E===`asset`){St(),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let j=w(),F=E===`file`?j.has(D)?[D]:[]:listAffectedDocNames(j,E,S);if(St(),F.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Br(F,`deleted-upstream`),Ie)for(let e of F)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of F)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});E===`folder`&&at(S),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:F},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=getDocExtension(t),w,E;if(S.title!==void 0)w=S.title,E=S.icon;else{w=t;try{let s=readFileSync(resolve(g,`${t}${e}`),`utf-8`);w=extractPageTitle(s,t),E=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}}s.push({docName:t,title:w,docExt:e,size:S.size,modified:S.modified,icon:E})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Ic=withValidation(EmptyRequestSchema,async(e,s)=>{try{let g=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!g){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(g)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(g)||isConfigDoc(g)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${g}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(s,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:w(),docName:g}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function Lc(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let s;try{s=await readUploadBody(e,Ce??g)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:S,tempPath:w,sha:D,byteLength:O,parentDocName:k,placement:j}=s,F=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:k,placement:j||void 0},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B,placement:H}=L.value,{agentId:q,agentName:ee}=Qi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(O===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(g),Y;try{Y=H===`parent-dir`?`./`:E?.()??`./`}catch(e){F(),log$7.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!isValidAttachmentFolderPath(Y)){F(),errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let te=resolveUploadDestDir(B,normalizeAttachmentFolderPath(Y),J);if(!isWithinContentDir(te,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(te,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$7.error({err:e,destDir:te},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(te,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();let s=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(s),s,uploadTitleFor(s),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(te),s;try{s=realpathSync(J)}catch{s=J}if(!isWithinContentDir(e,s)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ne=readTempFileHead(w,4100),ae=await fileTypeFromBuffer(ne),oe=ae?.mime,se=ae?.ext;if(!oe){let e=ne.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(oe=`image/svg+xml`,se=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let ce;if(!S||S===`upload`||GENERIC_PASTE_NAMES.test(S)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=S?extname(S).slice(1):``,s=se??t??``;ce=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else ce=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,ce),S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!1},{handler:`upload-asset`})}catch(s){let g=s instanceof UploadWriteError?s.reason:`urn:ok:error:storage-error`;log$7.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:ce,size:O,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Rc=`/api/local-op/clone`,zc=`/api/local-op/ok-init`,Bc=600*1e3,Vc=45e3,Hc={stdio:[`ignore`,`ignore`,`pipe`]},Uc={stdio:[`ignore`,`pipe`,`pipe`]},Wc={stdio:`ignore`},Gc=`local-op-clone`,Kc=withValidation(LocalOpCloneRequestSchema,qc,{handler:Gc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Gc})});async function qc(e,t,s){let{url:g,dir:S,branch:w}=s;if(!isAllowedGitUrl(g)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Gc,cause:Error(`url=${g}`)});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Gc,cause:Error(`dir=${S}`)});return}if(!Ge.tryAcquire(Rc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Gc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Gc),D=null,O=runCloneSubprocess({cliArgs:ye,url:g,dir:S,branch:w,timeoutMs:Bc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$7.warn({stderr:redactShareSubprocessStderr(e.message),url:g,dir:S},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);E(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await O.done,D&&!t.writableEnded&&!t.destroyed){let e=await Jc(D);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:D})}\n`):E(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?E(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$7.error({err:e,handler:Gc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ge.release(Rc)}})(),t.on(`close`,()=>{O.cancel()})}async function Jc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=ye,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),withHiddenWindowsConsole({...Hc,cwd:s,detached:!0,env:{...process.env,OK_LOCK_KIND:`interactive`}})),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$7.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$7.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Yc=`local-op-ok-init`,Xc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Yc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Yc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Yc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:Yc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Yc});return}if(!Ge.tryAcquire(zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Yc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Yc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:Yc})}finally{Ge.release(zc)}},{handler:Yc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Yc})}),Zc=`/api/local-op/auth/login`,Qc=`/api/local-op/auth/status`,$c=`/api/local-op/auth/repos`,dl=`/api/local-op/auth/signout`,ml=()=>originGitHubHost(Ce??g),hl=null,gl=`local-op-auth-login`,_l=withValidation(LocalOpAuthHostRequestSchema,vl,{handler:gl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:gl})});async function vl(e,t,s){let g=s.host??ml();if(!Ge.tryAcquire(Zc)){let e=hl;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:gl,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),hl=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,gl),w=runDeviceFlowSubprocess({cliArgs:ye,host:g,timeoutMs:Bc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});hl=w;let E=()=>{w.cancel(),hl===w&&(hl=null,Ge.release(Zc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}hl===w&&(hl=null,Ge.release(Zc))})}let yl=`local-op-auth-status`,xl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??ml();if(!Ge.tryAcquire(Qc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:yl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,withHiddenWindowsConsole({...Uc,env:{...process.env}})),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
1953
- `).map(e=>e.trim()).filter(Boolean),E=null;for(let e=w.length-1;e>=0;e--)try{E=JSON.parse(w[e]);break}catch{}E===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:yl}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:yl})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:yl,cause:e})}finally{Ge.release(Qc)}},{handler:yl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:yl})}),Cl=`local-op-auth-repos`,Tl=withValidation(LocalOpAuthHostRequestSchema,El,{handler:Cl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Cl})});async function El(e,t,s){let g=s.host??ml();if(!Ge.tryAcquire($c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Cl,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,Cl),[w,...E]=ye,D=[...E,`auth`,`repos`,`--json`,`--host`,g],O=!1,k=``,j=spawn(w,D,withHiddenWindowsConsole({...Uc,env:{...process.env}})),F=setTimeout(()=>{j.kill(`SIGTERM`)},Bc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
1954
- `);k=s.pop()??``;for(let e of s){if(!e.trim())continue;let s=null;try{s=JSON.parse(e)}catch{}if(s&&s.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof s.message==`string`?s.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),j.stderr.on(`data`,e=>{log$7.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Ge.release($c))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Ge.release($c))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ge.release($c))})}let Dl=`local-op-auth-signout`,Ol=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??ml();if(!Ge.tryAcquire(dl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Dl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,withHiddenWindowsConsole({...Wc,env:{...process.env}})),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Dl})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Dl,cause:e})}finally{Ge.release(dl)}},{handler:Dl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Dl})}),kl=`/api/local-op/auth/set-identity`,jl=`local-op-auth-set-identity`,Ml=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:jl});return}if(!Ge.tryAcquire(kl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:jl,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:jl})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:jl,cause:e})}finally{Ge.release(kl)}},{handler:jl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:jl})});async function Pl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Fl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Il(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Ll=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Rl(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Ce){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=ve?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:Ce,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Re?Re(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function zl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let s=new URL(e.url??`/`,`http://localhost`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Bl=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function Vl(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let Hl=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function Ul(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Tt.probeAll)}catch(e){t.headersSent||(log$7.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let Wl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Gl(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:jt(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Kl(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let ql=/^[A-Za-z0-9_-]+$/;function Jl(e,t,s=`template`){return!e||!ql.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:s}),!1):!0}function Yl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Xl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function Zl(e,t){if(e.method===`GET`)return Ql(e,t);if(e.method===`PUT`)return $l(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Ql=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Kl(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),$l=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=Kl(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(Cs(e,xs(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Ts(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function eu(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}function tu(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!0):!1}let nu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function ru(e,t){if(e.method===`GET`)return au(e,t);if(e.method===`PUT`)return ou(e,t);if(e.method===`POST`)return cu(e,t);if(e.method===`DELETE`)return su(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let iu=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},au=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Jl(g,t,`template-get`))return;let S=Kl(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Yl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),ou=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!Jl(S,t,`template-put`))return;let w=Kl(g.folder,t,`folder`,`template-put`);if(!w||eu(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Xl(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=mu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=Qi(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Ut(j);if(ee?.kind===`failure`){Wt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){Xt(t,`template-put`);return}Cs(e,xs(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Ts(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),su=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Jl(g,t,`template-delete`))return;let S=Kl(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(eu(S.folderRel,g,`template-delete`,t))return;await Br([mu(S.folderRel,g)],`deleted-upstream`);let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}D.existed&&(Cs(E,xs(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Ts(`template-delete`)),successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),cu=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Jl(s.fromName,t,`template-move`)||!Jl(s.toName,t,`template-move`))return;let g=Kl(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Kl(s.toFolder,t,`folder`,`template-move`);if(!S||eu(g.folderRel,s.fromName,`template-move`,t))return;await Br([mu(g.folderRel,s.fromName)],`renamed`);let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=Yl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Xl(s.frontmatter)});t.ok||(E=t.error)}}if(Cs(e,xs(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Ts(`template-move`),fe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),lu=500;function uu(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function du(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let fu=Te??homedir();function pu(e){return resolve(e===`global`?fu:g,`.ok`,`skills`)}function mu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function hu(e){return e===`navigation`||e===`relevance`?e:void 0}function gu(e,t){return relative(t===`global`?fu:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function _u(e){return e===`global`?fu:Ce}async function vu(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function yu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=iu(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:gu(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let bu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=yu(pu(`project`),`project`),s=yu(pu(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(fu).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function xu(e,t){if(e.method===`GET`)return Du(e,t);if(e.method===`PUT`)return Ou(e,t);if(e.method===`POST`)return Au(e,t);if(e.method===`DELETE`)return ku(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Su=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),Cu=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:pu(`project`)}):0}),wu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,Su,Cu(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),Tu=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:pu(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,Su,Cu(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function Eu(e,t){if(e.method===`GET`)return wu(e,t);if(e.method===`PUT`)return Tu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let Du=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!uu(g,t,`skill-get`))return;let S=du(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=pu(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=iu(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:gu(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),Ou=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!uu(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=pu(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(tu(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Qi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){Xt(t,`skill-put`);return}g.scope===`project`&&(Cs(e,xs(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Ts(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),ku=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!uu(g,t,`skill-delete`))return;let S=du(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=pu(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Br([skillLiveDocName(S,g)],`deleted-upstream`);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Cs(D,xs(`skill`,``,g),`skill-delete: ${O.path}`),await Ts(`skill-delete`)),fe?.(`files`));let k=_u(S);k&&await vu(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Au=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!uu(s.fromName,t,`skill-move`)||!uu(s.toName,t,`skill-move`))return;let g=pu(s.scope);await Br([skillLiveDocName(s.scope,s.fromName)],`renamed`);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=iu(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{Fu(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=gu(resolve(g,s.fromName),s.scope),B=gu(resolve(g,s.toName),s.scope);s.scope===`project`&&(Cs(e,xs(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Ts(`skill-move`));let H=_u(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function ju(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Mu(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function Nu(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function Pu(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function Fu(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of Pu(e,s))g(Nu(t,S),Nu(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Iu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!uu(g,t,`skill-file-get`))return;let S=du(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=ju(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(pu(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Lu=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!uu(g.name,t,`skill-file-put`))return;let S=ju(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=pu(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=Mu(g.scope,S,E),O;if(D){let e=Nu(g.name,E);if(tu(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=Qi(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Ut(e);if(L?.kind===`failure`){Wt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){Xt(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Cs(e,xs(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Ts(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Ru=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!uu(g,t,`skill-file-delete`))return;let S=du(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=ju(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=pu(S);Mu(S,E,w)&&await Br([Nu(g,w)],`deleted-upstream`);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Cs(D,xs(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Ts(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function zu(e,t){if(e.method===`GET`)return Iu(e,t);if(e.method===`PUT`)return Lu(e,t);if(e.method===`DELETE`)return Ru(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Bu=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=pu(s.scope);if(!uu(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=_u(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Vu=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!uu(s.name,t,`skill-uninstall`))return;let e=_u(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await vu(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Hu(e,t){if(e.method===`GET`)return Uu(e,t);if(e.method===`PUT`)return Wu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Uu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Wu=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=pu(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),Gu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!uu(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Cs(e,xs(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Ts(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Ku=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!uu(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(pu(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(tu(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Qi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){Xt(t,`skill-update`);return}Cs(e,xs(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Ts(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function qu(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Ju(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,`�`)}function Yu(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Xu(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let s=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return s.length>0?s:void 0}function Zu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Qu(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function $u(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function ed(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Ju(e.document.content,t):void 0}}async function td(e){let t=performance.now();if(dd())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await fd(),S=await $u(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>ed(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function nd(){let e=pu(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function rd(){let e=[];for(let t of nd()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=iu(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function ad(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let od=new Map;async function sd(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=ad(S),E=od.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||od.set(g,{key:w,doc:j}),e.push(j)}for(let e of od.keys())s.has(e)||od.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...rd(),...S,...qu([...e,...S])],truncated:w}}function cd(){return nd().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function ld(){return k?`gen:${k()}|skills${cd()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${ad(t)}`).join(``)}|skills${cd()}`}let ud=Pe===void 0;Pe?.then(()=>{ud=!0},e=>{ud=!0,log$7.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function dd(){return!ud}async function fd(){let e=`${g}${Ce??``}`,t=ld(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=sd().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function pd(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{fd().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}pd();async function md(e,t){if(e.method===`GET`)return hd(e,t);if(e.method===`POST`)return gd(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let hd=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Yu(s.searchParams.get(`intent`)),E=hu(s.searchParams.get(`ranking`)),D=Xu(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=Zu(s.searchParams.get(`semantic`)),k=Qu(s.searchParams.get(`source`)),j=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await td({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),gd=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Yu(s.intent),w=hu(s.ranking),E=Xu(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=Zu(s.semantic),k=Qu(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await td({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),_d=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function vd(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:Tt.probeWithCache})}catch(e){t.headersSent||(log$7.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function yd(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$7.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let bd=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=s.kind===`doc`?s.docPath:s.folderPath;if(!isValidSharePath(e,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readGitHeadBranch(Ce);if(S===null){if(readOriginGitHubRepo(Ce).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(Ce);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`||w.host!==`github.com`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(Ce,S)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:S},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=toGitRelativePath(Ce,g);if(E===null)throw Error(`content dir is not contained within the project dir`);let D=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;E!==``&&D&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let O;if(s.kind===`doc`)O=buildGitHubBlobUrl(w.owner,w.repo,S,s.docPath);else{let e=s.folderPath===``?E:s.folderPath;O=buildGitHubTreeUrl(w.owner,w.repo,S,e)}let k=`${SHARE_BASE_URL}${encodeShareUrl(O)}`,j=await computeShareFreshness(Ce,S,E===``?e:e===``?E:`${E}/${e}`,s.kind);emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind,freshness:j}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:k,sharedUrl:O,branch:S,freshness:j},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),xd=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(Ce,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),Sd=withValidation(ShareTargetStatusRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}if(!isValidBranchInfoPath(s.path,s.kind)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}let e=toGitRelativePath(Ce,g);if(e===null)throw Error(`content dir is not contained within the project dir`);let S=e===``?s.path:s.path===``?e:`${e}/${s.path}`;successResponse(t,200,ShareTargetStatusResponseSchema,await computeShareTargetStatus(Ce,s.branch,S,s.kind),{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG,cause:e})}},{handler:SHARE_TARGET_STATUS_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}),Cd=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(Ce,s.branch,{fastForward:s.fastForward===!0})),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function wd(e){let[t,...s]=ye,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,withHiddenWindowsConsole({...Uc,env:{...process.env}})),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let Td=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await wd([`share`,`owners`,`--json`]),s=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,s.ok?`ok`:s.error,s.ok?{count:s.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,s,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),Ed=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await wd([`share`,`name-check`,`--owner`,g,`--name`,S,`--json`]),s=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,s.ok?`ok`:s.error,s.ok?{available:s.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,s,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),Dd=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(s.owner)||!isValidShareRepoName(s.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,s.owner,`--name`,s.name,`--visibility`,s.visibility,`--project-dir`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await wd(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),Od=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),kd=Ce?getLocalDir(Ce):null;async function Ad(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:kd?readServerLock(kd)?.port??0:0,singleFile:We};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let jd=`local-op-embeddings-set-key`,Md=`local-op-embeddings-clear-key`,Nd=`/api/local-op/embeddings`,Pd=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(Nd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:jd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:jd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:jd,cause:e})}finally{Ge.release(Nd)}},{handler:jd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:jd})}),Fd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(Nd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Md,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:Md,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Md,cause:e})}finally{Ge.release(Nd)}},{handler:Md,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Md})}),Id=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Ld={"/api/config":Ad,"/api/asset":Cc,"/api/asset-text":Tc,"/api/document":Ns,"/api/documents":Ps,"/api/backlinks":Is,"/api/backlink-counts":Ls,"/api/forward-links":Rs,"/api/link-graph":ec,"/api/dead-links":rc,"/api/orphans":tc,"/api/hubs":nc,"/api/tags":Wl,"/api/pages":Fc,"/api/folder-config":Zl,"/api/template":ru,"/api/templates":nu,"/api/skill":xu,"/api/skill-file":zu,"/api/skills":bu,"/api/skills/management":Eu,"/api/skill/install":Bu,"/api/skill/uninstall":Vu,"/api/skill/restore":Gu,"/api/skill/update":Ku,"/api/skill-targets":Hu,"/api/search":md,"/api/semantic-status":Id,"/api/suggest-links":Ic,"/api/page-headings":jc,"/api/create-page":Oc,"/api/create-folder":kc,"/api/duplicate-path":Ac,"/api/rename-path":Mc,"/api/delete-path":Nc,"/api/trash/cleanup":Pc,"/api/upload":Lc,"/api/agent-write":Ds,"/api/agent-write-md":Os,"/api/frontmatter-patch":ks,"/api/agent-patch":ic,"/api/agent-undo":ac,"/api/agent-activity":oc,"/api/agent-burst-diff":sc,"/api/save-version":fc,"/api/history":pc,"/api/rollback":hc,"/api/metrics/reconciliation":gc,"/api/metrics/parse-health":_c,"/api/metrics/agent-presence":bc,"/api/__embed-detect":xc,"/api/server-info":vc,"/api/share/construct-url":bd,"/api/share/target-status":Sd,"/api/git/branch-info":xd,"/api/git/checkout":Cd,"/api/share/publish/owners":Td,"/api/share/publish/name-check":Ed,"/api/share/publish":Dd,"/api/principal":yc,"/api/rescue":Dc,"/api/workspace":Sc,"/api/sync/status":Pl,"/api/sync/trigger":Fl,"/api/sync/conflicts":Il,"/api/sync/conflict-content":Rl,"/api/sync/resolve-conflict":Ll,"/api/local-op/clone":Kc,"/api/local-op/ok-init":Xc,"/api/local-op/auth/login":_l,"/api/local-op/auth/status":xl,"/api/local-op/auth/repos":Tl,"/api/local-op/auth/signout":Ol,"/api/local-op/auth/set-identity":Ml,"/api/local-op/embeddings/set-key":Pd,"/api/local-op/embeddings/clear-key":Fd,"/api/installed-agents":Ul,"/api/spawn-cursor":yd,"/api/handoff":vd,"/api/install-skill":Hl,"/api/skill/install-state":_d,"/api/seed/plan":zl,"/api/seed/apply":Bl,"/api/seed/packs":Vl,"/api/client-logs":Od};q&&(Ld[`/api/test-reset`]=lc,Ld[`/api/test-flush-git`]=cc,Ld[`/api/test-rescan-backlinks`]=uc,Ld[`/api/test-rescan-files`]=dc);let Rd=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),zd=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),s.startsWith(`/api/`)){let s=e.headers.origin;if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Rd.has(s)||zd.some(e=>s.startsWith(e))){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(We&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Ld[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=Ld[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await mc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Gl(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=toPosix(relative(t,w));if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$6=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$6.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$6.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$6.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-BMLM1Bxa-C8CZ9W34.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(!isWithinDir(g,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$6.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=await listNames(w.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:s});g=e.length>0}catch(e){log$6.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}g||this.addConflict({file:e,detectedAt:s}),log$6.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let S=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${g?`unmerged files re-added`:`original file re-added`} — ${S}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,s=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,g=0,S=null,w=null,E=!1,D=!1;function O(){S!==null&&(t.clearTimeout(S),S=null),w!==null&&(t.clearTimeout(w),w=null)}function k(){O(),!(D||E)&&g===0&&(s>0&&s<e.thresholdMs&&(w=t.setTimeout(()=>{w=null,g===0&&!E&&e.log?.warn({msUntilShutdown:s,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-s)),S=t.setTimeout(()=>{if(S=null,!(D||E)&&g===0){E=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let j=(e,t)=>{e.url?.startsWith(`/collab`)&&(g++,O(),t.once(`close`,()=>{g--,g<0&&(g=0),g===0&&k()}))};return e.httpServer.on(`upgrade`,j),k(),{detach:()=>{D||(D=!0,e.httpServer.off(`upgrade`,j),O())}}}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function readRawSinkBlock(e){if(!existsSync(e))return{};let t;try{t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!isObject(t))return{};let s=t.telemetry;if(!isObject(s))return{};let g=s.localSink;return isObject(g)?g:{}}function readBoolean(e){return typeof e==`boolean`?e:void 0}function readPositiveNumber(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function readStringArray(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function readMaxBytes(e){if(isObject(e))return readPositiveNumber(e.maxBytes)}function resolveLocalSinkConfig(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=readRawSinkBlock(resolveConfigPath(`project`,e.projectDir)),s=readRawSinkBlock(resolveConfigPath(`project-local`,e.projectDir));if((readBoolean(s.enabled)??readBoolean(t.enabled)??!0)===!1)return null;let g=readMaxBytes(s.spans)??readMaxBytes(t.spans)??52428800,S=readMaxBytes(s.logs)??readMaxBytes(t.logs)??26214400,w=readStringArray(s.attributeDenylist)??readStringArray(t.attributeDenylist)??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:g,attributeDenylist:w},logs:{projectDir:e.projectDir,maxBytes:S}}}const MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let s=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return s?s.slice(0,128):t}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let s=t.validateToolInput;if(typeof s!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,g){if(!e.inputSchema||!isZodSchema(e.inputSchema))return s.call(this,e,t,g);let S=await e.inputSchema.safeParseAsync(t);if(S.success)return S.data;let w=prettifyError(S.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${g}:\n${w}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const SPAWN_TIMEOUT_MS=2e3,LOCK_SCAN_MAX_DEPTH=3,LOCK_SCAN_MAX_ENTRIES=2e3,OK_LOCK_DIR_ARG_PREFIX=`--ok-lock-dir-b64=`,OK_PROJECT_PATH_ARG_PREFIX=`--ok-project-path=`,OK_PROCESS_PGREP_QUERY=`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`,OK_PROCESS_PATTERNS=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function isOkProcess(e){return OK_PROCESS_PATTERNS.some(t=>t.test(e))}function extractMarkedLockDir(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(OK_LOCK_DIR_ARG_PREFIX));if(t==null)return null;let s=t.slice(18);if(!s)return null;try{let e=Buffer.from(s,`base64url`).toString(`utf8`);return isAbsolute(e)?e:null}catch{return null}}function extractProjectPathArg(e){let t=e.indexOf(OK_PROJECT_PATH_ARG_PREFIX);if(t===-1)return null;let s=t+18,g=e.slice(s),S=g.search(/\s--/),w=(S===-1?g:g.slice(0,S)).trim();return w&&isAbsolute(w)?w:null}function parsePgrepOutput(e){let t=[];for(let s of e.split(`
1952
+ `:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),ce=!0}se=!0},te.origin)})}finally{ge?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]:oe.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(se&&ue.length>0){if(recordContributor(D,O,k,j,void 0,to({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),xs(ee),ce){let e=await Xt(D);if(e?.kind===`failure`){Zt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){$t(w,`frontmatter-patch`);return}}Wt(D,`frontmatter-patch`)}me?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),_e?.();let de=Ht(D),fe=Ut();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=en(ne);jr(D,te.dc.document.getText(`source`).toString());let ye=rn();ye.add(D);let Ce=computeBrokenOutboundLinks(te.dc.document.getText(`source`).toString(),D,ye,sn);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:de,systemSubscriberCount:fe,appliedKeys:ue,...J?{summary:J}:{},...ve?{warning:ve,warnings:[ve]}:{},brokenLinks:Ce},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ps(e){let t=e.getMap(`lifecycle`),s=t.get(`status`);if(typeof s!=`string`||s.length===0)return null;let g=t.get(`reason`);return{status:s,reason:typeof g==`string`?g:``}}let Is=withValidation(EmptyRequestSchema,async(e,s)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(S)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let w=Vt(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`document-read`});return}let E=t.documents.get(w);if(E){successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:E.getText(`source`).toString(),lifecycle:Ps(E)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(g,`file`,w))){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document not found: ${w}.`,{handler:`document-read`});return}let D=await t.openDirectConnection(w);try{let e=D.document;if(!e){errorResponse(s,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:e.getText(`source`).toString(),lifecycle:Ps(e)},{handler:`document-read`})}finally{await D.disconnect()}}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Ls=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=s.searchParams.get(`dir`),E=s.searchParams.get(`showAll`)===`true`,O=s.searchParams.get(`showOk`)===`true`,k=s.searchParams.get(`depth`)===`1`?1:1/0;if(S)try{safeSubdir(g,S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(E&&De&&showAllWantsNdjson(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let s=createStreamingErrorWriter(t,`document-list`),w=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let s=()=>{t.off(`drain`,s),t.off(`close`,s),e()};t.once(`drain`,s),t.once(`close`,s)})};try{let t=getShowAllMaxEntries(),s=streamShowAllEntries({contentDir:g,contentFilter:De,dirFilter:S,maxEntries:t,maxDepth:k,showOk:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:j}=D.value;j&&log$7.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:j,count:E})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?s(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):log$7.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(E&&De){let e=`showAll:${k===1?`d1:`:``}${O?`ok:`:``}${S??``}`,s=$e.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:De,dirFilter:S,documents:e,maxEntries:s,maxDepth:k,showOk:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$7.info({handler:`document-list`,maxEntries:s,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:w}})();s={promise:w,controller:t,waiters:0};let E=s;$e.set(e,E),w.finally(()=>{$e.get(e)===E&&$e.delete(e)})}let w=s;w.waiters+=1;let E=!1,D=()=>{t.writableEnded||E||(E=!0,--w.waiters,w.waiters<=0&&(w.controller.abort(),$e.get(e)===w&&$e.delete(e)))};t.on(`close`,D);try{let{documents:e,truncated:s}=await w.promise;if(E)return;successResponse(t,200,DocumentListSuccessSchema,s?{documents:e,truncated:s}:{documents:e},{handler:`document-list`})}catch(e){if(E)return;errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,D)}return}let F=w(),L=D(),H=j?.()??new Map,q=[];for(let[e,t]of H)S&&!e.startsWith(`${S}/`)&&e!==S||q.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let ee=[];try{let e=Tt(F);rt?.signature!==e&&(rt={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:F,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:De?e=>De.isPathIgnored(e):void 0})}),ee=rt?.assets??[]}catch(e){rt=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let J=new Set;for(let e of ee)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||(J.add(e.path),q.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of L){if(t.kind===`markdown`){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);q.push({kind:`document`,docName:e,docExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let w of t.aliases){if(S&&!w.startsWith(`${S}/`)&&w!==S)continue;let E=toPosix(relative(g,t.canonicalPath));q.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}continue}if((!S||e===S||e.startsWith(`${S}/`))&&!J.has(e)){let s=synthesizeShowAllAssetExt(e);q.push({kind:`file`,docName:e,path:e,docExt:`.${s}`,assetExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let s of t.aliases){if(!(!S||s===S||s.startsWith(`${S}/`))||J.has(s))continue;let w=toPosix(relative(g,t.canonicalPath)),E=synthesizeShowAllAssetExt(s);q.push({kind:`file`,docName:s,path:s,docExt:`.${E}`,assetExt:E,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:w})}}let Y=B?.()??new Map;if(Y.size>0){let e=e=>!S||e===S||e.startsWith(`${S}/`),t=new Map;for(let[e,s]of Y){let g=t.get(s);g?g.push(e):t.set(s,[e])}for(let[s,S]of t){let t=H.get(s),w=t?toPosix(relative(g,t.canonicalPath)):s;for(let g of S)e(g)&&q.push({kind:`folder`,path:g,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:w})}let s=(s,g)=>{for(let S=s.indexOf(`/`);S!==-1;S=s.indexOf(`/`,S+1)){let w=t.get(s.slice(0,S));if(!w)continue;let E=s.slice(S);for(let t of w){let s=`${t}${E}`;e(s)&&g(s)}}};for(let[e,t]of H)s(e,s=>{q.push({kind:`folder`,path:s,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:toPosix(relative(g,t.canonicalPath))})});for(let[e,t]of L)s(e,s=>{let S=toPosix(relative(g,t.canonicalPath));if(t.kind===`markdown`)q.push({kind:`document`,docName:s,docExt:getDocExtension(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S});else{let g=synthesizeShowAllAssetExt(s);q.push({kind:`file`,docName:s,path:s,docExt:`.${g}`,assetExt:g,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S})}})}q.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),successResponse(t,200,DocumentListSuccessSchema,{documents:q},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:s,backlinks:ue.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:Ft(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let g={};for(let e of s.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(g[t]=ue.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:g},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let g=rn();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ue.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:It(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`docName`);if(g&&!isSafeDocName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let S=s.searchParams.get(`degrees`);if(S&&!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let w,E;if(S&&g){let e=Number.parseInt(S,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:w,links:E}=ue.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ue.getLinkGraph());let D=rn();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=zt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:It(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ue.getOrphans([...w().keys()],s).map(e=>({docName:e,title:Ft(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),ic=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),g=s?Number.parseInt(s,10):20,S=Number.isFinite(g)&&g>0?g:20,w=rn();successResponse(t,200,HubsSuccessSchema,{hubs:ue.getHubs(S).map(e=>({docName:e.docName,title:It(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),ac=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(s.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let g=s.length?[...new Set(s.map(e=>Vt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ue.getDeadLinks(rn(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Ft(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),oc=withValidation(AgentPatchRequestSchema,async(S,w,E)=>{try{let{find:S,replace:D,offset:O}=E,k=requireNonEmptyDocName(E.docName,w,`agent-patch`);if(k===null)return;let j=Vt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=eo(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,se=!1,ce;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ge?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){se=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));ce=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),ce!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:ce.intendedBytes,actualBytes:ce.actualBytes,byteDelta:ce.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!se){let{stored:e}=so(J);recordContributor(j,F,L,B,void 0,to({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),xs(J),recordContentDivergenceGate(`agent-patch`,ce)}}finally{ge?.touchMode(F,`idle`)}if(oe){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ae){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(se){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ue=await Xt(j);if(ue?.kind===`failure`){Zt(w,ue.failure,`agent-patch`);return}if(ue?.kind===`divergence`){$t(w,`agent-patch`);return}Wt(j,`agent-patch`),me?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),_e?.();let de=Ht(j),fe=Ut();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=so(J),ye=Y.dc.document.getText(`source`).toString();jr(j,ye);let Ce=await validateMermaidFences(ye,j),we=rn();we.add(j);let Te=computeBrokenOutboundLinks(ye,j,we,sn),De=en(te),je=ce===void 0?void 0:toContentDivergenceWarning(ce),Me=[...je?[je]:[],...De?[De]:[],...Ce??[]];successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:de,systemSubscriberCount:fe,...ve?{summary:ve}:{},...je?{warning:je}:De?{warning:De}:{},...Me.length>0?{warnings:Me}:{},brokenLinks:Te},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),sc=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=Vt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=eo(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(g,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:L}=S,B=S.scope===`session`||S.scope===`file`?`session`:`last`;if(!s.hasSession(w,L)){errorResponse(g,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let H=await s.getSession(w,L),q=!1;try{let t=iconFromClientName(k),s=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);ge?.setPresence(E,{displayName:D,icon:t,color:s,currentDoc:w,mode:`writing`,ts:Date.now()}),q=applyAgentUndo(H,B,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:w}:void 0),q&&recordContributor(w,L,D,O,void 0,to({clientName:k,clientVersion:j,label:F}))}finally{ge?.touchMode(E,`idle`)}if(q){let e=await Xt(w);if(e?.kind===`failure`){Zt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){$t(g,`agent-undo`);return}Wt(w,`agent-undo`)}me?.setFocus(L,{agentName:L,currentDoc:w,writeKind:`undo`,ts:Date.now()}),successResponse(g,200,AgentUndoSuccessSchema,{docName:w,scope:B,undone:q},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(g,e,`agent-undo`);return}log$7.error({err:e},`[agent-undo] handler failed`),errorResponse(g,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(g===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(s,g),{handler:`agent-activity`})}catch(e){log$7.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=validateAgentId(g.searchParams.get(`agentId`)),w=g.searchParams.get(`docName`),E=g.searchParams.get(`stackIndex`);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!w||w.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let D=Vt(w);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!E||Number.isNaN(Number(E))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let O=Number(E);if(!Number.isInteger(O)||O<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let k=s.getLiveSession(D,S);if(!k){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let j=k.um;if(O>=j.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${O} out of range (stack has ${j.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let F=j.undoStack[O];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(F,k.dc.document.getText(`source`),D),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$7.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{await J?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$7.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),dc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=Vt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$7.error({err:e,docName:E},`[test-reset] safeContentPath rejected docName`),errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(E),t.closeConnections(E);let O=`onStoreDocument-${E}`;t.debouncer.isDebounced(O)&&await t.debouncer.executeNow(O);let k=t.documents.get(E);if(k&&await(Me??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ue&&(ue.deleteDocument(E),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),w.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(g,`.okignore`),s=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(s){let e=s.getText(`source`);e.length>0&&s.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),De&&await De.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`files`),successResponse(S,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ue.rebuildFromDisk(),await ue.ingestGlobalSkillBundles([resolve(mu,`.ok`,`skills`)]),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),pc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!H){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await H(),fe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),mc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=eo(s),E=ee?.current;if(!E){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let D=/^[a-zA-Z0-9_-]+$/,O=[],k=!1;if(Array.isArray(s.writers))try{O=s.writers.map(e=>{let t=e.id??`unknown`;if(!D.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let j=oe?.()??`main`;if(O.length===0)if(e!==void 0)O=[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}];else{let e=(await enumerateWipChains(E,j)).filter(e=>!e.isPark);O=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[SERVICE_WRITER],k=!0}let F=ce??`.`,L=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),B=await saveVersion(E,F,O,j,L.kind===`value`?L.value:void 0,k?{includeUpstream:!1}:void 0);getLogger(`history`).info({checkpointRef:B.checkpointRef},`checkpoint`);try{await gcRenameLog(E,getOrLoadRenameLogIndex(E.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:B.checkpointRef},{handler:`save-version`})}catch(e){log$7.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),hc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=ee?.current;if(!s){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`docName`)??``,w=g.searchParams.get(`folder`),E=g.searchParams.get(`branch`)??oe?.()??`main`;if(!S&&w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(E.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(w!==null&&!S){let e=Jl(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0),j=`folder\0${E}\0${e.folderRel}\0${D}\0${k}`,{promise:F,coalesced:L}=nt.run(j,()=>getFolderTimeline(s,e.folderRel,ce??`.`,{branch:E,limit:D,offset:k}));L&&recordTimelineCoalesced(`folder`),successResponse(t,200,HistorySuccessSchema,{...await F},{handler:`history`});return}let D=ce??`.`,O=safeDocPath(S,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history`});return}let k=Number(g.searchParams.get(`limit`)??`50`),j=Number(g.searchParams.get(`offset`)??`0`),F=Math.min(200,Number.isFinite(k)?k:50),L=Number.isFinite(j)?j:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=g.searchParams.get(`includeAutoCheckpoints`)===`true`,Y=`doc\0${E}\0${S}\0${F}\0${L}\0${B??``}\0${H??``}\0${q??``}\0${J?`1`:`0`}`,te=Date.now();try{let{promise:e,coalesced:g}=nt.run(Y,()=>getDocumentHistory(s,{docName:S,branch:E,limit:F,offset:L,type:B,author:H,excludeAuthor:q,includeAutoCheckpoints:J},D));g&&recordTimelineCoalesced(`doc`);let w=await e,O=Date.now()-te;getLogger(`timeline`).info({docName:S,entries:w.entries.length,durationMs:O},`query`),successResponse(t,200,HistorySuccessSchema,{...w},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function gc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let g=ee?.current;if(!g){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,w=ce??`.`,E=safeDocPath(S,w);if(`error`in E){errorResponse(t,400,`urn:ok:error:invalid-request`,E.error,{handler:`history-version`});return}let D=shadowGit(g),O=oe?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(g,S,s,O,getOrLoadRenameLogIndex(g.gitDir),e=>{let t=safeDocPath(e,w);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let E=await D.raw(`show`,`${s}:${e}`),[k=``,j=``]=(await D.raw(`log`,`-1`,`--format=%aI%x00%an`,s)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:s,content:E,timestamp:k,author:j},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let _c=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,we);if(w.kind===`invalid-summary`){errorResponse(g,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let E=t.documents.get(S.docName);if(E&&isDocInConflict(E)){respondDocInConflict(g,new DocInConflictError({file:docNameToRelativePath(S.docName)}),`rollback`);return}let D=ee?.current;if(!D){errorResponse(g,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:O,commitSha:k}=S,j=ce??`.`,F=safeDocPath(O,j);if(`error`in F){errorResponse(g,400,`urn:ok:error:invalid-request`,F.error,{handler:`rollback`});return}let L=shadowGit(D),B=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,oe?.()??`main`,s,e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path},S);if(E===null){errorResponse(g,404,`urn:ok:error:doc-not-found`,`Commit ${k.slice(0,7)} does not contain document ${O} at any known historical path.`,{handler:`rollback`});return}let F=await L.raw(`show`,`${k}:${E}`),H=new Date().toISOString();await safetyCheckpoint(D,j,{action:`rollback`,context:{docName:O,targetSha:k}});let q=t.documents.get(O);if(!q){errorResponse(g,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,J;q.transact(()=>{replaceRawBody(q,F,ee),J=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),J!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:J.intendedBytes,actualBytes:J.actualBytes,byteDelta:J.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,J);let Y;switch(w.kind){case`agent`:{let e=k.slice(0,8),t=w.summary.kind===`value`,s=t?w.summary:normalizeSummary(`Restored to ${e}`),g=so(s);Y=t||!g.response?g.response:_s(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),xs(s,!t);break}case`principal`:{let e=so(w.summary);Y=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),xs(w.summary,!1);break}case`anonymous`:log$7.debug({docName:O,commitSha:k.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(w.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:w.kind});let te=await Xt(O);if(te?.kind===`failure`){Zt(g,te.failure,`rollback`);return}if(te?.kind===`divergence`){$t(g,`rollback`);return}Wt(O,`rollback`);let ne=Date.now()-B;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ne},`rollback`),w.kind===`agent`&&me?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()});let ae=J===void 0?void 0:toContentDivergenceWarning(J);successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:H,...Y?{summary:Y}:{},...ae?{warning:ae,warnings:[ae]}:{}},{handler:`rollback`})}catch(e){errorResponse(g,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),vc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$7.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),yc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$7.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),bc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.(),g=getBootTimings();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s},...g===void 0?{}:{boot:g}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function xc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let s=we?.()??null;if(!s){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,s,{handler:`principal`})}async function Sc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=ge?.getPresenceMap()??{},s=Date.now(),g={};for(let[t,S]of Object.entries(e))s-S.ts<2e4&&(g[t]=S);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:g},{handler:`metrics-agent-presence`})}catch(e){log$7.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function Cc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function wc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let s=resolve(g),S=s,w=!0;try{S=realpathSync(s)}catch(e){let g=e?.code;if(g===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:s}),w=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:s,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:g??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:S,pathSeparator:sep,symlinkResolved:w},{handler:`workspace`})}let Tc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(De?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$7.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:s,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Ec=1048576,Dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let S=realpathSync(g),w=resolve(S,s),E;try{E=realpathSync(w)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(E,S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let D;try{D=statSync(E)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!D.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(S,E)!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(D.size>Ec){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Ec}-byte text-viewer cap.`,{handler:`asset-text`});return}let O=(await readFile$1(E)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(O)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Oc=1440*60*1e3,kc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(ee.current.gitDir,`rescue`);if(existsSync(g))try{let t=readdirSync(g).filter(e=>isSupportedDocFile(e));for(let S of t){let t=resolve(g,S),w=statSync(t);if(e-w.mtimeMs>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$7.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=oe?.()??`main`,t=await listRescueCheckpoints(ee.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$7.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,s,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),Ac=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let S=s.path;if(!isSupportedDocFile(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(S.includes(`..`)||S.startsWith(`/`)||S.includes(`\0`)||S.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let w=resolve(g),E=resolve(w,S);if(!isWithinDir(E,w)){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let D=stripDocExtension(S);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`});return}if(isReservedProjectStatePath(S)||isManagedArtifactDocName(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let k=typeof s.template==`string`?s.template.trim():``,j=``,F;if(k.length>0){if(!/^[A-Za-z0-9_-]+$/.test(k)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let s=S.includes(`/`)?S.slice(0,S.lastIndexOf(`/`)):``,g=resolveTemplatesAvailable(w,s),E=g.find(e=>e.name===k);if(!E){let e=g.length===0?`(none)`:g.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${k}" does not resolve for folder "${s||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let D=resolve(w,E.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${E.path}.`,{handler:`create-page`,cause:e});return}let L=instantiateDoc(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=E.scope}mkdirSync(dirname(E),{recursive:!0});try{writeFileSync(E,j,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let L=stripDocExtension(S);switch(Ie?.delete(L),De&&De.incrementMdDir(dirname(L)),registerWrite(E,contentHash(j)),e.kind){case`agent`:case`principal`:recordContributor(L,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}O?.({kind:`create`,path:E,docName:L,content:j}),ue&&(ue.updateDocumentFromMarkdown(L,j),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),F!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:k,templateScope:F,docName:L})),successResponse(t,200,CreatePageSuccessSchema,{docName:L},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),jc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=s.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(isReservedProjectStatePath(e)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(De?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let S=resolveContentEntryPath(g,`folder`,e);if(existsSync(S)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(S,{recursive:!0}),st(e),fe?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Mc=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:w}=S,E=S.path,D=w===`file`?stripDocExtension(E):E;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(isReservedProjectStatePath(E)||w===`file`&&(isSystemDoc(D)||isConfigDoc(D))||w===`folder`&&isReservedSyntheticFolderPath(E)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}w===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=resolveContentEntryPath(g,w,E);if(!existsSync(k)){if(w===`file`){let e=resolveContentEntryPath(g,`folder`,E);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${w} does not exist.`,{handler:`duplicate-path`});return}let j=statSync(k);if(w===`file`&&!j.isFile()||w===`folder`&&!j.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let F=w===`file`?[docNameForFileOperationPath(g,E)]:Ji(resolveContentEntryPath(g,`folder`,E)),L=ve?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let e of F){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=B.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let H,q=[];if(w===`file`){let e=extname(k);if(H=nextAvailableDuplicateDocName(g,D).docName,isSystemDoc(H)||isConfigDoc(H)||De?.isExcluded(`${H}${e}`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(g,H,e),S=readFileSync(k,`utf-8`),w=dirname(t),E=existsSync(w);try{tracedMkdirSync(w,{recursive:!0}),tracedWriteFileSync(t,S,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!E)try{tracedRmdirSync(w)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:w,err:e})}throw e}let j=!1;try{registerDocExtension(H,e),Ie?.delete(H),De&&(De.incrementMdDir(dirname(H)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:H,content:S}),ue?.updateDocumentFromMarkdown(H,S),q=[H]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(H),De&&j&&De.decrementMdDir(dirname(H)),O?.({kind:`delete`,path:t,docName:H}),e}}else{if(H=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.isDirExcluded(H)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(g,`folder`,H);try{tracedCpSync(k,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(g,H))st(e);let e=collectMarkdownCopies(g,H);q=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(stripDocExtension(t.docName),e),Ie?.delete(t.docName),De&&De.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),O?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),ue?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of q)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ue&&q.length>0&&(ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:w,path:H,duplicatedDocNames:q},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(s,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),Nc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s||s.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let g=Mt(s);if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(g)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:s,headings:extractHeadings(readFileSync(g,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Pc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:w,fromPath:E,toPath:D}=S;if(!isValidRelativeContentPath(E)||!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(w===`file`&&(isSystemDoc(E)||isSystemDoc(D)||isConfigDoc(E)||isConfigDoc(D))){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(isReservedProjectStatePath(E)||isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let O=w===`asset`&&isSupportedDocFile(E)&&isSupportedDocFile(D)?`file`:w;if(O===`asset`){let t;try{t=isSupportedDocFile(E)&&!isSupportedDocFile(D)?await Qi(E,D):await Xi(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Vr(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&Et();let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=Cs(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$7.debug({kind:`asset`,fromPath:E,toPath:D,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...g?{summary:g}:{}},{handler:`rename-path`});return}O===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=O===`file`?[docNameForFileOperationPath(g,E)]:Ji(resolveContentEntryPath(g,`folder`,E)),j=ve?.(),F=new Set(j?j.getConflicts().map(e=>e.file):[]);for(let e of k){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=F.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(De){let e=isSupportedDocFile(E)?extname(E):getDocExtension(E);if(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${e}`):De.isDirExcluded(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let L=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,B;try{B=await Ra(E,D,O,L?{actor:L}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Br(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(B.renamed.length===0&&B.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}B.renamedAssets.length>0&&Et();let H,q=B.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(q.length>0&&(H=Cs(e,`Renamed ${E} → ${D}`,q.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$7.debug({kind:w,fromPath:E,toPath:D,affectedDocs:B.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:B.renamed,renamedAssets:B.renamedAssets,rewrittenDocs:B.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=Vr(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Fc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{eo(S);let{kind:e,path:w}=S;if(!isValidRelativeContentPath(w)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let E=e===`asset`?Ki(w):{path:w,ambiguous:!1};if(E.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let D=E.path,k=e===`asset`&&isSupportedDocFile(D)?`file`:e;if(k===`file`&&probeAndRegisterSourceFileExtension(g,D),isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let j=k===`asset`?resolveContentEntryPath(g,`folder`,D):resolveContentEntryPath(g,k,D);if(!existsSync(j)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${k} does not exist.`,{handler:`delete-path`});return}let F=statSync(j);if(k===`file`&&!F.isFile()||k===`asset`&&!F.isFile()||k===`folder`&&!F.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${k}.`,{handler:`delete-path`});return}let L=k===`asset`?[]:k===`file`?[docNameForFileOperationPath(g,D)]:Ji(resolveContentEntryPath(g,`folder`,D)),B=ve?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=H.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Hr(L,`deleted-upstream`),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));k===`file`||k===`asset`?tracedUnlinkSync(j):(tracedRmSync(j,{recursive:!0,force:!1}),vt(D)),Et();for(let e of L)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});fe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:L},{handler:`delete-path`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ic=withValidation(TrashCleanupRequestSchema,async(e,t,s)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":s.kind,"ok.cleanup.path":normalizeFsPath(s.path),"ok.cleanup.path.role":classifyFsPath(s.path)}},async()=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:S}=s;if(!isValidRelativeContentPath(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let E=e===`asset`&&isSupportedDocFile(S)?`file`:e,D=stripDocExtension(S);E===`file`&&probeAndRegisterSourceFileExtension(g,S);let k=E===`folder`&&isReservedSyntheticFolderPath(S);if(E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||k||isReservedProjectStatePath(S)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(E===`asset`){Et(),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let j=w(),F=E===`file`?j.has(D)?[D]:[]:listAffectedDocNames(j,E,S);if(Et(),F.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Hr(F,`deleted-upstream`),Ie)for(let e of F)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of F)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});E===`folder`&&vt(S),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:F},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=getDocExtension(t),w,E;if(S.title!==void 0)w=S.title,E=S.icon;else{w=t;try{let s=readFileSync(resolve(g,`${t}${e}`),`utf-8`);w=extractPageTitle(s,t),E=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}}s.push({docName:t,title:w,docExt:e,size:S.size,modified:S.modified,icon:E})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Rc=withValidation(EmptyRequestSchema,async(e,s)=>{try{let g=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!g){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(g)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(g)||isConfigDoc(g)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${g}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(s,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:w(),docName:g}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function zc(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let s;try{s=await readUploadBody(e,Ce??g)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:S,tempPath:w,sha:D,byteLength:O,parentDocName:k,placement:j}=s,F=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:k,placement:j||void 0},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B,placement:H}=L.value,{agentId:q,agentName:ee}=eo(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(O===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(g),Y;try{Y=H===`parent-dir`?`./`:E?.()??`./`}catch(e){F(),log$7.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!isValidAttachmentFolderPath(Y)){F(),errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let te=resolveUploadDestDir(B,normalizeAttachmentFolderPath(Y),J);if(!isWithinContentDir(te,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(te,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$7.error({err:e,destDir:te},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(te,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();let s=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(s),s,uploadTitleFor(s),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(te),s;try{s=realpathSync(J)}catch{s=J}if(!isWithinContentDir(e,s)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ne=readTempFileHead(w,4100),ae=await fileTypeFromBuffer(ne),oe=ae?.mime,se=ae?.ext;if(!oe){let e=ne.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(oe=`image/svg+xml`,se=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let ce;if(!S||S===`upload`||GENERIC_PASTE_NAMES.test(S)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=S?extname(S).slice(1):``,s=se??t??``;ce=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else ce=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,ce),S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!1},{handler:`upload-asset`})}catch(s){let g=s instanceof UploadWriteError?s.reason:`urn:ok:error:storage-error`;log$7.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:ce,size:O,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Bc=`/api/local-op/clone`,Vc=`/api/local-op/ok-init`,Hc=600*1e3,Uc=45e3,Wc={stdio:[`ignore`,`ignore`,`pipe`]},Gc={stdio:[`ignore`,`pipe`,`pipe`]},Kc={stdio:`ignore`},qc=`local-op-clone`,Jc=withValidation(LocalOpCloneRequestSchema,Yc,{handler:qc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:qc})});async function Yc(e,t,s){let{url:g,dir:S,branch:w}=s;if(!isAllowedGitUrl(g)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:qc,cause:Error(`url=${g}`)});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:qc,cause:Error(`dir=${S}`)});return}if(!Xe.tryAcquire(Bc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:qc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,qc),D=null,O=runCloneSubprocess({cliArgs:ye,url:g,dir:S,branch:w,timeoutMs:Hc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$7.warn({stderr:redactShareSubprocessStderr(e.message),url:g,dir:S},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);E(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await O.done,D&&!t.writableEnded&&!t.destroyed){let e=await Xc(D);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:D})}\n`):E(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?E(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$7.error({err:e,handler:qc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Xe.release(Bc)}})(),t.on(`close`,()=>{O.cancel()})}async function Xc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=ye,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),withHiddenWindowsConsole({...Wc,cwd:s,detached:!0,env:{...process.env,OK_LOCK_KIND:`interactive`}})),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$7.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$7.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Zc=`local-op-ok-init`,Qc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Zc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Zc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Zc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:Zc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Zc});return}if(!Xe.tryAcquire(Vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Zc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Zc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:Zc})}finally{Xe.release(Vc)}},{handler:Zc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Zc})}),$c=`/api/local-op/auth/login`,dl=`/api/local-op/auth/status`,ml=`/api/local-op/auth/repos`,hl=`/api/local-op/auth/signout`,gl=()=>originGitHubHost(Ce??g),_l=null,vl=`local-op-auth-login`,yl=withValidation(LocalOpAuthHostRequestSchema,xl,{handler:vl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:vl})});async function xl(e,t,s){let g=s.host??gl();if(!Xe.tryAcquire($c)){let e=_l;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:vl,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),_l=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,vl),w=runDeviceFlowSubprocess({cliArgs:ye,host:g,timeoutMs:Hc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});_l=w;let E=()=>{w.cancel(),_l===w&&(_l=null,Xe.release($c))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}_l===w&&(_l=null,Xe.release($c))})}let Cl=`local-op-auth-status`,Tl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??gl();if(!Xe.tryAcquire(dl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Cl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,withHiddenWindowsConsole({...Gc,env:{...process.env}})),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
1953
+ `).map(e=>e.trim()).filter(Boolean),E=null;for(let e=w.length-1;e>=0;e--)try{E=JSON.parse(w[e]);break}catch{}E===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:Cl}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:Cl})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Cl,cause:e})}finally{Xe.release(dl)}},{handler:Cl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Cl})}),El=`local-op-auth-repos`,Dl=withValidation(LocalOpAuthHostRequestSchema,Ol,{handler:El,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:El})});async function Ol(e,t,s){let g=s.host??gl();if(!Xe.tryAcquire(ml)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:El,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,El),[w,...E]=ye,D=[...E,`auth`,`repos`,`--json`,`--host`,g],O=!1,k=``,j=spawn(w,D,withHiddenWindowsConsole({...Gc,env:{...process.env}})),F=setTimeout(()=>{j.kill(`SIGTERM`)},Hc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
1954
+ `);k=s.pop()??``;for(let e of s){if(!e.trim())continue;let s=null;try{s=JSON.parse(e)}catch{}if(s&&s.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof s.message==`string`?s.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),j.stderr.on(`data`,e=>{log$7.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Xe.release(ml))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Xe.release(ml))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Xe.release(ml))})}let kl=`local-op-auth-signout`,jl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??gl();if(!Xe.tryAcquire(hl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:kl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,withHiddenWindowsConsole({...Kc,env:{...process.env}})),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:kl})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:kl,cause:e})}finally{Xe.release(hl)}},{handler:kl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:kl})}),Ml=`/api/local-op/auth/set-identity`,Pl=`local-op-auth-set-identity`,Fl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Pl});return}if(!Xe.tryAcquire(Ml)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Pl,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Pl})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Pl,cause:e})}finally{Xe.release(Ml)}},{handler:Pl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Pl})});async function Il(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Ll=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Rl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let zl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Bl(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Ce){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=ve?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:Ce,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Re?Re(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Vl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let s=new URL(e.url??`/`,`http://localhost`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Hl=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function Ul(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let Wl=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function Gl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,jt.probeAll)}catch(e){t.headersSent||(log$7.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let Kl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function ql(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:Ft(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Jl(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let Yl=/^[A-Za-z0-9_-]+$/;function Xl(e,t,s=`template`){return!e||!Yl.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:s}),!1):!0}function Zl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Ql(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function $l(e,t){if(e.method===`GET`)return eu(e,t);if(e.method===`PUT`)return tu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let eu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Jl(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),tu=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=Jl(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(Ds(e,Ts(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Os(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function nu(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}function ru(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!0):!1}let iu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function au(e,t){if(e.method===`GET`)return su(e,t);if(e.method===`PUT`)return cu(e,t);if(e.method===`POST`)return uu(e,t);if(e.method===`DELETE`)return lu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let ou=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},su=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Xl(g,t,`template-get`))return;let S=Jl(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Zl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),cu=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!Xl(S,t,`template-put`))return;let w=Jl(g.folder,t,`folder`,`template-put`);if(!w||nu(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Ql(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=gu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=eo(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Xt(j);if(ee?.kind===`failure`){Zt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){$t(t,`template-put`);return}Ds(e,Ts(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Os(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),lu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Xl(g,t,`template-delete`))return;let S=Jl(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(nu(S.folderRel,g,`template-delete`,t))return;await Hr([gu(S.folderRel,g)],`deleted-upstream`);let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}D.existed&&(Ds(E,Ts(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Os(`template-delete`)),successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),uu=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Xl(s.fromName,t,`template-move`)||!Xl(s.toName,t,`template-move`))return;let g=Jl(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Jl(s.toFolder,t,`folder`,`template-move`);if(!S||nu(g.folderRel,s.fromName,`template-move`,t))return;await Hr([gu(g.folderRel,s.fromName)],`renamed`);let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=Zl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Ql(s.frontmatter)});t.ok||(E=t.error)}}if(Ds(e,Ts(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Os(`template-move`),fe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),du=500;function fu(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function pu(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let mu=Te??homedir();function hu(e){return resolve(e===`global`?mu:g,`.ok`,`skills`)}function gu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function _u(e){return e===`navigation`||e===`relevance`?e:void 0}function vu(e,t){return relative(t===`global`?mu:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function yu(e){return e===`global`?mu:Ce}async function bu(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function xu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=ou(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:vu(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let Su=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=xu(hu(`project`),`project`),s=xu(hu(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(mu).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function Cu(e,t){if(e.method===`GET`)return ku(e,t);if(e.method===`PUT`)return Au(e,t);if(e.method===`POST`)return Mu(e,t);if(e.method===`DELETE`)return ju(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let wu=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),Tu=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:hu(`project`)}):0}),Eu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,wu,Tu(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),Du=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:hu(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,wu,Tu(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function Ou(e,t){if(e.method===`GET`)return Eu(e,t);if(e.method===`PUT`)return Du(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let ku=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!fu(g,t,`skill-get`))return;let S=pu(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=hu(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=ou(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:vu(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),Au=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!fu(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=hu(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(ru(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=eo(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Xt(k);if(q?.kind===`failure`){Zt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){$t(t,`skill-put`);return}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Os(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),ju=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!fu(g,t,`skill-delete`))return;let S=pu(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=hu(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Hr([skillLiveDocName(S,g)],`deleted-upstream`);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-delete: ${O.path}`),await Os(`skill-delete`)),fe?.(`files`));let k=yu(S);k&&await bu(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Mu=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!fu(s.fromName,t,`skill-move`)||!fu(s.toName,t,`skill-move`))return;let g=hu(s.scope);await Hr([skillLiveDocName(s.scope,s.fromName)],`renamed`);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=ou(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{Lu(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=vu(resolve(g,s.fromName),s.scope),B=vu(resolve(g,s.toName),s.scope);s.scope===`project`&&(Ds(e,Ts(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Os(`skill-move`));let H=yu(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function Nu(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Pu(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function Fu(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function Iu(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function Lu(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of Iu(e,s))g(Fu(t,S),Fu(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Ru=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!fu(g,t,`skill-file-get`))return;let S=pu(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=Nu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(hu(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),zu=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!fu(g.name,t,`skill-file-put`))return;let S=Nu(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=hu(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=Pu(g.scope,S,E),O;if(D){let e=Fu(g.name,E);if(ru(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=eo(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Xt(e);if(L?.kind===`failure`){Zt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){$t(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Os(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Bu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!fu(g,t,`skill-file-delete`))return;let S=pu(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=Nu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=hu(S);Pu(S,E,w)&&await Hr([Fu(g,w)],`deleted-upstream`);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Os(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function Vu(e,t){if(e.method===`GET`)return Ru(e,t);if(e.method===`PUT`)return zu(e,t);if(e.method===`DELETE`)return Bu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Hu=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=hu(s.scope);if(!fu(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=yu(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Uu=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!fu(s.name,t,`skill-uninstall`))return;let e=yu(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await bu(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Wu(e,t){if(e.method===`GET`)return Gu(e,t);if(e.method===`PUT`)return Ku(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Gu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Ku=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=hu(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),qu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!fu(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Ds(e,Ts(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Os(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Ju=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!fu(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(hu(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(ru(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=eo(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Xt(k);if(q?.kind===`failure`){Zt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){$t(t,`skill-update`);return}Ds(e,Ts(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Os(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Yu(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Xu(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,`�`)}function Zu(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Qu(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let s=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return s.length>0?s:void 0}function $u(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function ed(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function td(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function nd(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Xu(e.document.content,t):void 0}}async function rd(e){let t=performance.now();if(pd())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await md(),S=await td(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>nd(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function ad(){let e=hu(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function od(){let e=[];for(let t of ad()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=ou(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function sd(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let cd=new Map;async function ld(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=sd(S),E=cd.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||cd.set(g,{key:w,doc:j}),e.push(j)}for(let e of cd.keys())s.has(e)||cd.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...od(),...S,...Yu([...e,...S])],truncated:w}}function ud(){return ad().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function dd(){return k?`gen:${k()}|skills${ud()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${sd(t)}`).join(``)}|skills${ud()}`}let fd=Pe===void 0;Pe?.then(()=>{fd=!0},e=>{fd=!0,log$7.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function pd(){return!fd}async function md(){let e=`${g}${Ce??``}`,t=dd(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=ld().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function hd(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{md().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}hd();async function gd(e,t){if(e.method===`GET`)return _d(e,t);if(e.method===`POST`)return vd(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let _d=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Zu(s.searchParams.get(`intent`)),E=_u(s.searchParams.get(`ranking`)),D=Qu(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=$u(s.searchParams.get(`semantic`)),k=ed(s.searchParams.get(`source`)),j=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await rd({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),vd=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Zu(s.intent),w=_u(s.ranking),E=Qu(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=$u(s.semantic),k=ed(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await rd({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),yd=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function bd(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:jt.probeWithCache})}catch(e){t.headersSent||(log$7.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function xd(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$7.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let Sd=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=s.kind===`doc`?s.docPath:s.folderPath;if(!isValidSharePath(e,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readGitHeadBranch(Ce);if(S===null){if(readOriginGitHubRepo(Ce).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(Ce);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`||w.host!==`github.com`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(Ce,S)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:S},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=toGitRelativePath(Ce,g);if(E===null)throw Error(`content dir is not contained within the project dir`);let D=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;E!==``&&D&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let O;if(s.kind===`doc`)O=buildGitHubBlobUrl(w.owner,w.repo,S,s.docPath);else{let e=s.folderPath===``?E:s.folderPath;O=buildGitHubTreeUrl(w.owner,w.repo,S,e)}let k=`${SHARE_BASE_URL}${encodeShareUrl(O)}`,j=await computeShareFreshness(Ce,S,E===``?e:e===``?E:`${E}/${e}`,s.kind);emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind,freshness:j}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:k,sharedUrl:O,branch:S,freshness:j},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),Cd=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(Ce,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),wd=withValidation(ShareTargetStatusRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}if(!isValidBranchInfoPath(s.path,s.kind)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}let e=toGitRelativePath(Ce,g);if(e===null)throw Error(`content dir is not contained within the project dir`);let S=e===``?s.path:s.path===``?e:`${e}/${s.path}`;successResponse(t,200,ShareTargetStatusResponseSchema,await computeShareTargetStatus(Ce,s.branch,S,s.kind),{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG,cause:e})}},{handler:SHARE_TARGET_STATUS_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}),Td=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(Ce,s.branch,{fastForward:s.fastForward===!0})),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function Ed(e){let[t,...s]=ye,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,withHiddenWindowsConsole({...Gc,env:{...process.env}})),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let Dd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Xe.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ed([`share`,`owners`,`--json`]),s=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,s.ok?`ok`:s.error,s.ok?{count:s.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,s,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Xe.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),Od=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Xe.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ed([`share`,`name-check`,`--owner`,g,`--name`,S,`--json`]),s=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,s.ok?`ok`:s.error,s.ok?{available:s.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,s,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Xe.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),kd=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(s.owner)||!isValidShareRepoName(s.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Xe.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,s.owner,`--name`,s.name,`--visibility`,s.visibility,`--project-dir`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await Ed(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Xe.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),Ad=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),jd=Ce?getLocalDir(Ce):null;async function Md(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:jd?readServerLock(jd)?.port??0:0,singleFile:We};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let Nd=`local-op-embeddings-set-key`,Pd=`local-op-embeddings-clear-key`,Fd=`/api/local-op/embeddings`,Id=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Xe.tryAcquire(Fd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Nd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:Nd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Nd,cause:e})}finally{Xe.release(Fd)}},{handler:Nd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Nd})}),Ld=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Xe.tryAcquire(Fd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Pd,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:Pd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Pd,cause:e})}finally{Xe.release(Fd)}},{handler:Pd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Pd})}),Rd=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),zd=`link-preview`,Bd=new LinkPreviewCache({cacheDir:We?null:resolve(Ce??g,`.ok`,`local`,`link-previews`)}),Vd=null,Hd=()=>(Vd??=Bd.init(),Vd),Ud=Ge??guardedFetch;async function Wd(e){let t=await Ud(e);return t.ok?{ok:!0,metadata:await buildLinkPreviewMetadata({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Ud})}:{ok:!1,reason:t.reason}}let Gd=()=>{try{return Ke?.()===!0}catch{return!1}},Kd=withValidation(LinkPreviewRequestSchema,async(e,t,s)=>{try{if(!Gd()){log$7.debug({outcome:`disabled`},`[link-preview] request outcome`),successResponse(t,200,LinkPreviewResponseSchema,{ok:!1,reason:`disabled`},{handler:zd});return}await Hd();let e=!1,g=await Bd.load(s.url,()=>(e=!0,Wd(s.url)));Bd.persist();let S=g.ok?g:{ok:!1,reason:`blocked`};log$7.debug({outcome:e?g.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),successResponse(t,200,LinkPreviewResponseSchema,S,{handler:zd})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:zd,cause:e})}},{handler:zd,method:`POST`,preBodyGate:(e,t)=>{let s=classifyLinkPreviewRequest({origin:e.headers.origin,contentType:e.headers[`content-type`]});return s.ok?!0:(s.reason===`origin`?errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:zd}):errorResponse(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:zd}),!1)}}),qd={"/api/config":Md,"/api/asset":Tc,"/api/asset-text":Dc,"/api/document":Is,"/api/documents":Ls,"/api/backlinks":Rs,"/api/backlink-counts":ec,"/api/link-preview":Kd,"/api/forward-links":tc,"/api/link-graph":nc,"/api/dead-links":ac,"/api/orphans":rc,"/api/hubs":ic,"/api/tags":Kl,"/api/pages":Lc,"/api/folder-config":$l,"/api/template":au,"/api/templates":iu,"/api/skill":Cu,"/api/skill-file":Vu,"/api/skills":Su,"/api/skills/management":Ou,"/api/skill/install":Hu,"/api/skill/uninstall":Uu,"/api/skill/restore":qu,"/api/skill/update":Ju,"/api/skill-targets":Wu,"/api/search":gd,"/api/semantic-status":Rd,"/api/suggest-links":Rc,"/api/page-headings":Nc,"/api/create-page":Ac,"/api/create-folder":jc,"/api/duplicate-path":Mc,"/api/rename-path":Pc,"/api/delete-path":Fc,"/api/trash/cleanup":Ic,"/api/upload":zc,"/api/agent-write":ks,"/api/agent-write-md":Ms,"/api/frontmatter-patch":Ns,"/api/agent-patch":oc,"/api/agent-undo":sc,"/api/agent-activity":cc,"/api/agent-burst-diff":lc,"/api/save-version":mc,"/api/history":hc,"/api/rollback":_c,"/api/metrics/reconciliation":vc,"/api/metrics/parse-health":yc,"/api/metrics/agent-presence":Sc,"/api/__embed-detect":Cc,"/api/server-info":bc,"/api/share/construct-url":Sd,"/api/share/target-status":wd,"/api/git/branch-info":Cd,"/api/git/checkout":Td,"/api/share/publish/owners":Dd,"/api/share/publish/name-check":Od,"/api/share/publish":kd,"/api/principal":xc,"/api/rescue":kc,"/api/workspace":wc,"/api/sync/status":Il,"/api/sync/trigger":Ll,"/api/sync/conflicts":Rl,"/api/sync/conflict-content":Bl,"/api/sync/resolve-conflict":zl,"/api/local-op/clone":Jc,"/api/local-op/ok-init":Qc,"/api/local-op/auth/login":yl,"/api/local-op/auth/status":Tl,"/api/local-op/auth/repos":Dl,"/api/local-op/auth/signout":jl,"/api/local-op/auth/set-identity":Fl,"/api/local-op/embeddings/set-key":Id,"/api/local-op/embeddings/clear-key":Ld,"/api/installed-agents":Gl,"/api/spawn-cursor":xd,"/api/handoff":bd,"/api/install-skill":Wl,"/api/skill/install-state":yd,"/api/seed/plan":Vl,"/api/seed/apply":Hl,"/api/seed/packs":Ul,"/api/client-logs":Ad};q&&(qd[`/api/test-reset`]=dc,qd[`/api/test-flush-git`]=uc,qd[`/api/test-rescan-backlinks`]=fc,qd[`/api/test-rescan-files`]=pc);let Jd=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Yd=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),s.startsWith(`/api/`)){let s=e.headers.origin;if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Jd.has(s)||Yd.some(e=>s.startsWith(e))){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(We&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:qd[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=qd[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await gc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await ql(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=toPosix(relative(t,w));if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$6=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$6.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$6.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$6.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-BMLM1Bxa-C8CZ9W34.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(!isWithinDir(g,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$6.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=await listNames(w.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:s});g=e.length>0}catch(e){log$6.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}g||this.addConflict({file:e,detectedAt:s}),log$6.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let S=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${g?`unmerged files re-added`:`original file re-added`} — ${S}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,s=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,g=0,S=null,w=null,E=!1,D=!1;function O(){S!==null&&(t.clearTimeout(S),S=null),w!==null&&(t.clearTimeout(w),w=null)}function k(){O(),!(D||E)&&g===0&&(s>0&&s<e.thresholdMs&&(w=t.setTimeout(()=>{w=null,g===0&&!E&&e.log?.warn({msUntilShutdown:s,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-s)),S=t.setTimeout(()=>{if(S=null,!(D||E)&&g===0){E=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let j=(e,t)=>{e.url?.startsWith(`/collab`)&&(g++,O(),t.once(`close`,()=>{g--,g<0&&(g=0),g===0&&k()}))};return e.httpServer.on(`upgrade`,j),k(),{detach:()=>{D||(D=!0,e.httpServer.off(`upgrade`,j),O())}}}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function readRawSinkBlock(e){if(!existsSync(e))return{};let t;try{t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!isObject(t))return{};let s=t.telemetry;if(!isObject(s))return{};let g=s.localSink;return isObject(g)?g:{}}function readBoolean(e){return typeof e==`boolean`?e:void 0}function readPositiveNumber(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function readStringArray(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function readMaxBytes(e){if(isObject(e))return readPositiveNumber(e.maxBytes)}function resolveLocalSinkConfig(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=readRawSinkBlock(resolveConfigPath(`project`,e.projectDir)),s=readRawSinkBlock(resolveConfigPath(`project-local`,e.projectDir));if((readBoolean(s.enabled)??readBoolean(t.enabled)??!0)===!1)return null;let g=readMaxBytes(s.spans)??readMaxBytes(t.spans)??52428800,S=readMaxBytes(s.logs)??readMaxBytes(t.logs)??26214400,w=readStringArray(s.attributeDenylist)??readStringArray(t.attributeDenylist)??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:g,attributeDenylist:w},logs:{projectDir:e.projectDir,maxBytes:S}}}const MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let s=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return s?s.slice(0,128):t}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let s=t.validateToolInput;if(typeof s!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,g){if(!e.inputSchema||!isZodSchema(e.inputSchema))return s.call(this,e,t,g);let S=await e.inputSchema.safeParseAsync(t);if(S.success)return S.data;let w=prettifyError(S.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${g}:\n${w}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const SPAWN_TIMEOUT_MS=2e3,LOCK_SCAN_MAX_DEPTH=3,LOCK_SCAN_MAX_ENTRIES=2e3,OK_LOCK_DIR_ARG_PREFIX=`--ok-lock-dir-b64=`,OK_PROJECT_PATH_ARG_PREFIX=`--ok-project-path=`,OK_PROCESS_PGREP_QUERY=`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`,OK_PROCESS_PATTERNS=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function isOkProcess(e){return OK_PROCESS_PATTERNS.some(t=>t.test(e))}function extractMarkedLockDir(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(OK_LOCK_DIR_ARG_PREFIX));if(t==null)return null;let s=t.slice(18);if(!s)return null;try{let e=Buffer.from(s,`base64url`).toString(`utf8`);return isAbsolute(e)?e:null}catch{return null}}function extractProjectPathArg(e){let t=e.indexOf(OK_PROJECT_PATH_ARG_PREFIX);if(t===-1)return null;let s=t+18,g=e.slice(s),S=g.search(/\s--/),w=(S===-1?g:g.slice(0,S)).trim();return w&&isAbsolute(w)?w:null}function parsePgrepOutput(e){let t=[];for(let s of e.split(`
1955
1955
  `)){let e=s.trim();if(!e)continue;let g=e.indexOf(` `);if(g===-1)continue;let S=e.slice(0,g),w=e.slice(g+1),E=Number.parseInt(S,10);!Number.isNaN(E)&&isOkProcess(w)&&t.push({pid:E,command:w})}return t}function parsePsOutput(e){let t=[],s=e.split(`
1956
1956
  `);for(let e=1;e<s.length;e++){let g=s[e]?.trim();if(!g)continue;let S=g.indexOf(` `);if(S===-1)continue;let w=g.slice(0,S),E=g.slice(S+1).trim(),D=Number.parseInt(w,10);!Number.isNaN(D)&&isOkProcess(E)&&t.push({pid:D,command:E})}return t}async function findOkProcessEntries(){let e=spawnSync(`pgrep`,[`-a`,`-f`,OK_PROCESS_PGREP_QUERY],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,s=parsePgrepOutput(t);if(s.length>0||t.trim()===``)return s}let t=spawnSync(`ps`,[`-axo`,`pid,command`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));return t.error!=null||!t.stdout?[]:parsePsOutput(t.stdout)}function extractOkBinaryPath(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=basename(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function processCommand(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`command=`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function processUsage(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));if(t.error!=null||!t.stdout)return null;let[s,g]=t.stdout.trim().split(/\s+/),S=Number.parseFloat(s??``),w=Number.parseFloat(g??``);return Number.isNaN(S)||Number.isNaN(w)?null:{cpuPercent:S,memPercent:w}}async function pidCwd(e){let t=spawnSync(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));if(t.error!=null)return null;let s=t.stdout??``;for(let e of s.split(`
1957
1957
  `))if(e.startsWith(`n`)&&e.length>1)return e.slice(1);return null}function parseListeningPids(e){let t=[],s=e.split(`
@@ -3259,7 +3259,7 @@ Incremental by default — don't re-read the whole repo.
3259
3259
  `,`
3260
3260
  `).split(`
3261
3261
  `),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(!isLinkIndexExcludedDoc(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(isLinkIndexExcludedDoc(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=toPosix(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=toPosix(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 resolveUpstreamChanges(e,t,s,g){let S=new Map;if(!s)return S;let w;try{w=spawnSync(`git`,[`-c`,`core.quotePath=false`,`log`,`${s}..${g}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return getLogger(`upstream-attribution`).warn({err:e,oldHead:s,newHead:g},`git log spawn threw; upstream docs keep file-system attribution`),S}if(w.error||w.status!==0||typeof w.stdout!=`string`)return getLogger(`upstream-attribution`).warn({err:w.error,status:w.status,signal:w.signal,stderr:typeof w.stderr==`string`?w.stderr.slice(0,500):void 0,oldHead:s,newHead:g},`git log failed; upstream docs keep file-system attribution`),S;let E=null;for(let s of w.stdout.split(`
3262
- `)){let g=s.trim();if(g===``)continue;if(g.startsWith(`C\0`)){let[,e,t]=g.split(`\0`);E=e&&t?{name:e,email:t}:null;continue}if(!E||!g.endsWith(`.md`)&&!g.endsWith(`.mdx`))continue;let w=resolve(e,g);if(!isWithinContentDir(w,t))continue;let D=pathToDocName(w,t);S.has(D)||existsSync(w)&&S.set(D,E)}return S}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`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=isKnownConfigError(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}Y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ne(){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;if(t!=null)return t===!0;e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let g=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});return g.valid||Y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),g.value.autoSync?.default===!0}function ae(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function oe(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function se(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=ne(),jr?.setEnabled(t).catch(s=>{Y.warn({err:s,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let s=ae();ze.applyConfig({enabled:s.enabled,providerFingerprint:oe(s)}),Y.info({docName:e,autoSyncEnabled:t,semanticEnabled:s.enabled},`[config] applied persisted config to in-process consumers`)}initTelemetry();let ce=randomUUID(),ue=getLocalDir(s);if(acquireServerLock(ue,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:ue,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(ue),e}let de=createBasenameIndex(),fe=(e,t)=>de.resolveEmbed(e,t),me=(e,s)=>{let g=de.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g);if(!isWithinDir(S,resolve(t)))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},ge,_e,ve,ye,Ce,we,Te,De,je=null,Me=null,Pe=null,Ie=null,Re=ae(),ze=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Re.enabled,providerFingerprint:oe(Re)}),Be=null,Ve=new Set,Ue=!1,We,Ge,Ke,Xe=new Promise((e,t)=>{Ge=e,Ke=t});function $e(e){je?.signal(e)}let nt=2e3,rt=null;function it(){rt!==null&&clearTimeout(rt),rt=setTimeout(()=>{rt=null,_e.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let at=2e3,st=null,vt=!1,St=()=>{try{saveRemovedDocsJournal(s,Tt.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Tt=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e),onMutate:()=>{!vt||st!==null||(st=setTimeout(()=>{st=null,St()},2e3))}});for(let[e,g]of loadRemovedDocsJournal(s))isReservedForUserTree(e)||isSafeDocName(e)&&([`.md`,`.mdx`].some(s=>{let g=resolve(t,`${e}${s}`);return isWithinDir(g,resolve(t))&&existsSync(g)})||Tt.restore(e,g));vt=!0;let Et=(e,t)=>{isReservedForUserTree(e)||Tt.setRenamed(e,t)},jt=e=>{if(!isReservedForUserTree(e)){if(Tt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Tt.setDeleted(e)}},Mt=e=>{isReservedForUserTree(e)||Tt.delete(e)};try{ge=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{_e.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild(rn).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`)})}}),_e=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:ge}),ve=new TagIndex({contentDir:t,contentFilter:ge}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),ye={current:F},Ce=E?createMaintenanceCoordinator({getShadow:()=>ye.current??null,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,contentRoot:L??``,projectGitDir:resolveGitDir(s)??void 0,isWriterLive:e=>{if(!Pe&&!De)return getLogger(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Pe?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of De?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,we=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:ye,ephemeral:J,contentRoot:L,backlinkIndex:_e,configHomedirOverride:k,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me,getPrincipal:()=>Be,onAgentCommit:()=>je?.signal(`session-activity`),onFlushCommit:()=>Ce?.noteFlushCommit(),onDiskFlush:(e,t,s,g)=>{je?.emitDiskAck(e,t),!isReservedForUserTree(e)&&assetReferencesChanged(g,s)&&(Ie?.(),$e(`files`))},onConfigRejected:(e,t)=>je?.emitConfigValidationRejected(e,t),onConfigPersisted:se,isRecentlyRemoved:e=>Tt.has(e),mdManager:e.mdManager}),Te=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[we.extension]});let B=Te.shouldUnloadDocument.bind(Te);Te.shouldUnloadDocument=e=>{if(Ve.has(e)||Ue&&B(e))return!0;let t=e.name;return isReservedForUserTree(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},We=async e=>{Ve.add(e);try{await Te.unloadDocument(e)}finally{Ve.delete(e)}},je=new CC1Broadcaster(Te),Me=new AgentFocusBroadcaster(Te),Pe=new AgentPresenceBroadcaster(Te),De=new AgentSessionManager(Te);let q=createLiveDerivedIndexExtension({backlinkIndex:_e,tagIndex:ve,signalChannel:$e});Te.configuration.extensions.push(q),Te.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!==ce)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ce}`);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`&&(Be&&s.principalId===Be.id?E.principalId=Be.id:Be?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Be.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),Te.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName)&&!isManagedArtifactDoc(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 ne(e){if(!isSafeDocName(e))return null;let t=resolve(Y,docNameToRelativePath(e));return isWithinDir(t,Y)?t:null}Te.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Tt,resolveFilePath:ne,fileExists:existsSync})}}),Te.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Te.documents.get(e)})}}),Te.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 oe=createApiExtension({hocuspocus:Te,sessionManager:De,contentDir:t,contentFilter:ge,serverInstanceId:ce,getFileIndex:()=>rn?rn.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>rn?rn.getAllFilesIndex():new Map,getFileIndexGeneration:()=>rn?.getFileIndexGeneration()??0,mutateFileIndex:e=>rn?.mutateFileIndex(e),getFolderIndex:()=>rn?rn.getFolderIndex():new Map,getAliasMap:()=>rn?rn.getAliasMap():new Map,getFolderAliasIndex:()=>rn?rn.getFolderAliasIndex():new Map,rescanFiles:()=>rn?.rescanFromDisk(),enableTestRoutes:j,shadowRef:ye,flushGitCommit:()=>we.flushPendingGitCommit(),flushContributors:()=>we.flushContributors(),takeStoreFailure:e=>we.takeStoreFailure(e),takeStoreDivergence:e=>we.takeStoreDivergence(e),markAgentWriteStore:e=>we.markAgentWriteStore(e),getCurrentBranch:()=>sn?.getLastKnownBranch()??null,getDiskAckSVs:()=>je?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:_e,tagIndex:ve,signalChannel:$e,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>jr,localOpCliArgs:H,projectDir:s,resolveEmbed:fe,getPrincipal:()=>Be,homeDirOverride:k,forceUnloadDocument:We,ready:Xe,recentlyRemovedDocs:Tt,serializeDoc:zt,evictManagedArtifactLkg:e=>{we.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ze,getSemanticSimilarityFloor:()=>ae().similarityFloor,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Ie=e}});Te.configuration.extensions.push(oe),Te.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:ye,contentRoot:L,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me})),Te.configuration.extensions.push(createSyncHandshakeSpanExtension()),Te.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>jr,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(ue),e}let Ft=null,It=new Map,Lt=[];function Rt(e,t){let s=resolve(e,`rescue`),g=resolve(s,docNameToRelativePath(t));return isWithinDir(g,s)?g:null}function zt(e){let t=Te.documents.get(e);return t?serializeYDocSource(t):null}let Bt=(e,t)=>applyExternalChange(Te,e,t,fe,me);function Vt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ht=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of Te.documents){if(isReservedForUserTree(s))continue;let g=Te.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,fe,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}`)}}},Ut=null,Wt=e=>{e&&(Ut===null&&(Ut=new Set,setImmediate(()=>{let e=Ut;if(Ut=null,e)try{for(let t of e)Ht(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Ut.add(e))};function Xt(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 Zt(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),_e.updateDocumentFromMarkdown(e.docName,e.content),it(),ve.updateDocumentFromMarkdown(e.docName,e.content),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Mt(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=Te.documents.get(t);if(!g){_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);return}let S=getReconciledBase(t)??``,w=zt(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`:Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);break;case`clean`:try{Bt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Vt(g)}break;case`merged`:try{Bt(t,E.newContent),setReconciledBase(t,s),incrementReconcile(),Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Vt(g)}break;case`conflicts`:try{Bt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`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=Te.documents.get(t);if(!s){_e.deleteDocument(t),it(),ve.deleteDocument(t),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),jt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=zt(t)??``,w=S!==g;if(w&&ye.current){let e=ye.current,s=sn?.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),_e.deleteDocument(t),it(),ve.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),Te.closeConnections(t),await We(s),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),jt(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=Te.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),_e.renameDocument(t,s,g),it(),ve.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}`),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Et(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=Te.documents.get(t);if(!s)return;let g=zt(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`:de.add(e.relativePath),$e(`files`),Wt(basename(e.relativePath));break;case`asset-delete`:de.remove(e.relativePath),$e(`files`),Wt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:$e(`files`);break;case`file-create`:case`file-update`:case`file-delete`:$e(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Xt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let $t=[];async function en(e){if(isBatchInProgress()){$t.push(e);return}await Zt(e)}async function tn(){let e=$t.splice(0,$t.length);for(let t of e)await Zt(t)}let rn=null,sn=null,jr=null,Mr=null;async function zr(e){if(Te.documents.size===0)return;let t=!1,s=new Promise(e=>{Te.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(Te.documents.keys());Te.closeConnections(),Te.flushPendingStores();for(let e of Te.documents.values())e.getConnectionsCount()===0&&Te.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(Te.documents.keys()),S=[],E=[];if(ye.current){for(let e of s)if(!isReservedForUserTree(e))try{let t=zt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Rt(ye.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:ye.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 Br(){return Mr||(Mr=(async()=>{let e=Date.now(),t=[];Ue=!0;try{markServerLockDraining(ue)}catch(e){Y.warn({err:e},`[server] failed to mark server.lock draining`)}if(rt!==null&&(clearTimeout(rt),rt=null),st!==null&&(clearTimeout(st),st=null),vt)try{saveRemovedDocsJournal(s,Tt.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let g,S=await Promise.race([Xe.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=Te.documents.size;Ce?.destroy();try{try{try{sn&&=(await sn.unsubscribe(),null),rn&&=(await rn.unsubscribe(),null);for(let{docName:e,cleanup:t}of Lt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Lt.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{je?.destroy(),Pe?.destroy(),Ft&&=(await Ft.disconnect(),null);for(let[e,t]of It)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}It.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 De.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 zr(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 we.flushPendingGitCommit(),await we.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{jr&&=(await jr.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(ye.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(ye.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(ye.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(ue,{deferUnlinkToExit:!0})}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)})}}})(),Mr)}let Vr=[];async function Hr(){try{Be=await loadPrincipal(s),Y.info({principalId:Be.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ye.current)try{ye.current=await initShadowRepo(s),Y.info({gitDir:ye.current.gitDir},`[server] history repo initialized at ${ye.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Vr.push(`shadow-repo`)}if(ye.current){let e=null;try{e=loadRenameLogIndex(ye.current.gitDir),sweepLazyPopOrphans(ye.current.gitDir,e),setRenameLogIndex(ye.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(ye.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 Ce?.runBootMaintenance()}catch(e){Y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ye.current)try{await shadowGit(ye.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{ye.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),ye.current=void 0,Vr.includes(`shadow-repo`)||Vr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(ye.current)try{let e=resolve(ye.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(ye.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`),Vr.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`),Vr.push(`upload-tempfile-sweep`)}try{Ft=await Te.openDirectConnection(SYSTEM_DOC_NAME),je?.emitServerInfo(ce,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Vr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await Te.openDirectConnection(e);It.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Vr.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=Te.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,we.configPersistenceCtx);Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),se(e)});Lt.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}`),Vr.push(`config-file-watcher:${e}`)}}if(!J){let e=(e,t)=>{let s=managedArtifactDocNameForPath(e,we.managedArtifactCtx);if(!s)return;let g=applyExternalManagedArtifactChange(Te.documents.get(s)??null,s,t,we.managedArtifactCtx);Y.info({docName:s,outcome:g},`[managed-artifact-watcher] external change`),parseGlobalSkillBundleDoc(s)&&_e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),getActiveBranch()).then(()=>{$e(`backlinks`),$e(`graph`)}).catch(e=>{Y.warn({err:e,docName:s},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=managedArtifactSkillsRoots(we.managedArtifactCtx),s=await startManagedArtifactWatcher(t,e);Lt.push({docName:`__skill-files__`,cleanup:s}),Y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Vr.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of resolveProjectTemplates(s).templates)t.add(e.source_folder)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let g=[...t].map(e=>e?resolve(s,e,`.ok`,`templates`):resolve(s,`.ok`,`templates`)),S=await startManagedArtifactWatcher(g,e,TEMPLATE_WATCH_OPTIONS);Lt.push({docName:`__template-files__`,cleanup:S}),Y.info({rootCount:g.length},`[managed-artifact-watcher] templates started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),Vr.push(`managed-artifact-watcher:templates`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],withHiddenWindowsConsole({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(Te.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,we.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 ge.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`),je?.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`),je?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Lt.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`),Vr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),_e.switchBranch(E);let D=performance.now();try{await withSpan(`ok.boot.indexes`,void 0,async()=>{let e=getActiveBranch();try{if(await _e.loadFromDisk(e)){let t=await _e.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info({added:t.added,updated:t.updated,deleted:t.deleted},`[backlinks] startup reconcile: offline changes applied`);let s=0;for(let e of t.deletedDocNames)isReservedForUserTree(e)||Tt.peek(e)?.kind!==`renamed`&&(Tt.setDeleted(e),s++);s>0&&Y.info({count:s},`[removal-guard] tombstoned docs deleted while the server was down`)}else await _e.rebuildFromDisk(e);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),e)}catch(t){Y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}_e.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`)}let s=performance.now();rn=await withSpan(`ok.boot.seed-walk`,void 0,async()=>startWatcher(t,en,ge)),recordBootPhase(`seedWalkMs`,Math.round(performance.now()-s));{let e=resolve(t),s=0;for(let[t]of Tt.entries()){if(!isSafeDocName(t))continue;let g=resolve(e,`${t}${getDocExtension(t)}`);isWithinDir(g,e)&&existsSync(g)&&(Tt.delete(t),s++)}s>0&&Y.info({count:s},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{await ve.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Vr.push(`tag-index`)}let g=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),g>0&&(Y.warn({count:g},`[basename-index] startup seed completed with ${g} skipped entries — embeds under inaccessible subtrees will not resolve`),Vr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Vr.push(`basename-index`)}})}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Vr.push(`file-watcher`)}finally{recordBootPhase(`indexesMs`,Math.round(performance.now()-D)),rn&&setBootField(`fileCount`,rn.getFileIndex().size)}try{sn=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),Te.flushPendingStores(),await we.flushPendingGitCommit(),setBatchInProgress(!0),ye.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of Te.documents){if(isReservedForUserTree(e))continue;let s=null;if(t.transact(()=>{s=zt(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(ye.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 g=$t.length,S=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:g,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${g}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await tn(),e.headMoved&&e.newHead){let g=resolveUpstreamChanges(s,resolve(t),e.oldHead,e.newHead);if(g.size>0){dropPendingDocs(g.keys());for(let[e,t]of g)recordContributor(e,gitAuthorWriterId(t.email),t.name,t.email,formatReconcileSubject(e));await we.flushContributors()}}if(await we.flushDeferredStores(`within-branch`),jr!==null)try{await jr.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),$t.splice(0,$t.length),switchReconciledBaseScope(S),rt!==null&&(clearTimeout(rt),rt=null),_e.switchBranch(S),ge.rebuildDirCount();try{let e=0;de.clear(),await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g,branch:S},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:S},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Vr.includes(`basename-index-partial`)||Vr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:S},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of Te.documents)if(!isReservedForUserTree(e))try{let g=safeContentPath(e,t);if(!existsSync(g)){let t=getReconciledBase(e)??``,g=zt(e)??``;if(g!==t&&ye.current){let t=ye.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:g,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,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:S},`[branch-switch] tombstone: ${e} (not on ${S})`);continue}let w=readFileSync(g,`utf-8`);Bt(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:S,docCount:Te.documents.size},`[branch-switch] loaded branch ${S} (${Te.documents.size} docs)`);try{if(await _e.loadFromDisk(S)){let e=await _e.reconcileWithDisk(S);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${S}`)}else await _e.rebuildFromDisk(S);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),S)}catch(e){Y.warn({err:e,branch:S},`[backlinks] branch-switch global skill bundle ingest failed`)}_e.saveToDisk(S).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${S}:`,e)})}catch(e){Y.error({err:e,branch:S},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ve.init(),ye.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Te.documents)if(!isReservedForUserTree(t))try{let s=await readParkedState(ye.current,S,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let g=getReconciledBase(t);if(!g)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:g});switch(w.kind){case`merged`:case`clean`:Bt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:Bt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=Te.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:S},`[branch-switch] restored ${e} parked docs on ${S}`)}if(e.oldBranch?.startsWith(`detached-`)&&ye.current)try{let t=shadowGit(ye.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
3263
- `))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 we.flushDeferredStores(`discard-stale`),je?.emitBranchSwitched(S)}if(e.headMoved&&e.newHead&&ye.current&&g>0){let t=L??`.`;try{let s=await commitUpstreamImport(ye.current,t,e.oldHead,e.newHead,S);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`),Vr.push(`head-watcher`)}function O(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Te.documents.get(S);if(!w)continue;let E=zt(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 j=buildSyncCredentialArgs(H);try{jr=new SyncEngine({projectDir:s,contentDir:t,contentFilter:ge,contentRoot:L,syncEnabled:ne(),credentialArgs:j,cc1Broadcaster:je,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||we.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:O,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 jr.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),jr=null}$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`);let F=bootElapsedMs();F!==void 0&&recordBootPhase(`readyMs`,F)}return Hr().then(Ge,Ke),{hocuspocus:Te,sessionManager:De,cc1Broadcaster:je,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,maintenanceCoordinator:Ce,contentFilter:ge,basenameIndex:de,serverInstanceId:ce,destroy:Br,ready:Xe,degraded:Vr,lockDir:ue,get syncEngine(){return jr}}}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){startBootTimings();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};S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S));let E=process.env.OK_STARTUP_TRACEPARENT,D=()=>withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e));if(E)try{let e=propagation.extract(context.active(),{traceparent:E});return context.with(e,D)}catch(e){getLogger(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return D()}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`),{markServerLockDraining:O,releaseServerLock:k,updateServerLockPort:j}=await import(`./server-lock-GuuouVft-CPaJpyJ7.mjs`),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.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 H=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&H()}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 q=findLegacyRuntimeFiles(B);q.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${q.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let ee=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:J,destroy:Y,ready:te,degraded:ne,lockDir:ae,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue}=ee,de=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),fe=e.port??0,me=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${de}:${fe}`,log:S}),ge=D();ge.headersTimeout=3e4,ge.requestTimeout=6e4;let _e=e.serveContentAssets===!1?void 0:createAssetServeMiddleware({contentFilter:ee.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}),ve=!1;if(e.reactShellDistDir)try{acquireUiLock(ae,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ve=!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:ae},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),k(ae),e}let ye=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,Ce=mountMcpAndApi({httpServer:ge,hocuspocus:J,mcpHttpHandler:me,log:S,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:_e,reactShellMiddleware:ye,ephemeral:e.ephemeral}),we=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Te=null;g!==null&&(Te=attachIdleShutdown({httpServer:ge,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await we()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);ge.once(`error`,g),ge.listen(e.port,e.host,()=>{ge.removeListener(`error`,g),t()})})}catch(e){if(ve)try{releaseUiLock(ae)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),k(ae),e}let De=bootElapsedMs();De!==void 0&&recordBootPhase(`httpListenMs`,De);let je=ge.address(),Me=typeof je==`object`&&je?je.port:e.port??0;if(fe=Me,j(ae,Me),ve&&updateUiLockPort(ae,Me),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ae,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Pe=!1,Ie=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)}};we=async()=>{if(Pe)return;Pe=!0;let e=[],t=async(t,s)=>{try{await Ie(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{O(ae),ve&&markUiLockDraining(ae)}catch(e){S.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{Te?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>Ce.shutdown()),me!==void 0&&await t(`mcpHttpHandler.close`,()=>me.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{Ce.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ge.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ge.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>Y()),ve&&await t(`releaseUiLock`,async()=>releaseUiLock(ae,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:L,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ge,destroy:we,lockDir:ae,contentDir:e.contentDir,port:Me,ready:te,degraded:ne,didAutoInit:F,serverInstance:ee}}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=simpleGit({baseDir:s,timeout:{block:5e3}});E=new Set(await listNames(g,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e,t){try{let{stdout:s}=await execFileAsync(e,[`rev-parse`,`--is-inside-work-tree`],withHiddenWindowsConsole({cwd:t,encoding:`utf-8`}));return s.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}let w;try{w=assertGitAvailable()}catch(e){throw e instanceof GitNotAvailableError||e instanceof GitTooOldError?(emitPreflightFailureSpan(e),log.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:e instanceof GitTooOldError?e.detected:``},e instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let E=w.resolvedPath;if(!S&&await isInsideExistingWorkTree(E,t))return{didInit:!1};let D=``;try{D=(await execFileAsync(E,[`init`,`--initial-branch=main`,t],withHiddenWindowsConsole({encoding:`utf-8`}))).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,D);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
3262
+ `)){let g=s.trim();if(g===``)continue;if(g.startsWith(`C\0`)){let[,e,t]=g.split(`\0`);E=e&&t?{name:e,email:t}:null;continue}if(!E||!g.endsWith(`.md`)&&!g.endsWith(`.mdx`))continue;let w=resolve(e,g);if(!isWithinContentDir(w,t))continue;let D=pathToDocName(w,t);S.has(D)||existsSync(w)&&S.set(D,E)}return S}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`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=isKnownConfigError(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}Y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ne(){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;if(t!=null)return t===!0;e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let g=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});return g.valid||Y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),g.value.autoSync?.default===!0}function ae(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function oe(){return readConfigSafely({absPath:resolveConfigPath(`project-local`,s,k),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project-local config`)}).value.linkPreviews?.enabled===!0}function se(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function ce(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=ne(),Mr?.setEnabled(t).catch(s=>{Y.warn({err:s,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let s=ae();Be.applyConfig({enabled:s.enabled,providerFingerprint:se(s)}),Y.info({docName:e,autoSyncEnabled:t,semanticEnabled:s.enabled},`[config] applied persisted config to in-process consumers`)}initTelemetry();let ue=randomUUID(),de=getLocalDir(s);if(acquireServerLock(de,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:de,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(de),e}let fe=createBasenameIndex(),me=(e,t)=>fe.resolveEmbed(e,t),ge=(e,s)=>{let g=fe.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g);if(!isWithinDir(S,resolve(t)))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},_e,ve,ye,Ce,we,Te,De,je,Me=null,Pe=null,Ie=null,Re=null,ze=ae(),Be=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:ze.enabled,providerFingerprint:se(ze)}),Ve=null,Ue=new Set,We=!1,Ge,Ke,Xe,$e=new Promise((e,t)=>{Ke=e,Xe=t});function nt(e){Me?.signal(e)}let rt=2e3,it=null;function at(){it!==null&&clearTimeout(it),it=setTimeout(()=>{it=null,ve.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let st=2e3,vt=null,St=!1,Tt=()=>{try{saveRemovedDocsJournal(s,Et.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Et=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e),onMutate:()=>{!St||vt!==null||(vt=setTimeout(()=>{vt=null,Tt()},2e3))}});for(let[e,g]of loadRemovedDocsJournal(s))isReservedForUserTree(e)||isSafeDocName(e)&&([`.md`,`.mdx`].some(s=>{let g=resolve(t,`${e}${s}`);return isWithinDir(g,resolve(t))&&existsSync(g)})||Et.restore(e,g));St=!0;let jt=(e,t)=>{isReservedForUserTree(e)||Et.setRenamed(e,t)},Mt=e=>{if(!isReservedForUserTree(e)){if(Et.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Et.setDeleted(e)}},Ft=e=>{isReservedForUserTree(e)||Et.delete(e)};try{_e=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{ve.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ye.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild(sn).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`)})}}),ve=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:_e}),ye=new TagIndex({contentDir:t,contentFilter:_e}),ye.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),Ce={current:F},we=E?createMaintenanceCoordinator({getShadow:()=>Ce.current??null,getCurrentBranch:()=>jr?.getLastKnownBranch()??null,contentRoot:L??``,projectGitDir:resolveGitDir(s)??void 0,isWriterLive:e=>{if(!Ie&&!je)return getLogger(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Ie?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of je?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,Te=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:Ce,ephemeral:J,contentRoot:L,backlinkIndex:ve,configHomedirOverride:k,getCurrentBranch:()=>jr?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:ge,getPrincipal:()=>Ve,onAgentCommit:()=>Me?.signal(`session-activity`),onFlushCommit:()=>we?.noteFlushCommit(),onDiskFlush:(e,t,s,g)=>{Me?.emitDiskAck(e,t),!isReservedForUserTree(e)&&assetReferencesChanged(g,s)&&(Re?.(),nt(`files`))},onConfigRejected:(e,t)=>Me?.emitConfigValidationRejected(e,t),onConfigPersisted:ce,isRecentlyRemoved:e=>Et.has(e),mdManager:e.mdManager}),De=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[Te.extension]});let B=De.shouldUnloadDocument.bind(De);De.shouldUnloadDocument=e=>{if(Ue.has(e)||We&&B(e))return!0;let t=e.name;return isReservedForUserTree(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},Ge=async e=>{Ue.add(e);try{await De.unloadDocument(e)}finally{Ue.delete(e)}},Me=new CC1Broadcaster(De),Pe=new AgentFocusBroadcaster(De),Ie=new AgentPresenceBroadcaster(De),je=new AgentSessionManager(De);let q=createLiveDerivedIndexExtension({backlinkIndex:ve,tagIndex:ye,signalChannel:nt});De.configuration.extensions.push(q),De.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!==ue)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ue}`);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`&&(Ve&&s.principalId===Ve.id?E.principalId=Ve.id:Ve?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Ve.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),De.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName)&&!isManagedArtifactDoc(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 ne(e){if(!isSafeDocName(e))return null;let t=resolve(Y,docNameToRelativePath(e));return isWithinDir(t,Y)?t:null}De.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Et,resolveFilePath:ne,fileExists:existsSync})}}),De.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>De.documents.get(e)})}}),De.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 se=createApiExtension({hocuspocus:De,sessionManager:je,contentDir:t,contentFilter:_e,serverInstanceId:ue,getFileIndex:()=>sn?sn.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>sn?sn.getAllFilesIndex():new Map,getFileIndexGeneration:()=>sn?.getFileIndexGeneration()??0,mutateFileIndex:e=>sn?.mutateFileIndex(e),getFolderIndex:()=>sn?sn.getFolderIndex():new Map,getAliasMap:()=>sn?sn.getAliasMap():new Map,getFolderAliasIndex:()=>sn?sn.getFolderAliasIndex():new Map,rescanFiles:()=>sn?.rescanFromDisk(),enableTestRoutes:j,shadowRef:Ce,flushGitCommit:()=>Te.flushPendingGitCommit(),flushContributors:()=>Te.flushContributors(),takeStoreFailure:e=>Te.takeStoreFailure(e),takeStoreDivergence:e=>Te.takeStoreDivergence(e),markAgentWriteStore:e=>Te.markAgentWriteStore(e),getCurrentBranch:()=>jr?.getLastKnownBranch()??null,getDiskAckSVs:()=>Me?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:ve,tagIndex:ye,signalChannel:nt,agentFocusBroadcaster:Pe,agentPresenceBroadcaster:Ie,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Mr,localOpCliArgs:H,projectDir:s,resolveEmbed:me,getPrincipal:()=>Ve,homeDirOverride:k,forceUnloadDocument:Ge,ready:$e,recentlyRemovedDocs:Et,serializeDoc:Bt,evictManagedArtifactLkg:e=>{Te.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Be,getSemanticSimilarityFloor:()=>ae().similarityFloor,getLinkPreviewsEnabled:oe,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Re=e}});De.configuration.extensions.push(se),De.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:Ce,contentRoot:L,getCurrentBranch:()=>jr?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:ge})),De.configuration.extensions.push(createSyncHandshakeSpanExtension()),De.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Mr,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(de),e}let It=null,Lt=new Map,Rt=[];function zt(e,t){let s=resolve(e,`rescue`),g=resolve(s,docNameToRelativePath(t));return isWithinDir(g,s)?g:null}function Bt(e){let t=De.documents.get(e);return t?serializeYDocSource(t):null}let Vt=(e,t)=>applyExternalChange(De,e,t,me,ge);function Ht(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ut=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of De.documents){if(isReservedForUserTree(s))continue;let g=De.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,me,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}`)}}},Wt=null,Xt=e=>{e&&(Wt===null&&(Wt=new Set,setImmediate(()=>{let e=Wt;if(Wt=null,e)try{for(let t of e)Ut(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Wt.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 $t(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),ve.updateDocumentFromMarkdown(e.docName,e.content),at(),ye.updateDocumentFromMarkdown(e.docName,e.content),nt(`files`),nt(`backlinks`),nt(`graph`),nt(`tags`),Ft(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=De.documents.get(t);if(!g){ve.updateDocumentFromMarkdown(t,s),at(),ye.updateDocumentFromMarkdown(t,s),nt(`backlinks`),nt(`graph`),nt(`tags`);return}let S=getReconciledBase(t)??``,w=Bt(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`:Ht(g),ve.updateDocumentFromMarkdown(t,s),at(),ye.updateDocumentFromMarkdown(t,s),nt(`backlinks`),nt(`graph`),nt(`tags`);break;case`clean`:try{Vt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Ht(g),ve.updateDocumentFromMarkdown(t,s),at(),ye.updateDocumentFromMarkdown(t,s),nt(`backlinks`),nt(`graph`),nt(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Ht(g)}break;case`merged`:try{Vt(t,E.newContent),setReconciledBase(t,s),incrementReconcile(),Ht(g),ve.updateDocumentFromMarkdown(t,s),at(),ye.updateDocumentFromMarkdown(t,s),nt(`backlinks`),nt(`graph`),nt(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Ht(g)}break;case`conflicts`:try{Vt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),ve.updateDocumentFromMarkdown(t,s),at(),ye.updateDocumentFromMarkdown(t,s),nt(`backlinks`),nt(`graph`),nt(`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=De.documents.get(t);if(!s){ve.deleteDocument(t),at(),ye.deleteDocument(t),nt(`files`),nt(`backlinks`),nt(`graph`),nt(`tags`),Mt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=Bt(t)??``,w=S!==g;if(w&&Ce.current){let e=Ce.current,s=jr?.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),ve.deleteDocument(t),at(),ye.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),De.closeConnections(t),await Ge(s),nt(`files`),nt(`backlinks`),nt(`graph`),nt(`tags`),Mt(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=De.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),ve.renameDocument(t,s,g),at(),ye.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}`),nt(`files`),nt(`backlinks`),nt(`graph`),nt(`tags`),jt(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=De.documents.get(t);if(!s)return;let g=Bt(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`:fe.add(e.relativePath),nt(`files`),Xt(basename(e.relativePath));break;case`asset-delete`:fe.remove(e.relativePath),nt(`files`),Xt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:nt(`files`);break;case`file-create`:case`file-update`:case`file-delete`:nt(`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 en=[];async function tn(e){if(isBatchInProgress()){en.push(e);return}await $t(e)}async function rn(){let e=en.splice(0,en.length);for(let t of e)await $t(t)}let sn=null,jr=null,Mr=null,zr=null;async function Br(e){if(De.documents.size===0)return;let t=!1,s=new Promise(e=>{De.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(De.documents.keys());De.closeConnections(),De.flushPendingStores();for(let e of De.documents.values())e.getConnectionsCount()===0&&De.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(De.documents.keys()),S=[],E=[];if(Ce.current){for(let e of s)if(!isReservedForUserTree(e))try{let t=Bt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=zt(Ce.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:Ce.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 Vr(){return zr||(zr=(async()=>{let e=Date.now(),t=[];We=!0;try{markServerLockDraining(de)}catch(e){Y.warn({err:e},`[server] failed to mark server.lock draining`)}if(it!==null&&(clearTimeout(it),it=null),vt!==null&&(clearTimeout(vt),vt=null),St)try{saveRemovedDocsJournal(s,Et.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let g,S=await Promise.race([$e.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=De.documents.size;we?.destroy();try{try{try{jr&&=(await jr.unsubscribe(),null),sn&&=(await sn.unsubscribe(),null);for(let{docName:e,cleanup:t}of Rt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Rt.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{Me?.destroy(),Ie?.destroy(),It&&=(await It.disconnect(),null);for(let[e,t]of Lt)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Lt.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 je.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 Br(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 Te.flushPendingGitCommit(),await Te.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{Mr&&=(await Mr.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(Ce.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(Ce.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(Ce.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(de,{deferUnlinkToExit:!0})}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)})}}})(),zr)}let Hr=[];async function Ur(){try{Ve=await loadPrincipal(s),Y.info({principalId:Ve.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!Ce.current)try{Ce.current=await initShadowRepo(s),Y.info({gitDir:Ce.current.gitDir},`[server] history repo initialized at ${Ce.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Hr.push(`shadow-repo`)}if(Ce.current){let e=null;try{e=loadRenameLogIndex(Ce.current.gitDir),sweepLazyPopOrphans(Ce.current.gitDir,e),setRenameLogIndex(Ce.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(Ce.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 we?.runBootMaintenance()}catch(e){Y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(Ce.current)try{await shadowGit(Ce.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{Ce.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),Ce.current=void 0,Hr.includes(`shadow-repo`)||Hr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(Ce.current)try{let e=resolve(Ce.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(Ce.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`),Hr.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`),Hr.push(`upload-tempfile-sweep`)}try{It=await De.openDirectConnection(SYSTEM_DOC_NAME),Me?.emitServerInfo(ue,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Hr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await De.openDirectConnection(e);Lt.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Hr.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=De.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,Te.configPersistenceCtx);Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),ce(e)});Rt.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}`),Hr.push(`config-file-watcher:${e}`)}}if(!J){let e=(e,t)=>{let s=managedArtifactDocNameForPath(e,Te.managedArtifactCtx);if(!s)return;let g=applyExternalManagedArtifactChange(De.documents.get(s)??null,s,t,Te.managedArtifactCtx);Y.info({docName:s,outcome:g},`[managed-artifact-watcher] external change`),parseGlobalSkillBundleDoc(s)&&ve.ingestGlobalSkillBundles(managedArtifactSkillsRoots(Te.managedArtifactCtx),getActiveBranch()).then(()=>{nt(`backlinks`),nt(`graph`)}).catch(e=>{Y.warn({err:e,docName:s},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=managedArtifactSkillsRoots(Te.managedArtifactCtx),s=await startManagedArtifactWatcher(t,e);Rt.push({docName:`__skill-files__`,cleanup:s}),Y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Hr.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of resolveProjectTemplates(s).templates)t.add(e.source_folder)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let g=[...t].map(e=>e?resolve(s,e,`.ok`,`templates`):resolve(s,`.ok`,`templates`)),S=await startManagedArtifactWatcher(g,e,TEMPLATE_WATCH_OPTIONS);Rt.push({docName:`__template-files__`,cleanup:S}),Y.info({rootCount:g.length},`[managed-artifact-watcher] templates started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),Hr.push(`managed-artifact-watcher:templates`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],withHiddenWindowsConsole({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(De.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,Te.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 _e.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`),Me?.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`),Me?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Rt.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`),Hr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),ve.switchBranch(E);let D=performance.now();try{await withSpan(`ok.boot.indexes`,void 0,async()=>{let e=getActiveBranch();try{if(await ve.loadFromDisk(e)){let t=await ve.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info({added:t.added,updated:t.updated,deleted:t.deleted},`[backlinks] startup reconcile: offline changes applied`);let s=0;for(let e of t.deletedDocNames)isReservedForUserTree(e)||Et.peek(e)?.kind!==`renamed`&&(Et.setDeleted(e),s++);s>0&&Y.info({count:s},`[removal-guard] tombstoned docs deleted while the server was down`)}else await ve.rebuildFromDisk(e);try{await ve.ingestGlobalSkillBundles(managedArtifactSkillsRoots(Te.managedArtifactCtx),e)}catch(t){Y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}ve.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`)}let s=performance.now();sn=await withSpan(`ok.boot.seed-walk`,void 0,async()=>startWatcher(t,tn,_e)),recordBootPhase(`seedWalkMs`,Math.round(performance.now()-s));{let e=resolve(t),s=0;for(let[t]of Et.entries()){if(!isSafeDocName(t))continue;let g=resolve(e,`${t}${getDocExtension(t)}`);isWithinDir(g,e)&&existsSync(g)&&(Et.delete(t),s++)}s>0&&Y.info({count:s},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{await ye.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Hr.push(`tag-index`)}let g=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:_e,basenameIndex:fe,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:fe,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),g>0&&(Y.warn({count:g},`[basename-index] startup seed completed with ${g} skipped entries — embeds under inaccessible subtrees will not resolve`),Hr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Hr.push(`basename-index`)}})}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Hr.push(`file-watcher`)}finally{recordBootPhase(`indexesMs`,Math.round(performance.now()-D)),sn&&setBootField(`fileCount`,sn.getFileIndex().size)}try{jr=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),De.flushPendingStores(),await Te.flushPendingGitCommit(),setBatchInProgress(!0),Ce.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of De.documents){if(isReservedForUserTree(e))continue;let s=null;if(t.transact(()=>{s=Bt(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(Ce.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 g=en.length,S=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:g,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${g}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await rn(),e.headMoved&&e.newHead){let g=resolveUpstreamChanges(s,resolve(t),e.oldHead,e.newHead);if(g.size>0){dropPendingDocs(g.keys());for(let[e,t]of g)recordContributor(e,gitAuthorWriterId(t.email),t.name,t.email,formatReconcileSubject(e));await Te.flushContributors()}}if(await Te.flushDeferredStores(`within-branch`),Mr!==null)try{await Mr.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),en.splice(0,en.length),switchReconciledBaseScope(S),it!==null&&(clearTimeout(it),it=null),ve.switchBranch(S),_e.rebuildDirCount();try{let e=0;fe.clear(),await seedBasenameIndex({contentDir:t,contentFilter:_e,basenameIndex:fe,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g,branch:S},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:S},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Hr.includes(`basename-index-partial`)||Hr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:S},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of De.documents)if(!isReservedForUserTree(e))try{let g=safeContentPath(e,t);if(!existsSync(g)){let t=getReconciledBase(e)??``,g=Bt(e)??``;if(g!==t&&Ce.current){let t=Ce.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:g,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,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:S},`[branch-switch] tombstone: ${e} (not on ${S})`);continue}let w=readFileSync(g,`utf-8`);Vt(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:S,docCount:De.documents.size},`[branch-switch] loaded branch ${S} (${De.documents.size} docs)`);try{if(await ve.loadFromDisk(S)){let e=await ve.reconcileWithDisk(S);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${S}`)}else await ve.rebuildFromDisk(S);try{await ve.ingestGlobalSkillBundles(managedArtifactSkillsRoots(Te.managedArtifactCtx),S)}catch(e){Y.warn({err:e,branch:S},`[backlinks] branch-switch global skill bundle ingest failed`)}ve.saveToDisk(S).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${S}:`,e)})}catch(e){Y.error({err:e,branch:S},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ye.init(),Ce.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of De.documents)if(!isReservedForUserTree(t))try{let s=await readParkedState(Ce.current,S,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let g=getReconciledBase(t);if(!g)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:g});switch(w.kind){case`merged`:case`clean`:Vt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:Vt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=De.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:S},`[branch-switch] restored ${e} parked docs on ${S}`)}if(e.oldBranch?.startsWith(`detached-`)&&Ce.current)try{let t=shadowGit(Ce.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
3263
+ `))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 Te.flushDeferredStores(`discard-stale`),Me?.emitBranchSwitched(S)}if(e.headMoved&&e.newHead&&Ce.current&&g>0){let t=L??`.`;try{let s=await commitUpstreamImport(Ce.current,t,e.oldHead,e.newHead,S);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`),Hr.push(`head-watcher`)}function O(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=De.documents.get(S);if(!w)continue;let E=Bt(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 j=buildSyncCredentialArgs(H);try{Mr=new SyncEngine({projectDir:s,contentDir:t,contentFilter:_e,contentRoot:L,syncEnabled:ne(),credentialArgs:j,cc1Broadcaster:Me,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||Te.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:O,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 Mr.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Mr=null}nt(`files`),nt(`backlinks`),nt(`graph`),nt(`tags`);let F=bootElapsedMs();F!==void 0&&recordBootPhase(`readyMs`,F)}return Ur().then(Ke,Xe),{hocuspocus:De,sessionManager:je,cc1Broadcaster:Me,agentFocusBroadcaster:Pe,agentPresenceBroadcaster:Ie,maintenanceCoordinator:we,contentFilter:_e,basenameIndex:fe,serverInstanceId:ue,destroy:Vr,ready:$e,degraded:Hr,lockDir:de,get syncEngine(){return Mr}}}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){startBootTimings();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};S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S));let E=process.env.OK_STARTUP_TRACEPARENT,D=()=>withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e));if(E)try{let e=propagation.extract(context.active(),{traceparent:E});return context.with(e,D)}catch(e){getLogger(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return D()}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`),{markServerLockDraining:O,releaseServerLock:k,updateServerLockPort:j}=await import(`./server-lock-GuuouVft-CO_sPVNi.mjs`),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.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 H=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&H()}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 q=findLegacyRuntimeFiles(B);q.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${q.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let ee=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:J,destroy:Y,ready:te,degraded:ne,lockDir:ae,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue}=ee,de=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),fe=e.port??0,me=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${de}:${fe}`,log:S}),ge=D();ge.headersTimeout=3e4,ge.requestTimeout=6e4;let _e=e.serveContentAssets===!1?void 0:createAssetServeMiddleware({contentFilter:ee.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}),ve=!1;if(e.reactShellDistDir)try{acquireUiLock(ae,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ve=!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:ae},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),k(ae),e}let ye=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,Ce=mountMcpAndApi({httpServer:ge,hocuspocus:J,mcpHttpHandler:me,log:S,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:_e,reactShellMiddleware:ye,ephemeral:e.ephemeral}),we=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Te=null;g!==null&&(Te=attachIdleShutdown({httpServer:ge,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await we()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);ge.once(`error`,g),ge.listen(e.port,e.host,()=>{ge.removeListener(`error`,g),t()})})}catch(e){if(ve)try{releaseUiLock(ae)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),k(ae),e}let De=bootElapsedMs();De!==void 0&&recordBootPhase(`httpListenMs`,De);let je=ge.address(),Me=typeof je==`object`&&je?je.port:e.port??0;if(fe=Me,j(ae,Me),ve&&updateUiLockPort(ae,Me),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ae,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Pe=!1,Ie=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)}};we=async()=>{if(Pe)return;Pe=!0;let e=[],t=async(t,s)=>{try{await Ie(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{O(ae),ve&&markUiLockDraining(ae)}catch(e){S.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{Te?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>Ce.shutdown()),me!==void 0&&await t(`mcpHttpHandler.close`,()=>me.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{Ce.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ge.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ge.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>Y()),ve&&await t(`releaseUiLock`,async()=>releaseUiLock(ae,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:L,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ge,destroy:we,lockDir:ae,contentDir:e.contentDir,port:Me,ready:te,degraded:ne,didAutoInit:F,serverInstance:ee}}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=simpleGit({baseDir:s,timeout:{block:5e3}});E=new Set(await listNames(g,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e,t){try{let{stdout:s}=await execFileAsync(e,[`rev-parse`,`--is-inside-work-tree`],withHiddenWindowsConsole({cwd:t,encoding:`utf-8`}));return s.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}let w;try{w=assertGitAvailable()}catch(e){throw e instanceof GitNotAvailableError||e instanceof GitTooOldError?(emitPreflightFailureSpan(e),log.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:e instanceof GitTooOldError?e.detected:``},e instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let E=w.resolvedPath;if(!S&&await isInsideExistingWorkTree(E,t))return{didInit:!1};let D=``;try{D=(await execFileAsync(E,[`init`,`--initial-branch=main`,t],withHiddenWindowsConsole({encoding:`utf-8`}))).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,D);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
3264
3264
  `,`utf-8`),t}export{STARTER_PACK_IDS as $,withSpan as $i,isKnownPackId as $n,resolveCursorBinaryDefault as $r,createMcpHttpHandler as $t,HocuspocusAuthRejection as A,splitMarkdownBlocks as Ai,getLocalDir as An,processCommand as Ar,classifyFsPath as At,McpLogger as B,tracedRename as Bi,incrementCollabSocketFilteredError as Bn,readTargetRecordedAt as Br,contributorCount as Bt,FILE_WATCHER_ORIGIN as C,setupServerObservers as Ci,flushFileLogger as Cn,parseAuthRejectionWire as Cr,buildConfigYmlContent as Ct,GitNotAvailableError as D,spansCurrentPath as Di,formatPackRationale as Dn,pathToDocName as Dr,buildWipTree as Dt,GIT_UPSTREAM_WRITER as E,skillManagementPath as Ei,formatContributorsFrom as En,parseKeepaliveConnectionId as Er,buildStarterFolderFrontmatterYaml as Et,MANAGED_RENAME_ORIGIN as F,toBroadcasterKey as Fi,getMetrics as Fn,readProjectLocalSemanticConfig as Fr,commitWip as Ft,ProjectGitInitError as G,tracedWriteFile as Gi,initToleranceTelemetryWriter as Gn,recordSkillInstallEvent as Gr,createAssetServeMiddleware as Gt,OBSERVER_SYNC_ORIGIN as H,tracedRmSync as Hi,initContent as Hn,readUiLock as Hr,countStaleAgentWipRefs as Ht,MAX_AGENT_SESSIONS as I,tracedAppendFileSync as Ii,getTracer as In,readServerPackageVersion as Ir,commitWipFromTree as It,SERVICE_WRITER as J,updateUiLockPort as Ji,installUserSkill as Jn,releaseUiLock as Jr,createEmbeddingsSecretStore as Jt,ROLLBACK_ORIGIN as K,tracedWriteFileSync as Ki,installPrettyZodErrors as Kn,registerAllTools as Kr,createContentFilter as Kt,MCP_CONNECTION_ID_HEADER as L,tracedLinkSync as Li,handleCollabSocketError as Ln,readSkillInstallStateSnapshot as Lr,compareSemver as Lt,INSTALLED_AGENTS_SCHEMES as M,streamingProblemEvent as Mi,getLogger as Mn,readAllTargets as Mr,clearEmbeddingsKeyFromAllBackends as Mt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as N,swapContributors as Ni,getLogsDir as Nn,readBranchFromHead as Nr,coercePackId as Nt,GitTooOldError as O,spansPreviousPath as Oi,gcCheckpointRefs as On,planSeed as Or,bundleSkillMdPath as Ot,LOG_MD_TEMPLATE as P,teardownToleranceTelemetryWriter as Pi,getMeter as Pn,readBundleDecision as Pr,commitUpstreamImport as Pt,STARTER_PACKS as Q,withHiddenWindowsConsole as Qi,isHocuspocusAuthRejectionReason as Qn,resolveContentDir as Qr,createLiveDerivedIndexExtension as Qt,MIN_GIT_VERSION as R,tracedMkdir as Ri,handleSpawnCursor as Rn,readSkillManagement as Rr,containsConflictMarkers as Rt,FILE_SYSTEM_WRITER as S,resolveShadowDir as Sa,setActiveSpanAttributes as Si,findEnclosingProjectRoot as Sn,packageVersionMajorMinor as Sr,buildAndOpenSkill as St,GIT_PREFLIGHT_FAIL_SPAN_NAME as T,shutdownTelemetry as Ti,formatContributors as Tn,parseHocuspocusAuthToken as Tr,buildSkillZip as Tt,OK_OKIGNORE_TEMPLATE as U,tracedRmdirSync as Ui,initShadowRepo as Un,reconcile as Ur,countWipRefs as Ut,MissingOkConfigError as V,tracedRenameSync as Vi,incrementServerObserverFire as Vn,readTargetVersion as Vr,countShadowObjects as Vt,PinoLogger as W,tracedUnlinkSync as Wi,initTelemetry as Wn,recordContributor as Wr,createApiExtension as Wt,STARTER_FOLDERS as X,validateCloneInputs as Xi,isAllowedWorkspaceHostHeader as Xn,resetMetrics as Xr,createExternalChangeHandler as Xt,SKILL_INSTALL_EVENTS_FILE_REL as Y,validateAgentId as Yi,isAllowedApiOrigin as Yn,removeLastKnownHash as Yr,createEphemeralProjectDir as Yt,STARTER_FOLDER_FRONTMATTER_FILENAME as Z,validateSkillZip as Zi,isConfigDoc as Zn,resolveBundledSkillDir as Zr,createFileLogger as Zt,ConfigSchema as _,writeConfigPatch as _a,sanitizeClientName as _i,evictStaleTrackerEntries as _n,logsPreviousPath as _r,assertCompatibleStateManifest as _t,AgentPresenceBroadcaster as a,writeTargetVersion as aa,restoreContributors as ai,createTestLogger as an,isProjectRoot as ar,SingleFileNotFoundError as at,DEFAULT_PACK_ID as b,parseCheckpoint as ba,seedBasenameIndex as bi,fallbackPaths as bn,normalizeFsPath as br,attachIdleShutdown as bt,AutoStartDisabledError as c,JSONRPCMessageSchema as ca,rewriteWikiLinksForDocumentRename as ci,detectGit as cn,isSelfWrite as cr,TagIndex as ct,BUNDLE_SKILL_NAME as d,isJSONRPCRequest as da,runCloneSubprocess as di,emitPreflightFailureSpan as dn,lastKnownHash as dr,__getShowAllWalkStatsForTesting as dt,withSpanSync as ea,resolveCursorSpawnInvocation as ei,createOsProbe as en,isLinkIndexExcludedDoc as er,STARTER_TEMPLATES as et,BacklinkIndex as f,isJSONRPCResultResponse as fa,runDeviceFlowSubprocess as fi,encodeDocName as fn,listRescueCheckpoints as fr,__resetShowAllWalkStatsForTesting as ft,CURSOR_BUNDLE_PATHS_BY_PLATFORM as g,withFileLockSync as ga,safetyCheckpoint as gi,errorResponse as gn,logsCurrentPath as gr,applySeed as gt,CONFLICT_MARKER_RE as h,resolveConfigPath as ha,safeSubdir as hi,ensureProjectGit as hn,loggerFactory as hr,applyExternalChange as ht,AgentFocusBroadcaster as i,writeStateManifest as ia,resolveUiInfo as ii,createStreamingErrorWriter as in,isPathWithinDir as ir,SingleFileNotAFileError as it,HocuspocusAuthTokenSchema as j,startWatcher as ji,getLogFilePath as jn,processUsage as jr,clearContributors as jt,HOCUSPOCUS_AUTH_REJECTION_REASONS as k,spawnDetached as ki,getCurrentMcpLogger as kn,prepareSingleFileOpen as kr,classifyEvents as kt,BUNDLE_IDS as l,LATEST_PROTOCOL_VERSION as la,runAuthReposSubprocess as li,detectProjectShape as ln,isSystemDoc as lr,USER_GLOBAL_BUNDLE_IDS as lt,CONFIG_FILENAME as m,readConfigSafely as ma,safeContentPath as mi,encodeSkillRoute as mn,loadPrincipal as mr,applyAgentMarkdownWrite as mt,AGENT_ID_RE as n,writeRootGitignoreForNewRepo as na,resolvePack as ni,createServer$1 as nn,isManagedArtifactDoc as nr,SeedPrerequisiteError as nt,AgentSessionCapacityError as o,writeTracker as oa,restoreLifecycleFromConflictsJson as oi,describeStoredEmbeddingsKey as on,isProjectSkillManaged as or,SingleFileNotMarkdownError as ot,CC1Broadcaster as p,atomicWriteFileSync as pa,runWithMcpLogger as pi,encodeFolderRoute as pn,listStarterPacks as pr,acquireUiLock as pt,ROOT_GITIGNORE_TEMPLATE as q,updateLastKnownHash as qi,installTestLoggers as qn,registerWrite as qr,createContentFilterAsync as qt,AGENT_WRITE_ORIGIN as r,writeSkillManagement as ra,resolvePackageVersion as ri,createServerObserverExtension as rn,isPairedWriteOrigin as rr,SeedRootDirError as rt,AgentSessionManager as s,McpServer as sa,rewriteMarkdownLinksForDocumentRename as si,detectClaudeDesktopPresence as sn,isReservedForUserTree as sr,StateManifestError as st,AGENT_ID_MAX_LEN as t,writeBundleDecision as ta,resolveLockDir as ti,createPersistenceExtension as tn,isLoopbackAddress as tr,STATE_MANIFEST_FILENAME as tt,BUNDLE_SCOPE as u,isInitializedNotification as ua,runAuthStatusSubprocess as ui,discoverLockDirs as un,isToleranceTelemetryEnabled as ur,UiLockCollisionError as ut,DEFAULT_CHECKPOINT_RETENTION as v,GitDirAccessError as va,saveInMemoryCheckpoint as vi,extractOkBinaryPath as vn,makeLazyEmbeddingsKeyStore as vr,assertGitAvailable as vt,FileEmbeddingsBackend as w,shadowGit as wi,formatAuthRejectionWire as wn,parseGitVersion as wr,buildExecResult as wt,EMBEDDINGS_API_KEY_ENV as x,resolveGitDirDetailed as xa,serializeError as xi,findEnclosingGitRoot as xn,originGitHubHost as xr,bootServer as xt,DEFAULT_EMBEDDINGS_DIMENSIONS as y,MalformedGitPointerError as ya,saveVersion as yi,extractWikiLinksFromMarkdown as yn,mountMcpAndApi as yr,assertNeverDiskEvent as yt,MISSING_OK_CONFIG_MESSAGE as z,tracedMkdirSync as zi,hasGcLogLatch as zn,readStateManifest as zr,contentHash as zt};
3265
- //# sourceMappingURL=dist-DEBa6nkk.mjs.map
3265
+ //# sourceMappingURL=dist-Pe1Q8dMj.mjs.map