@inkeep/open-knowledge 0.10.0-beta.2 → 0.10.0-beta.3

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 (57) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/packs/entity-vault/SKILL.md +1 -1
  3. package/dist/assets/skills/packs/knowledge-base/SKILL.md +4 -4
  4. package/dist/assets/skills/packs/software-lifecycle/SKILL.md +1 -1
  5. package/dist/assets/skills/packs/worldbuilding/SKILL.md +1 -1
  6. package/dist/assets/skills/packs/writing-pipeline/SKILL.md +1 -1
  7. package/dist/assets/skills/project/SKILL.md +96 -84
  8. package/dist/cli.mjs +44 -44
  9. package/dist/constants-CyZAfnKE.mjs +2 -0
  10. package/dist/{dist-DmAclKYw.mjs → dist-BQBP5cHC.mjs} +101 -110
  11. package/dist/{dist-BChJILrk.mjs → dist-CN7LYh2I.mjs} +1 -1
  12. package/dist/{gh-detect-DjiocciN.mjs → gh-detect-7CewBTHd.mjs} +2 -2
  13. package/dist/index.mjs +1 -1
  14. package/dist/init-DTxIVXsK.mjs +1 -0
  15. package/dist/{init-B1U5zssu.mjs → init-rBOx-UoS.mjs} +6 -6
  16. package/dist/{loader-D-MyijDv.mjs → loader-C18y4751.mjs} +3 -3
  17. package/dist/loader-CIjGJokl.mjs +1 -0
  18. package/dist/preview-8HmIikBL.mjs +1 -0
  19. package/dist/{preview-CgQ_96_Y.mjs → preview-B9e0FTnb.mjs} +2 -2
  20. package/dist/public/assets/{ActivityModeContent-Cag3qsEp.js → ActivityModeContent-BltN0GR_.js} +1 -1
  21. package/dist/public/assets/DocumentContext-Dzuik8cQ.js +61 -0
  22. package/dist/public/assets/{GraphPanel-2TcKJgp2.js → GraphPanel-DWqoIFOB.js} +3 -3
  23. package/dist/public/assets/SettingsDialogBody-BAnoCuwv.js +7 -0
  24. package/dist/public/assets/{SourceEditor-BDifJ_-m.js → SourceEditor-D6wlbSv0.js} +1 -1
  25. package/dist/public/assets/config-validation-events-CbnMrOc_.js +12 -0
  26. package/dist/public/assets/index-B3eQbsM3.css +1 -0
  27. package/dist/public/assets/index-BDVVBSJl.js +1915 -0
  28. package/dist/public/assets/keyboard-shortcuts-C6IgDAxF.js +1 -0
  29. package/dist/public/assets/prop-types-ClZR0brz.js +500 -0
  30. package/dist/public/assets/{target-navigation-intent-CxMMZ391.js → target-navigation-intent-DJ_3bEwP.js} +1 -1
  31. package/dist/public/assets/{typing-burst-detector-DMPAdHvx.js → typing-burst-detector-BAa7NaBj.js} +2 -2
  32. package/dist/public/index.html +8 -8
  33. package/dist/{repair-launch-json-t7SBBUmJ.mjs → repair-launch-json-vsisOvsp.mjs} +2 -2
  34. package/dist/{repair-mcp-configs-CFt0S96K.mjs → repair-mcp-configs-DYuJxjMq.mjs} +2 -2
  35. package/dist/repair-skills-C6jToz6v.mjs +1 -0
  36. package/dist/{repair-skills-4GbGPfQs.mjs → repair-skills-DPZPmw_o.mjs} +2 -2
  37. package/dist/{server-lock-BpjJj3OD-CpgmesYM.mjs → server-lock-BpjJj3OD-wzz0WNKm.mjs} +88 -88
  38. package/dist/server-lock-CyhBidkz-DrsmjbY0.mjs +1 -0
  39. package/dist/{src-DyJezQur.mjs → src-BF03oCTQ.mjs} +2 -2
  40. package/dist/start-D6rIJZX1.mjs +1 -0
  41. package/dist/{start-ddvEdLDZ.mjs → start-DTuGxWbd.mjs} +2 -2
  42. package/dist/{write-project-skill-Bc9GzRes.mjs → write-project-skill-UXN6czYz.mjs} +2 -2
  43. package/package.json +1 -1
  44. package/dist/constants-Aooo5mZf.mjs +0 -2
  45. package/dist/init-C2apfDIg.mjs +0 -1
  46. package/dist/loader-BEfkXa6p.mjs +0 -1
  47. package/dist/preview-B7k4yYED.mjs +0 -1
  48. package/dist/public/assets/DocumentContext-CV395VYL.js +0 -61
  49. package/dist/public/assets/SettingsDialogBody-Co5_Xo6m.js +0 -7
  50. package/dist/public/assets/config-validation-events-B5G3zveS.js +0 -12
  51. package/dist/public/assets/index-BE5VlQ00.js +0 -1915
  52. package/dist/public/assets/index-CYUEwyxk.css +0 -1
  53. package/dist/public/assets/keyboard-shortcuts-B4aOgyRn.js +0 -1
  54. package/dist/public/assets/prop-types-mM2mU4oh.js +0 -500
  55. package/dist/repair-skills-CEYqx9v7.mjs +0 -1
  56. package/dist/server-lock-CyhBidkz-3npi9JMD.mjs +0 -1
  57. package/dist/start-BSDJmh5u.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{a as __toCommonJS,i as __require$2,n as __esmMin,o as __toESM$2,r as __exportAll,t as __commonJSMin$2}from"./chunk-FK9Q3tQk.mjs";import{$ as CONFIG_DOC_NAME_USER,$i as datetime,$n as TemplatePutRequestSchema,$r as resolveInternalHref,$t as MetricsAgentPresenceSuccessSchema,A as ApiConfigSuccessSchema,Ai as withConfigSpan,An as ShareConstructUrlRequestSchema,Ar as encodeShareUrl,At as FrontmatterPatchRequestSchema,B as CC1DiskAckPayloadSchema,Bi as discriminatedUnion,Bn as SuggestLinksSuccessSchema,Br as isBranchNotFoundGitError,Bt as LocalOpAuthEmptySuccessSchema,C as AgentPatchSuccessSchema,Ci as detectRemovedKeys,Cn as SearchRequestSchema,Cr as createWorkspaceSearchCorpus,Ct as EXECUTABLE_BLOCKLIST_EXTENSIONS,D as AgentWriteMdSuccessSchema,Di as locateIssue,Dn as SeedListPacksSuccessSchema,Dr as detectFmRegion,Dt as FolderConfigPutRequestSchema,E as AgentWriteMdRequestSchema,Ei as isKnownConfigError,En as SeedApplySuccessSchema,Er as detectAppliedToleranceClasses,Et as FolderConfigGetSuccessSchema,F as BridgeMergeContentLossError,Fi as _null,Fn as SharePublishResponseSchema,Fr as getAgentCanonicalDescriptors,Ft as INLINE_RENDERABLE_EXTENSIONS,G as CC1_CHANNEL_DISK_ACK,Gi as object$1,Gn as SyncResolveConflictSuccessSchema,Gr as normalizeBridge,Gt as LocalOpAuthSetIdentityRequestSchema,H as CC1_CHANNEL_BRANCH_SWITCHED,Hi as literal,Hn as SyncConflictContentSuccessSchema,Hr as isValidBranchName,Ht as LocalOpAuthIdentitySuccessSchema,I as CC1BranchSwitchedPayloadSchema,In as SkillInstallStateSuccessSchema,Ir as getHeadingSlug,It as InstallSkillRequestSchema,J as CLIENT_VERSION_HEADER,Ji as record,Jn as SyncTriggerSuccessSchema,Jr as previewEmbedFence,Jt as LocalOpOkInitRequestSchema,K as CC1_CHANNEL_SERVER_INFO,Ki as optional,Kn as SyncStatusSchema,Kr as parseFrontmatterYaml,Kt as LocalOpAuthStatusSuccessSchema,L as CC1ConfigIgnoreNestedErrorPayloadSchema,Li as array,Ln as SkillStateSchema,Lr as getParseHealth,Lt as InstallSkillSuccessSchema,M as BacklinksSuccessSchema,Mn as SharePublishNameCheckResponseSchema,Mr as extractFrontmatterTags,Mt as HistorySuccessSchema,N as BranchInfoResponseSchema,Ni as ZodOptional$1,Nn as SharePublishOwnersResponseSchema,Nr as fnv1aDigest,Nt as HistoryVersionSuccessSchema,O as AgentWriteRequestSchema,Oi as toConfigIssue,On as SeedPlanSuccessSchema,Or as displayNameFromClientName,Ot as FolderConfigPutSuccessSchema,P as BridgeInvariantViolationError,Pi as _enum,Pn as SharePublishRequestSchema,Pr as formatFileSize,Pt as HubsSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT_LOCAL,Qn as TemplateGetSuccessSchema,Qr as resolveAssetProjectPath,Qt as MarkdownManager,R as CC1ConfigValidationRejectedPayloadSchema,Ri as boolean,Rn as SpawnCursorSuccessSchema,Rr as getWikiLinkText,Rt as InstalledAgentsSuccessSchema,S as AgentPatchRequestSchema,Si as applyPatchToDocument,Sn as SaveVersionSuccessSchema,Sr as createTagInTextRegex,T as AgentUndoSuccessSchema,Ti as isFrontmatterValueEmpty,Tn as SeedApplyRequestSchema,Tr as defaultScheduler,Tt as EmptyRequestSchema,U as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ui as looseObject,Un as SyncConflictsSuccessSchema,Ur as mediaKindForSidebarAssetExtension,Ut as LocalOpAuthPatRequestSchema,V as CC1ServerInfoPayloadSchema,Vi as intersection,Vn as SyncAbortMergeSuccessSchema,Vr as isOrphanMode,Vt as LocalOpAuthHostRequestSchema,W as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Wi as number,Wn as SyncResolveConflictRequestSchema,Wr as mergeThreeWay,Wt as LocalOpAuthPatSuccessSchema,X as CONFIG_DOC_NAME_OKIGNORE,Xi as union,Xn as TagsListSuccessSchema,Xr as readFmMap,Xt as LocalOpOpenRequestSchema,Y as CONFIG_DOC_NAMES,Yi as string,Yn as TagsForNameSuccessSchema,Yr as projectFull,Yt as LocalOpOkInitResponseSchema,Z as CONFIG_DOC_NAME_PROJECT,Zi as unknown,Zn as TemplateDeleteSuccessSchema,Zr as renderInventoryFooter,Zt as LocalOpOpenSuccessSchema,_ as AGENT_ICON_COLORS,_i as FrontmatterValueSchema,_n as SKILL_STATE_TARGETS,_r as classifyWikiLinkTarget,_t as DiffSuccessSchema,a as acquireProcessLock,aa as $ZodType,ai as toWikiLinkSlug,an as PREVIEW_THEME_TOKENS,ar as TrashCleanupRequestSchema,at as CreateFolderRequestSchema,b as AgentActivitySuccessSchema,bn as SYSTEM_DOC_NAME,br as createBasenameIndex,bt as DuplicatePathRequestSchema,c as isValidLockPid,ca as safeParse$1,ci as getSchema,cn as PagesSuccessSchema,cr as UploadAssetSuccessSchema,ct as CreatePageSuccessSchema,da as clone,di as CONFIG_SCHEMA_MAJOR_PATH,dn as RenamePathRequestSchema,dr as WriteWarningSchema,ea as toJSONSchema,ei as searchWorkspaceCorpus,en as MetricsParseHealthSuccessSchema,er as TemplatePutSuccessSchema,et as CheckoutRequestSchema,f as readServerLock,fa as defineLazy,fi as ConfigSchema$1,fn as RenamePathSuccessSchema,fr as applyFastDiff,ga as require_dist$1,gi as FRONTMATTER_TYPES,gn as SKILL_STATE_REL,gr as classifyMarkdownHref,gt as DeletePathSuccessSchema,h as updateProcessLockPort,hi as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,hn as RollbackSuccessSchema,hr as assertNeverProblemType,ht as DeletePathRequestSchema,ia as $ZodObject,ii as toBridgeInvariantLog,in as PREVIEW_EMBED_STARTERS,ir as TestResetSuccessSchema,it as ConflictEntrySchema,j as BacklinkCountsSuccessSchema,ji as withConfigSpanSync,jn as ShareConstructUrlResponseSchema,jr as expandTagToHierarchy,jt as FrontmatterPatchSuccessSchema,k as AgentWriteSuccessSchema,ki as validatePatchScopes,kn as ServerInfoSuccessSchema,kr as emptySkillState,kt as ForwardLinksSuccessSchema,la as safeParseAsync$1,li as PluginKey,ln as PrincipalSuccessSchema,lr as UploadRequestSchema,lt as DEFAULT_DEDUP_MODE,m as releaseServerLock,ma as $constructor,mi as DEFAULT_SPANS_MAX_BYTES,mn as RollbackRequestSchema,mr as applyPatchToFm,mt as DeadLinksSuccessSchema,n as RUNTIME_VERSION,na as describe$1,ni as stripFrontmatter,nn as ORPHAN_MODES,nr as TestRescanBacklinksSuccessSchema,nt as ClientLogsRequestSchema,o as acquireServerLock,oa as parse$1,oi as unwrapFrontmatterFences,on as PROTOCOL_VERSION,or as TrashCleanupSuccessSchema,ot as CreateFolderSuccessSchema,p as releaseProcessLock,pa as normalizeParams,pi as DEFAULT_LOGS_MAX_BYTES,pn as RescueListSuccessSchema,pr as applyIncrementalDiff,pt as DOCUMENT_OPEN_BYTE_LIMIT,q as CC1_CONTRACT_VERSION,qi as preprocess,qn as SyncTriggerRequestSchema,qr as prependFrontmatter,qt as LocalOpCloneRequestSchema,ra as meta$1,ri as tagsMatchingPrefix,rn as OrphansSuccessSchema,rr as TestRescanFilesSuccessSchema,rt as ClientLogsSuccessSchema,s as isProcessAlive,sa as parseAsync,si as validateDocName,sn as PageHeadingsSuccessSchema,sr as UA_PATTERNS,st as CreatePageRequestSchema,t as ProcessLockCollisionError,ti as sharedExtensions,tn as MetricsReconciliationSuccessSchema,tr as TemplatesListSuccessSchema,tt as CheckoutResponseSchema,u as readProcessLock,ua as prettifyError,ui as Fragment,un as ProblemDetailsSchema,ur as WorkspaceSuccessSchema,vi as LOCAL_DIR,vn as SKILL_STATE_VERSION_RE,vt as DocumentListSuccessSchema,w as AgentUndoRequestSchema,wi as humanFormat,wn as SearchSuccessSchema,wr as createWorkspaceSearchDocument,wt as EmbedDetectSuccessSchema,x as AgentBurstDiffSuccessSchema,xi as addConfigSpanEvent,xn as SaveVersionRequestSchema,xr as createCodeFenceTracker,xt as DuplicatePathSuccessSchema,y as ASSET_EXTENSIONS,yi as OK_PROJECT_MARKER,yr as colorFromSeed,yt as DocumentReadSuccessSchema,z as CC1DerivedViewPayloadSchema,zi as custom,zn as StreamingProblemEventSchema,zr as iconFromClientName,zt as LinkGraphSuccessSchema}from"./server-lock-BpjJj3OD-CpgmesYM.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-s2X3YAg-.mjs";import{a as require_src$15,i as simpleGit,n as withParentLock,r as esm_default,t as createGitInstance}from"./git-handle-BSAUg1L_-CUJRlGhd.mjs";import{r as diffLines,t as createPatch}from"./libesm-B_qVEpZ1.mjs";import{n as mimes,t as build_default}from"./build-CHU3LuiR.mjs";import{t as require_yazl}from"./yazl-DjRp4wSy.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DesxOVHh.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-DnjwTqP3.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-C25Und0M.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-akBjDPaR.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-FwG_Za20.mjs";import{r as o$1}from"./chunk-CWQS3NFK-Co4ALolT.mjs";import"./chunk-DXB73IDG-DIKSLkPq.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-CAp625aG.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DvJz5Cpw.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-ikvLWpfV.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-B6yIPkk2.mjs";import{n as n$1}from"./chunk-3THT3N7L-DztAF386.mjs";import{t as n$2}from"./chunk-44UOCSGV-CaFxJDHm.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,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$1 from"zlib";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{Http2ServerRequest,constants as constants$2}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
1
+ import{a as __toCommonJS,i as __require$2,n as __esmMin,o as __toESM$2,r as __exportAll,t as __commonJSMin$2}from"./chunk-FK9Q3tQk.mjs";import{$ as CONFIG_DOC_NAME_USER,$i as datetime,$n as TemplateMoveRequestSchema,$r as readFmMap,$t as MetricsAgentPresenceSuccessSchema,A as ApiConfigSuccessSchema,Ai as withConfigSpan,An as ShareConstructUrlRequestSchema,Ar as displayNameFromClientName,At as FrontmatterPatchSuccessSchema,B as CC1DiskAckPayloadSchema,Bi as discriminatedUnion,Bn as SuggestLinksSuccessSchema,Br as getWikiLinkText,Bt as LocalOpAuthEmptySuccessSchema,C as AgentPatchSuccessSchema,Ci as applyPatchToDocument,Cn as SearchRequestSchema,Cr as createCodeFenceTracker,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdSuccessSchema,Di as locateIssue,Dn as SeedListPacksSuccessSchema,Dr as defaultScheduler,Dt as FolderConfigPutSuccessSchema,E as AgentWriteMdRequestSchema,Ei as isKnownConfigError,En as SeedApplySuccessSchema,Er as createWorkspaceSearchDocument,Et as FolderConfigPutRequestSchema,F as BridgeMergeContentLossError,Fi as _null,Fn as SharePublishResponseSchema,Fr as fnv1aDigest,Ft as INLINE_RENDERABLE_EXTENSIONS,G as CC1_CHANNEL_DISK_ACK,Gi as object$1,Gn as SyncResolveConflictSuccessSchema,Gr as isValidBranchName,Gt as LocalOpAuthSetIdentityRequestSchema,H as CC1_CHANNEL_BRANCH_SWITCHED,Hi as literal,Hn as SyncConflictContentSuccessSchema,Hr as isBranchNotFoundGitError,Ht as LocalOpAuthIdentitySuccessSchema,I as CC1BranchSwitchedPayloadSchema,In as SkillInstallStateSuccessSchema,Ir as formatFileSize,It as InstallSkillRequestSchema,J as CLIENT_VERSION_HEADER,Ji as record,Jn as SyncTriggerSuccessSchema,Jr as normalizeBridge,Jt as LocalOpOkInitRequestSchema,K as CC1_CHANNEL_SERVER_INFO,Ki as optional,Kn as SyncStatusSchema,Kr as mediaKindForSidebarAssetExtension,Kt as LocalOpAuthStatusSuccessSchema,L as CC1ConfigIgnoreNestedErrorPayloadSchema,Li as array,Ln as SkillStateSchema,Lr as getAgentCanonicalDescriptors,Lt as InstallSkillSuccessSchema,M as BacklinksSuccessSchema,Mn as SharePublishNameCheckResponseSchema,Mr as encodeShareUrl,Mt as HistorySuccessSchema,N as BranchInfoResponseSchema,Ni as ZodOptional$1,Nn as SharePublishOwnersResponseSchema,Nr as expandTagToHierarchy,Nt as HistoryVersionSuccessSchema,O as AgentWriteRequestSchema,Oi as toConfigIssue,On as SeedPlanSuccessSchema,Or as detectAppliedToleranceClasses,Ot as ForwardLinksSuccessSchema,P as BridgeInvariantViolationError,Pi as _enum,Pn as SharePublishRequestSchema,Pr as extractFrontmatterTags,Pt as HubsSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT_LOCAL,Qn as TemplateGetSuccessSchema,Qr as projectFull,Qt as MarkdownManager,R as CC1ConfigValidationRejectedPayloadSchema,Ri as boolean,Rn as SpawnCursorSuccessSchema,Rr as getHeadingSlug,Rt as InstalledAgentsSuccessSchema,S as AgentPatchRequestSchema,Si as addConfigSpanEvent,Sn as SaveVersionSuccessSchema,Sr as createBasenameIndex,St as EXECUTABLE_BLOCKLIST_EXTENSIONS,T as AgentUndoSuccessSchema,Ti as humanFormat,Tn as SeedApplyRequestSchema,Tr as createWorkspaceSearchCorpus,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ui as looseObject,Un as SyncConflictsSuccessSchema,Ur as isFrontmatterValueEmpty,Ut as LocalOpAuthPatRequestSchema,V as CC1ServerInfoPayloadSchema,Vi as intersection,Vn as SyncAbortMergeSuccessSchema,Vr as iconFromClientName,Vt as LocalOpAuthHostRequestSchema,W as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Wi as number,Wn as SyncResolveConflictRequestSchema,Wr as isOrphanMode,Wt as LocalOpAuthPatSuccessSchema,X as CONFIG_DOC_NAME_OKIGNORE,Xi as union,Xn as TagsListSuccessSchema,Xr as prependFrontmatter,Xt as LocalOpOpenRequestSchema,Y as CONFIG_DOC_NAMES,Yi as string,Yn as TagsForNameSuccessSchema,Yr as parseFrontmatterYaml,Yt as LocalOpOkInitResponseSchema,Z as CONFIG_DOC_NAME_PROJECT,Zi as unknown,Zn as TemplateDeleteSuccessSchema,Zr as previewEmbedFence,Zt as LocalOpOpenSuccessSchema,_ as AGENT_ICON_COLORS,_i as DEFAULT_SPANS_MAX_BYTES,_n as SKILL_STATE_TARGETS,_r as assertNeverProblemType,_t as DocumentListSuccessSchema,a as acquireProcessLock,aa as $ZodType,ai as stripFrontmatter,an as PREVIEW_THEME_TOKENS,ar as TestRescanFilesSuccessSchema,at as CreateFolderSuccessSchema,b as AgentActivitySuccessSchema,bi as OK_PROJECT_MARKER,bn as SYSTEM_DOC_NAME,bt as DuplicatePathSuccessSchema,c as isValidLockPid,ca as safeParse$1,ci as toWikiLinkSlug,cn as PagesSuccessSchema,cr as TrashCleanupSuccessSchema,ct as DEFAULT_DEDUP_MODE,da as clone,di as getSchema,dn as RenamePathRequestSchema,dr as UploadRequestSchema,ea as toJSONSchema,ei as renderInventoryFooter,en as MetricsParseHealthSuccessSchema,er as TemplateMoveSuccessSchema,et as CheckoutRequestSchema,f as readServerLock,fa as defineLazy,fi as PluginKey,fn as RenamePathSuccessSchema,fr as WorkspaceSuccessSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as require_dist$1,gi as DEFAULT_LOGS_MAX_BYTES,gn as SKILL_STATE_REL,gr as applyPatchToFm,gt as DiffSuccessSchema,h as updateProcessLockPort,hi as ConfigSchema$1,hn as RollbackSuccessSchema,hr as applyIncrementalDiff,ht as DeletePathSuccessSchema,ia as $ZodObject,ii as sharedExtensions,in as PREVIEW_EMBED_STARTERS,ir as TestRescanBacklinksSuccessSchema,it as CreateFolderRequestSchema,j as BacklinkCountsSuccessSchema,ji as withConfigSpanSync,jn as ShareConstructUrlResponseSchema,jr as emptySkillState,jt as FrontmatterValueSchema,k as AgentWriteSuccessSchema,ki as validatePatchScopes,kn as ServerInfoSuccessSchema,kr as detectFmRegion,kt as FrontmatterPatchRequestSchema,la as safeParseAsync$1,li as unwrapFrontmatterFences,ln as PrincipalSuccessSchema,lr as UA_PATTERNS,m as releaseServerLock,ma as $constructor,mi as CONFIG_SCHEMA_MAJOR_PATH,mn as RollbackRequestSchema,mr as applyFastDiff,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as describe$1,ni as resolveInternalHref,nn as ORPHAN_MODES,nr as TemplatePutSuccessSchema,nt as ClientLogsRequestSchema,o as acquireServerLock,oa as parse$1,oi as tagsMatchingPrefix,on as PROTOCOL_VERSION,or as TestResetSuccessSchema,ot as CreatePageRequestSchema,p as releaseProcessLock,pa as normalizeParams,pi as Fragment,pn as RescueListSuccessSchema,pr as WriteWarningSchema,pt as DeadLinksSuccessSchema,q as CC1_CONTRACT_VERSION,qi as preprocess,qn as SyncTriggerRequestSchema,qr as mergeThreeWay,qt as LocalOpCloneRequestSchema,ra as meta$1,ri as searchWorkspaceCorpus,rn as OrphansSuccessSchema,rr as TemplatesListSuccessSchema,rt as ClientLogsSuccessSchema,s as isProcessAlive,sa as parseAsync,si as toBridgeInvariantLog,sn as PageHeadingsSuccessSchema,sr as TrashCleanupRequestSchema,st as CreatePageSuccessSchema,t as ProcessLockCollisionError,ti as resolveAssetProjectPath,tn as MetricsReconciliationSuccessSchema,tr as TemplatePutRequestSchema,tt as CheckoutResponseSchema,u as readProcessLock,ua as prettifyError,ui as validateDocName,un as ProblemDetailsSchema,ur as UploadAssetSuccessSchema,vi as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,vn as SKILL_STATE_VERSION_RE,vr as classifyMarkdownHref,vt as DocumentReadSuccessSchema,w as AgentUndoRequestSchema,wi as detectRemovedKeys,wn as SearchSuccessSchema,wr as createTagInTextRegex,wt as EmptyRequestSchema,x as AgentBurstDiffSuccessSchema,xn as SaveVersionRequestSchema,xr as colorFromSeed,y as ASSET_EXTENSIONS,yi as LOCAL_DIR,yr as classifyWikiLinkTarget,yt as DuplicatePathRequestSchema,z as CC1DerivedViewPayloadSchema,zi as custom,zn as StreamingProblemEventSchema,zr as getParseHealth,zt as LinkGraphSuccessSchema}from"./server-lock-BpjJj3OD-wzz0WNKm.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-s2X3YAg-.mjs";import{a as require_src$15,i as simpleGit,n as withParentLock,r as esm_default,t as createGitInstance}from"./git-handle-BSAUg1L_-CUJRlGhd.mjs";import{r as diffLines,t as createPatch}from"./libesm-B_qVEpZ1.mjs";import{n as mimes,t as build_default}from"./build-CHU3LuiR.mjs";import{t as require_yazl}from"./yazl-DjRp4wSy.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DesxOVHh.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-DnjwTqP3.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-C25Und0M.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-akBjDPaR.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-FwG_Za20.mjs";import{r as o$1}from"./chunk-CWQS3NFK-Co4ALolT.mjs";import"./chunk-DXB73IDG-DIKSLkPq.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-CAp625aG.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DvJz5Cpw.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-ikvLWpfV.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-B6yIPkk2.mjs";import{n as n$1}from"./chunk-3THT3N7L-DztAF386.mjs";import{t as n$2}from"./chunk-44UOCSGV-CaFxJDHm.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,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$1 from"zlib";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{Http2ServerRequest,constants as constants$2}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
2
2
  `)){let e=s.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let s=JSON.parse(e.slice(17));if(typeof s==`object`&&s&&`id`in s&&typeof s.id==`string`&&`name`in s&&typeof s.name==`string`&&`docs`in s&&Array.isArray(s.docs)&&s.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in s)||typeof s.colorSeed==`string`)){let e=s;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(s)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let s;try{s=JSON.parse(e.slice(18))}catch{return null}if(typeof s!=`object`||!s)return null;let g=s,S=g.kind,w=g.metadata;if(typeof w!=`object`||!w)return null;let E=typeof g.docName==`string`?g.docName:null,D=typeof g.size==`number`&&Number.isFinite(g.size)?g.size:null;if(S===`bridge-merge-loss`){let e=w;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:E,size:D,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(S===`external-change-rescue`){let e=w;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:E,size:D,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}return null}return null}function formatCheckpointBodyLine(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${OK_CHECKPOINT_PREFIX}${JSON.stringify(t)}`}const OK_ACTOR_PREFIX=`ok-actor: `;function formatOkActor(e){let{summaries:t,previous_paths:s,...g}=e,S={...g};return t&&t.length>0&&(S.summaries=t),s&&s.length>0&&(S.previous_paths=s),`${OK_ACTOR_PREFIX}${JSON.stringify(S)}`}function parseOkActorObject(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,s=typeof e.agent_session==`string`?e.agent_session:null,g;if(typeof e.writer_id==`string`&&e.writer_id.length>0)g=e.writer_id;else if(s)g=`agent-${s}`;else if(t)g=t;else switch(e.display_name){case`File System`:g=`file-system`;break;case`Git (upstream)`:g=`git-upstream`;break;default:g=`openknowledge-service`}let S=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,w=parsePreviousPaths(e);return{v:1,writer_id:g,principal:t,agent_session:s,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...S&&S.length>0?{summaries:S}:{},...w&&w.length>0?{previous_paths:w}:{}}}function parsePreviousPaths(e){if(!(`previous_paths`in e)||!Array.isArray(e.previous_paths))return;let t=[];for(let s of e.previous_paths){if(typeof s!=`object`||!s)continue;let e=s;typeof e.from!=`string`||typeof e.to!=`string`||t.push({from:e.from,to:e.to})}return t}function parseOkActors(e){if(!e)return[];let t=[];for(let s of e.split(`
4
4
  `)){let e=s.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let g;try{g=JSON.parse(e.slice(10))}catch{continue}if(typeof g!=`object`||!g)continue;let S=parseOkActorObject(g);S&&t.push(S)}return t}function okActorToShadowContributor(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function readContributors(e){let t=parseOkActors(e);return t.length>0?t.map(okActorToShadowContributor):parseContributors(e)}function formatWipSubject(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function formatReconcileSubject(e){return`reconcile: ${e}`}function formatRollbackSubject(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function formatParkSubject(e,t){return`park: ${e} -> ${t}`}function formatRenameSubject(e,t){return`rename: ${e} -> ${t}`}function formatCheckpointSubject(e){return`checkpoint: ${e}`}function formatImportSubject(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const SUBJECT_LINE_BREAK_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function stripLineBreaks(e){return e.replace(SUBJECT_LINE_BREAK_RE,` `)}function composeCommitSubject(e,t){let s=stripLineBreaks(e);if(t.length===0)return s;if(t.length>=2)return`${s} (${t.length} edits)`;let[g]=t;if(g===void 0)return s;let S=stripLineBreaks(g),w=`${s} — ${S}`;if(w.length<=72)return w;let E=`${s} — `,D=72-E.length-1;return D<=0?w.slice(0,72):`${E}${S.slice(0,D)}…`}function parseWriterId(e){return WRITER_ID_RE.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var require_suppress_tracing$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isTracingSuppressed=e.unsuppressTracing=e.suppressTracing=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key SUPPRESS_TRACING`);function s(e){return e.setValue(t,!0)}e.suppressTracing=s;function g(e){return e.deleteValue(t)}e.unsuppressTracing=g;function S(e){return e.getValue(t)===!0}e.isTracingSuppressed=S})),require_constants$7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BAGGAGE_MAX_TOTAL_LENGTH=e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=e.BAGGAGE_MAX_NAME_VALUE_PAIRS=e.BAGGAGE_HEADER=e.BAGGAGE_ITEMS_SEPARATOR=e.BAGGAGE_PROPERTIES_SEPARATOR=e.BAGGAGE_KEY_PAIR_SEPARATOR=void 0,e.BAGGAGE_KEY_PAIR_SEPARATOR=`=`,e.BAGGAGE_PROPERTIES_SEPARATOR=`;`,e.BAGGAGE_ITEMS_SEPARATOR=`,`,e.BAGGAGE_HEADER=`baggage`,e.BAGGAGE_MAX_NAME_VALUE_PAIRS=180,e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,e.BAGGAGE_MAX_TOTAL_LENGTH=8192})),require_utils$16=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_constants$7();function g(e){return e.reduce((e,t)=>{let g=`${e}${e===``?``:s.BAGGAGE_ITEMS_SEPARATOR}${t}`;return g.length>s.BAGGAGE_MAX_TOTAL_LENGTH?e:g},``)}e.serializeKeyPairs=g;function S(e){return e.getAllEntries().map(([e,t])=>{let g=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return t.metadata!==void 0&&(g+=s.BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),g})}e.getKeyPairs=S;function w(e){if(!e)return;let g=e.indexOf(s.BAGGAGE_PROPERTIES_SEPARATOR),S=g===-1?e:e.substring(0,g),w=S.indexOf(s.BAGGAGE_KEY_PAIR_SEPARATOR);if(w<=0)return;let E=S.substring(0,w).trim(),D=S.substring(w+1).trim();if(!E||!D)return;let O,k;try{O=decodeURIComponent(E),k=decodeURIComponent(D)}catch{return}let j;if(g!==-1&&g<e.length-1){let s=e.substring(g+1);j=(0,t.baggageEntryMetadataFromString)(s)}return{key:O,value:k,metadata:j}}e.parsePairKeyValue=w;function E(e){let t={};return typeof e==`string`&&e.length>0&&e.split(s.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let s=w(e);s!==void 0&&s.value.length>0&&(t[s.key]=s.value)}),t}e.parseKeyPairsIntoRecord=E})),require_W3CBaggagePropagator$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$3(),g=require_constants$7(),S=require_utils$16();e.W3CBaggagePropagator=class{inject(e,w,E){let D=t.propagation.getBaggage(e);if(!D||(0,s.isTracingSuppressed)(e))return;let O=(0,S.getKeyPairs)(D).filter(e=>e.length<=g.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,g.BAGGAGE_MAX_NAME_VALUE_PAIRS),k=(0,S.serializeKeyPairs)(O);k.length>0&&E.set(w,g.BAGGAGE_HEADER,k)}extract(e,s,w){let E=w.get(s,g.BAGGAGE_HEADER),D=Array.isArray(E)?E.join(g.BAGGAGE_ITEMS_SEPARATOR):E;if(!D)return e;let O={};return D.length===0||(D.split(g.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let t=(0,S.parsePairKeyValue)(e);if(t){let e={value:t.value};t.metadata&&(e.metadata=t.metadata),O[t.key]=e}}),Object.entries(O).length===0)?e:t.propagation.setBaggage(e,t.propagation.createBaggage(O))}fields(){return[g.BAGGAGE_HEADER]}}})),require_anchored_clock$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AnchoredClock=void 0,e.AnchoredClock=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}})),require_attributes$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isAttributeValue=e.isAttributeKey=e.sanitizeAttributes=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function s(e){let s={};if(typeof e!=`object`||!e)return s;for(let w in e){if(!Object.prototype.hasOwnProperty.call(e,w))continue;if(!g(w)){t.diag.warn(`Invalid attribute key: ${w}`);continue}let E=e[w];if(!S(E)){t.diag.warn(`Invalid attribute value set for key: ${w}`);continue}Array.isArray(E)?s[w]=E.slice():s[w]=E}return s}e.sanitizeAttributes=s;function g(e){return typeof e==`string`&&e!==``}e.isAttributeKey=g;function S(e){return e==null?!0:Array.isArray(e)?w(e):E(typeof e)}e.isAttributeValue=S;function w(e){let t;for(let s of e){if(s==null)continue;let e=typeof s;if(e!==t){if(!t){if(E(e)){t=e;continue}return!1}return!1}}return!0}function E(e){switch(e){case`number`:case`boolean`:case`string`:return!0}return!1}})),require_logging_error_handler$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.loggingErrorHandler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function s(){return e=>{t.diag.error(g(e))}}e.loggingErrorHandler=s;function g(e){return typeof e==`string`?e:JSON.stringify(S(e))}function S(e){let t={},s=e;for(;s!==null;)Object.getOwnPropertyNames(s).forEach(e=>{if(t[e])return;let g=s[e];g&&(t[e]=String(g))}),s=Object.getPrototypeOf(s);return t}})),require_global_error_handler$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,require_logging_error_handler$3().loggingErrorHandler)();function s(e){t=e}e.setGlobalErrorHandler=s;function g(e){try{t(e)}catch{}}e.globalErrorHandler=g})),require_environment$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e.getNumberFromEnv=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=__require$2(`util`);function g(e){let g=process.env[e];if(g==null||g.trim()===``)return;let S=Number(g);if(isNaN(S)){t.diag.warn(`Unknown value ${(0,s.inspect)(g)} for ${e}, expected a number, using defaults`);return}return S}e.getNumberFromEnv=g;function S(e){let t=process.env[e];if(!(t==null||t.trim()===``))return t}e.getStringFromEnv=S;function w(e){let g=process.env[e]?.trim().toLowerCase();return g==null||g===``?!1:g===`true`?!0:(g===`false`||t.diag.warn(`Unknown value ${(0,s.inspect)(g)} for ${e}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}e.getBooleanFromEnv=w;function E(e){return S(e)?.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}e.getStringListFromEnv=E})),require_globalThis$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=globalThis})),require_version$6=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.7.0`}));function createConstMap(e){let t={},s=e.length;for(let g=0;g<s;g++){let s=e[g];s&&(t[String(s).toUpperCase().replace(/[-.]/g,`_`)]=s)}return t}var init_utils=__esmMin((()=>{})),TMP_AWS_LAMBDA_INVOKED_ARN,TMP_DB_SYSTEM,TMP_DB_CONNECTION_STRING,TMP_DB_USER,TMP_DB_JDBC_DRIVER_CLASSNAME,TMP_DB_NAME,TMP_DB_STATEMENT,TMP_DB_OPERATION,TMP_DB_MSSQL_INSTANCE_NAME,TMP_DB_CASSANDRA_KEYSPACE,TMP_DB_CASSANDRA_PAGE_SIZE,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,TMP_DB_CASSANDRA_TABLE,TMP_DB_CASSANDRA_IDEMPOTENCE,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,TMP_DB_CASSANDRA_COORDINATOR_ID,TMP_DB_CASSANDRA_COORDINATOR_DC,TMP_DB_HBASE_NAMESPACE,TMP_DB_REDIS_DATABASE_INDEX,TMP_DB_MONGODB_COLLECTION,TMP_DB_SQL_TABLE,TMP_EXCEPTION_TYPE,TMP_EXCEPTION_MESSAGE,TMP_EXCEPTION_STACKTRACE,TMP_EXCEPTION_ESCAPED,TMP_FAAS_TRIGGER,TMP_FAAS_EXECUTION,TMP_FAAS_DOCUMENT_COLLECTION,TMP_FAAS_DOCUMENT_OPERATION,TMP_FAAS_DOCUMENT_TIME,TMP_FAAS_DOCUMENT_NAME,TMP_FAAS_TIME,TMP_FAAS_CRON,TMP_FAAS_COLDSTART,TMP_FAAS_INVOKED_NAME,TMP_FAAS_INVOKED_PROVIDER,TMP_FAAS_INVOKED_REGION,TMP_NET_TRANSPORT,TMP_NET_PEER_IP,TMP_NET_PEER_PORT,TMP_NET_PEER_NAME,TMP_NET_HOST_IP,TMP_NET_HOST_PORT,TMP_NET_HOST_NAME,TMP_NET_HOST_CONNECTION_TYPE,TMP_NET_HOST_CONNECTION_SUBTYPE,TMP_NET_HOST_CARRIER_NAME,TMP_NET_HOST_CARRIER_MCC,TMP_NET_HOST_CARRIER_MNC,TMP_NET_HOST_CARRIER_ICC,TMP_PEER_SERVICE,TMP_ENDUSER_ID,TMP_ENDUSER_ROLE,TMP_ENDUSER_SCOPE,TMP_THREAD_ID,TMP_THREAD_NAME,TMP_CODE_FUNCTION,TMP_CODE_NAMESPACE,TMP_CODE_FILEPATH,TMP_CODE_LINENO,TMP_HTTP_METHOD,TMP_HTTP_URL,TMP_HTTP_TARGET,TMP_HTTP_HOST,TMP_HTTP_SCHEME,TMP_HTTP_STATUS_CODE,TMP_HTTP_FLAVOR,TMP_HTTP_USER_AGENT,TMP_HTTP_REQUEST_CONTENT_LENGTH,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_RESPONSE_CONTENT_LENGTH,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_SERVER_NAME,TMP_HTTP_ROUTE,TMP_HTTP_CLIENT_IP,TMP_AWS_DYNAMODB_TABLE_NAMES,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,TMP_AWS_DYNAMODB_CONSISTENT_READ,TMP_AWS_DYNAMODB_PROJECTION,TMP_AWS_DYNAMODB_LIMIT,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,TMP_AWS_DYNAMODB_INDEX_NAME,TMP_AWS_DYNAMODB_SELECT,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,TMP_AWS_DYNAMODB_TABLE_COUNT,TMP_AWS_DYNAMODB_SCAN_FORWARD,TMP_AWS_DYNAMODB_SEGMENT,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,TMP_AWS_DYNAMODB_COUNT,TMP_AWS_DYNAMODB_SCANNED_COUNT,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,TMP_MESSAGING_SYSTEM,TMP_MESSAGING_DESTINATION,TMP_MESSAGING_DESTINATION_KIND,TMP_MESSAGING_TEMP_DESTINATION,TMP_MESSAGING_PROTOCOL,TMP_MESSAGING_PROTOCOL_VERSION,TMP_MESSAGING_URL,TMP_MESSAGING_MESSAGE_ID,TMP_MESSAGING_CONVERSATION_ID,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,TMP_MESSAGING_OPERATION,TMP_MESSAGING_CONSUMER_ID,TMP_MESSAGING_RABBITMQ_ROUTING_KEY,TMP_MESSAGING_KAFKA_MESSAGE_KEY,TMP_MESSAGING_KAFKA_CONSUMER_GROUP,TMP_MESSAGING_KAFKA_CLIENT_ID,TMP_MESSAGING_KAFKA_PARTITION,TMP_MESSAGING_KAFKA_TOMBSTONE,TMP_RPC_SYSTEM,TMP_RPC_SERVICE,TMP_RPC_METHOD,TMP_RPC_GRPC_STATUS_CODE,TMP_RPC_JSONRPC_VERSION,TMP_RPC_JSONRPC_REQUEST_ID,TMP_RPC_JSONRPC_ERROR_CODE,TMP_RPC_JSONRPC_ERROR_MESSAGE,TMP_MESSAGE_TYPE,TMP_MESSAGE_ID,TMP_MESSAGE_COMPRESSED_SIZE,TMP_MESSAGE_UNCOMPRESSED_SIZE,SEMATTRS_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_DB_SYSTEM,SEMATTRS_DB_CONNECTION_STRING,SEMATTRS_DB_USER,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_NAME,SEMATTRS_DB_STATEMENT,SEMATTRS_DB_OPERATION,SEMATTRS_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_TABLE,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_HBASE_NAMESPACE,SEMATTRS_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_MONGODB_COLLECTION,SEMATTRS_DB_SQL_TABLE,SEMATTRS_EXCEPTION_TYPE,SEMATTRS_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_ESCAPED,SEMATTRS_FAAS_TRIGGER,SEMATTRS_FAAS_EXECUTION,SEMATTRS_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_TIME,SEMATTRS_FAAS_CRON,SEMATTRS_FAAS_COLDSTART,SEMATTRS_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION,SEMATTRS_NET_TRANSPORT,SEMATTRS_NET_PEER_IP,SEMATTRS_NET_PEER_PORT,SEMATTRS_NET_PEER_NAME,SEMATTRS_NET_HOST_IP,SEMATTRS_NET_HOST_PORT,SEMATTRS_NET_HOST_NAME,SEMATTRS_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_ICC,SEMATTRS_PEER_SERVICE,SEMATTRS_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE,SEMATTRS_THREAD_ID,SEMATTRS_THREAD_NAME,SEMATTRS_CODE_FUNCTION,SEMATTRS_CODE_NAMESPACE,SEMATTRS_CODE_FILEPATH,SEMATTRS_CODE_LINENO,SEMATTRS_HTTP_METHOD,SEMATTRS_HTTP_URL,SEMATTRS_HTTP_TARGET,SEMATTRS_HTTP_HOST,SEMATTRS_HTTP_SCHEME,SEMATTRS_HTTP_STATUS_CODE,SEMATTRS_HTTP_FLAVOR,SEMATTRS_HTTP_USER_AGENT,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_SERVER_NAME,SEMATTRS_HTTP_ROUTE,SEMATTRS_HTTP_CLIENT_IP,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_URL,SEMATTRS_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION,SEMATTRS_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_RPC_SYSTEM,SEMATTRS_RPC_SERVICE,SEMATTRS_RPC_METHOD,SEMATTRS_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_VERSION,SEMATTRS_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_MESSAGE_TYPE,SEMATTRS_MESSAGE_ID,SEMATTRS_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE,SemanticAttributes,TMP_DBSYSTEMVALUES_OTHER_SQL,TMP_DBSYSTEMVALUES_MSSQL,TMP_DBSYSTEMVALUES_MYSQL,TMP_DBSYSTEMVALUES_ORACLE,TMP_DBSYSTEMVALUES_DB2,TMP_DBSYSTEMVALUES_POSTGRESQL,TMP_DBSYSTEMVALUES_REDSHIFT,TMP_DBSYSTEMVALUES_HIVE,TMP_DBSYSTEMVALUES_CLOUDSCAPE,TMP_DBSYSTEMVALUES_HSQLDB,TMP_DBSYSTEMVALUES_PROGRESS,TMP_DBSYSTEMVALUES_MAXDB,TMP_DBSYSTEMVALUES_HANADB,TMP_DBSYSTEMVALUES_INGRES,TMP_DBSYSTEMVALUES_FIRSTSQL,TMP_DBSYSTEMVALUES_EDB,TMP_DBSYSTEMVALUES_CACHE,TMP_DBSYSTEMVALUES_ADABAS,TMP_DBSYSTEMVALUES_FIREBIRD,TMP_DBSYSTEMVALUES_DERBY,TMP_DBSYSTEMVALUES_FILEMAKER,TMP_DBSYSTEMVALUES_INFORMIX,TMP_DBSYSTEMVALUES_INSTANTDB,TMP_DBSYSTEMVALUES_INTERBASE,TMP_DBSYSTEMVALUES_MARIADB,TMP_DBSYSTEMVALUES_NETEZZA,TMP_DBSYSTEMVALUES_PERVASIVE,TMP_DBSYSTEMVALUES_POINTBASE,TMP_DBSYSTEMVALUES_SQLITE,TMP_DBSYSTEMVALUES_SYBASE,TMP_DBSYSTEMVALUES_TERADATA,TMP_DBSYSTEMVALUES_VERTICA,TMP_DBSYSTEMVALUES_H2,TMP_DBSYSTEMVALUES_COLDFUSION,TMP_DBSYSTEMVALUES_CASSANDRA,TMP_DBSYSTEMVALUES_HBASE,TMP_DBSYSTEMVALUES_MONGODB,TMP_DBSYSTEMVALUES_REDIS,TMP_DBSYSTEMVALUES_COUCHBASE,TMP_DBSYSTEMVALUES_COUCHDB,TMP_DBSYSTEMVALUES_COSMOSDB,TMP_DBSYSTEMVALUES_DYNAMODB,TMP_DBSYSTEMVALUES_NEO4J,TMP_DBSYSTEMVALUES_GEODE,TMP_DBSYSTEMVALUES_ELASTICSEARCH,TMP_DBSYSTEMVALUES_MEMCACHED,TMP_DBSYSTEMVALUES_COCKROACHDB,DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_DB2,DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_EDB,DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA,DBSYSTEMVALUES_H2,DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_COCKROACHDB,DbSystemValues,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_ALL,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_TWO,DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_ANY,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DbCassandraConsistencyLevelValues,TMP_FAASTRIGGERVALUES_DATASOURCE,TMP_FAASTRIGGERVALUES_HTTP,TMP_FAASTRIGGERVALUES_PUBSUB,TMP_FAASTRIGGERVALUES_TIMER,TMP_FAASTRIGGERVALUES_OTHER,FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER,FAASTRIGGERVALUES_OTHER,FaasTriggerValues,TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE,FAASDOCUMENTOPERATIONVALUES_INSERT,FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_DELETE,FaasDocumentOperationValues,TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,TMP_FAASINVOKEDPROVIDERVALUES_AWS,TMP_FAASINVOKEDPROVIDERVALUES_AZURE,TMP_FAASINVOKEDPROVIDERVALUES_GCP,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AWS,FAASINVOKEDPROVIDERVALUES_AZURE,FAASINVOKEDPROVIDERVALUES_GCP,FaasInvokedProviderValues,TMP_NETTRANSPORTVALUES_IP_TCP,TMP_NETTRANSPORTVALUES_IP_UDP,TMP_NETTRANSPORTVALUES_IP,TMP_NETTRANSPORTVALUES_UNIX,TMP_NETTRANSPORTVALUES_PIPE,TMP_NETTRANSPORTVALUES_INPROC,TMP_NETTRANSPORTVALUES_OTHER,NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_IP,NETTRANSPORTVALUES_UNIX,NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_OTHER,NetTransportValues,TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED,NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NetHostConnectionTypeValues,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_LTE,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_GSM,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_NR,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NetHostConnectionSubtypeValues,TMP_HTTPFLAVORVALUES_HTTP_1_0,TMP_HTTPFLAVORVALUES_HTTP_1_1,TMP_HTTPFLAVORVALUES_HTTP_2_0,TMP_HTTPFLAVORVALUES_SPDY,TMP_HTTPFLAVORVALUES_QUIC,HTTPFLAVORVALUES_HTTP_1_0,HTTPFLAVORVALUES_HTTP_1_1,HTTPFLAVORVALUES_HTTP_2_0,HTTPFLAVORVALUES_SPDY,HTTPFLAVORVALUES_QUIC,HttpFlavorValues,TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC,MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC,MessagingDestinationKindValues,TMP_MESSAGINGOPERATIONVALUES_RECEIVE,TMP_MESSAGINGOPERATIONVALUES_PROCESS,MESSAGINGOPERATIONVALUES_RECEIVE,MESSAGINGOPERATIONVALUES_PROCESS,MessagingOperationValues,TMP_RPCGRPCSTATUSCODEVALUES_OK,TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,RPCGRPCSTATUSCODEVALUES_OK,RPCGRPCSTATUSCODEVALUES_CANCELLED,RPCGRPCSTATUSCODEVALUES_UNKNOWN,RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,RPCGRPCSTATUSCODEVALUES_NOT_FOUND,RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,RPCGRPCSTATUSCODEVALUES_ABORTED,RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,RPCGRPCSTATUSCODEVALUES_INTERNAL,RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,RPCGRPCSTATUSCODEVALUES_DATA_LOSS,RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,RpcGrpcStatusCodeValues,TMP_MESSAGETYPEVALUES_SENT,TMP_MESSAGETYPEVALUES_RECEIVED,MESSAGETYPEVALUES_SENT,MESSAGETYPEVALUES_RECEIVED,MessageTypeValues,init_SemanticAttributes=__esmMin((()=>{init_utils(),TMP_AWS_LAMBDA_INVOKED_ARN=`aws.lambda.invoked_arn`,TMP_DB_SYSTEM=`db.system`,TMP_DB_CONNECTION_STRING=`db.connection_string`,TMP_DB_USER=`db.user`,TMP_DB_JDBC_DRIVER_CLASSNAME=`db.jdbc.driver_classname`,TMP_DB_NAME=`db.name`,TMP_DB_STATEMENT=`db.statement`,TMP_DB_OPERATION=`db.operation`,TMP_DB_MSSQL_INSTANCE_NAME=`db.mssql.instance_name`,TMP_DB_CASSANDRA_KEYSPACE=`db.cassandra.keyspace`,TMP_DB_CASSANDRA_PAGE_SIZE=`db.cassandra.page_size`,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL=`db.cassandra.consistency_level`,TMP_DB_CASSANDRA_TABLE=`db.cassandra.table`,TMP_DB_CASSANDRA_IDEMPOTENCE=`db.cassandra.idempotence`,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT=`db.cassandra.speculative_execution_count`,TMP_DB_CASSANDRA_COORDINATOR_ID=`db.cassandra.coordinator.id`,TMP_DB_CASSANDRA_COORDINATOR_DC=`db.cassandra.coordinator.dc`,TMP_DB_HBASE_NAMESPACE=`db.hbase.namespace`,TMP_DB_REDIS_DATABASE_INDEX=`db.redis.database_index`,TMP_DB_MONGODB_COLLECTION=`db.mongodb.collection`,TMP_DB_SQL_TABLE=`db.sql.table`,TMP_EXCEPTION_TYPE=`exception.type`,TMP_EXCEPTION_MESSAGE=`exception.message`,TMP_EXCEPTION_STACKTRACE=`exception.stacktrace`,TMP_EXCEPTION_ESCAPED=`exception.escaped`,TMP_FAAS_TRIGGER=`faas.trigger`,TMP_FAAS_EXECUTION=`faas.execution`,TMP_FAAS_DOCUMENT_COLLECTION=`faas.document.collection`,TMP_FAAS_DOCUMENT_OPERATION=`faas.document.operation`,TMP_FAAS_DOCUMENT_TIME=`faas.document.time`,TMP_FAAS_DOCUMENT_NAME=`faas.document.name`,TMP_FAAS_TIME=`faas.time`,TMP_FAAS_CRON=`faas.cron`,TMP_FAAS_COLDSTART=`faas.coldstart`,TMP_FAAS_INVOKED_NAME=`faas.invoked_name`,TMP_FAAS_INVOKED_PROVIDER=`faas.invoked_provider`,TMP_FAAS_INVOKED_REGION=`faas.invoked_region`,TMP_NET_TRANSPORT=`net.transport`,TMP_NET_PEER_IP=`net.peer.ip`,TMP_NET_PEER_PORT=`net.peer.port`,TMP_NET_PEER_NAME=`net.peer.name`,TMP_NET_HOST_IP=`net.host.ip`,TMP_NET_HOST_PORT=`net.host.port`,TMP_NET_HOST_NAME=`net.host.name`,TMP_NET_HOST_CONNECTION_TYPE=`net.host.connection.type`,TMP_NET_HOST_CONNECTION_SUBTYPE=`net.host.connection.subtype`,TMP_NET_HOST_CARRIER_NAME=`net.host.carrier.name`,TMP_NET_HOST_CARRIER_MCC=`net.host.carrier.mcc`,TMP_NET_HOST_CARRIER_MNC=`net.host.carrier.mnc`,TMP_NET_HOST_CARRIER_ICC=`net.host.carrier.icc`,TMP_PEER_SERVICE=`peer.service`,TMP_ENDUSER_ID=`enduser.id`,TMP_ENDUSER_ROLE=`enduser.role`,TMP_ENDUSER_SCOPE=`enduser.scope`,TMP_THREAD_ID=`thread.id`,TMP_THREAD_NAME=`thread.name`,TMP_CODE_FUNCTION=`code.function`,TMP_CODE_NAMESPACE=`code.namespace`,TMP_CODE_FILEPATH=`code.filepath`,TMP_CODE_LINENO=`code.lineno`,TMP_HTTP_METHOD=`http.method`,TMP_HTTP_URL=`http.url`,TMP_HTTP_TARGET=`http.target`,TMP_HTTP_HOST=`http.host`,TMP_HTTP_SCHEME=`http.scheme`,TMP_HTTP_STATUS_CODE=`http.status_code`,TMP_HTTP_FLAVOR=`http.flavor`,TMP_HTTP_USER_AGENT=`http.user_agent`,TMP_HTTP_REQUEST_CONTENT_LENGTH=`http.request_content_length`,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=`http.request_content_length_uncompressed`,TMP_HTTP_RESPONSE_CONTENT_LENGTH=`http.response_content_length`,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED=`http.response_content_length_uncompressed`,TMP_HTTP_SERVER_NAME=`http.server_name`,TMP_HTTP_ROUTE=`http.route`,TMP_HTTP_CLIENT_IP=`http.client_ip`,TMP_AWS_DYNAMODB_TABLE_NAMES=`aws.dynamodb.table_names`,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY=`aws.dynamodb.consumed_capacity`,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS=`aws.dynamodb.item_collection_metrics`,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY=`aws.dynamodb.provisioned_read_capacity`,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY=`aws.dynamodb.provisioned_write_capacity`,TMP_AWS_DYNAMODB_CONSISTENT_READ=`aws.dynamodb.consistent_read`,TMP_AWS_DYNAMODB_PROJECTION=`aws.dynamodb.projection`,TMP_AWS_DYNAMODB_LIMIT=`aws.dynamodb.limit`,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET=`aws.dynamodb.attributes_to_get`,TMP_AWS_DYNAMODB_INDEX_NAME=`aws.dynamodb.index_name`,TMP_AWS_DYNAMODB_SELECT=`aws.dynamodb.select`,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES=`aws.dynamodb.global_secondary_indexes`,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES=`aws.dynamodb.local_secondary_indexes`,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE=`aws.dynamodb.exclusive_start_table`,TMP_AWS_DYNAMODB_TABLE_COUNT=`aws.dynamodb.table_count`,TMP_AWS_DYNAMODB_SCAN_FORWARD=`aws.dynamodb.scan_forward`,TMP_AWS_DYNAMODB_SEGMENT=`aws.dynamodb.segment`,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS=`aws.dynamodb.total_segments`,TMP_AWS_DYNAMODB_COUNT=`aws.dynamodb.count`,TMP_AWS_DYNAMODB_SCANNED_COUNT=`aws.dynamodb.scanned_count`,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS=`aws.dynamodb.attribute_definitions`,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES=`aws.dynamodb.global_secondary_index_updates`,TMP_MESSAGING_SYSTEM=`messaging.system`,TMP_MESSAGING_DESTINATION=`messaging.destination`,TMP_MESSAGING_DESTINATION_KIND=`messaging.destination_kind`,TMP_MESSAGING_TEMP_DESTINATION=`messaging.temp_destination`,TMP_MESSAGING_PROTOCOL=`messaging.protocol`,TMP_MESSAGING_PROTOCOL_VERSION=`messaging.protocol_version`,TMP_MESSAGING_URL=`messaging.url`,TMP_MESSAGING_MESSAGE_ID=`messaging.message_id`,TMP_MESSAGING_CONVERSATION_ID=`messaging.conversation_id`,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES=`messaging.message_payload_size_bytes`,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES=`messaging.message_payload_compressed_size_bytes`,TMP_MESSAGING_OPERATION=`messaging.operation`,TMP_MESSAGING_CONSUMER_ID=`messaging.consumer_id`,TMP_MESSAGING_RABBITMQ_ROUTING_KEY=`messaging.rabbitmq.routing_key`,TMP_MESSAGING_KAFKA_MESSAGE_KEY=`messaging.kafka.message_key`,TMP_MESSAGING_KAFKA_CONSUMER_GROUP=`messaging.kafka.consumer_group`,TMP_MESSAGING_KAFKA_CLIENT_ID=`messaging.kafka.client_id`,TMP_MESSAGING_KAFKA_PARTITION=`messaging.kafka.partition`,TMP_MESSAGING_KAFKA_TOMBSTONE=`messaging.kafka.tombstone`,TMP_RPC_SYSTEM=`rpc.system`,TMP_RPC_SERVICE=`rpc.service`,TMP_RPC_METHOD=`rpc.method`,TMP_RPC_GRPC_STATUS_CODE=`rpc.grpc.status_code`,TMP_RPC_JSONRPC_VERSION=`rpc.jsonrpc.version`,TMP_RPC_JSONRPC_REQUEST_ID=`rpc.jsonrpc.request_id`,TMP_RPC_JSONRPC_ERROR_CODE=`rpc.jsonrpc.error_code`,TMP_RPC_JSONRPC_ERROR_MESSAGE=`rpc.jsonrpc.error_message`,TMP_MESSAGE_TYPE=`message.type`,TMP_MESSAGE_ID=`message.id`,TMP_MESSAGE_COMPRESSED_SIZE=`message.compressed_size`,TMP_MESSAGE_UNCOMPRESSED_SIZE=`message.uncompressed_size`,SEMATTRS_AWS_LAMBDA_INVOKED_ARN=TMP_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_DB_SYSTEM=TMP_DB_SYSTEM,SEMATTRS_DB_CONNECTION_STRING=TMP_DB_CONNECTION_STRING,SEMATTRS_DB_USER=TMP_DB_USER,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME=TMP_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_NAME=TMP_DB_NAME,SEMATTRS_DB_STATEMENT=TMP_DB_STATEMENT,SEMATTRS_DB_OPERATION=TMP_DB_OPERATION,SEMATTRS_DB_MSSQL_INSTANCE_NAME=TMP_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_CASSANDRA_KEYSPACE=TMP_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE=TMP_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL=TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_TABLE=TMP_DB_CASSANDRA_TABLE,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE=TMP_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT=TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID=TMP_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC=TMP_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_HBASE_NAMESPACE=TMP_DB_HBASE_NAMESPACE,SEMATTRS_DB_REDIS_DATABASE_INDEX=TMP_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_MONGODB_COLLECTION=TMP_DB_MONGODB_COLLECTION,SEMATTRS_DB_SQL_TABLE=TMP_DB_SQL_TABLE,SEMATTRS_EXCEPTION_TYPE=TMP_EXCEPTION_TYPE,SEMATTRS_EXCEPTION_MESSAGE=TMP_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE=TMP_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_ESCAPED=TMP_EXCEPTION_ESCAPED,SEMATTRS_FAAS_TRIGGER=TMP_FAAS_TRIGGER,SEMATTRS_FAAS_EXECUTION=TMP_FAAS_EXECUTION,SEMATTRS_FAAS_DOCUMENT_COLLECTION=TMP_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_OPERATION=TMP_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME=TMP_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_DOCUMENT_NAME=TMP_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_TIME=TMP_FAAS_TIME,SEMATTRS_FAAS_CRON=TMP_FAAS_CRON,SEMATTRS_FAAS_COLDSTART=TMP_FAAS_COLDSTART,SEMATTRS_FAAS_INVOKED_NAME=TMP_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER=TMP_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION=TMP_FAAS_INVOKED_REGION,SEMATTRS_NET_TRANSPORT=TMP_NET_TRANSPORT,SEMATTRS_NET_PEER_IP=TMP_NET_PEER_IP,SEMATTRS_NET_PEER_PORT=TMP_NET_PEER_PORT,SEMATTRS_NET_PEER_NAME=TMP_NET_PEER_NAME,SEMATTRS_NET_HOST_IP=TMP_NET_HOST_IP,SEMATTRS_NET_HOST_PORT=TMP_NET_HOST_PORT,SEMATTRS_NET_HOST_NAME=TMP_NET_HOST_NAME,SEMATTRS_NET_HOST_CONNECTION_TYPE=TMP_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE=TMP_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CARRIER_NAME=TMP_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CARRIER_MCC=TMP_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC=TMP_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_ICC=TMP_NET_HOST_CARRIER_ICC,SEMATTRS_PEER_SERVICE=TMP_PEER_SERVICE,SEMATTRS_ENDUSER_ID=TMP_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE=TMP_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE=TMP_ENDUSER_SCOPE,SEMATTRS_THREAD_ID=TMP_THREAD_ID,SEMATTRS_THREAD_NAME=TMP_THREAD_NAME,SEMATTRS_CODE_FUNCTION=TMP_CODE_FUNCTION,SEMATTRS_CODE_NAMESPACE=TMP_CODE_NAMESPACE,SEMATTRS_CODE_FILEPATH=TMP_CODE_FILEPATH,SEMATTRS_CODE_LINENO=TMP_CODE_LINENO,SEMATTRS_HTTP_METHOD=TMP_HTTP_METHOD,SEMATTRS_HTTP_URL=TMP_HTTP_URL,SEMATTRS_HTTP_TARGET=TMP_HTTP_TARGET,SEMATTRS_HTTP_HOST=TMP_HTTP_HOST,SEMATTRS_HTTP_SCHEME=TMP_HTTP_SCHEME,SEMATTRS_HTTP_STATUS_CODE=TMP_HTTP_STATUS_CODE,SEMATTRS_HTTP_FLAVOR=TMP_HTTP_FLAVOR,SEMATTRS_HTTP_USER_AGENT=TMP_HTTP_USER_AGENT,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH=TMP_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH=TMP_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED=TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_SERVER_NAME=TMP_HTTP_SERVER_NAME,SEMATTRS_HTTP_ROUTE=TMP_HTTP_ROUTE,SEMATTRS_HTTP_CLIENT_IP=TMP_HTTP_CLIENT_IP,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES=TMP_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY=TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS=TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY=TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY=TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ=TMP_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_PROJECTION=TMP_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_LIMIT=TMP_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET=TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_INDEX_NAME=TMP_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_SELECT=TMP_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES=TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES=TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE=TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT=TMP_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD=TMP_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT=TMP_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS=TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_DYNAMODB_COUNT=TMP_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT=TMP_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS=TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES=TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_MESSAGING_SYSTEM=TMP_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_DESTINATION=TMP_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND=TMP_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_TEMP_DESTINATION=TMP_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_PROTOCOL=TMP_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION=TMP_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_URL=TMP_MESSAGING_URL,SEMATTRS_MESSAGING_MESSAGE_ID=TMP_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_CONVERSATION_ID=TMP_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES=TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES=TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION=TMP_MESSAGING_OPERATION,SEMATTRS_MESSAGING_CONSUMER_ID=TMP_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY=TMP_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY=TMP_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP=TMP_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID=TMP_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_PARTITION=TMP_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE=TMP_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_RPC_SYSTEM=TMP_RPC_SYSTEM,SEMATTRS_RPC_SERVICE=TMP_RPC_SERVICE,SEMATTRS_RPC_METHOD=TMP_RPC_METHOD,SEMATTRS_RPC_GRPC_STATUS_CODE=TMP_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_VERSION=TMP_RPC_JSONRPC_VERSION,SEMATTRS_RPC_JSONRPC_REQUEST_ID=TMP_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_ERROR_CODE=TMP_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE=TMP_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_MESSAGE_TYPE=TMP_MESSAGE_TYPE,SEMATTRS_MESSAGE_ID=TMP_MESSAGE_ID,SEMATTRS_MESSAGE_COMPRESSED_SIZE=TMP_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE=TMP_MESSAGE_UNCOMPRESSED_SIZE,SemanticAttributes=createConstMap([TMP_AWS_LAMBDA_INVOKED_ARN,TMP_DB_SYSTEM,TMP_DB_CONNECTION_STRING,TMP_DB_USER,TMP_DB_JDBC_DRIVER_CLASSNAME,TMP_DB_NAME,TMP_DB_STATEMENT,TMP_DB_OPERATION,TMP_DB_MSSQL_INSTANCE_NAME,TMP_DB_CASSANDRA_KEYSPACE,TMP_DB_CASSANDRA_PAGE_SIZE,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,TMP_DB_CASSANDRA_TABLE,TMP_DB_CASSANDRA_IDEMPOTENCE,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,TMP_DB_CASSANDRA_COORDINATOR_ID,TMP_DB_CASSANDRA_COORDINATOR_DC,TMP_DB_HBASE_NAMESPACE,TMP_DB_REDIS_DATABASE_INDEX,TMP_DB_MONGODB_COLLECTION,TMP_DB_SQL_TABLE,TMP_EXCEPTION_TYPE,TMP_EXCEPTION_MESSAGE,TMP_EXCEPTION_STACKTRACE,TMP_EXCEPTION_ESCAPED,TMP_FAAS_TRIGGER,TMP_FAAS_EXECUTION,TMP_FAAS_DOCUMENT_COLLECTION,TMP_FAAS_DOCUMENT_OPERATION,TMP_FAAS_DOCUMENT_TIME,TMP_FAAS_DOCUMENT_NAME,TMP_FAAS_TIME,TMP_FAAS_CRON,TMP_FAAS_COLDSTART,TMP_FAAS_INVOKED_NAME,TMP_FAAS_INVOKED_PROVIDER,TMP_FAAS_INVOKED_REGION,TMP_NET_TRANSPORT,TMP_NET_PEER_IP,TMP_NET_PEER_PORT,TMP_NET_PEER_NAME,TMP_NET_HOST_IP,TMP_NET_HOST_PORT,TMP_NET_HOST_NAME,TMP_NET_HOST_CONNECTION_TYPE,TMP_NET_HOST_CONNECTION_SUBTYPE,TMP_NET_HOST_CARRIER_NAME,TMP_NET_HOST_CARRIER_MCC,TMP_NET_HOST_CARRIER_MNC,TMP_NET_HOST_CARRIER_ICC,TMP_PEER_SERVICE,TMP_ENDUSER_ID,TMP_ENDUSER_ROLE,TMP_ENDUSER_SCOPE,TMP_THREAD_ID,TMP_THREAD_NAME,TMP_CODE_FUNCTION,TMP_CODE_NAMESPACE,TMP_CODE_FILEPATH,TMP_CODE_LINENO,TMP_HTTP_METHOD,TMP_HTTP_URL,TMP_HTTP_TARGET,TMP_HTTP_HOST,TMP_HTTP_SCHEME,TMP_HTTP_STATUS_CODE,TMP_HTTP_FLAVOR,TMP_HTTP_USER_AGENT,TMP_HTTP_REQUEST_CONTENT_LENGTH,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_RESPONSE_CONTENT_LENGTH,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_SERVER_NAME,TMP_HTTP_ROUTE,TMP_HTTP_CLIENT_IP,TMP_AWS_DYNAMODB_TABLE_NAMES,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,TMP_AWS_DYNAMODB_CONSISTENT_READ,TMP_AWS_DYNAMODB_PROJECTION,TMP_AWS_DYNAMODB_LIMIT,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,TMP_AWS_DYNAMODB_INDEX_NAME,TMP_AWS_DYNAMODB_SELECT,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,TMP_AWS_DYNAMODB_TABLE_COUNT,TMP_AWS_DYNAMODB_SCAN_FORWARD,TMP_AWS_DYNAMODB_SEGMENT,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,TMP_AWS_DYNAMODB_COUNT,TMP_AWS_DYNAMODB_SCANNED_COUNT,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,TMP_MESSAGING_SYSTEM,TMP_MESSAGING_DESTINATION,TMP_MESSAGING_DESTINATION_KIND,TMP_MESSAGING_TEMP_DESTINATION,TMP_MESSAGING_PROTOCOL,TMP_MESSAGING_PROTOCOL_VERSION,TMP_MESSAGING_URL,TMP_MESSAGING_MESSAGE_ID,TMP_MESSAGING_CONVERSATION_ID,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,TMP_MESSAGING_OPERATION,TMP_MESSAGING_CONSUMER_ID,TMP_MESSAGING_RABBITMQ_ROUTING_KEY,TMP_MESSAGING_KAFKA_MESSAGE_KEY,TMP_MESSAGING_KAFKA_CONSUMER_GROUP,TMP_MESSAGING_KAFKA_CLIENT_ID,TMP_MESSAGING_KAFKA_PARTITION,TMP_MESSAGING_KAFKA_TOMBSTONE,TMP_RPC_SYSTEM,TMP_RPC_SERVICE,TMP_RPC_METHOD,TMP_RPC_GRPC_STATUS_CODE,TMP_RPC_JSONRPC_VERSION,TMP_RPC_JSONRPC_REQUEST_ID,TMP_RPC_JSONRPC_ERROR_CODE,TMP_RPC_JSONRPC_ERROR_MESSAGE,TMP_MESSAGE_TYPE,TMP_MESSAGE_ID,TMP_MESSAGE_COMPRESSED_SIZE,TMP_MESSAGE_UNCOMPRESSED_SIZE]),TMP_DBSYSTEMVALUES_OTHER_SQL=`other_sql`,TMP_DBSYSTEMVALUES_MSSQL=`mssql`,TMP_DBSYSTEMVALUES_MYSQL=`mysql`,TMP_DBSYSTEMVALUES_ORACLE=`oracle`,TMP_DBSYSTEMVALUES_DB2=`db2`,TMP_DBSYSTEMVALUES_POSTGRESQL=`postgresql`,TMP_DBSYSTEMVALUES_REDSHIFT=`redshift`,TMP_DBSYSTEMVALUES_HIVE=`hive`,TMP_DBSYSTEMVALUES_CLOUDSCAPE=`cloudscape`,TMP_DBSYSTEMVALUES_HSQLDB=`hsqldb`,TMP_DBSYSTEMVALUES_PROGRESS=`progress`,TMP_DBSYSTEMVALUES_MAXDB=`maxdb`,TMP_DBSYSTEMVALUES_HANADB=`hanadb`,TMP_DBSYSTEMVALUES_INGRES=`ingres`,TMP_DBSYSTEMVALUES_FIRSTSQL=`firstsql`,TMP_DBSYSTEMVALUES_EDB=`edb`,TMP_DBSYSTEMVALUES_CACHE=`cache`,TMP_DBSYSTEMVALUES_ADABAS=`adabas`,TMP_DBSYSTEMVALUES_FIREBIRD=`firebird`,TMP_DBSYSTEMVALUES_DERBY=`derby`,TMP_DBSYSTEMVALUES_FILEMAKER=`filemaker`,TMP_DBSYSTEMVALUES_INFORMIX=`informix`,TMP_DBSYSTEMVALUES_INSTANTDB=`instantdb`,TMP_DBSYSTEMVALUES_INTERBASE=`interbase`,TMP_DBSYSTEMVALUES_MARIADB=`mariadb`,TMP_DBSYSTEMVALUES_NETEZZA=`netezza`,TMP_DBSYSTEMVALUES_PERVASIVE=`pervasive`,TMP_DBSYSTEMVALUES_POINTBASE=`pointbase`,TMP_DBSYSTEMVALUES_SQLITE=`sqlite`,TMP_DBSYSTEMVALUES_SYBASE=`sybase`,TMP_DBSYSTEMVALUES_TERADATA=`teradata`,TMP_DBSYSTEMVALUES_VERTICA=`vertica`,TMP_DBSYSTEMVALUES_H2=`h2`,TMP_DBSYSTEMVALUES_COLDFUSION=`coldfusion`,TMP_DBSYSTEMVALUES_CASSANDRA=`cassandra`,TMP_DBSYSTEMVALUES_HBASE=`hbase`,TMP_DBSYSTEMVALUES_MONGODB=`mongodb`,TMP_DBSYSTEMVALUES_REDIS=`redis`,TMP_DBSYSTEMVALUES_COUCHBASE=`couchbase`,TMP_DBSYSTEMVALUES_COUCHDB=`couchdb`,TMP_DBSYSTEMVALUES_COSMOSDB=`cosmosdb`,TMP_DBSYSTEMVALUES_DYNAMODB=`dynamodb`,TMP_DBSYSTEMVALUES_NEO4J=`neo4j`,TMP_DBSYSTEMVALUES_GEODE=`geode`,TMP_DBSYSTEMVALUES_ELASTICSEARCH=`elasticsearch`,TMP_DBSYSTEMVALUES_MEMCACHED=`memcached`,TMP_DBSYSTEMVALUES_COCKROACHDB=`cockroachdb`,DBSYSTEMVALUES_OTHER_SQL=TMP_DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_MSSQL=TMP_DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL=TMP_DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_ORACLE=TMP_DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_POSTGRESQL=TMP_DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_REDSHIFT=TMP_DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_HIVE=TMP_DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_CLOUDSCAPE=TMP_DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_HSQLDB=TMP_DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_PROGRESS=TMP_DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_MAXDB=TMP_DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_HANADB=TMP_DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_INGRES=TMP_DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_FIRSTSQL=TMP_DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_CACHE=TMP_DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_ADABAS=TMP_DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_FIREBIRD=TMP_DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_DERBY=TMP_DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_FILEMAKER=TMP_DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_INFORMIX=TMP_DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INSTANTDB=TMP_DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE=TMP_DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB=TMP_DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_NETEZZA=TMP_DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_PERVASIVE=TMP_DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE=TMP_DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_SQLITE=TMP_DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE=TMP_DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA=TMP_DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA=TMP_DBSYSTEMVALUES_VERTICA,DBSYSTEMVALUES_COLDFUSION=TMP_DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_CASSANDRA=TMP_DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_HBASE=TMP_DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_MONGODB=TMP_DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_REDIS=TMP_DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_COUCHBASE=TMP_DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB=TMP_DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_COSMOSDB=TMP_DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_DYNAMODB=TMP_DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_NEO4J=TMP_DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_GEODE=TMP_DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_ELASTICSEARCH=TMP_DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_MEMCACHED=TMP_DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_COCKROACHDB=TMP_DBSYSTEMVALUES_COCKROACHDB,DbSystemValues=createConstMap([TMP_DBSYSTEMVALUES_OTHER_SQL,TMP_DBSYSTEMVALUES_MSSQL,TMP_DBSYSTEMVALUES_MYSQL,TMP_DBSYSTEMVALUES_ORACLE,TMP_DBSYSTEMVALUES_DB2,TMP_DBSYSTEMVALUES_POSTGRESQL,TMP_DBSYSTEMVALUES_REDSHIFT,TMP_DBSYSTEMVALUES_HIVE,TMP_DBSYSTEMVALUES_CLOUDSCAPE,TMP_DBSYSTEMVALUES_HSQLDB,TMP_DBSYSTEMVALUES_PROGRESS,TMP_DBSYSTEMVALUES_MAXDB,TMP_DBSYSTEMVALUES_HANADB,TMP_DBSYSTEMVALUES_INGRES,TMP_DBSYSTEMVALUES_FIRSTSQL,TMP_DBSYSTEMVALUES_EDB,TMP_DBSYSTEMVALUES_CACHE,TMP_DBSYSTEMVALUES_ADABAS,TMP_DBSYSTEMVALUES_FIREBIRD,TMP_DBSYSTEMVALUES_DERBY,TMP_DBSYSTEMVALUES_FILEMAKER,TMP_DBSYSTEMVALUES_INFORMIX,TMP_DBSYSTEMVALUES_INSTANTDB,TMP_DBSYSTEMVALUES_INTERBASE,TMP_DBSYSTEMVALUES_MARIADB,TMP_DBSYSTEMVALUES_NETEZZA,TMP_DBSYSTEMVALUES_PERVASIVE,TMP_DBSYSTEMVALUES_POINTBASE,TMP_DBSYSTEMVALUES_SQLITE,TMP_DBSYSTEMVALUES_SYBASE,TMP_DBSYSTEMVALUES_TERADATA,TMP_DBSYSTEMVALUES_VERTICA,TMP_DBSYSTEMVALUES_H2,TMP_DBSYSTEMVALUES_COLDFUSION,TMP_DBSYSTEMVALUES_CASSANDRA,TMP_DBSYSTEMVALUES_HBASE,TMP_DBSYSTEMVALUES_MONGODB,TMP_DBSYSTEMVALUES_REDIS,TMP_DBSYSTEMVALUES_COUCHBASE,TMP_DBSYSTEMVALUES_COUCHDB,TMP_DBSYSTEMVALUES_COSMOSDB,TMP_DBSYSTEMVALUES_DYNAMODB,TMP_DBSYSTEMVALUES_NEO4J,TMP_DBSYSTEMVALUES_GEODE,TMP_DBSYSTEMVALUES_ELASTICSEARCH,TMP_DBSYSTEMVALUES_MEMCACHED,TMP_DBSYSTEMVALUES_COCKROACHDB]),TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL=`all`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM=`each_quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM=`quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM=`local_quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE=`one`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO=`two`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE=`three`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE=`local_one`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY=`any`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL=`serial`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL=`local_serial`,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_THREE=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DbCassandraConsistencyLevelValues=createConstMap([TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL]),TMP_FAASTRIGGERVALUES_DATASOURCE=`datasource`,TMP_FAASTRIGGERVALUES_HTTP=`http`,TMP_FAASTRIGGERVALUES_PUBSUB=`pubsub`,TMP_FAASTRIGGERVALUES_TIMER=`timer`,TMP_FAASTRIGGERVALUES_OTHER=`other`,FAASTRIGGERVALUES_DATASOURCE=TMP_FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP=TMP_FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_PUBSUB=TMP_FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER=TMP_FAASTRIGGERVALUES_TIMER,FAASTRIGGERVALUES_OTHER=TMP_FAASTRIGGERVALUES_OTHER,FaasTriggerValues=createConstMap([TMP_FAASTRIGGERVALUES_DATASOURCE,TMP_FAASTRIGGERVALUES_HTTP,TMP_FAASTRIGGERVALUES_PUBSUB,TMP_FAASTRIGGERVALUES_TIMER,TMP_FAASTRIGGERVALUES_OTHER]),TMP_FAASDOCUMENTOPERATIONVALUES_INSERT=`insert`,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT=`edit`,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE=`delete`,FAASDOCUMENTOPERATIONVALUES_INSERT=TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,FAASDOCUMENTOPERATIONVALUES_EDIT=TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_DELETE=TMP_FAASDOCUMENTOPERATIONVALUES_DELETE,FaasDocumentOperationValues=createConstMap([TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE]),TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD=`alibaba_cloud`,TMP_FAASINVOKEDPROVIDERVALUES_AWS=`aws`,TMP_FAASINVOKEDPROVIDERVALUES_AZURE=`azure`,TMP_FAASINVOKEDPROVIDERVALUES_GCP=`gcp`,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD=TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AZURE=TMP_FAASINVOKEDPROVIDERVALUES_AZURE,FaasInvokedProviderValues=createConstMap([TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,TMP_FAASINVOKEDPROVIDERVALUES_AWS,TMP_FAASINVOKEDPROVIDERVALUES_AZURE,TMP_FAASINVOKEDPROVIDERVALUES_GCP]),TMP_NETTRANSPORTVALUES_IP_TCP=`ip_tcp`,TMP_NETTRANSPORTVALUES_IP_UDP=`ip_udp`,TMP_NETTRANSPORTVALUES_IP=`ip`,TMP_NETTRANSPORTVALUES_UNIX=`unix`,TMP_NETTRANSPORTVALUES_PIPE=`pipe`,TMP_NETTRANSPORTVALUES_INPROC=`inproc`,TMP_NETTRANSPORTVALUES_OTHER=`other`,NETTRANSPORTVALUES_IP_TCP=TMP_NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP=TMP_NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_UNIX=TMP_NETTRANSPORTVALUES_UNIX,NETTRANSPORTVALUES_PIPE=TMP_NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_INPROC=TMP_NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_OTHER=TMP_NETTRANSPORTVALUES_OTHER,NetTransportValues=createConstMap([TMP_NETTRANSPORTVALUES_IP_TCP,TMP_NETTRANSPORTVALUES_IP_UDP,TMP_NETTRANSPORTVALUES_IP,TMP_NETTRANSPORTVALUES_UNIX,TMP_NETTRANSPORTVALUES_PIPE,TMP_NETTRANSPORTVALUES_INPROC,TMP_NETTRANSPORTVALUES_OTHER]),TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI=`wifi`,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED=`wired`,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL=`cell`,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE=`unavailable`,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN=`unknown`,NETHOSTCONNECTIONTYPEVALUES_WIFI=TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED=TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,NETHOSTCONNECTIONTYPEVALUES_CELL=TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE=TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN=TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NetHostConnectionTypeValues=createConstMap([TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN]),TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS=`gprs`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE=`edge`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS=`umts`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA=`cdma`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0=`evdo_0`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A=`evdo_a`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT=`cdma2000_1xrtt`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA=`hsdpa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA=`hsupa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA=`hspa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN=`iden`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B=`evdo_b`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE=`lte`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD=`ehrpd`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP=`hspap`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM=`gsm`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA=`td_scdma`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN=`iwlan`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR=`nr`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA=`nrnsa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA=`lte_ca`,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NetHostConnectionSubtypeValues=createConstMap([TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA]),TMP_HTTPFLAVORVALUES_HTTP_1_0=`1.0`,TMP_HTTPFLAVORVALUES_HTTP_1_1=`1.1`,TMP_HTTPFLAVORVALUES_HTTP_2_0=`2.0`,TMP_HTTPFLAVORVALUES_SPDY=`SPDY`,TMP_HTTPFLAVORVALUES_QUIC=`QUIC`,HTTPFLAVORVALUES_SPDY=TMP_HTTPFLAVORVALUES_SPDY,HTTPFLAVORVALUES_QUIC=TMP_HTTPFLAVORVALUES_QUIC,HttpFlavorValues={HTTP_1_0:TMP_HTTPFLAVORVALUES_HTTP_1_0,HTTP_1_1:TMP_HTTPFLAVORVALUES_HTTP_1_1,HTTP_2_0:TMP_HTTPFLAVORVALUES_HTTP_2_0,SPDY:TMP_HTTPFLAVORVALUES_SPDY,QUIC:TMP_HTTPFLAVORVALUES_QUIC},TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE=`queue`,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC=`topic`,MESSAGINGDESTINATIONKINDVALUES_QUEUE=TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC=TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC,MessagingDestinationKindValues=createConstMap([TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC]),TMP_MESSAGINGOPERATIONVALUES_RECEIVE=`receive`,TMP_MESSAGINGOPERATIONVALUES_PROCESS=`process`,MESSAGINGOPERATIONVALUES_RECEIVE=TMP_MESSAGINGOPERATIONVALUES_RECEIVE,MESSAGINGOPERATIONVALUES_PROCESS=TMP_MESSAGINGOPERATIONVALUES_PROCESS,MessagingOperationValues=createConstMap([TMP_MESSAGINGOPERATIONVALUES_RECEIVE,TMP_MESSAGINGOPERATIONVALUES_PROCESS]),TMP_RPCGRPCSTATUSCODEVALUES_OK=0,TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED=1,TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN=2,TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT=3,TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED=4,TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND=5,TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS=6,TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED=7,TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED=8,TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION=9,TMP_RPCGRPCSTATUSCODEVALUES_ABORTED=10,TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE=11,TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED=12,TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL=13,TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE=14,TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS=15,TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED=16,RpcGrpcStatusCodeValues={OK:TMP_RPCGRPCSTATUSCODEVALUES_OK,CANCELLED:TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,UNKNOWN:TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,INVALID_ARGUMENT:TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,DEADLINE_EXCEEDED:TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,NOT_FOUND:TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,ALREADY_EXISTS:TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,PERMISSION_DENIED:TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,RESOURCE_EXHAUSTED:TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,FAILED_PRECONDITION:TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,ABORTED:TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,OUT_OF_RANGE:TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,UNIMPLEMENTED:TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,INTERNAL:TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,UNAVAILABLE:TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,DATA_LOSS:TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,UNAUTHENTICATED:TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED},TMP_MESSAGETYPEVALUES_SENT=`SENT`,TMP_MESSAGETYPEVALUES_RECEIVED=`RECEIVED`,MESSAGETYPEVALUES_SENT=TMP_MESSAGETYPEVALUES_SENT,MESSAGETYPEVALUES_RECEIVED=TMP_MESSAGETYPEVALUES_RECEIVED,MessageTypeValues=createConstMap([TMP_MESSAGETYPEVALUES_SENT,TMP_MESSAGETYPEVALUES_RECEIVED])})),init_trace=__esmMin((()=>{init_SemanticAttributes()})),TMP_CLOUD_PROVIDER,TMP_CLOUD_ACCOUNT_ID,TMP_CLOUD_REGION,TMP_CLOUD_AVAILABILITY_ZONE,TMP_CLOUD_PLATFORM,TMP_AWS_ECS_CONTAINER_ARN,TMP_AWS_ECS_CLUSTER_ARN,TMP_AWS_ECS_LAUNCHTYPE,TMP_AWS_ECS_TASK_ARN,TMP_AWS_ECS_TASK_FAMILY,TMP_AWS_ECS_TASK_REVISION,TMP_AWS_EKS_CLUSTER_ARN,TMP_AWS_LOG_GROUP_NAMES,TMP_AWS_LOG_GROUP_ARNS,TMP_AWS_LOG_STREAM_NAMES,TMP_AWS_LOG_STREAM_ARNS,TMP_CONTAINER_NAME,TMP_CONTAINER_ID,TMP_CONTAINER_RUNTIME,TMP_CONTAINER_IMAGE_NAME,TMP_CONTAINER_IMAGE_TAG,TMP_DEPLOYMENT_ENVIRONMENT,TMP_DEVICE_ID,TMP_DEVICE_MODEL_IDENTIFIER,TMP_DEVICE_MODEL_NAME,TMP_FAAS_NAME,TMP_FAAS_ID,TMP_FAAS_VERSION,TMP_FAAS_INSTANCE,TMP_FAAS_MAX_MEMORY,TMP_HOST_ID,TMP_HOST_NAME,TMP_HOST_TYPE,TMP_HOST_ARCH,TMP_HOST_IMAGE_NAME,TMP_HOST_IMAGE_ID,TMP_HOST_IMAGE_VERSION,TMP_K8S_CLUSTER_NAME,TMP_K8S_NODE_NAME,TMP_K8S_NODE_UID,TMP_K8S_NAMESPACE_NAME,TMP_K8S_POD_UID,TMP_K8S_POD_NAME,TMP_K8S_CONTAINER_NAME,TMP_K8S_REPLICASET_UID,TMP_K8S_REPLICASET_NAME,TMP_K8S_DEPLOYMENT_UID,TMP_K8S_DEPLOYMENT_NAME,TMP_K8S_STATEFULSET_UID,TMP_K8S_STATEFULSET_NAME,TMP_K8S_DAEMONSET_UID,TMP_K8S_DAEMONSET_NAME,TMP_K8S_JOB_UID,TMP_K8S_JOB_NAME,TMP_K8S_CRONJOB_UID,TMP_K8S_CRONJOB_NAME,TMP_OS_TYPE,TMP_OS_DESCRIPTION,TMP_OS_NAME,TMP_OS_VERSION,TMP_PROCESS_PID,TMP_PROCESS_EXECUTABLE_NAME,TMP_PROCESS_EXECUTABLE_PATH,TMP_PROCESS_COMMAND,TMP_PROCESS_COMMAND_LINE,TMP_PROCESS_COMMAND_ARGS,TMP_PROCESS_OWNER,TMP_PROCESS_RUNTIME_NAME,TMP_PROCESS_RUNTIME_VERSION,TMP_PROCESS_RUNTIME_DESCRIPTION,TMP_SERVICE_NAME,TMP_SERVICE_NAMESPACE,TMP_SERVICE_INSTANCE_ID,TMP_SERVICE_VERSION,TMP_TELEMETRY_SDK_NAME,TMP_TELEMETRY_SDK_LANGUAGE,TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRY_AUTO_VERSION,TMP_WEBENGINE_NAME,TMP_WEBENGINE_VERSION,TMP_WEBENGINE_DESCRIPTION,SEMRESATTRS_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_REGION,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM,SEMRESATTRS_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS,SEMRESATTRS_CONTAINER_NAME,SEMRESATTRS_CONTAINER_ID,SEMRESATTRS_CONTAINER_RUNTIME,SEMRESATTRS_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_NAME,SEMRESATTRS_FAAS_ID,SEMRESATTRS_FAAS_VERSION,SEMRESATTRS_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY,SEMRESATTRS_HOST_ID,SEMRESATTRS_HOST_NAME,SEMRESATTRS_HOST_TYPE,SEMRESATTRS_HOST_ARCH,SEMRESATTRS_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_VERSION,SEMRESATTRS_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID,SEMRESATTRS_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_POD_UID,SEMRESATTRS_K8S_POD_NAME,SEMRESATTRS_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_REPLICASET_UID,SEMRESATTRS_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_STATEFULSET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_JOB_UID,SEMRESATTRS_K8S_JOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID,SEMRESATTRS_K8S_CRONJOB_NAME,SEMRESATTRS_OS_TYPE,SEMRESATTRS_OS_DESCRIPTION,SEMRESATTRS_OS_NAME,SEMRESATTRS_OS_VERSION,SEMRESATTRS_PROCESS_PID,SEMRESATTRS_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_OWNER,SEMRESATTRS_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION,SEMRESATTRS_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION,SemanticResourceAttributes,TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,TMP_CLOUDPROVIDERVALUES_AWS,TMP_CLOUDPROVIDERVALUES_AZURE,TMP_CLOUDPROVIDERVALUES_GCP,CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AWS,CLOUDPROVIDERVALUES_AZURE,CLOUDPROVIDERVALUES_GCP,CloudProviderValues,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,TMP_CLOUDPLATFORMVALUES_AWS_EC2,TMP_CLOUDPLATFORMVALUES_AWS_ECS,TMP_CLOUDPLATFORMVALUES_AWS_EKS,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,TMP_CLOUDPLATFORMVALUES_AZURE_VM,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,TMP_CLOUDPLATFORMVALUES_AZURE_AKS,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CloudPlatformValues,TMP_AWSECSLAUNCHTYPEVALUES_EC2,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE,AWSECSLAUNCHTYPEVALUES_EC2,AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues,TMP_HOSTARCHVALUES_AMD64,TMP_HOSTARCHVALUES_ARM32,TMP_HOSTARCHVALUES_ARM64,TMP_HOSTARCHVALUES_IA64,TMP_HOSTARCHVALUES_PPC32,TMP_HOSTARCHVALUES_PPC64,TMP_HOSTARCHVALUES_X86,HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64,HOSTARCHVALUES_X86,HostArchValues,TMP_OSTYPEVALUES_WINDOWS,TMP_OSTYPEVALUES_LINUX,TMP_OSTYPEVALUES_DARWIN,TMP_OSTYPEVALUES_FREEBSD,TMP_OSTYPEVALUES_NETBSD,TMP_OSTYPEVALUES_OPENBSD,TMP_OSTYPEVALUES_DRAGONFLYBSD,TMP_OSTYPEVALUES_HPUX,TMP_OSTYPEVALUES_AIX,TMP_OSTYPEVALUES_SOLARIS,TMP_OSTYPEVALUES_Z_OS,OSTYPEVALUES_WINDOWS,OSTYPEVALUES_LINUX,OSTYPEVALUES_DARWIN,OSTYPEVALUES_FREEBSD,OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD,OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_HPUX,OSTYPEVALUES_AIX,OSTYPEVALUES_SOLARIS,OSTYPEVALUES_Z_OS,OsTypeValues,TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TMP_TELEMETRYSDKLANGUAGEVALUES_GO,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,TELEMETRYSDKLANGUAGEVALUES_CPP,TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_GO,TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PHP,TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS,TelemetrySdkLanguageValues,init_SemanticResourceAttributes=__esmMin((()=>{init_utils(),TMP_CLOUD_PROVIDER=`cloud.provider`,TMP_CLOUD_ACCOUNT_ID=`cloud.account.id`,TMP_CLOUD_REGION=`cloud.region`,TMP_CLOUD_AVAILABILITY_ZONE=`cloud.availability_zone`,TMP_CLOUD_PLATFORM=`cloud.platform`,TMP_AWS_ECS_CONTAINER_ARN=`aws.ecs.container.arn`,TMP_AWS_ECS_CLUSTER_ARN=`aws.ecs.cluster.arn`,TMP_AWS_ECS_LAUNCHTYPE=`aws.ecs.launchtype`,TMP_AWS_ECS_TASK_ARN=`aws.ecs.task.arn`,TMP_AWS_ECS_TASK_FAMILY=`aws.ecs.task.family`,TMP_AWS_ECS_TASK_REVISION=`aws.ecs.task.revision`,TMP_AWS_EKS_CLUSTER_ARN=`aws.eks.cluster.arn`,TMP_AWS_LOG_GROUP_NAMES=`aws.log.group.names`,TMP_AWS_LOG_GROUP_ARNS=`aws.log.group.arns`,TMP_AWS_LOG_STREAM_NAMES=`aws.log.stream.names`,TMP_AWS_LOG_STREAM_ARNS=`aws.log.stream.arns`,TMP_CONTAINER_NAME=`container.name`,TMP_CONTAINER_ID=`container.id`,TMP_CONTAINER_RUNTIME=`container.runtime`,TMP_CONTAINER_IMAGE_NAME=`container.image.name`,TMP_CONTAINER_IMAGE_TAG=`container.image.tag`,TMP_DEPLOYMENT_ENVIRONMENT=`deployment.environment`,TMP_DEVICE_ID=`device.id`,TMP_DEVICE_MODEL_IDENTIFIER=`device.model.identifier`,TMP_DEVICE_MODEL_NAME=`device.model.name`,TMP_FAAS_NAME=`faas.name`,TMP_FAAS_ID=`faas.id`,TMP_FAAS_VERSION=`faas.version`,TMP_FAAS_INSTANCE=`faas.instance`,TMP_FAAS_MAX_MEMORY=`faas.max_memory`,TMP_HOST_ID=`host.id`,TMP_HOST_NAME=`host.name`,TMP_HOST_TYPE=`host.type`,TMP_HOST_ARCH=`host.arch`,TMP_HOST_IMAGE_NAME=`host.image.name`,TMP_HOST_IMAGE_ID=`host.image.id`,TMP_HOST_IMAGE_VERSION=`host.image.version`,TMP_K8S_CLUSTER_NAME=`k8s.cluster.name`,TMP_K8S_NODE_NAME=`k8s.node.name`,TMP_K8S_NODE_UID=`k8s.node.uid`,TMP_K8S_NAMESPACE_NAME=`k8s.namespace.name`,TMP_K8S_POD_UID=`k8s.pod.uid`,TMP_K8S_POD_NAME=`k8s.pod.name`,TMP_K8S_CONTAINER_NAME=`k8s.container.name`,TMP_K8S_REPLICASET_UID=`k8s.replicaset.uid`,TMP_K8S_REPLICASET_NAME=`k8s.replicaset.name`,TMP_K8S_DEPLOYMENT_UID=`k8s.deployment.uid`,TMP_K8S_DEPLOYMENT_NAME=`k8s.deployment.name`,TMP_K8S_STATEFULSET_UID=`k8s.statefulset.uid`,TMP_K8S_STATEFULSET_NAME=`k8s.statefulset.name`,TMP_K8S_DAEMONSET_UID=`k8s.daemonset.uid`,TMP_K8S_DAEMONSET_NAME=`k8s.daemonset.name`,TMP_K8S_JOB_UID=`k8s.job.uid`,TMP_K8S_JOB_NAME=`k8s.job.name`,TMP_K8S_CRONJOB_UID=`k8s.cronjob.uid`,TMP_K8S_CRONJOB_NAME=`k8s.cronjob.name`,TMP_OS_TYPE=`os.type`,TMP_OS_DESCRIPTION=`os.description`,TMP_OS_NAME=`os.name`,TMP_OS_VERSION=`os.version`,TMP_PROCESS_PID=`process.pid`,TMP_PROCESS_EXECUTABLE_NAME=`process.executable.name`,TMP_PROCESS_EXECUTABLE_PATH=`process.executable.path`,TMP_PROCESS_COMMAND=`process.command`,TMP_PROCESS_COMMAND_LINE=`process.command_line`,TMP_PROCESS_COMMAND_ARGS=`process.command_args`,TMP_PROCESS_OWNER=`process.owner`,TMP_PROCESS_RUNTIME_NAME=`process.runtime.name`,TMP_PROCESS_RUNTIME_VERSION=`process.runtime.version`,TMP_PROCESS_RUNTIME_DESCRIPTION=`process.runtime.description`,TMP_SERVICE_NAME=`service.name`,TMP_SERVICE_NAMESPACE=`service.namespace`,TMP_SERVICE_INSTANCE_ID=`service.instance.id`,TMP_SERVICE_VERSION=`service.version`,TMP_TELEMETRY_SDK_NAME=`telemetry.sdk.name`,TMP_TELEMETRY_SDK_LANGUAGE=`telemetry.sdk.language`,TMP_TELEMETRY_SDK_VERSION=`telemetry.sdk.version`,TMP_TELEMETRY_AUTO_VERSION=`telemetry.auto.version`,TMP_WEBENGINE_NAME=`webengine.name`,TMP_WEBENGINE_VERSION=`webengine.version`,TMP_WEBENGINE_DESCRIPTION=`webengine.description`,SEMRESATTRS_CLOUD_PROVIDER=TMP_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_ACCOUNT_ID=TMP_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_REGION=TMP_CLOUD_REGION,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE=TMP_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM=TMP_CLOUD_PLATFORM,SEMRESATTRS_AWS_ECS_CONTAINER_ARN=TMP_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_CLUSTER_ARN=TMP_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE=TMP_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN=TMP_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY=TMP_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION=TMP_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN=TMP_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_NAMES=TMP_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_GROUP_ARNS=TMP_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES=TMP_AWS_LOG_STREAM_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS=TMP_AWS_LOG_STREAM_ARNS,SEMRESATTRS_CONTAINER_NAME=TMP_CONTAINER_NAME,SEMRESATTRS_CONTAINER_ID=TMP_CONTAINER_ID,SEMRESATTRS_CONTAINER_RUNTIME=TMP_CONTAINER_RUNTIME,SEMRESATTRS_CONTAINER_IMAGE_NAME=TMP_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG=TMP_CONTAINER_IMAGE_TAG,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT=TMP_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID=TMP_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER=TMP_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME=TMP_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_NAME=TMP_FAAS_NAME,SEMRESATTRS_FAAS_ID=TMP_FAAS_ID,SEMRESATTRS_FAAS_VERSION=TMP_FAAS_VERSION,SEMRESATTRS_FAAS_INSTANCE=TMP_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY=TMP_FAAS_MAX_MEMORY,SEMRESATTRS_HOST_ID=TMP_HOST_ID,SEMRESATTRS_HOST_NAME=TMP_HOST_NAME,SEMRESATTRS_HOST_TYPE=TMP_HOST_TYPE,SEMRESATTRS_HOST_ARCH=TMP_HOST_ARCH,SEMRESATTRS_HOST_IMAGE_NAME=TMP_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_ID=TMP_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_VERSION=TMP_HOST_IMAGE_VERSION,SEMRESATTRS_K8S_CLUSTER_NAME=TMP_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_NODE_NAME=TMP_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID=TMP_K8S_NODE_UID,SEMRESATTRS_K8S_NAMESPACE_NAME=TMP_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_POD_UID=TMP_K8S_POD_UID,SEMRESATTRS_K8S_POD_NAME=TMP_K8S_POD_NAME,SEMRESATTRS_K8S_CONTAINER_NAME=TMP_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_REPLICASET_UID=TMP_K8S_REPLICASET_UID,SEMRESATTRS_K8S_REPLICASET_NAME=TMP_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID=TMP_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME=TMP_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_STATEFULSET_UID=TMP_K8S_STATEFULSET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME=TMP_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID=TMP_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DAEMONSET_NAME=TMP_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_JOB_UID=TMP_K8S_JOB_UID,SEMRESATTRS_K8S_JOB_NAME=TMP_K8S_JOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID=TMP_K8S_CRONJOB_UID,SEMRESATTRS_K8S_CRONJOB_NAME=TMP_K8S_CRONJOB_NAME,SEMRESATTRS_OS_TYPE=TMP_OS_TYPE,SEMRESATTRS_OS_DESCRIPTION=TMP_OS_DESCRIPTION,SEMRESATTRS_OS_NAME=TMP_OS_NAME,SEMRESATTRS_OS_VERSION=TMP_OS_VERSION,SEMRESATTRS_PROCESS_PID=TMP_PROCESS_PID,SEMRESATTRS_PROCESS_EXECUTABLE_NAME=TMP_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH=TMP_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_COMMAND=TMP_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_LINE=TMP_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_COMMAND_ARGS=TMP_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_OWNER=TMP_PROCESS_OWNER,SEMRESATTRS_PROCESS_RUNTIME_NAME=TMP_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION=TMP_PROCESS_RUNTIME_VERSION,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION=TMP_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_SERVICE_NAME=TMP_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE=TMP_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_INSTANCE_ID=TMP_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_VERSION=TMP_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_SDK_NAME=TMP_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE=TMP_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION=TMP_TELEMETRY_SDK_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION=TMP_TELEMETRY_AUTO_VERSION,SEMRESATTRS_WEBENGINE_NAME=TMP_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION=TMP_WEBENGINE_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION=TMP_WEBENGINE_DESCRIPTION,SemanticResourceAttributes=createConstMap([TMP_CLOUD_PROVIDER,TMP_CLOUD_ACCOUNT_ID,TMP_CLOUD_REGION,TMP_CLOUD_AVAILABILITY_ZONE,TMP_CLOUD_PLATFORM,TMP_AWS_ECS_CONTAINER_ARN,TMP_AWS_ECS_CLUSTER_ARN,TMP_AWS_ECS_LAUNCHTYPE,TMP_AWS_ECS_TASK_ARN,TMP_AWS_ECS_TASK_FAMILY,TMP_AWS_ECS_TASK_REVISION,TMP_AWS_EKS_CLUSTER_ARN,TMP_AWS_LOG_GROUP_NAMES,TMP_AWS_LOG_GROUP_ARNS,TMP_AWS_LOG_STREAM_NAMES,TMP_AWS_LOG_STREAM_ARNS,TMP_CONTAINER_NAME,TMP_CONTAINER_ID,TMP_CONTAINER_RUNTIME,TMP_CONTAINER_IMAGE_NAME,TMP_CONTAINER_IMAGE_TAG,TMP_DEPLOYMENT_ENVIRONMENT,TMP_DEVICE_ID,TMP_DEVICE_MODEL_IDENTIFIER,TMP_DEVICE_MODEL_NAME,TMP_FAAS_NAME,TMP_FAAS_ID,TMP_FAAS_VERSION,TMP_FAAS_INSTANCE,TMP_FAAS_MAX_MEMORY,TMP_HOST_ID,TMP_HOST_NAME,TMP_HOST_TYPE,TMP_HOST_ARCH,TMP_HOST_IMAGE_NAME,TMP_HOST_IMAGE_ID,TMP_HOST_IMAGE_VERSION,TMP_K8S_CLUSTER_NAME,TMP_K8S_NODE_NAME,TMP_K8S_NODE_UID,TMP_K8S_NAMESPACE_NAME,TMP_K8S_POD_UID,TMP_K8S_POD_NAME,TMP_K8S_CONTAINER_NAME,TMP_K8S_REPLICASET_UID,TMP_K8S_REPLICASET_NAME,TMP_K8S_DEPLOYMENT_UID,TMP_K8S_DEPLOYMENT_NAME,TMP_K8S_STATEFULSET_UID,TMP_K8S_STATEFULSET_NAME,TMP_K8S_DAEMONSET_UID,TMP_K8S_DAEMONSET_NAME,TMP_K8S_JOB_UID,TMP_K8S_JOB_NAME,TMP_K8S_CRONJOB_UID,TMP_K8S_CRONJOB_NAME,TMP_OS_TYPE,TMP_OS_DESCRIPTION,TMP_OS_NAME,TMP_OS_VERSION,TMP_PROCESS_PID,TMP_PROCESS_EXECUTABLE_NAME,TMP_PROCESS_EXECUTABLE_PATH,TMP_PROCESS_COMMAND,TMP_PROCESS_COMMAND_LINE,TMP_PROCESS_COMMAND_ARGS,TMP_PROCESS_OWNER,TMP_PROCESS_RUNTIME_NAME,TMP_PROCESS_RUNTIME_VERSION,TMP_PROCESS_RUNTIME_DESCRIPTION,TMP_SERVICE_NAME,TMP_SERVICE_NAMESPACE,TMP_SERVICE_INSTANCE_ID,TMP_SERVICE_VERSION,TMP_TELEMETRY_SDK_NAME,TMP_TELEMETRY_SDK_LANGUAGE,TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRY_AUTO_VERSION,TMP_WEBENGINE_NAME,TMP_WEBENGINE_VERSION,TMP_WEBENGINE_DESCRIPTION]),TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD=`alibaba_cloud`,TMP_CLOUDPROVIDERVALUES_AWS=`aws`,TMP_CLOUDPROVIDERVALUES_AZURE=`azure`,TMP_CLOUDPROVIDERVALUES_GCP=`gcp`,CLOUDPROVIDERVALUES_ALIBABA_CLOUD=TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AZURE=TMP_CLOUDPROVIDERVALUES_AZURE,CloudProviderValues=createConstMap([TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,TMP_CLOUDPROVIDERVALUES_AWS,TMP_CLOUDPROVIDERVALUES_AZURE,TMP_CLOUDPROVIDERVALUES_GCP]),TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS=`alibaba_cloud_ecs`,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC=`alibaba_cloud_fc`,TMP_CLOUDPLATFORMVALUES_AWS_EC2=`aws_ec2`,TMP_CLOUDPLATFORMVALUES_AWS_ECS=`aws_ecs`,TMP_CLOUDPLATFORMVALUES_AWS_EKS=`aws_eks`,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA=`aws_lambda`,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK=`aws_elastic_beanstalk`,TMP_CLOUDPLATFORMVALUES_AZURE_VM=`azure_vm`,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES=`azure_container_instances`,TMP_CLOUDPLATFORMVALUES_AZURE_AKS=`azure_aks`,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS=`azure_functions`,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE=`azure_app_service`,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE=`gcp_compute_engine`,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN=`gcp_cloud_run`,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE=`gcp_kubernetes_engine`,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS=`gcp_cloud_functions`,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE=`gcp_app_engine`,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS=TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC=TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2=TMP_CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS=TMP_CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS=TMP_CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_LAMBDA=TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK=TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AZURE_VM=TMP_CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES=TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_AKS=TMP_CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS=TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE=TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN=TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS=TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_APP_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CloudPlatformValues=createConstMap([TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,TMP_CLOUDPLATFORMVALUES_AWS_EC2,TMP_CLOUDPLATFORMVALUES_AWS_ECS,TMP_CLOUDPLATFORMVALUES_AWS_EKS,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,TMP_CLOUDPLATFORMVALUES_AZURE_VM,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,TMP_CLOUDPLATFORMVALUES_AZURE_AKS,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE]),TMP_AWSECSLAUNCHTYPEVALUES_EC2=`ec2`,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE=`fargate`,AWSECSLAUNCHTYPEVALUES_FARGATE=TMP_AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues=createConstMap([TMP_AWSECSLAUNCHTYPEVALUES_EC2,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE]),TMP_HOSTARCHVALUES_AMD64=`amd64`,TMP_HOSTARCHVALUES_ARM32=`arm32`,TMP_HOSTARCHVALUES_ARM64=`arm64`,TMP_HOSTARCHVALUES_IA64=`ia64`,TMP_HOSTARCHVALUES_PPC32=`ppc32`,TMP_HOSTARCHVALUES_PPC64=`ppc64`,TMP_HOSTARCHVALUES_X86=`x86`,HOSTARCHVALUES_AMD64=TMP_HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32=TMP_HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64=TMP_HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64=TMP_HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32=TMP_HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64=TMP_HOSTARCHVALUES_PPC64,HostArchValues=createConstMap([TMP_HOSTARCHVALUES_AMD64,TMP_HOSTARCHVALUES_ARM32,TMP_HOSTARCHVALUES_ARM64,TMP_HOSTARCHVALUES_IA64,TMP_HOSTARCHVALUES_PPC32,TMP_HOSTARCHVALUES_PPC64,TMP_HOSTARCHVALUES_X86]),TMP_OSTYPEVALUES_WINDOWS=`windows`,TMP_OSTYPEVALUES_LINUX=`linux`,TMP_OSTYPEVALUES_DARWIN=`darwin`,TMP_OSTYPEVALUES_FREEBSD=`freebsd`,TMP_OSTYPEVALUES_NETBSD=`netbsd`,TMP_OSTYPEVALUES_OPENBSD=`openbsd`,TMP_OSTYPEVALUES_DRAGONFLYBSD=`dragonflybsd`,TMP_OSTYPEVALUES_HPUX=`hpux`,TMP_OSTYPEVALUES_AIX=`aix`,TMP_OSTYPEVALUES_SOLARIS=`solaris`,TMP_OSTYPEVALUES_Z_OS=`z_os`,OSTYPEVALUES_WINDOWS=TMP_OSTYPEVALUES_WINDOWS,OSTYPEVALUES_LINUX=TMP_OSTYPEVALUES_LINUX,OSTYPEVALUES_DARWIN=TMP_OSTYPEVALUES_DARWIN,OSTYPEVALUES_FREEBSD=TMP_OSTYPEVALUES_FREEBSD,OSTYPEVALUES_NETBSD=TMP_OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD=TMP_OSTYPEVALUES_OPENBSD,OSTYPEVALUES_DRAGONFLYBSD=TMP_OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_HPUX=TMP_OSTYPEVALUES_HPUX,OSTYPEVALUES_SOLARIS=TMP_OSTYPEVALUES_SOLARIS,OSTYPEVALUES_Z_OS=TMP_OSTYPEVALUES_Z_OS,OsTypeValues=createConstMap([TMP_OSTYPEVALUES_WINDOWS,TMP_OSTYPEVALUES_LINUX,TMP_OSTYPEVALUES_DARWIN,TMP_OSTYPEVALUES_FREEBSD,TMP_OSTYPEVALUES_NETBSD,TMP_OSTYPEVALUES_OPENBSD,TMP_OSTYPEVALUES_DRAGONFLYBSD,TMP_OSTYPEVALUES_HPUX,TMP_OSTYPEVALUES_AIX,TMP_OSTYPEVALUES_SOLARIS,TMP_OSTYPEVALUES_Z_OS]),TMP_TELEMETRYSDKLANGUAGEVALUES_CPP=`cpp`,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET=`dotnet`,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG=`erlang`,TMP_TELEMETRYSDKLANGUAGEVALUES_GO=`go`,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA=`java`,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS=`nodejs`,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP=`php`,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON=`python`,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY=`ruby`,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS=`webjs`,TELEMETRYSDKLANGUAGEVALUES_DOTNET=TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG=TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_JAVA=TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS=TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PYTHON=TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY=TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS=TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,TelemetrySdkLanguageValues=createConstMap([TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TMP_TELEMETRYSDKLANGUAGEVALUES_GO,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS])})),init_resource=__esmMin((()=>{init_SemanticResourceAttributes()})),ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE,ATTR_ASPNETCORE_RATE_LIMITING_POLICY,ATTR_ASPNETCORE_RATE_LIMITING_RESULT,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED,ATTR_CLIENT_ADDRESS,ATTR_CLIENT_PORT,ATTR_CODE_COLUMN_NUMBER,ATTR_CODE_FILE_PATH,ATTR_CODE_FUNCTION_NAME,ATTR_CODE_LINE_NUMBER,ATTR_CODE_STACKTRACE,ATTR_DB_COLLECTION_NAME,ATTR_DB_NAMESPACE,ATTR_DB_OPERATION_BATCH_SIZE,ATTR_DB_OPERATION_NAME,ATTR_DB_QUERY_SUMMARY,ATTR_DB_QUERY_TEXT,ATTR_DB_RESPONSE_STATUS_CODE,ATTR_DB_STORED_PROCEDURE_NAME,ATTR_DB_SYSTEM_NAME,DB_SYSTEM_NAME_VALUE_MARIADB,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER,DB_SYSTEM_NAME_VALUE_MYSQL,DB_SYSTEM_NAME_VALUE_POSTGRESQL,ATTR_DOTNET_GC_HEAP_GENERATION,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2,DOTNET_GC_HEAP_GENERATION_VALUE_LOH,DOTNET_GC_HEAP_GENERATION_VALUE_POH,ATTR_ERROR_TYPE,ERROR_TYPE_VALUE_OTHER,ATTR_EXCEPTION_ESCAPED,ATTR_EXCEPTION_MESSAGE,ATTR_EXCEPTION_STACKTRACE,ATTR_EXCEPTION_TYPE,ATTR_HTTP_REQUEST_HEADER,ATTR_HTTP_REQUEST_METHOD,HTTP_REQUEST_METHOD_VALUE_OTHER,HTTP_REQUEST_METHOD_VALUE_CONNECT,HTTP_REQUEST_METHOD_VALUE_DELETE,HTTP_REQUEST_METHOD_VALUE_GET,HTTP_REQUEST_METHOD_VALUE_HEAD,HTTP_REQUEST_METHOD_VALUE_OPTIONS,HTTP_REQUEST_METHOD_VALUE_PATCH,HTTP_REQUEST_METHOD_VALUE_POST,HTTP_REQUEST_METHOD_VALUE_PUT,HTTP_REQUEST_METHOD_VALUE_TRACE,ATTR_HTTP_REQUEST_METHOD_ORIGINAL,ATTR_HTTP_REQUEST_RESEND_COUNT,ATTR_HTTP_RESPONSE_HEADER,ATTR_HTTP_RESPONSE_STATUS_CODE,ATTR_HTTP_ROUTE,ATTR_JVM_GC_ACTION,ATTR_JVM_GC_NAME,ATTR_JVM_MEMORY_POOL_NAME,ATTR_JVM_MEMORY_TYPE,JVM_MEMORY_TYPE_VALUE_HEAP,JVM_MEMORY_TYPE_VALUE_NON_HEAP,ATTR_JVM_THREAD_DAEMON,ATTR_JVM_THREAD_STATE,JVM_THREAD_STATE_VALUE_BLOCKED,JVM_THREAD_STATE_VALUE_NEW,JVM_THREAD_STATE_VALUE_RUNNABLE,JVM_THREAD_STATE_VALUE_TERMINATED,JVM_THREAD_STATE_VALUE_TIMED_WAITING,JVM_THREAD_STATE_VALUE_WAITING,ATTR_NETWORK_LOCAL_ADDRESS,ATTR_NETWORK_LOCAL_PORT,ATTR_NETWORK_PEER_ADDRESS,ATTR_NETWORK_PEER_PORT,ATTR_NETWORK_PROTOCOL_NAME,ATTR_NETWORK_PROTOCOL_VERSION,ATTR_NETWORK_TRANSPORT,NETWORK_TRANSPORT_VALUE_PIPE,NETWORK_TRANSPORT_VALUE_QUIC,NETWORK_TRANSPORT_VALUE_TCP,NETWORK_TRANSPORT_VALUE_UDP,NETWORK_TRANSPORT_VALUE_UNIX,ATTR_NETWORK_TYPE,NETWORK_TYPE_VALUE_IPV4,NETWORK_TYPE_VALUE_IPV6,ATTR_OTEL_SCOPE_NAME,ATTR_OTEL_SCOPE_VERSION,ATTR_OTEL_STATUS_CODE,OTEL_STATUS_CODE_VALUE_ERROR,OTEL_STATUS_CODE_VALUE_OK,ATTR_OTEL_STATUS_DESCRIPTION,ATTR_SERVER_ADDRESS,ATTR_SERVER_PORT,ATTR_SERVICE_INSTANCE_ID,ATTR_SERVICE_NAME,ATTR_SERVICE_NAMESPACE,ATTR_SERVICE_VERSION,ATTR_SIGNALR_CONNECTION_STATUS,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT,ATTR_SIGNALR_TRANSPORT,SIGNALR_TRANSPORT_VALUE_LONG_POLLING,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS,ATTR_TELEMETRY_SDK_LANGUAGE,TELEMETRY_SDK_LANGUAGE_VALUE_CPP,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG,TELEMETRY_SDK_LANGUAGE_VALUE_GO,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,TELEMETRY_SDK_LANGUAGE_VALUE_PHP,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY,TELEMETRY_SDK_LANGUAGE_VALUE_RUST,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,ATTR_TELEMETRY_SDK_NAME,ATTR_TELEMETRY_SDK_VERSION,ATTR_URL_FRAGMENT,ATTR_URL_FULL,ATTR_URL_PATH,ATTR_URL_QUERY,ATTR_URL_SCHEME,ATTR_USER_AGENT_ORIGINAL,init_stable_attributes=__esmMin((()=>{ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT=`aspnetcore.diagnostics.exception.result`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED=`aborted`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED=`handled`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED=`skipped`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED=`unhandled`,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE=`aspnetcore.diagnostics.handler.type`,ATTR_ASPNETCORE_RATE_LIMITING_POLICY=`aspnetcore.rate_limiting.policy`,ATTR_ASPNETCORE_RATE_LIMITING_RESULT=`aspnetcore.rate_limiting.result`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED=`acquired`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER=`endpoint_limiter`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER=`global_limiter`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED=`request_canceled`,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED=`aspnetcore.request.is_unhandled`,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK=`aspnetcore.routing.is_fallback`,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS=`aspnetcore.routing.match_status`,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE=`failure`,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS=`success`,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED=`aspnetcore.user.is_authenticated`,ATTR_CLIENT_ADDRESS=`client.address`,ATTR_CLIENT_PORT=`client.port`,ATTR_CODE_COLUMN_NUMBER=`code.column.number`,ATTR_CODE_FILE_PATH=`code.file.path`,ATTR_CODE_FUNCTION_NAME=`code.function.name`,ATTR_CODE_LINE_NUMBER=`code.line.number`,ATTR_CODE_STACKTRACE=`code.stacktrace`,ATTR_DB_COLLECTION_NAME=`db.collection.name`,ATTR_DB_NAMESPACE=`db.namespace`,ATTR_DB_OPERATION_BATCH_SIZE=`db.operation.batch.size`,ATTR_DB_OPERATION_NAME=`db.operation.name`,ATTR_DB_QUERY_SUMMARY=`db.query.summary`,ATTR_DB_QUERY_TEXT=`db.query.text`,ATTR_DB_RESPONSE_STATUS_CODE=`db.response.status_code`,ATTR_DB_STORED_PROCEDURE_NAME=`db.stored_procedure.name`,ATTR_DB_SYSTEM_NAME=`db.system.name`,DB_SYSTEM_NAME_VALUE_MARIADB=`mariadb`,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER=`microsoft.sql_server`,DB_SYSTEM_NAME_VALUE_MYSQL=`mysql`,DB_SYSTEM_NAME_VALUE_POSTGRESQL=`postgresql`,ATTR_DOTNET_GC_HEAP_GENERATION=`dotnet.gc.heap.generation`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0=`gen0`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1=`gen1`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2=`gen2`,ATTR_ERROR_TYPE=`error.type`,ERROR_TYPE_VALUE_OTHER=`_OTHER`,ATTR_EXCEPTION_ESCAPED=`exception.escaped`,ATTR_EXCEPTION_MESSAGE=`exception.message`,ATTR_EXCEPTION_STACKTRACE=`exception.stacktrace`,ATTR_EXCEPTION_TYPE=`exception.type`,ATTR_HTTP_REQUEST_HEADER=e=>`http.request.header.${e}`,ATTR_HTTP_REQUEST_METHOD=`http.request.method`,HTTP_REQUEST_METHOD_VALUE_OTHER=`_OTHER`,HTTP_REQUEST_METHOD_VALUE_CONNECT=`CONNECT`,HTTP_REQUEST_METHOD_VALUE_DELETE=`DELETE`,HTTP_REQUEST_METHOD_VALUE_HEAD=`HEAD`,HTTP_REQUEST_METHOD_VALUE_OPTIONS=`OPTIONS`,HTTP_REQUEST_METHOD_VALUE_PATCH=`PATCH`,HTTP_REQUEST_METHOD_VALUE_POST=`POST`,HTTP_REQUEST_METHOD_VALUE_TRACE=`TRACE`,ATTR_HTTP_REQUEST_METHOD_ORIGINAL=`http.request.method_original`,ATTR_HTTP_REQUEST_RESEND_COUNT=`http.request.resend_count`,ATTR_HTTP_RESPONSE_HEADER=e=>`http.response.header.${e}`,ATTR_HTTP_RESPONSE_STATUS_CODE=`http.response.status_code`,ATTR_HTTP_ROUTE=`http.route`,ATTR_JVM_GC_ACTION=`jvm.gc.action`,ATTR_JVM_GC_NAME=`jvm.gc.name`,ATTR_JVM_MEMORY_POOL_NAME=`jvm.memory.pool.name`,ATTR_JVM_MEMORY_TYPE=`jvm.memory.type`,JVM_MEMORY_TYPE_VALUE_HEAP=`heap`,JVM_MEMORY_TYPE_VALUE_NON_HEAP=`non_heap`,ATTR_JVM_THREAD_DAEMON=`jvm.thread.daemon`,ATTR_JVM_THREAD_STATE=`jvm.thread.state`,JVM_THREAD_STATE_VALUE_BLOCKED=`blocked`,JVM_THREAD_STATE_VALUE_RUNNABLE=`runnable`,JVM_THREAD_STATE_VALUE_TERMINATED=`terminated`,JVM_THREAD_STATE_VALUE_TIMED_WAITING=`timed_waiting`,JVM_THREAD_STATE_VALUE_WAITING=`waiting`,ATTR_NETWORK_LOCAL_ADDRESS=`network.local.address`,ATTR_NETWORK_LOCAL_PORT=`network.local.port`,ATTR_NETWORK_PEER_ADDRESS=`network.peer.address`,ATTR_NETWORK_PEER_PORT=`network.peer.port`,ATTR_NETWORK_PROTOCOL_NAME=`network.protocol.name`,ATTR_NETWORK_PROTOCOL_VERSION=`network.protocol.version`,ATTR_NETWORK_TRANSPORT=`network.transport`,NETWORK_TRANSPORT_VALUE_PIPE=`pipe`,NETWORK_TRANSPORT_VALUE_QUIC=`quic`,NETWORK_TRANSPORT_VALUE_UNIX=`unix`,ATTR_NETWORK_TYPE=`network.type`,NETWORK_TYPE_VALUE_IPV4=`ipv4`,NETWORK_TYPE_VALUE_IPV6=`ipv6`,ATTR_OTEL_SCOPE_NAME=`otel.scope.name`,ATTR_OTEL_SCOPE_VERSION=`otel.scope.version`,ATTR_OTEL_STATUS_CODE=`otel.status_code`,OTEL_STATUS_CODE_VALUE_ERROR=`ERROR`,ATTR_OTEL_STATUS_DESCRIPTION=`otel.status_description`,ATTR_SERVER_ADDRESS=`server.address`,ATTR_SERVER_PORT=`server.port`,ATTR_SERVICE_INSTANCE_ID=`service.instance.id`,ATTR_SERVICE_NAME=`service.name`,ATTR_SERVICE_NAMESPACE=`service.namespace`,ATTR_SERVICE_VERSION=`service.version`,ATTR_SIGNALR_CONNECTION_STATUS=`signalr.connection.status`,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN=`app_shutdown`,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE=`normal_closure`,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT=`timeout`,ATTR_SIGNALR_TRANSPORT=`signalr.transport`,SIGNALR_TRANSPORT_VALUE_LONG_POLLING=`long_polling`,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS=`server_sent_events`,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS=`web_sockets`,ATTR_TELEMETRY_SDK_LANGUAGE=`telemetry.sdk.language`,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET=`dotnet`,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG=`erlang`,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA=`java`,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS=`nodejs`,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON=`python`,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY=`ruby`,TELEMETRY_SDK_LANGUAGE_VALUE_RUST=`rust`,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT=`swift`,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS=`webjs`,ATTR_TELEMETRY_SDK_NAME=`telemetry.sdk.name`,ATTR_TELEMETRY_SDK_VERSION=`telemetry.sdk.version`,ATTR_URL_FRAGMENT=`url.fragment`,ATTR_URL_FULL=`url.full`,ATTR_URL_PATH=`url.path`,ATTR_URL_QUERY=`url.query`,ATTR_URL_SCHEME=`url.scheme`,ATTR_USER_AGENT_ORIGINAL=`user_agent.original`})),METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS,METRIC_DB_CLIENT_OPERATION_DURATION,METRIC_DOTNET_ASSEMBLY_COUNT,METRIC_DOTNET_EXCEPTIONS,METRIC_DOTNET_GC_COLLECTIONS,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE,METRIC_DOTNET_GC_PAUSE_TIME,METRIC_DOTNET_JIT_COMPILATION_TIME,METRIC_DOTNET_JIT_COMPILED_IL_SIZE,METRIC_DOTNET_JIT_COMPILED_METHODS,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS,METRIC_DOTNET_PROCESS_CPU_COUNT,METRIC_DOTNET_PROCESS_CPU_TIME,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT,METRIC_DOTNET_TIMER_COUNT,METRIC_HTTP_CLIENT_REQUEST_DURATION,METRIC_HTTP_SERVER_REQUEST_DURATION,METRIC_JVM_CLASS_COUNT,METRIC_JVM_CLASS_LOADED,METRIC_JVM_CLASS_UNLOADED,METRIC_JVM_CPU_COUNT,METRIC_JVM_CPU_RECENT_UTILIZATION,METRIC_JVM_CPU_TIME,METRIC_JVM_GC_DURATION,METRIC_JVM_MEMORY_COMMITTED,METRIC_JVM_MEMORY_LIMIT,METRIC_JVM_MEMORY_USED,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC,METRIC_JVM_THREAD_COUNT,METRIC_KESTREL_ACTIVE_CONNECTIONS,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES,METRIC_KESTREL_CONNECTION_DURATION,METRIC_KESTREL_QUEUED_CONNECTIONS,METRIC_KESTREL_QUEUED_REQUESTS,METRIC_KESTREL_REJECTED_CONNECTIONS,METRIC_KESTREL_TLS_HANDSHAKE_DURATION,METRIC_KESTREL_UPGRADED_CONNECTIONS,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS,METRIC_SIGNALR_SERVER_CONNECTION_DURATION,init_stable_metrics=__esmMin((()=>{METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS=`aspnetcore.diagnostics.exceptions`,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES=`aspnetcore.rate_limiting.active_request_leases`,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS=`aspnetcore.rate_limiting.queued_requests`,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE=`aspnetcore.rate_limiting.request.time_in_queue`,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION=`aspnetcore.rate_limiting.request_lease.duration`,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS=`aspnetcore.rate_limiting.requests`,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS=`aspnetcore.routing.match_attempts`,METRIC_DB_CLIENT_OPERATION_DURATION=`db.client.operation.duration`,METRIC_DOTNET_ASSEMBLY_COUNT=`dotnet.assembly.count`,METRIC_DOTNET_EXCEPTIONS=`dotnet.exceptions`,METRIC_DOTNET_GC_COLLECTIONS=`dotnet.gc.collections`,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED=`dotnet.gc.heap.total_allocated`,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE=`dotnet.gc.last_collection.heap.fragmentation.size`,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE=`dotnet.gc.last_collection.heap.size`,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE=`dotnet.gc.last_collection.memory.committed_size`,METRIC_DOTNET_GC_PAUSE_TIME=`dotnet.gc.pause.time`,METRIC_DOTNET_JIT_COMPILATION_TIME=`dotnet.jit.compilation.time`,METRIC_DOTNET_JIT_COMPILED_IL_SIZE=`dotnet.jit.compiled_il.size`,METRIC_DOTNET_JIT_COMPILED_METHODS=`dotnet.jit.compiled_methods`,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS=`dotnet.monitor.lock_contentions`,METRIC_DOTNET_PROCESS_CPU_COUNT=`dotnet.process.cpu.count`,METRIC_DOTNET_PROCESS_CPU_TIME=`dotnet.process.cpu.time`,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET=`dotnet.process.memory.working_set`,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH=`dotnet.thread_pool.queue.length`,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT=`dotnet.thread_pool.thread.count`,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT=`dotnet.thread_pool.work_item.count`,METRIC_DOTNET_TIMER_COUNT=`dotnet.timer.count`,METRIC_HTTP_CLIENT_REQUEST_DURATION=`http.client.request.duration`,METRIC_HTTP_SERVER_REQUEST_DURATION=`http.server.request.duration`,METRIC_JVM_CLASS_COUNT=`jvm.class.count`,METRIC_JVM_CLASS_LOADED=`jvm.class.loaded`,METRIC_JVM_CLASS_UNLOADED=`jvm.class.unloaded`,METRIC_JVM_CPU_COUNT=`jvm.cpu.count`,METRIC_JVM_CPU_RECENT_UTILIZATION=`jvm.cpu.recent_utilization`,METRIC_JVM_CPU_TIME=`jvm.cpu.time`,METRIC_JVM_GC_DURATION=`jvm.gc.duration`,METRIC_JVM_MEMORY_COMMITTED=`jvm.memory.committed`,METRIC_JVM_MEMORY_LIMIT=`jvm.memory.limit`,METRIC_JVM_MEMORY_USED=`jvm.memory.used`,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC=`jvm.memory.used_after_last_gc`,METRIC_JVM_THREAD_COUNT=`jvm.thread.count`,METRIC_KESTREL_ACTIVE_CONNECTIONS=`kestrel.active_connections`,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES=`kestrel.active_tls_handshakes`,METRIC_KESTREL_CONNECTION_DURATION=`kestrel.connection.duration`,METRIC_KESTREL_QUEUED_CONNECTIONS=`kestrel.queued_connections`,METRIC_KESTREL_QUEUED_REQUESTS=`kestrel.queued_requests`,METRIC_KESTREL_REJECTED_CONNECTIONS=`kestrel.rejected_connections`,METRIC_KESTREL_TLS_HANDSHAKE_DURATION=`kestrel.tls_handshake.duration`,METRIC_KESTREL_UPGRADED_CONNECTIONS=`kestrel.upgraded_connections`,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS=`signalr.server.active_connections`,METRIC_SIGNALR_SERVER_CONNECTION_DURATION=`signalr.server.connection.duration`})),EVENT_EXCEPTION,init_stable_events=__esmMin((()=>{EVENT_EXCEPTION=`exception`})),esm_exports$1=__exportAll({ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE:()=>ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS:()=>ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS,ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT:()=>ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE:()=>ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE,ATTR_ASPNETCORE_RATE_LIMITING_POLICY:()=>ATTR_ASPNETCORE_RATE_LIMITING_POLICY,ATTR_ASPNETCORE_RATE_LIMITING_RESULT:()=>ATTR_ASPNETCORE_RATE_LIMITING_RESULT,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED:()=>ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK:()=>ATTR_ASPNETCORE_ROUTING_IS_FALLBACK,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS:()=>ATTR_ASPNETCORE_ROUTING_MATCH_STATUS,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED:()=>ATTR_ASPNETCORE_USER_IS_AUTHENTICATED,ATTR_CLIENT_ADDRESS:()=>ATTR_CLIENT_ADDRESS,ATTR_CLIENT_PORT:()=>ATTR_CLIENT_PORT,ATTR_CODE_COLUMN_NUMBER:()=>ATTR_CODE_COLUMN_NUMBER,ATTR_CODE_FILE_PATH:()=>ATTR_CODE_FILE_PATH,ATTR_CODE_FUNCTION_NAME:()=>ATTR_CODE_FUNCTION_NAME,ATTR_CODE_LINE_NUMBER:()=>ATTR_CODE_LINE_NUMBER,ATTR_CODE_STACKTRACE:()=>ATTR_CODE_STACKTRACE,ATTR_DB_COLLECTION_NAME:()=>ATTR_DB_COLLECTION_NAME,ATTR_DB_NAMESPACE:()=>ATTR_DB_NAMESPACE,ATTR_DB_OPERATION_BATCH_SIZE:()=>ATTR_DB_OPERATION_BATCH_SIZE,ATTR_DB_OPERATION_NAME:()=>ATTR_DB_OPERATION_NAME,ATTR_DB_QUERY_SUMMARY:()=>ATTR_DB_QUERY_SUMMARY,ATTR_DB_QUERY_TEXT:()=>ATTR_DB_QUERY_TEXT,ATTR_DB_RESPONSE_STATUS_CODE:()=>ATTR_DB_RESPONSE_STATUS_CODE,ATTR_DB_STORED_PROCEDURE_NAME:()=>ATTR_DB_STORED_PROCEDURE_NAME,ATTR_DB_SYSTEM_NAME:()=>ATTR_DB_SYSTEM_NAME,ATTR_DOTNET_GC_HEAP_GENERATION:()=>ATTR_DOTNET_GC_HEAP_GENERATION,ATTR_ERROR_TYPE:()=>ATTR_ERROR_TYPE,ATTR_EXCEPTION_ESCAPED:()=>ATTR_EXCEPTION_ESCAPED,ATTR_EXCEPTION_MESSAGE:()=>ATTR_EXCEPTION_MESSAGE,ATTR_EXCEPTION_STACKTRACE:()=>ATTR_EXCEPTION_STACKTRACE,ATTR_EXCEPTION_TYPE:()=>ATTR_EXCEPTION_TYPE,ATTR_HTTP_REQUEST_HEADER:()=>ATTR_HTTP_REQUEST_HEADER,ATTR_HTTP_REQUEST_METHOD:()=>ATTR_HTTP_REQUEST_METHOD,ATTR_HTTP_REQUEST_METHOD_ORIGINAL:()=>ATTR_HTTP_REQUEST_METHOD_ORIGINAL,ATTR_HTTP_REQUEST_RESEND_COUNT:()=>ATTR_HTTP_REQUEST_RESEND_COUNT,ATTR_HTTP_RESPONSE_HEADER:()=>ATTR_HTTP_RESPONSE_HEADER,ATTR_HTTP_RESPONSE_STATUS_CODE:()=>ATTR_HTTP_RESPONSE_STATUS_CODE,ATTR_HTTP_ROUTE:()=>ATTR_HTTP_ROUTE,ATTR_JVM_GC_ACTION:()=>ATTR_JVM_GC_ACTION,ATTR_JVM_GC_NAME:()=>ATTR_JVM_GC_NAME,ATTR_JVM_MEMORY_POOL_NAME:()=>ATTR_JVM_MEMORY_POOL_NAME,ATTR_JVM_MEMORY_TYPE:()=>ATTR_JVM_MEMORY_TYPE,ATTR_JVM_THREAD_DAEMON:()=>ATTR_JVM_THREAD_DAEMON,ATTR_JVM_THREAD_STATE:()=>ATTR_JVM_THREAD_STATE,ATTR_NETWORK_LOCAL_ADDRESS:()=>ATTR_NETWORK_LOCAL_ADDRESS,ATTR_NETWORK_LOCAL_PORT:()=>ATTR_NETWORK_LOCAL_PORT,ATTR_NETWORK_PEER_ADDRESS:()=>ATTR_NETWORK_PEER_ADDRESS,ATTR_NETWORK_PEER_PORT:()=>ATTR_NETWORK_PEER_PORT,ATTR_NETWORK_PROTOCOL_NAME:()=>ATTR_NETWORK_PROTOCOL_NAME,ATTR_NETWORK_PROTOCOL_VERSION:()=>ATTR_NETWORK_PROTOCOL_VERSION,ATTR_NETWORK_TRANSPORT:()=>ATTR_NETWORK_TRANSPORT,ATTR_NETWORK_TYPE:()=>ATTR_NETWORK_TYPE,ATTR_OTEL_SCOPE_NAME:()=>ATTR_OTEL_SCOPE_NAME,ATTR_OTEL_SCOPE_VERSION:()=>ATTR_OTEL_SCOPE_VERSION,ATTR_OTEL_STATUS_CODE:()=>ATTR_OTEL_STATUS_CODE,ATTR_OTEL_STATUS_DESCRIPTION:()=>ATTR_OTEL_STATUS_DESCRIPTION,ATTR_SERVER_ADDRESS:()=>ATTR_SERVER_ADDRESS,ATTR_SERVER_PORT:()=>ATTR_SERVER_PORT,ATTR_SERVICE_INSTANCE_ID:()=>ATTR_SERVICE_INSTANCE_ID,ATTR_SERVICE_NAME:()=>ATTR_SERVICE_NAME,ATTR_SERVICE_NAMESPACE:()=>ATTR_SERVICE_NAMESPACE,ATTR_SERVICE_VERSION:()=>ATTR_SERVICE_VERSION,ATTR_SIGNALR_CONNECTION_STATUS:()=>ATTR_SIGNALR_CONNECTION_STATUS,ATTR_SIGNALR_TRANSPORT:()=>ATTR_SIGNALR_TRANSPORT,ATTR_TELEMETRY_SDK_LANGUAGE:()=>ATTR_TELEMETRY_SDK_LANGUAGE,ATTR_TELEMETRY_SDK_NAME:()=>ATTR_TELEMETRY_SDK_NAME,ATTR_TELEMETRY_SDK_VERSION:()=>ATTR_TELEMETRY_SDK_VERSION,ATTR_URL_FRAGMENT:()=>ATTR_URL_FRAGMENT,ATTR_URL_FULL:()=>ATTR_URL_FULL,ATTR_URL_PATH:()=>ATTR_URL_PATH,ATTR_URL_QUERY:()=>ATTR_URL_QUERY,ATTR_URL_SCHEME:()=>ATTR_URL_SCHEME,ATTR_USER_AGENT_ORIGINAL:()=>ATTR_USER_AGENT_ORIGINAL,AWSECSLAUNCHTYPEVALUES_EC2:()=>`ec2`,AWSECSLAUNCHTYPEVALUES_FARGATE:()=>AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues:()=>AwsEcsLaunchtypeValues,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS:()=>CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC:()=>CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2:()=>CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS:()=>CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS:()=>CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK:()=>CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AWS_LAMBDA:()=>CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AZURE_AKS:()=>CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE:()=>CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES:()=>CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS:()=>CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_VM:()=>CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_GCP_APP_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS:()=>CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN:()=>CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPROVIDERVALUES_ALIBABA_CLOUD:()=>CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AWS:()=>`aws`,CLOUDPROVIDERVALUES_AZURE:()=>CLOUDPROVIDERVALUES_AZURE,CLOUDPROVIDERVALUES_GCP:()=>`gcp`,CloudPlatformValues:()=>CloudPlatformValues,CloudProviderValues:()=>CloudProviderValues,DBCASSANDRACONSISTENCYLEVELVALUES_ALL:()=>`all`,DBCASSANDRACONSISTENCYLEVELVALUES_ANY:()=>`any`,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_ONE:()=>`one`,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL:()=>DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_THREE:()=>DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_TWO:()=>`two`,DBSYSTEMVALUES_ADABAS:()=>DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_CACHE:()=>DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_CASSANDRA:()=>DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_CLOUDSCAPE:()=>DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_COCKROACHDB:()=>DBSYSTEMVALUES_COCKROACHDB,DBSYSTEMVALUES_COLDFUSION:()=>DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_COSMOSDB:()=>DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_COUCHBASE:()=>DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB:()=>DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_DB2:()=>`db2`,DBSYSTEMVALUES_DERBY:()=>DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_DYNAMODB:()=>DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_EDB:()=>`edb`,DBSYSTEMVALUES_ELASTICSEARCH:()=>DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_FILEMAKER:()=>DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_FIREBIRD:()=>DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_FIRSTSQL:()=>DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_GEODE:()=>DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_H2:()=>`h2`,DBSYSTEMVALUES_HANADB:()=>DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_HBASE:()=>DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_HIVE:()=>DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_HSQLDB:()=>DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_INFORMIX:()=>DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INGRES:()=>DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_INSTANTDB:()=>DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE:()=>DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB:()=>DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_MAXDB:()=>DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_MEMCACHED:()=>DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_MONGODB:()=>DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_MSSQL:()=>DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL:()=>DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_NEO4J:()=>DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_NETEZZA:()=>DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_ORACLE:()=>DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_OTHER_SQL:()=>DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_PERVASIVE:()=>DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE:()=>DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_POSTGRESQL:()=>DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_PROGRESS:()=>DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_REDIS:()=>DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_REDSHIFT:()=>DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_SQLITE:()=>DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE:()=>DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA:()=>DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA:()=>DBSYSTEMVALUES_VERTICA,DB_SYSTEM_NAME_VALUE_MARIADB:()=>DB_SYSTEM_NAME_VALUE_MARIADB,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER:()=>DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER,DB_SYSTEM_NAME_VALUE_MYSQL:()=>DB_SYSTEM_NAME_VALUE_MYSQL,DB_SYSTEM_NAME_VALUE_POSTGRESQL:()=>DB_SYSTEM_NAME_VALUE_POSTGRESQL,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN0,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN1,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN2,DOTNET_GC_HEAP_GENERATION_VALUE_LOH:()=>`loh`,DOTNET_GC_HEAP_GENERATION_VALUE_POH:()=>`poh`,DbCassandraConsistencyLevelValues:()=>DbCassandraConsistencyLevelValues,DbSystemValues:()=>DbSystemValues,ERROR_TYPE_VALUE_OTHER:()=>ERROR_TYPE_VALUE_OTHER,EVENT_EXCEPTION:()=>EVENT_EXCEPTION,FAASDOCUMENTOPERATIONVALUES_DELETE:()=>FAASDOCUMENTOPERATIONVALUES_DELETE,FAASDOCUMENTOPERATIONVALUES_EDIT:()=>FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_INSERT:()=>FAASDOCUMENTOPERATIONVALUES_INSERT,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD:()=>FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AWS:()=>`aws`,FAASINVOKEDPROVIDERVALUES_AZURE:()=>FAASINVOKEDPROVIDERVALUES_AZURE,FAASINVOKEDPROVIDERVALUES_GCP:()=>`gcp`,FAASTRIGGERVALUES_DATASOURCE:()=>FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP:()=>FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_OTHER:()=>FAASTRIGGERVALUES_OTHER,FAASTRIGGERVALUES_PUBSUB:()=>FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER:()=>FAASTRIGGERVALUES_TIMER,FaasDocumentOperationValues:()=>FaasDocumentOperationValues,FaasInvokedProviderValues:()=>FaasInvokedProviderValues,FaasTriggerValues:()=>FaasTriggerValues,HOSTARCHVALUES_AMD64:()=>HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32:()=>HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64:()=>HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64:()=>HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32:()=>HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64:()=>HOSTARCHVALUES_PPC64,HOSTARCHVALUES_X86:()=>`x86`,HTTPFLAVORVALUES_HTTP_1_0:()=>`1.0`,HTTPFLAVORVALUES_HTTP_1_1:()=>`1.1`,HTTPFLAVORVALUES_HTTP_2_0:()=>`2.0`,HTTPFLAVORVALUES_QUIC:()=>HTTPFLAVORVALUES_QUIC,HTTPFLAVORVALUES_SPDY:()=>HTTPFLAVORVALUES_SPDY,HTTP_REQUEST_METHOD_VALUE_CONNECT:()=>HTTP_REQUEST_METHOD_VALUE_CONNECT,HTTP_REQUEST_METHOD_VALUE_DELETE:()=>HTTP_REQUEST_METHOD_VALUE_DELETE,HTTP_REQUEST_METHOD_VALUE_GET:()=>`GET`,HTTP_REQUEST_METHOD_VALUE_HEAD:()=>HTTP_REQUEST_METHOD_VALUE_HEAD,HTTP_REQUEST_METHOD_VALUE_OPTIONS:()=>HTTP_REQUEST_METHOD_VALUE_OPTIONS,HTTP_REQUEST_METHOD_VALUE_OTHER:()=>HTTP_REQUEST_METHOD_VALUE_OTHER,HTTP_REQUEST_METHOD_VALUE_PATCH:()=>HTTP_REQUEST_METHOD_VALUE_PATCH,HTTP_REQUEST_METHOD_VALUE_POST:()=>HTTP_REQUEST_METHOD_VALUE_POST,HTTP_REQUEST_METHOD_VALUE_PUT:()=>`PUT`,HTTP_REQUEST_METHOD_VALUE_TRACE:()=>HTTP_REQUEST_METHOD_VALUE_TRACE,HostArchValues:()=>HostArchValues,HttpFlavorValues:()=>HttpFlavorValues,JVM_MEMORY_TYPE_VALUE_HEAP:()=>JVM_MEMORY_TYPE_VALUE_HEAP,JVM_MEMORY_TYPE_VALUE_NON_HEAP:()=>JVM_MEMORY_TYPE_VALUE_NON_HEAP,JVM_THREAD_STATE_VALUE_BLOCKED:()=>JVM_THREAD_STATE_VALUE_BLOCKED,JVM_THREAD_STATE_VALUE_NEW:()=>`new`,JVM_THREAD_STATE_VALUE_RUNNABLE:()=>JVM_THREAD_STATE_VALUE_RUNNABLE,JVM_THREAD_STATE_VALUE_TERMINATED:()=>JVM_THREAD_STATE_VALUE_TERMINATED,JVM_THREAD_STATE_VALUE_TIMED_WAITING:()=>JVM_THREAD_STATE_VALUE_TIMED_WAITING,JVM_THREAD_STATE_VALUE_WAITING:()=>JVM_THREAD_STATE_VALUE_WAITING,MESSAGETYPEVALUES_RECEIVED:()=>MESSAGETYPEVALUES_RECEIVED,MESSAGETYPEVALUES_SENT:()=>MESSAGETYPEVALUES_SENT,MESSAGINGDESTINATIONKINDVALUES_QUEUE:()=>MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC:()=>MESSAGINGDESTINATIONKINDVALUES_TOPIC,MESSAGINGOPERATIONVALUES_PROCESS:()=>MESSAGINGOPERATIONVALUES_PROCESS,MESSAGINGOPERATIONVALUES_RECEIVE:()=>MESSAGINGOPERATIONVALUES_RECEIVE,METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS:()=>METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES:()=>METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS:()=>METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS:()=>METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS,METRIC_DB_CLIENT_OPERATION_DURATION:()=>METRIC_DB_CLIENT_OPERATION_DURATION,METRIC_DOTNET_ASSEMBLY_COUNT:()=>METRIC_DOTNET_ASSEMBLY_COUNT,METRIC_DOTNET_EXCEPTIONS:()=>METRIC_DOTNET_EXCEPTIONS,METRIC_DOTNET_GC_COLLECTIONS:()=>METRIC_DOTNET_GC_COLLECTIONS,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED:()=>METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE,METRIC_DOTNET_GC_PAUSE_TIME:()=>METRIC_DOTNET_GC_PAUSE_TIME,METRIC_DOTNET_JIT_COMPILATION_TIME:()=>METRIC_DOTNET_JIT_COMPILATION_TIME,METRIC_DOTNET_JIT_COMPILED_IL_SIZE:()=>METRIC_DOTNET_JIT_COMPILED_IL_SIZE,METRIC_DOTNET_JIT_COMPILED_METHODS:()=>METRIC_DOTNET_JIT_COMPILED_METHODS,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS:()=>METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS,METRIC_DOTNET_PROCESS_CPU_COUNT:()=>METRIC_DOTNET_PROCESS_CPU_COUNT,METRIC_DOTNET_PROCESS_CPU_TIME:()=>METRIC_DOTNET_PROCESS_CPU_TIME,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET:()=>METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH:()=>METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT:()=>METRIC_DOTNET_THREAD_POOL_THREAD_COUNT,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT:()=>METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT,METRIC_DOTNET_TIMER_COUNT:()=>METRIC_DOTNET_TIMER_COUNT,METRIC_HTTP_CLIENT_REQUEST_DURATION:()=>METRIC_HTTP_CLIENT_REQUEST_DURATION,METRIC_HTTP_SERVER_REQUEST_DURATION:()=>METRIC_HTTP_SERVER_REQUEST_DURATION,METRIC_JVM_CLASS_COUNT:()=>METRIC_JVM_CLASS_COUNT,METRIC_JVM_CLASS_LOADED:()=>METRIC_JVM_CLASS_LOADED,METRIC_JVM_CLASS_UNLOADED:()=>METRIC_JVM_CLASS_UNLOADED,METRIC_JVM_CPU_COUNT:()=>METRIC_JVM_CPU_COUNT,METRIC_JVM_CPU_RECENT_UTILIZATION:()=>METRIC_JVM_CPU_RECENT_UTILIZATION,METRIC_JVM_CPU_TIME:()=>METRIC_JVM_CPU_TIME,METRIC_JVM_GC_DURATION:()=>METRIC_JVM_GC_DURATION,METRIC_JVM_MEMORY_COMMITTED:()=>METRIC_JVM_MEMORY_COMMITTED,METRIC_JVM_MEMORY_LIMIT:()=>METRIC_JVM_MEMORY_LIMIT,METRIC_JVM_MEMORY_USED:()=>METRIC_JVM_MEMORY_USED,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC:()=>METRIC_JVM_MEMORY_USED_AFTER_LAST_GC,METRIC_JVM_THREAD_COUNT:()=>METRIC_JVM_THREAD_COUNT,METRIC_KESTREL_ACTIVE_CONNECTIONS:()=>METRIC_KESTREL_ACTIVE_CONNECTIONS,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES:()=>METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES,METRIC_KESTREL_CONNECTION_DURATION:()=>METRIC_KESTREL_CONNECTION_DURATION,METRIC_KESTREL_QUEUED_CONNECTIONS:()=>METRIC_KESTREL_QUEUED_CONNECTIONS,METRIC_KESTREL_QUEUED_REQUESTS:()=>METRIC_KESTREL_QUEUED_REQUESTS,METRIC_KESTREL_REJECTED_CONNECTIONS:()=>METRIC_KESTREL_REJECTED_CONNECTIONS,METRIC_KESTREL_TLS_HANDSHAKE_DURATION:()=>METRIC_KESTREL_TLS_HANDSHAKE_DURATION,METRIC_KESTREL_UPGRADED_CONNECTIONS:()=>METRIC_KESTREL_UPGRADED_CONNECTIONS,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS:()=>METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS,METRIC_SIGNALR_SERVER_CONNECTION_DURATION:()=>METRIC_SIGNALR_SERVER_CONNECTION_DURATION,MessageTypeValues:()=>MessageTypeValues,MessagingDestinationKindValues:()=>MessagingDestinationKindValues,MessagingOperationValues:()=>MessagingOperationValues,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT:()=>NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS:()=>NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_GSM:()=>`gsm`,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN:()=>NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN:()=>NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_LTE:()=>`lte`,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NETHOSTCONNECTIONSUBTYPEVALUES_NR:()=>`nr`,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS:()=>NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONTYPEVALUES_CELL:()=>NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE:()=>NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN:()=>NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NETHOSTCONNECTIONTYPEVALUES_WIFI:()=>NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED:()=>NETHOSTCONNECTIONTYPEVALUES_WIRED,NETTRANSPORTVALUES_INPROC:()=>NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_IP:()=>`ip`,NETTRANSPORTVALUES_IP_TCP:()=>NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP:()=>NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_OTHER:()=>NETTRANSPORTVALUES_OTHER,NETTRANSPORTVALUES_PIPE:()=>NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_UNIX:()=>NETTRANSPORTVALUES_UNIX,NETWORK_TRANSPORT_VALUE_PIPE:()=>NETWORK_TRANSPORT_VALUE_PIPE,NETWORK_TRANSPORT_VALUE_QUIC:()=>NETWORK_TRANSPORT_VALUE_QUIC,NETWORK_TRANSPORT_VALUE_TCP:()=>`tcp`,NETWORK_TRANSPORT_VALUE_UDP:()=>`udp`,NETWORK_TRANSPORT_VALUE_UNIX:()=>NETWORK_TRANSPORT_VALUE_UNIX,NETWORK_TYPE_VALUE_IPV4:()=>NETWORK_TYPE_VALUE_IPV4,NETWORK_TYPE_VALUE_IPV6:()=>NETWORK_TYPE_VALUE_IPV6,NetHostConnectionSubtypeValues:()=>NetHostConnectionSubtypeValues,NetHostConnectionTypeValues:()=>NetHostConnectionTypeValues,NetTransportValues:()=>NetTransportValues,OSTYPEVALUES_AIX:()=>`aix`,OSTYPEVALUES_DARWIN:()=>OSTYPEVALUES_DARWIN,OSTYPEVALUES_DRAGONFLYBSD:()=>OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_FREEBSD:()=>OSTYPEVALUES_FREEBSD,OSTYPEVALUES_HPUX:()=>OSTYPEVALUES_HPUX,OSTYPEVALUES_LINUX:()=>OSTYPEVALUES_LINUX,OSTYPEVALUES_NETBSD:()=>OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD:()=>OSTYPEVALUES_OPENBSD,OSTYPEVALUES_SOLARIS:()=>OSTYPEVALUES_SOLARIS,OSTYPEVALUES_WINDOWS:()=>OSTYPEVALUES_WINDOWS,OSTYPEVALUES_Z_OS:()=>OSTYPEVALUES_Z_OS,OTEL_STATUS_CODE_VALUE_ERROR:()=>OTEL_STATUS_CODE_VALUE_ERROR,OTEL_STATUS_CODE_VALUE_OK:()=>`OK`,OsTypeValues:()=>OsTypeValues,RPCGRPCSTATUSCODEVALUES_ABORTED:()=>10,RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS:()=>6,RPCGRPCSTATUSCODEVALUES_CANCELLED:()=>1,RPCGRPCSTATUSCODEVALUES_DATA_LOSS:()=>15,RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED:()=>4,RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION:()=>9,RPCGRPCSTATUSCODEVALUES_INTERNAL:()=>13,RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT:()=>3,RPCGRPCSTATUSCODEVALUES_NOT_FOUND:()=>5,RPCGRPCSTATUSCODEVALUES_OK:()=>0,RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE:()=>11,RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED:()=>7,RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED:()=>8,RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED:()=>16,RPCGRPCSTATUSCODEVALUES_UNAVAILABLE:()=>14,RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED:()=>12,RPCGRPCSTATUSCODEVALUES_UNKNOWN:()=>2,RpcGrpcStatusCodeValues:()=>RpcGrpcStatusCodeValues,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET:()=>SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS:()=>SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ:()=>SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_COUNT:()=>SEMATTRS_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE:()=>SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES:()=>SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES:()=>SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_AWS_DYNAMODB_INDEX_NAME:()=>SEMATTRS_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS:()=>SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_LIMIT:()=>SEMATTRS_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES:()=>SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_PROJECTION:()=>SEMATTRS_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT:()=>SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD:()=>SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT:()=>SEMATTRS_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_SELECT:()=>SEMATTRS_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT:()=>SEMATTRS_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES:()=>SEMATTRS_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS:()=>SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_LAMBDA_INVOKED_ARN:()=>SEMATTRS_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_CODE_FILEPATH:()=>SEMATTRS_CODE_FILEPATH,SEMATTRS_CODE_FUNCTION:()=>SEMATTRS_CODE_FUNCTION,SEMATTRS_CODE_LINENO:()=>SEMATTRS_CODE_LINENO,SEMATTRS_CODE_NAMESPACE:()=>SEMATTRS_CODE_NAMESPACE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL:()=>SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC:()=>SEMATTRS_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID:()=>SEMATTRS_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE:()=>SEMATTRS_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_KEYSPACE:()=>SEMATTRS_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE:()=>SEMATTRS_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT:()=>SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_TABLE:()=>SEMATTRS_DB_CASSANDRA_TABLE,SEMATTRS_DB_CONNECTION_STRING:()=>SEMATTRS_DB_CONNECTION_STRING,SEMATTRS_DB_HBASE_NAMESPACE:()=>SEMATTRS_DB_HBASE_NAMESPACE,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME:()=>SEMATTRS_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_MONGODB_COLLECTION:()=>SEMATTRS_DB_MONGODB_COLLECTION,SEMATTRS_DB_MSSQL_INSTANCE_NAME:()=>SEMATTRS_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_NAME:()=>SEMATTRS_DB_NAME,SEMATTRS_DB_OPERATION:()=>SEMATTRS_DB_OPERATION,SEMATTRS_DB_REDIS_DATABASE_INDEX:()=>SEMATTRS_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_SQL_TABLE:()=>SEMATTRS_DB_SQL_TABLE,SEMATTRS_DB_STATEMENT:()=>SEMATTRS_DB_STATEMENT,SEMATTRS_DB_SYSTEM:()=>SEMATTRS_DB_SYSTEM,SEMATTRS_DB_USER:()=>SEMATTRS_DB_USER,SEMATTRS_ENDUSER_ID:()=>SEMATTRS_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE:()=>SEMATTRS_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE:()=>SEMATTRS_ENDUSER_SCOPE,SEMATTRS_EXCEPTION_ESCAPED:()=>SEMATTRS_EXCEPTION_ESCAPED,SEMATTRS_EXCEPTION_MESSAGE:()=>SEMATTRS_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE:()=>SEMATTRS_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_TYPE:()=>SEMATTRS_EXCEPTION_TYPE,SEMATTRS_FAAS_COLDSTART:()=>SEMATTRS_FAAS_COLDSTART,SEMATTRS_FAAS_CRON:()=>SEMATTRS_FAAS_CRON,SEMATTRS_FAAS_DOCUMENT_COLLECTION:()=>SEMATTRS_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_NAME:()=>SEMATTRS_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_DOCUMENT_OPERATION:()=>SEMATTRS_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME:()=>SEMATTRS_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_EXECUTION:()=>SEMATTRS_FAAS_EXECUTION,SEMATTRS_FAAS_INVOKED_NAME:()=>SEMATTRS_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER:()=>SEMATTRS_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION:()=>SEMATTRS_FAAS_INVOKED_REGION,SEMATTRS_FAAS_TIME:()=>SEMATTRS_FAAS_TIME,SEMATTRS_FAAS_TRIGGER:()=>SEMATTRS_FAAS_TRIGGER,SEMATTRS_HTTP_CLIENT_IP:()=>SEMATTRS_HTTP_CLIENT_IP,SEMATTRS_HTTP_FLAVOR:()=>SEMATTRS_HTTP_FLAVOR,SEMATTRS_HTTP_HOST:()=>SEMATTRS_HTTP_HOST,SEMATTRS_HTTP_METHOD:()=>SEMATTRS_HTTP_METHOD,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH:()=>SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED:()=>SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH:()=>SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED:()=>SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_ROUTE:()=>SEMATTRS_HTTP_ROUTE,SEMATTRS_HTTP_SCHEME:()=>SEMATTRS_HTTP_SCHEME,SEMATTRS_HTTP_SERVER_NAME:()=>SEMATTRS_HTTP_SERVER_NAME,SEMATTRS_HTTP_STATUS_CODE:()=>SEMATTRS_HTTP_STATUS_CODE,SEMATTRS_HTTP_TARGET:()=>SEMATTRS_HTTP_TARGET,SEMATTRS_HTTP_URL:()=>SEMATTRS_HTTP_URL,SEMATTRS_HTTP_USER_AGENT:()=>SEMATTRS_HTTP_USER_AGENT,SEMATTRS_MESSAGE_COMPRESSED_SIZE:()=>SEMATTRS_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_ID:()=>SEMATTRS_MESSAGE_ID,SEMATTRS_MESSAGE_TYPE:()=>SEMATTRS_MESSAGE_TYPE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE:()=>SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE,SEMATTRS_MESSAGING_CONSUMER_ID:()=>SEMATTRS_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_CONVERSATION_ID:()=>SEMATTRS_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_DESTINATION:()=>SEMATTRS_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND:()=>SEMATTRS_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID:()=>SEMATTRS_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP:()=>SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY:()=>SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_PARTITION:()=>SEMATTRS_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE:()=>SEMATTRS_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_MESSAGING_MESSAGE_ID:()=>SEMATTRS_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES:()=>SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES:()=>SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION:()=>SEMATTRS_MESSAGING_OPERATION,SEMATTRS_MESSAGING_PROTOCOL:()=>SEMATTRS_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION:()=>SEMATTRS_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY:()=>SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_SYSTEM:()=>SEMATTRS_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_TEMP_DESTINATION:()=>SEMATTRS_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_URL:()=>SEMATTRS_MESSAGING_URL,SEMATTRS_NET_HOST_CARRIER_ICC:()=>SEMATTRS_NET_HOST_CARRIER_ICC,SEMATTRS_NET_HOST_CARRIER_MCC:()=>SEMATTRS_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC:()=>SEMATTRS_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_NAME:()=>SEMATTRS_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE:()=>SEMATTRS_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CONNECTION_TYPE:()=>SEMATTRS_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_IP:()=>SEMATTRS_NET_HOST_IP,SEMATTRS_NET_HOST_NAME:()=>SEMATTRS_NET_HOST_NAME,SEMATTRS_NET_HOST_PORT:()=>SEMATTRS_NET_HOST_PORT,SEMATTRS_NET_PEER_IP:()=>SEMATTRS_NET_PEER_IP,SEMATTRS_NET_PEER_NAME:()=>SEMATTRS_NET_PEER_NAME,SEMATTRS_NET_PEER_PORT:()=>SEMATTRS_NET_PEER_PORT,SEMATTRS_NET_TRANSPORT:()=>SEMATTRS_NET_TRANSPORT,SEMATTRS_PEER_SERVICE:()=>SEMATTRS_PEER_SERVICE,SEMATTRS_RPC_GRPC_STATUS_CODE:()=>SEMATTRS_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_ERROR_CODE:()=>SEMATTRS_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE:()=>SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_RPC_JSONRPC_REQUEST_ID:()=>SEMATTRS_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_VERSION:()=>SEMATTRS_RPC_JSONRPC_VERSION,SEMATTRS_RPC_METHOD:()=>SEMATTRS_RPC_METHOD,SEMATTRS_RPC_SERVICE:()=>SEMATTRS_RPC_SERVICE,SEMATTRS_RPC_SYSTEM:()=>SEMATTRS_RPC_SYSTEM,SEMATTRS_THREAD_ID:()=>SEMATTRS_THREAD_ID,SEMATTRS_THREAD_NAME:()=>SEMATTRS_THREAD_NAME,SEMRESATTRS_AWS_ECS_CLUSTER_ARN:()=>SEMRESATTRS_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_CONTAINER_ARN:()=>SEMRESATTRS_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE:()=>SEMRESATTRS_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN:()=>SEMRESATTRS_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY:()=>SEMRESATTRS_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION:()=>SEMRESATTRS_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN:()=>SEMRESATTRS_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_ARNS:()=>SEMRESATTRS_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_GROUP_NAMES:()=>SEMRESATTRS_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS:()=>SEMRESATTRS_AWS_LOG_STREAM_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES:()=>SEMRESATTRS_AWS_LOG_STREAM_NAMES,SEMRESATTRS_CLOUD_ACCOUNT_ID:()=>SEMRESATTRS_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE:()=>SEMRESATTRS_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM:()=>SEMRESATTRS_CLOUD_PLATFORM,SEMRESATTRS_CLOUD_PROVIDER:()=>SEMRESATTRS_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_REGION:()=>SEMRESATTRS_CLOUD_REGION,SEMRESATTRS_CONTAINER_ID:()=>SEMRESATTRS_CONTAINER_ID,SEMRESATTRS_CONTAINER_IMAGE_NAME:()=>SEMRESATTRS_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG:()=>SEMRESATTRS_CONTAINER_IMAGE_TAG,SEMRESATTRS_CONTAINER_NAME:()=>SEMRESATTRS_CONTAINER_NAME,SEMRESATTRS_CONTAINER_RUNTIME:()=>SEMRESATTRS_CONTAINER_RUNTIME,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT:()=>SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID:()=>SEMRESATTRS_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER:()=>SEMRESATTRS_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME:()=>SEMRESATTRS_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_ID:()=>SEMRESATTRS_FAAS_ID,SEMRESATTRS_FAAS_INSTANCE:()=>SEMRESATTRS_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY:()=>SEMRESATTRS_FAAS_MAX_MEMORY,SEMRESATTRS_FAAS_NAME:()=>SEMRESATTRS_FAAS_NAME,SEMRESATTRS_FAAS_VERSION:()=>SEMRESATTRS_FAAS_VERSION,SEMRESATTRS_HOST_ARCH:()=>SEMRESATTRS_HOST_ARCH,SEMRESATTRS_HOST_ID:()=>SEMRESATTRS_HOST_ID,SEMRESATTRS_HOST_IMAGE_ID:()=>SEMRESATTRS_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_NAME:()=>SEMRESATTRS_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_VERSION:()=>SEMRESATTRS_HOST_IMAGE_VERSION,SEMRESATTRS_HOST_NAME:()=>SEMRESATTRS_HOST_NAME,SEMRESATTRS_HOST_TYPE:()=>SEMRESATTRS_HOST_TYPE,SEMRESATTRS_K8S_CLUSTER_NAME:()=>SEMRESATTRS_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_CONTAINER_NAME:()=>SEMRESATTRS_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_CRONJOB_NAME:()=>SEMRESATTRS_K8S_CRONJOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID:()=>SEMRESATTRS_K8S_CRONJOB_UID,SEMRESATTRS_K8S_DAEMONSET_NAME:()=>SEMRESATTRS_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID:()=>SEMRESATTRS_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME:()=>SEMRESATTRS_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID:()=>SEMRESATTRS_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_JOB_NAME:()=>SEMRESATTRS_K8S_JOB_NAME,SEMRESATTRS_K8S_JOB_UID:()=>SEMRESATTRS_K8S_JOB_UID,SEMRESATTRS_K8S_NAMESPACE_NAME:()=>SEMRESATTRS_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_NODE_NAME:()=>SEMRESATTRS_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID:()=>SEMRESATTRS_K8S_NODE_UID,SEMRESATTRS_K8S_POD_NAME:()=>SEMRESATTRS_K8S_POD_NAME,SEMRESATTRS_K8S_POD_UID:()=>SEMRESATTRS_K8S_POD_UID,SEMRESATTRS_K8S_REPLICASET_NAME:()=>SEMRESATTRS_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_REPLICASET_UID:()=>SEMRESATTRS_K8S_REPLICASET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME:()=>SEMRESATTRS_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_STATEFULSET_UID:()=>SEMRESATTRS_K8S_STATEFULSET_UID,SEMRESATTRS_OS_DESCRIPTION:()=>SEMRESATTRS_OS_DESCRIPTION,SEMRESATTRS_OS_NAME:()=>SEMRESATTRS_OS_NAME,SEMRESATTRS_OS_TYPE:()=>SEMRESATTRS_OS_TYPE,SEMRESATTRS_OS_VERSION:()=>SEMRESATTRS_OS_VERSION,SEMRESATTRS_PROCESS_COMMAND:()=>SEMRESATTRS_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_ARGS:()=>SEMRESATTRS_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_COMMAND_LINE:()=>SEMRESATTRS_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_EXECUTABLE_NAME:()=>SEMRESATTRS_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH:()=>SEMRESATTRS_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_OWNER:()=>SEMRESATTRS_PROCESS_OWNER,SEMRESATTRS_PROCESS_PID:()=>SEMRESATTRS_PROCESS_PID,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION:()=>SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_PROCESS_RUNTIME_NAME:()=>SEMRESATTRS_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION:()=>SEMRESATTRS_PROCESS_RUNTIME_VERSION,SEMRESATTRS_SERVICE_INSTANCE_ID:()=>SEMRESATTRS_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_NAME:()=>SEMRESATTRS_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE:()=>SEMRESATTRS_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_VERSION:()=>SEMRESATTRS_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION:()=>SEMRESATTRS_TELEMETRY_AUTO_VERSION,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE:()=>SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_NAME:()=>SEMRESATTRS_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_VERSION:()=>SEMRESATTRS_TELEMETRY_SDK_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION:()=>SEMRESATTRS_WEBENGINE_DESCRIPTION,SEMRESATTRS_WEBENGINE_NAME:()=>SEMRESATTRS_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION:()=>SEMRESATTRS_WEBENGINE_VERSION,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN:()=>SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE:()=>SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT:()=>SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT,SIGNALR_TRANSPORT_VALUE_LONG_POLLING:()=>SIGNALR_TRANSPORT_VALUE_LONG_POLLING,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS:()=>SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS:()=>SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS,SemanticAttributes:()=>SemanticAttributes,SemanticResourceAttributes:()=>SemanticResourceAttributes,TELEMETRYSDKLANGUAGEVALUES_CPP:()=>`cpp`,TELEMETRYSDKLANGUAGEVALUES_DOTNET:()=>TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG:()=>TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_GO:()=>`go`,TELEMETRYSDKLANGUAGEVALUES_JAVA:()=>TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS:()=>TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PHP:()=>`php`,TELEMETRYSDKLANGUAGEVALUES_PYTHON:()=>TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY:()=>TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS:()=>TELEMETRYSDKLANGUAGEVALUES_WEBJS,TELEMETRY_SDK_LANGUAGE_VALUE_CPP:()=>`cpp`,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET:()=>TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG:()=>TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG,TELEMETRY_SDK_LANGUAGE_VALUE_GO:()=>`go`,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA:()=>TELEMETRY_SDK_LANGUAGE_VALUE_JAVA,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS:()=>TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,TELEMETRY_SDK_LANGUAGE_VALUE_PHP:()=>`php`,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON:()=>TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY:()=>TELEMETRY_SDK_LANGUAGE_VALUE_RUBY,TELEMETRY_SDK_LANGUAGE_VALUE_RUST:()=>TELEMETRY_SDK_LANGUAGE_VALUE_RUST,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT:()=>TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS:()=>TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,TelemetrySdkLanguageValues:()=>TelemetrySdkLanguageValues}),init_esm$1=__esmMin((()=>{init_trace(),init_resource(),init_stable_attributes(),init_stable_metrics(),init_stable_events()})),require_semconv$7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),require_sdk_info$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=require_version$6(),s=(init_esm$1(),__toCommonJS(esm_exports$1)),g=require_semconv$7();e.SDK_INFO={[s.ATTR_TELEMETRY_SDK_NAME]:`opentelemetry`,[g.ATTR_PROCESS_RUNTIME_NAME]:`node`,[s.ATTR_TELEMETRY_SDK_LANGUAGE]:s.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[s.ATTR_TELEMETRY_SDK_VERSION]:t.VERSION}})),require_node$11=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=e.SDK_INFO=e._globalThis=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=void 0;var t=require_environment$3();Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}});var s=require_globalThis$3();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return s._globalThis}});var g=require_sdk_info$3();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return g.SDK_INFO}}),e.otperformance=performance})),require_platform$11=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getNumberFromEnv=e.getStringFromEnv=e.getBooleanFromEnv=e.otperformance=e._globalThis=e.SDK_INFO=void 0;var t=require_node$11();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return t.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return t._globalThis}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return t.otperformance}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}})})),require_time$4=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.addHrTimes=e.isTimeInput=e.isTimeInputHrTime=e.hrTimeToMicroseconds=e.hrTimeToMilliseconds=e.hrTimeToNanoseconds=e.hrTimeToTimeStamp=e.hrTimeDuration=e.timeInputToHrTime=e.hrTime=e.getTimeOrigin=e.millisToHrTime=void 0;let t=require_platform$11(),s=9,g=10**6,S=10**9;function w(e){let t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*g)]}e.millisToHrTime=w;function E(){return t.otperformance.timeOrigin}e.getTimeOrigin=E;function D(e){return J(w(t.otperformance.timeOrigin),w(typeof e==`number`?e:t.otperformance.now()))}e.hrTime=D;function O(e){if(H(e))return e;if(typeof e==`number`)return e<t.otperformance.timeOrigin?D(e):w(e);if(e instanceof Date)return w(e.getTime());throw TypeError(`Invalid input type`)}e.timeInputToHrTime=O;function k(e,t){let s=t[0]-e[0],g=t[1]-e[1];return g<0&&(--s,g+=S),[s,g]}e.hrTimeDuration=k;function j(e){let t=9,s=`${`0`.repeat(9)}${e[1]}Z`,g=s.substring(s.length-9-1);return new Date(e[0]*1e3).toISOString().replace(`000Z`,g)}e.hrTimeToTimeStamp=j;function F(e){return e[0]*S+e[1]}e.hrTimeToNanoseconds=F;function L(e){return e[0]*1e3+e[1]/1e6}e.hrTimeToMilliseconds=L;function B(e){return e[0]*1e6+e[1]/1e3}e.hrTimeToMicroseconds=B;function H(e){return Array.isArray(e)&&e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`}e.isTimeInputHrTime=H;function q(e){return H(e)||typeof e==`number`||e instanceof Date}e.isTimeInput=q;function J(e,t){let s=[e[0]+t[0],e[1]+t[1]];return s[1]>=S&&(s[1]-=S,s[0]+=1),s}e.addHrTimes=J})),require_timer_util$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=void 0;function t(e){typeof e!=`number`&&e.unref()}e.unrefTimer=t})),require_ExportResult$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExportResultCode=void 0,(function(e){e[e.SUCCESS=0]=`SUCCESS`,e[e.FAILED=1]=`FAILED`})(e.ExportResultCode||={})})),require_composite$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CompositePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));e.CompositePropagator=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>typeof e.fields==`function`?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,s,g){for(let S of this._propagators)try{S.inject(e,s,g)}catch(e){t.diag.warn(`Failed to inject with ${S.constructor.name}. Err: ${e.message}`)}}extract(e,s,g){return this._propagators.reduce((e,S)=>{try{return S.extract(e,s,g)}catch(e){t.diag.warn(`Failed to extract with ${S.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}})),require_validators$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateValue=e.validateKey=void 0;let t=`[_0-9a-z-*/]`,s=`[a-z]${t}{0,255}`,g=`[a-z0-9]${t}{0,240}@[a-z]${t}{0,13}`,S=RegExp(`^(?:${s}|${g})$`),w=/^[ -~]{0,255}[!-~]$/,E=/,|=/;function D(e){return S.test(e)}e.validateKey=D;function O(e){return w.test(e)&&!E.test(e)}e.validateValue=O})),require_TraceState$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceState=void 0;let t=require_validators$3(),s=32,g=512,S=`,`,w=`=`;e.TraceState=class e{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){let s=this._clone();return s._internalState.has(e)&&s._internalState.delete(e),s._internalState.set(e,t),s}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+`=`+this.get(t)),e),[]).join(`,`)}_parse(e){e.length>512||(this._internalState=e.split(`,`).reverse().reduce((e,s)=>{let g=s.trim(),S=g.indexOf(`=`);if(S!==-1){let w=g.slice(0,S),E=g.slice(S+1,s.length);(0,t.validateKey)(w)&&(0,t.validateValue)(E)&&e.set(w,E)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let t=new e;return t._internalState=new Map(this._internalState),t}}})),require_W3CTraceContextPropagator$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CTraceContextPropagator=e.parseTraceParent=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$3(),g=require_TraceState$3();e.TRACE_PARENT_HEADER=`traceparent`,e.TRACE_STATE_HEADER=`tracestate`;let S=`00`,w=RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`);function E(e){let t=w.exec(e);return!t||t[1]===`00`&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}}e.parseTraceParent=E,e.W3CTraceContextPropagator=class{inject(g,S,w){let E=t.trace.getSpanContext(g);if(!E||(0,s.isTracingSuppressed)(g)||!(0,t.isSpanContextValid)(E))return;let D=`00-${E.traceId}-${E.spanId}-0${Number(E.traceFlags||t.TraceFlags.NONE).toString(16)}`;w.set(S,e.TRACE_PARENT_HEADER,D),E.traceState&&w.set(S,e.TRACE_STATE_HEADER,E.traceState.serialize())}extract(s,S,w){let D=w.get(S,e.TRACE_PARENT_HEADER);if(!D)return s;let O=Array.isArray(D)?D[0]:D;if(typeof O!=`string`)return s;let k=E(O);if(!k)return s;k.isRemote=!0;let j=w.get(S,e.TRACE_STATE_HEADER);if(j){let e=Array.isArray(j)?j.join(`,`):j;k.traceState=new g.TraceState(typeof e==`string`?e:void 0)}return t.trace.setSpanContext(s,k)}fields(){return[e.TRACE_PARENT_HEADER,e.TRACE_STATE_HEADER]}}})),require_rpc_metadata$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRPCMetadata=e.deleteRPCMetadata=e.setRPCMetadata=e.RPCType=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key RPC_METADATA`);(function(e){e.HTTP=`http`})(e.RPCType||={});function s(e,s){return e.setValue(t,s)}e.setRPCMetadata=s;function g(e){return e.deleteValue(t)}e.deleteRPCMetadata=g;function S(e){return e.getValue(t)}e.getRPCMetadata=S})),require_lodash_merge$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isPlainObject=void 0;let t=`[object Object]`,s=`[object Null]`,g=`[object Undefined]`,S=Function.prototype.toString,w=S.call(Object),E=Object.getPrototypeOf,D=Object.prototype,O=D.hasOwnProperty,k=Symbol?Symbol.toStringTag:void 0,j=D.toString;function F(e){if(!L(e)||B(e)!==`[object Object]`)return!1;let t=E(e);if(t===null)return!0;let s=O.call(t,`constructor`)&&t.constructor;return typeof s==`function`&&s instanceof s&&S.call(s)===w}e.isPlainObject=F;function L(e){return typeof e==`object`&&!!e}function B(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:k&&k in Object(e)?H(e):q(e)}function H(e){let t=O.call(e,k),s=e[k],g=!1;try{e[k]=void 0,g=!0}catch{}let S=j.call(e);return g&&(t?e[k]=s:delete e[k]),S}function q(e){return j.call(e)}})),require_merge$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=require_lodash_merge$3(),s=20;function g(...e){let t=e.shift(),s=new WeakMap;for(;e.length>0;)t=w(t,e.shift(),0,s);return t}e.merge=g;function S(e){return D(e)?e.slice():e}function w(e,t,s=0,g){let L;if(!(s>20)){if(s++,j(e)||j(t)||O(t))L=S(t);else if(D(e)){if(L=e.slice(),D(t))for(let e=0,s=t.length;e<s;e++)L.push(S(t[e]));else if(k(t)){let e=Object.keys(t);for(let s=0,g=e.length;s<g;s++){let g=e[s];g===`__proto__`||g===`constructor`||g===`prototype`||(L[g]=S(t[g]))}}}else if(k(e))if(k(t)){if(!F(e,t))return t;L=Object.assign({},e);let S=Object.keys(t);for(let D=0,O=S.length;D<O;D++){let O=S[D];if(O===`__proto__`||O===`constructor`||O===`prototype`)continue;let F=t[O];if(j(F))F===void 0?delete L[O]:L[O]=F;else{let S=L[O],D=F;if(E(e,O,g)||E(t,O,g))delete L[O];else{if(k(S)&&k(D)){let s=g.get(S)||[],w=g.get(D)||[];s.push({obj:e,key:O}),w.push({obj:t,key:O}),g.set(S,s),g.set(D,w)}L[O]=w(L[O],F,s,g)}}}}else L=t;return L}}function E(e,t,s){let g=s.get(e[t])||[];for(let s=0,S=g.length;s<S;s++){let S=g[s];if(S.key===t&&S.obj===e)return!0}return!1}function D(e){return Array.isArray(e)}function O(e){return typeof e==`function`}function k(e){return!j(e)&&!D(e)&&!O(e)&&typeof e==`object`}function j(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===void 0||e instanceof Date||e instanceof RegExp||e===null}function F(e,s){return!(!(0,t.isPlainObject)(e)||!(0,t.isPlainObject)(s))}})),require_timeout$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callWithTimeout=e.TimeoutError=void 0;var t=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=t;function s(e,s){let g,S=new Promise(function(e,S){g=setTimeout(function(){S(new t(`Operation timed out.`))},s)});return Promise.race([e,S]).then(e=>(clearTimeout(g),e),e=>{throw clearTimeout(g),e})}e.callWithTimeout=s})),require_url$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isUrlIgnored=e.urlMatches=void 0;function t(e,t){return typeof t==`string`?e===t:!!e.match(t)}e.urlMatches=t;function s(e,s){if(!s)return!1;for(let g of s)if(t(e,g))return!0;return!1}e.isUrlIgnored=s})),require_promise$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Deferred=void 0,e.Deferred=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}})),require_callback$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BindOnceFuture=void 0;let t=require_promise$3();e.BindOnceFuture=class{_isCalled=!1;_deferred=new t.Deferred;_callback;_that;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}})),require_configuration$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.diagLogLevelFromString=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s={ALL:t.DiagLogLevel.ALL,VERBOSE:t.DiagLogLevel.VERBOSE,DEBUG:t.DiagLogLevel.DEBUG,INFO:t.DiagLogLevel.INFO,WARN:t.DiagLogLevel.WARN,ERROR:t.DiagLogLevel.ERROR,NONE:t.DiagLogLevel.NONE};function g(e){return e==null?void 0:s[e.toUpperCase()]??(t.diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(s)}, using default`),t.DiagLogLevel.INFO)}e.diagLogLevelFromString=g})),require_exporter$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._export=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$3();function g(e,g){return new Promise(S=>{t.context.with((0,s.suppressTracing)(t.context.active()),()=>{e.export(g,S)})})}e._export=g})),require_src$14=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.internal=e.diagLogLevelFromString=e.BindOnceFuture=e.urlMatches=e.isUrlIgnored=e.callWithTimeout=e.TimeoutError=e.merge=e.TraceState=e.unsuppressTracing=e.suppressTracing=e.isTracingSuppressed=e.setRPCMetadata=e.getRPCMetadata=e.deleteRPCMetadata=e.RPCType=e.parseTraceParent=e.W3CTraceContextPropagator=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=e.CompositePropagator=e.otperformance=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e._globalThis=e.SDK_INFO=e.parseKeyPairsIntoRecord=e.ExportResultCode=e.unrefTimer=e.timeInputToHrTime=e.millisToHrTime=e.isTimeInputHrTime=e.isTimeInput=e.hrTimeToTimeStamp=e.hrTimeToNanoseconds=e.hrTimeToMilliseconds=e.hrTimeToMicroseconds=e.hrTimeDuration=e.hrTime=e.getTimeOrigin=e.addHrTimes=e.loggingErrorHandler=e.setGlobalErrorHandler=e.globalErrorHandler=e.sanitizeAttributes=e.isAttributeValue=e.AnchoredClock=e.W3CBaggagePropagator=void 0;var t=require_W3CBaggagePropagator$3();Object.defineProperty(e,`W3CBaggagePropagator`,{enumerable:!0,get:function(){return t.W3CBaggagePropagator}});var s=require_anchored_clock$3();Object.defineProperty(e,`AnchoredClock`,{enumerable:!0,get:function(){return s.AnchoredClock}});var g=require_attributes$3();Object.defineProperty(e,`isAttributeValue`,{enumerable:!0,get:function(){return g.isAttributeValue}}),Object.defineProperty(e,`sanitizeAttributes`,{enumerable:!0,get:function(){return g.sanitizeAttributes}});var S=require_global_error_handler$3();Object.defineProperty(e,`globalErrorHandler`,{enumerable:!0,get:function(){return S.globalErrorHandler}}),Object.defineProperty(e,`setGlobalErrorHandler`,{enumerable:!0,get:function(){return S.setGlobalErrorHandler}});var w=require_logging_error_handler$3();Object.defineProperty(e,`loggingErrorHandler`,{enumerable:!0,get:function(){return w.loggingErrorHandler}});var E=require_time$4();Object.defineProperty(e,`addHrTimes`,{enumerable:!0,get:function(){return E.addHrTimes}}),Object.defineProperty(e,`getTimeOrigin`,{enumerable:!0,get:function(){return E.getTimeOrigin}}),Object.defineProperty(e,`hrTime`,{enumerable:!0,get:function(){return E.hrTime}}),Object.defineProperty(e,`hrTimeDuration`,{enumerable:!0,get:function(){return E.hrTimeDuration}}),Object.defineProperty(e,`hrTimeToMicroseconds`,{enumerable:!0,get:function(){return E.hrTimeToMicroseconds}}),Object.defineProperty(e,`hrTimeToMilliseconds`,{enumerable:!0,get:function(){return E.hrTimeToMilliseconds}}),Object.defineProperty(e,`hrTimeToNanoseconds`,{enumerable:!0,get:function(){return E.hrTimeToNanoseconds}}),Object.defineProperty(e,`hrTimeToTimeStamp`,{enumerable:!0,get:function(){return E.hrTimeToTimeStamp}}),Object.defineProperty(e,`isTimeInput`,{enumerable:!0,get:function(){return E.isTimeInput}}),Object.defineProperty(e,`isTimeInputHrTime`,{enumerable:!0,get:function(){return E.isTimeInputHrTime}}),Object.defineProperty(e,`millisToHrTime`,{enumerable:!0,get:function(){return E.millisToHrTime}}),Object.defineProperty(e,`timeInputToHrTime`,{enumerable:!0,get:function(){return E.timeInputToHrTime}});var D=require_timer_util$3();Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return D.unrefTimer}});var O=require_ExportResult$3();Object.defineProperty(e,`ExportResultCode`,{enumerable:!0,get:function(){return O.ExportResultCode}});var k=require_utils$16();Object.defineProperty(e,`parseKeyPairsIntoRecord`,{enumerable:!0,get:function(){return k.parseKeyPairsIntoRecord}});var j=require_platform$11();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return j.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return j._globalThis}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return j.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return j.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return j.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return j.getStringListFromEnv}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return j.otperformance}});var F=require_composite$3();Object.defineProperty(e,`CompositePropagator`,{enumerable:!0,get:function(){return F.CompositePropagator}});var L=require_W3CTraceContextPropagator$3();Object.defineProperty(e,`TRACE_PARENT_HEADER`,{enumerable:!0,get:function(){return L.TRACE_PARENT_HEADER}}),Object.defineProperty(e,`TRACE_STATE_HEADER`,{enumerable:!0,get:function(){return L.TRACE_STATE_HEADER}}),Object.defineProperty(e,`W3CTraceContextPropagator`,{enumerable:!0,get:function(){return L.W3CTraceContextPropagator}}),Object.defineProperty(e,`parseTraceParent`,{enumerable:!0,get:function(){return L.parseTraceParent}});var B=require_rpc_metadata$3();Object.defineProperty(e,`RPCType`,{enumerable:!0,get:function(){return B.RPCType}}),Object.defineProperty(e,`deleteRPCMetadata`,{enumerable:!0,get:function(){return B.deleteRPCMetadata}}),Object.defineProperty(e,`getRPCMetadata`,{enumerable:!0,get:function(){return B.getRPCMetadata}}),Object.defineProperty(e,`setRPCMetadata`,{enumerable:!0,get:function(){return B.setRPCMetadata}});var H=require_suppress_tracing$3();Object.defineProperty(e,`isTracingSuppressed`,{enumerable:!0,get:function(){return H.isTracingSuppressed}}),Object.defineProperty(e,`suppressTracing`,{enumerable:!0,get:function(){return H.suppressTracing}}),Object.defineProperty(e,`unsuppressTracing`,{enumerable:!0,get:function(){return H.unsuppressTracing}});var q=require_TraceState$3();Object.defineProperty(e,`TraceState`,{enumerable:!0,get:function(){return q.TraceState}});var J=require_merge$3();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return J.merge}});var Y=require_timeout$3();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return Y.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return Y.callWithTimeout}});var ee=require_url$3();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return ee.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return ee.urlMatches}});var te=require_callback$3();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return te.BindOnceFuture}});var ne=require_configuration$3();Object.defineProperty(e,`diagLogLevelFromString`,{enumerable:!0,get:function(){return ne.diagLogLevelFromString}}),e.internal={_export:require_exporter$3()._export}})),require_aspromise=__commonJSMin$2(((e,t)=>{t.exports=s;function s(e,t){for(var s=Array(arguments.length-1),g=0,S=2,w=!0;S<arguments.length;)s[g++]=arguments[S++];return new Promise(function(S,E){s[g]=function(e){if(w)if(w=!1,e)E(e);else{for(var t=Array(arguments.length-1),s=0;s<t.length;)t[s++]=arguments[s];S.apply(null,t)}};try{e.apply(t||null,s)}catch(e){w&&(w=!1,E(e))}})}})),require_base64=__commonJSMin$2((e=>{var t=e;t.length=function(e){var t=e.length;if(!t)return 0;for(var s=0;--t%4>1&&e.charAt(t)===`=`;)++s;return Math.ceil(e.length*3)/4-s};for(var s=Array(64),g=Array(123),S=0;S<64;)g[s[S]=S<26?S+65:S<52?S+71:S<62?S-4:S-59|43]=S++;t.encode=function(e,t,g){for(var S=null,w=[],E=0,D=0,O;t<g;){var k=e[t++];switch(D){case 0:w[E++]=s[k>>2],O=(k&3)<<4,D=1;break;case 1:w[E++]=s[O|k>>4],O=(k&15)<<2,D=2;break;case 2:w[E++]=s[O|k>>6],w[E++]=s[k&63],D=0;break}E>8191&&((S||=[]).push(String.fromCharCode.apply(String,w)),E=0)}return D&&(w[E++]=s[O],w[E++]=61,D===1&&(w[E++]=61)),S?(E&&S.push(String.fromCharCode.apply(String,w.slice(0,E))),S.join(``)):String.fromCharCode.apply(String,w.slice(0,E))};var w=`invalid encoding`;t.decode=function(e,t,s){for(var S=s,E=0,D,O=0;O<e.length;){var k=e.charCodeAt(O++);if(k===61&&E>1)break;if((k=g[k])===void 0)throw Error(w);switch(E){case 0:D=k,E=1;break;case 1:t[s++]=D<<2|(k&48)>>4,D=k,E=2;break;case 2:t[s++]=(D&15)<<4|(k&60)>>2,D=k,E=3;break;case 3:t[s++]=(D&3)<<6|k,E=0;break}}if(E===1)throw Error(w);return s-S},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}})),require_eventemitter=__commonJSMin$2(((e,t)=>{t.exports=s;function s(){this._listeners={}}s.prototype.on=function(e,t,s){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:s||this}),this},s.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var s=this._listeners[e],g=0;g<s.length;)s[g].fn===t?s.splice(g,1):++g;return this},s.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var s=[],g=1;g<arguments.length;)s.push(arguments[g++]);for(g=0;g<t.length;)t[g].fn.apply(t[g++].ctx,s)}return this}})),require_float=__commonJSMin$2(((e,t)=>{t.exports=s(s);function s(e){return typeof Float32Array<`u`?(function(){var t=new Float32Array([-0]),s=new Uint8Array(t.buffer),g=s[3]===128;function S(e,g,S){t[0]=e,g[S]=s[0],g[S+1]=s[1],g[S+2]=s[2],g[S+3]=s[3]}function w(e,g,S){t[0]=e,g[S]=s[3],g[S+1]=s[2],g[S+2]=s[1],g[S+3]=s[0]}e.writeFloatLE=g?S:w,e.writeFloatBE=g?w:S;function E(e,g){return s[0]=e[g],s[1]=e[g+1],s[2]=e[g+2],s[3]=e[g+3],t[0]}function D(e,g){return s[3]=e[g],s[2]=e[g+1],s[1]=e[g+2],s[0]=e[g+3],t[0]}e.readFloatLE=g?E:D,e.readFloatBE=g?D:E})():(function(){function t(e,t,s,g){var S=t<0?1:0;if(S&&(t=-t),t===0)e(1/t>0?0:2147483648,s,g);else if(isNaN(t))e(2143289344,s,g);else if(t>34028234663852886e22)e((S<<31|2139095040)>>>0,s,g);else if(t<11754943508222875e-54)e((S<<31|Math.round(t/1401298464324817e-60))>>>0,s,g);else{var w=Math.floor(Math.log(t)/Math.LN2),E=Math.round(t*2**-w*8388608)&8388607;e((S<<31|w+127<<23|E)>>>0,s,g)}}e.writeFloatLE=t.bind(null,g),e.writeFloatBE=t.bind(null,S);function s(e,t,s){var g=e(t,s),S=(g>>31)*2+1,w=g>>>23&255,E=g&8388607;return w===255?E?NaN:S*(1/0):w===0?S*1401298464324817e-60*E:S*2**(w-150)*(E+8388608)}e.readFloatLE=s.bind(null,w),e.readFloatBE=s.bind(null,E)})(),typeof Float64Array<`u`?(function(){var t=new Float64Array([-0]),s=new Uint8Array(t.buffer),g=s[7]===128;function S(e,g,S){t[0]=e,g[S]=s[0],g[S+1]=s[1],g[S+2]=s[2],g[S+3]=s[3],g[S+4]=s[4],g[S+5]=s[5],g[S+6]=s[6],g[S+7]=s[7]}function w(e,g,S){t[0]=e,g[S]=s[7],g[S+1]=s[6],g[S+2]=s[5],g[S+3]=s[4],g[S+4]=s[3],g[S+5]=s[2],g[S+6]=s[1],g[S+7]=s[0]}e.writeDoubleLE=g?S:w,e.writeDoubleBE=g?w:S;function E(e,g){return s[0]=e[g],s[1]=e[g+1],s[2]=e[g+2],s[3]=e[g+3],s[4]=e[g+4],s[5]=e[g+5],s[6]=e[g+6],s[7]=e[g+7],t[0]}function D(e,g){return s[7]=e[g],s[6]=e[g+1],s[5]=e[g+2],s[4]=e[g+3],s[3]=e[g+4],s[2]=e[g+5],s[1]=e[g+6],s[0]=e[g+7],t[0]}e.readDoubleLE=g?E:D,e.readDoubleBE=g?D:E})():(function(){function t(e,t,s,g,S,w){var E=g<0?1:0;if(E&&(g=-g),g===0)e(0,S,w+t),e(1/g>0?0:2147483648,S,w+s);else if(isNaN(g))e(0,S,w+t),e(2146959360,S,w+s);else if(g>17976931348623157e292)e(0,S,w+t),e((E<<31|2146435072)>>>0,S,w+s);else{var D;if(g<22250738585072014e-324)D=g/5e-324,e(D>>>0,S,w+t),e((E<<31|D/4294967296)>>>0,S,w+s);else{var O=Math.floor(Math.log(g)/Math.LN2);O===1024&&(O=1023),D=g*2**-O,e(D*4503599627370496>>>0,S,w+t),e((E<<31|O+1023<<20|D*1048576&1048575)>>>0,S,w+s)}}}e.writeDoubleLE=t.bind(null,g,0,4),e.writeDoubleBE=t.bind(null,S,4,0);function s(e,t,s,g,S){var w=e(g,S+t),E=e(g,S+s),D=(E>>31)*2+1,O=E>>>20&2047,k=4294967296*(E&1048575)+w;return O===2047?k?NaN:D*(1/0):O===0?D*5e-324*k:D*2**(O-1075)*(k+4503599627370496)}e.readDoubleLE=s.bind(null,w,0,4),e.readDoubleBE=s.bind(null,E,4,0)})(),e}function g(e,t,s){t[s]=e&255,t[s+1]=e>>>8&255,t[s+2]=e>>>16&255,t[s+3]=e>>>24}function S(e,t,s){t[s]=e>>>24,t[s+1]=e>>>16&255,t[s+2]=e>>>8&255,t[s+3]=e&255}function w(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function E(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}})),require_inquire=__commonJSMin$2(((exports,module)=>{module.exports=inquire;function inquire(moduleName){try{var mod=eval(`quire`.replace(/^/,`re`))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch{}return null}})),require_utf8=__commonJSMin$2((e=>{var t=e;t.length=function(e){for(var t=0,s=0,g=0;g<e.length;++g)s=e.charCodeAt(g),s<128?t+=1:s<2048?t+=2:(s&64512)==55296&&(e.charCodeAt(g+1)&64512)==56320?(++g,t+=4):t+=3;return t},t.read=function(e,t,s){if(s-t<1)return``;for(var g=null,S=[],w=0,E;t<s;)E=e[t++],E<128?S[w++]=E:E>191&&E<224?S[w++]=(E&31)<<6|e[t++]&63:E>239&&E<365?(E=((E&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,S[w++]=55296+(E>>10),S[w++]=56320+(E&1023)):S[w++]=(E&15)<<12|(e[t++]&63)<<6|e[t++]&63,w>8191&&((g||=[]).push(String.fromCharCode.apply(String,S)),w=0);return g?(w&&g.push(String.fromCharCode.apply(String,S.slice(0,w))),g.join(``)):String.fromCharCode.apply(String,S.slice(0,w))},t.write=function(e,t,s){for(var g=s,S,w,E=0;E<e.length;++E)S=e.charCodeAt(E),S<128?t[s++]=S:S<2048?(t[s++]=S>>6|192,t[s++]=S&63|128):(S&64512)==55296&&((w=e.charCodeAt(E+1))&64512)==56320?(S=65536+((S&1023)<<10)+(w&1023),++E,t[s++]=S>>18|240,t[s++]=S>>12&63|128,t[s++]=S>>6&63|128,t[s++]=S&63|128):(t[s++]=S>>12|224,t[s++]=S>>6&63|128,t[s++]=S&63|128);return s-g}})),require_pool=__commonJSMin$2(((e,t)=>{t.exports=s;function s(e,t,s){var g=s||8192,S=g>>>1,w=null,E=g;return function(s){if(s<1||s>S)return e(s);E+s>g&&(w=e(g),E=0);var D=t.call(w,E,E+=s);return E&7&&(E=(E|7)+1),D}}})),require_longbits=__commonJSMin$2(((e,t)=>{t.exports=g;var s=require_minimal$1();function g(e,t){this.lo=e>>>0,this.hi=t>>>0}var S=g.zero=new g(0,0);S.toNumber=function(){return 0},S.zzEncode=S.zzDecode=function(){return this},S.length=function(){return 1};var w=g.zeroHash=`\0\0\0\0\0\0\0\0`;g.fromNumber=function(e){if(e===0)return S;var t=e<0;t&&(e=-e);var s=e>>>0,w=(e-s)/4294967296>>>0;return t&&(w=~w>>>0,s=~s>>>0,++s>4294967295&&(s=0,++w>4294967295&&(w=0))),new g(s,w)},g.from=function(e){if(typeof e==`number`)return g.fromNumber(e);if(s.isString(e))if(s.Long)e=s.Long.fromString(e);else return g.fromNumber(parseInt(e,10));return e.low||e.high?new g(e.low>>>0,e.high>>>0):S},g.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=~this.lo+1>>>0,s=~this.hi>>>0;return t||(s=s+1>>>0),-(t+s*4294967296)}return this.lo+this.hi*4294967296},g.prototype.toLong=function(e){return s.Long?new s.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var E=String.prototype.charCodeAt;g.fromHash=function(e){return e===w?S:new g((E.call(e,0)|E.call(e,1)<<8|E.call(e,2)<<16|E.call(e,3)<<24)>>>0,(E.call(e,4)|E.call(e,5)<<8|E.call(e,6)<<16|E.call(e,7)<<24)>>>0)},g.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},g.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},g.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},g.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,s=this.hi>>>24;return s===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:s<128?9:10}})),require_minimal$1=__commonJSMin$2((e=>{var t=e;t.asPromise=require_aspromise(),t.base64=require_base64(),t.EventEmitter=require_eventemitter(),t.float=require_float(),t.inquire=require_inquire(),t.utf8=require_utf8(),t.pool=require_pool(),t.LongBits=require_longbits(),t.isNode=!!(typeof global<`u`&&global&&global.process&&global.process.versions&&global.process.versions.node),t.global=t.isNode&&global||typeof window<`u`&&window||typeof self<`u`&&self||e,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e},t.isString=function(e){return typeof e==`string`||e instanceof String},t.isObject=function(e){return e&&typeof e==`object`},t.isset=t.isSet=function(e,t){var s=e[t];return s!=null&&e.hasOwnProperty(t)?typeof s!=`object`||(Array.isArray(s)?s.length:Object.keys(s).length)>0:!1},t.Buffer=(function(){try{var e=t.inquire(`buffer`).Buffer;return e.prototype.utf8Write?e:null}catch{return null}})(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(e){return typeof e==`number`?t.Buffer?t._Buffer_allocUnsafe(e):new t.Array(e):t.Buffer?t._Buffer_from(e):typeof Uint8Array>`u`?e:new Uint8Array(e)},t.Array=typeof Uint8Array<`u`?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||t.inquire(`long`),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(e){return e?t.LongBits.from(e).toHash():t.LongBits.zeroHash},t.longFromHash=function(e,s){var g=t.LongBits.fromHash(e);return t.Long?t.Long.fromBits(g.lo,g.hi,s):g.toNumber(!!s)};function s(e,t,s){for(var g=Object.keys(t),S=0;S<g.length;++S)(e[g[S]]===void 0||!s)&&(e[g[S]]=t[g[S]]);return e}t.merge=s,t.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function g(e){function t(e,g){if(!(this instanceof t))return new t(e,g);Object.defineProperty(this,`message`,{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,`stack`,{value:Error().stack||``}),g&&s(this,g)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+`: `+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}t.newError=g,t.ProtocolError=g(`ProtocolError`),t.oneOfGetter=function(e){for(var t={},s=0;s<e.length;++s)t[e[s]]=1;return function(){for(var e=Object.keys(this),s=e.length-1;s>-1;--s)if(t[e[s]]===1&&this[e[s]]!==void 0&&this[e[s]]!==null)return e[s]}},t.oneOfSetter=function(e){return function(t){for(var s=0;s<e.length;++s)e[s]!==t&&delete this[e[s]]}},t.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},t._configure=function(){var e=t.Buffer;if(!e){t._Buffer_from=t._Buffer_allocUnsafe=null;return}t._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,s){return new e(t,s)},t._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}}})),require_writer=__commonJSMin$2(((e,t)=>{t.exports=j;var s=require_minimal$1(),g,S=s.LongBits,w=s.base64,E=s.utf8;function D(e,t,s){this.fn=e,this.len=t,this.next=void 0,this.val=s}function O(){}function k(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function j(){this.len=0,this.head=new D(O,0,0),this.tail=this.head,this.states=null}var F=function(){return s.Buffer?function(){return(j.create=function(){return new g})()}:function(){return new j}};j.create=F(),j.alloc=function(e){return new s.Array(e)},s.Array!==Array&&(j.alloc=s.pool(j.alloc,s.Array.prototype.subarray)),j.prototype._push=function(e,t,s){return this.tail=this.tail.next=new D(e,t,s),this.len+=t,this};function L(e,t,s){t[s]=e&255}function B(e,t,s){for(;e>127;)t[s++]=e&127|128,e>>>=7;t[s]=e}function H(e,t){this.len=e,this.next=void 0,this.val=t}H.prototype=Object.create(D.prototype),H.prototype.fn=B,j.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new H((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},j.prototype.int32=function(e){return e<0?this._push(q,10,S.fromNumber(e)):this.uint32(e)},j.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function q(e,t,s){for(;e.hi;)t[s++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[s++]=e.lo&127|128,e.lo>>>=7;t[s++]=e.lo}j.prototype.uint64=function(e){var t=S.from(e);return this._push(q,t.length(),t)},j.prototype.int64=j.prototype.uint64,j.prototype.sint64=function(e){var t=S.from(e).zzEncode();return this._push(q,t.length(),t)},j.prototype.bool=function(e){return this._push(L,1,e?1:0)};function J(e,t,s){t[s]=e&255,t[s+1]=e>>>8&255,t[s+2]=e>>>16&255,t[s+3]=e>>>24}j.prototype.fixed32=function(e){return this._push(J,4,e>>>0)},j.prototype.sfixed32=j.prototype.fixed32,j.prototype.fixed64=function(e){var t=S.from(e);return this._push(J,4,t.lo)._push(J,4,t.hi)},j.prototype.sfixed64=j.prototype.fixed64,j.prototype.float=function(e){return this._push(s.float.writeFloatLE,4,e)},j.prototype.double=function(e){return this._push(s.float.writeDoubleLE,8,e)};var Y=s.Array.prototype.set?function(e,t,s){t.set(e,s)}:function(e,t,s){for(var g=0;g<e.length;++g)t[s+g]=e[g]};j.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(L,1,0);if(s.isString(e)){var g=j.alloc(t=w.length(e));w.decode(e,g,0),e=g}return this.uint32(t)._push(Y,t,e)},j.prototype.string=function(e){var t=E.length(e);return t?this.uint32(t)._push(E.write,t,e):this._push(L,1,0)},j.prototype.fork=function(){return this.states=new k(this),this.head=this.tail=new D(O,0,0),this.len=0,this},j.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new D(O,0,0),this.len=0),this},j.prototype.ldelim=function(){var e=this.head,t=this.tail,s=this.len;return this.reset().uint32(s),s&&(this.tail.next=e.next,this.tail=t,this.len+=s),this},j.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),s=0;e;)e.fn(e.val,t,s),s+=e.len,e=e.next;return t},j._configure=function(e){g=e,j.create=F(),g._configure()}})),require_writer_buffer=__commonJSMin$2(((e,t)=>{t.exports=S;var s=require_writer();(S.prototype=Object.create(s.prototype)).constructor=S;var g=require_minimal$1();function S(){s.call(this)}S._configure=function(){S.alloc=g._Buffer_allocUnsafe,S.writeBytesBuffer=g.Buffer&&g.Buffer.prototype instanceof Uint8Array&&g.Buffer.prototype.set.name===`set`?function(e,t,s){t.set(e,s)}:function(e,t,s){if(e.copy)e.copy(t,s,0,e.length);else for(var g=0;g<e.length;)t[s++]=e[g++]}},S.prototype.bytes=function(e){g.isString(e)&&(e=g._Buffer_from(e,`base64`));var t=e.length>>>0;return this.uint32(t),t&&this._push(S.writeBytesBuffer,t,e),this};function w(e,t,s){e.length<40?g.utf8.write(e,t,s):t.utf8Write?t.utf8Write(e,s):t.write(e,s)}S.prototype.string=function(e){var t=g.Buffer.byteLength(e);return this.uint32(t),t&&this._push(w,t,e),this},S._configure()})),require_reader=__commonJSMin$2(((e,t)=>{t.exports=D;var s=require_minimal$1(),g,S=s.LongBits,w=s.utf8;function E(e,t){return RangeError(`index out of range: `+e.pos+` + `+(t||1)+` > `+e.len)}function D(e){this.buf=e,this.pos=0,this.len=e.length}var O=typeof Uint8Array<`u`?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new D(e);throw Error(`illegal buffer`)}:function(e){if(Array.isArray(e))return new D(e);throw Error(`illegal buffer`)},k=function(){return s.Buffer?function(e){return(D.create=function(e){return s.Buffer.isBuffer(e)?new g(e):O(e)})(e)}:O};D.create=k(),D.prototype._slice=s.Array.prototype.subarray||s.Array.prototype.slice,D.prototype.uint32=(function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,E(this,10);return e}})(),D.prototype.int32=function(){return this.uint32()|0},D.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function j(){var e=new S(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw E(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw E(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error(`invalid varint encoding`)}D.prototype.bool=function(){return this.uint32()!==0};function F(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}D.prototype.fixed32=function(){if(this.pos+4>this.len)throw E(this,4);return F(this.buf,this.pos+=4)},D.prototype.sfixed32=function(){if(this.pos+4>this.len)throw E(this,4);return F(this.buf,this.pos+=4)|0};function L(){if(this.pos+8>this.len)throw E(this,8);return new S(F(this.buf,this.pos+=4),F(this.buf,this.pos+=4))}D.prototype.float=function(){if(this.pos+4>this.len)throw E(this,4);var e=s.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},D.prototype.double=function(){if(this.pos+8>this.len)throw E(this,4);var e=s.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},D.prototype.bytes=function(){var e=this.uint32(),t=this.pos,g=this.pos+e;if(g>this.len)throw E(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,g);if(t===g){var S=s.Buffer;return S?S.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,g)},D.prototype.string=function(){var e=this.bytes();return w.read(e,0,e.length)},D.prototype.skip=function(e){if(typeof e==`number`){if(this.pos+e>this.len)throw E(this,e);this.pos+=e}else do if(this.pos>=this.len)throw E(this);while(this.buf[this.pos++]&128);return this},D.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!=4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type `+e+` at offset `+this.pos)}return this},D._configure=function(e){g=e,D.create=k(),g._configure();var t=s.Long?`toLong`:`toNumber`;s.merge(D.prototype,{int64:function(){return j.call(this)[t](!1)},uint64:function(){return j.call(this)[t](!0)},sint64:function(){return j.call(this).zzDecode()[t](!1)},fixed64:function(){return L.call(this)[t](!0)},sfixed64:function(){return L.call(this)[t](!1)}})}})),require_reader_buffer=__commonJSMin$2(((e,t)=>{t.exports=S;var s=require_reader();(S.prototype=Object.create(s.prototype)).constructor=S;var g=require_minimal$1();function S(e){s.call(this,e)}S._configure=function(){g.Buffer&&(S.prototype._slice=g.Buffer.prototype.slice)},S.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString(`utf-8`,this.pos,this.pos=Math.min(this.pos+e,this.len))},S._configure()})),require_service=__commonJSMin$2(((e,t)=>{t.exports=g;var s=require_minimal$1();(g.prototype=Object.create(s.EventEmitter.prototype)).constructor=g;function g(e,t,g){if(typeof e!=`function`)throw TypeError(`rpcImpl must be a function`);s.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=!!t,this.responseDelimited=!!g}g.prototype.rpcCall=function e(t,g,S,w,E){if(!w)throw TypeError(`request must be specified`);var D=this;if(!E)return s.asPromise(e,D,t,g,S,w);if(!D.rpcImpl){setTimeout(function(){E(Error(`already ended`))},0);return}try{return D.rpcImpl(t,g[D.requestDelimited?`encodeDelimited`:`encode`](w).finish(),function(e,s){if(e)return D.emit(`error`,e,t),E(e);if(s===null){D.end(!0);return}if(!(s instanceof S))try{s=S[D.responseDelimited?`decodeDelimited`:`decode`](s)}catch(e){return D.emit(`error`,e,t),E(e)}return D.emit(`data`,s,t),E(null,s)})}catch(e){D.emit(`error`,e,t),setTimeout(function(){E(e)},0);return}},g.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit(`end`).off()),this}})),require_rpc=__commonJSMin$2((e=>{var t=e;t.Service=require_service()})),require_roots=__commonJSMin$2(((e,t)=>{t.exports={}})),require_index_minimal=__commonJSMin$2((e=>{var t=e;t.build=`minimal`,t.Writer=require_writer(),t.BufferWriter=require_writer_buffer(),t.Reader=require_reader(),t.BufferReader=require_reader_buffer(),t.util=require_minimal$1(),t.rpc=require_rpc(),t.roots=require_roots(),t.configure=s;function s(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}s()})),require_minimal=__commonJSMin$2(((e,t)=>{t.exports=require_index_minimal()})),require_root=__commonJSMin$2(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});var s=require_minimal(),g=s.Reader,S=s.Writer,w=s.util,E=s.roots.default||(s.roots.default={});E.opentelemetry=(function(){var e={};return e.proto=(function(){var e={};return e.common=(function(){var e={};return e.v1=(function(){var e={};return e.AnyValue=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.stringValue=null,e.prototype.boolValue=null,e.prototype.intValue=null,e.prototype.doubleValue=null,e.prototype.arrayValue=null,e.prototype.kvlistValue=null,e.prototype.bytesValue=null;var t;return Object.defineProperty(e.prototype,`value`,{get:w.oneOfGetter(t=[`stringValue`,`boolValue`,`intValue`,`doubleValue`,`arrayValue`,`kvlistValue`,`bytesValue`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.stringValue!=null&&Object.hasOwnProperty.call(e,`stringValue`)&&t.uint32(10).string(e.stringValue),e.boolValue!=null&&Object.hasOwnProperty.call(e,`boolValue`)&&t.uint32(16).bool(e.boolValue),e.intValue!=null&&Object.hasOwnProperty.call(e,`intValue`)&&t.uint32(24).int64(e.intValue),e.doubleValue!=null&&Object.hasOwnProperty.call(e,`doubleValue`)&&t.uint32(33).double(e.doubleValue),e.arrayValue!=null&&Object.hasOwnProperty.call(e,`arrayValue`)&&E.opentelemetry.proto.common.v1.ArrayValue.encode(e.arrayValue,t.uint32(42).fork()).ldelim(),e.kvlistValue!=null&&Object.hasOwnProperty.call(e,`kvlistValue`)&&E.opentelemetry.proto.common.v1.KeyValueList.encode(e.kvlistValue,t.uint32(50).fork()).ldelim(),e.bytesValue!=null&&Object.hasOwnProperty.call(e,`bytesValue`)&&t.uint32(58).bytes(e.bytesValue),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.AnyValue;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.stringValue=e.string();break;case 2:w.boolValue=e.bool();break;case 3:w.intValue=e.int64();break;case 4:w.doubleValue=e.double();break;case 5:w.arrayValue=E.opentelemetry.proto.common.v1.ArrayValue.decode(e,e.uint32());break;case 6:w.kvlistValue=E.opentelemetry.proto.common.v1.KeyValueList.decode(e,e.uint32());break;case 7:w.bytesValue=e.bytes();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.stringValue!=null&&e.hasOwnProperty(`stringValue`)&&(t.value=1,!w.isString(e.stringValue)))return`stringValue: string expected`;if(e.boolValue!=null&&e.hasOwnProperty(`boolValue`)){if(t.value===1)return`value: multiple values`;if(t.value=1,typeof e.boolValue!=`boolean`)return`boolValue: boolean expected`}if(e.intValue!=null&&e.hasOwnProperty(`intValue`)){if(t.value===1)return`value: multiple values`;if(t.value=1,!w.isInteger(e.intValue)&&!(e.intValue&&w.isInteger(e.intValue.low)&&w.isInteger(e.intValue.high)))return`intValue: integer|Long expected`}if(e.doubleValue!=null&&e.hasOwnProperty(`doubleValue`)){if(t.value===1)return`value: multiple values`;if(t.value=1,typeof e.doubleValue!=`number`)return`doubleValue: number expected`}if(e.arrayValue!=null&&e.hasOwnProperty(`arrayValue`)){if(t.value===1)return`value: multiple values`;t.value=1;var s=E.opentelemetry.proto.common.v1.ArrayValue.verify(e.arrayValue);if(s)return`arrayValue.`+s}if(e.kvlistValue!=null&&e.hasOwnProperty(`kvlistValue`)){if(t.value===1)return`value: multiple values`;t.value=1;var s=E.opentelemetry.proto.common.v1.KeyValueList.verify(e.kvlistValue);if(s)return`kvlistValue.`+s}if(e.bytesValue!=null&&e.hasOwnProperty(`bytesValue`)){if(t.value===1)return`value: multiple values`;if(t.value=1,!(e.bytesValue&&typeof e.bytesValue.length==`number`||w.isString(e.bytesValue)))return`bytesValue: buffer expected`}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.AnyValue)return e;var t=new E.opentelemetry.proto.common.v1.AnyValue;if(e.stringValue!=null&&(t.stringValue=String(e.stringValue)),e.boolValue!=null&&(t.boolValue=!!e.boolValue),e.intValue!=null&&(w.Long?(t.intValue=w.Long.fromValue(e.intValue)).unsigned=!1:typeof e.intValue==`string`?t.intValue=parseInt(e.intValue,10):typeof e.intValue==`number`?t.intValue=e.intValue:typeof e.intValue==`object`&&(t.intValue=new w.LongBits(e.intValue.low>>>0,e.intValue.high>>>0).toNumber())),e.doubleValue!=null&&(t.doubleValue=Number(e.doubleValue)),e.arrayValue!=null){if(typeof e.arrayValue!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.AnyValue.arrayValue: object expected`);t.arrayValue=E.opentelemetry.proto.common.v1.ArrayValue.fromObject(e.arrayValue)}if(e.kvlistValue!=null){if(typeof e.kvlistValue!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.AnyValue.kvlistValue: object expected`);t.kvlistValue=E.opentelemetry.proto.common.v1.KeyValueList.fromObject(e.kvlistValue)}return e.bytesValue!=null&&(typeof e.bytesValue==`string`?w.base64.decode(e.bytesValue,t.bytesValue=w.newBuffer(w.base64.length(e.bytesValue)),0):e.bytesValue.length>=0&&(t.bytesValue=e.bytesValue)),t},e.toObject=function(e,t){t||={};var s={};return e.stringValue!=null&&e.hasOwnProperty(`stringValue`)&&(s.stringValue=e.stringValue,t.oneofs&&(s.value=`stringValue`)),e.boolValue!=null&&e.hasOwnProperty(`boolValue`)&&(s.boolValue=e.boolValue,t.oneofs&&(s.value=`boolValue`)),e.intValue!=null&&e.hasOwnProperty(`intValue`)&&(typeof e.intValue==`number`?s.intValue=t.longs===String?String(e.intValue):e.intValue:s.intValue=t.longs===String?w.Long.prototype.toString.call(e.intValue):t.longs===Number?new w.LongBits(e.intValue.low>>>0,e.intValue.high>>>0).toNumber():e.intValue,t.oneofs&&(s.value=`intValue`)),e.doubleValue!=null&&e.hasOwnProperty(`doubleValue`)&&(s.doubleValue=t.json&&!isFinite(e.doubleValue)?String(e.doubleValue):e.doubleValue,t.oneofs&&(s.value=`doubleValue`)),e.arrayValue!=null&&e.hasOwnProperty(`arrayValue`)&&(s.arrayValue=E.opentelemetry.proto.common.v1.ArrayValue.toObject(e.arrayValue,t),t.oneofs&&(s.value=`arrayValue`)),e.kvlistValue!=null&&e.hasOwnProperty(`kvlistValue`)&&(s.kvlistValue=E.opentelemetry.proto.common.v1.KeyValueList.toObject(e.kvlistValue,t),t.oneofs&&(s.value=`kvlistValue`)),e.bytesValue!=null&&e.hasOwnProperty(`bytesValue`)&&(s.bytesValue=t.bytes===String?w.base64.encode(e.bytesValue,0,e.bytesValue.length):t.bytes===Array?Array.prototype.slice.call(e.bytesValue):e.bytesValue,t.oneofs&&(s.value=`bytesValue`)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.AnyValue`},e})(),e.ArrayValue=(function(){function e(e){if(this.values=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.values=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.values!=null&&e.values.length)for(var s=0;s<e.values.length;++s)E.opentelemetry.proto.common.v1.AnyValue.encode(e.values[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.ArrayValue;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.values&&w.values.length||(w.values=[]),w.values.push(E.opentelemetry.proto.common.v1.AnyValue.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.values!=null&&e.hasOwnProperty(`values`)){if(!Array.isArray(e.values))return`values: array expected`;for(var t=0;t<e.values.length;++t){var s=E.opentelemetry.proto.common.v1.AnyValue.verify(e.values[t]);if(s)return`values.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.ArrayValue)return e;var t=new E.opentelemetry.proto.common.v1.ArrayValue;if(e.values){if(!Array.isArray(e.values))throw TypeError(`.opentelemetry.proto.common.v1.ArrayValue.values: array expected`);t.values=[];for(var s=0;s<e.values.length;++s){if(typeof e.values[s]!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.ArrayValue.values: object expected`);t.values[s]=E.opentelemetry.proto.common.v1.AnyValue.fromObject(e.values[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.values=[]),e.values&&e.values.length){s.values=[];for(var g=0;g<e.values.length;++g)s.values[g]=E.opentelemetry.proto.common.v1.AnyValue.toObject(e.values[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.ArrayValue`},e})(),e.KeyValueList=(function(){function e(e){if(this.values=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.values=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.values!=null&&e.values.length)for(var s=0;s<e.values.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.values[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.KeyValueList;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.values&&w.values.length||(w.values=[]),w.values.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.values!=null&&e.hasOwnProperty(`values`)){if(!Array.isArray(e.values))return`values: array expected`;for(var t=0;t<e.values.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.values[t]);if(s)return`values.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.KeyValueList)return e;var t=new E.opentelemetry.proto.common.v1.KeyValueList;if(e.values){if(!Array.isArray(e.values))throw TypeError(`.opentelemetry.proto.common.v1.KeyValueList.values: array expected`);t.values=[];for(var s=0;s<e.values.length;++s){if(typeof e.values[s]!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.KeyValueList.values: object expected`);t.values[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.values[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.values=[]),e.values&&e.values.length){s.values=[];for(var g=0;g<e.values.length;++g)s.values[g]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.values[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.KeyValueList`},e})(),e.KeyValue=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.key=null,e.prototype.value=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.key!=null&&Object.hasOwnProperty.call(e,`key`)&&t.uint32(10).string(e.key),e.value!=null&&Object.hasOwnProperty.call(e,`value`)&&E.opentelemetry.proto.common.v1.AnyValue.encode(e.value,t.uint32(18).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.KeyValue;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.key=e.string();break;case 2:w.value=E.opentelemetry.proto.common.v1.AnyValue.decode(e,e.uint32());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.key!=null&&e.hasOwnProperty(`key`)&&!w.isString(e.key))return`key: string expected`;if(e.value!=null&&e.hasOwnProperty(`value`)){var t=E.opentelemetry.proto.common.v1.AnyValue.verify(e.value);if(t)return`value.`+t}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.KeyValue)return e;var t=new E.opentelemetry.proto.common.v1.KeyValue;if(e.key!=null&&(t.key=String(e.key)),e.value!=null){if(typeof e.value!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.KeyValue.value: object expected`);t.value=E.opentelemetry.proto.common.v1.AnyValue.fromObject(e.value)}return t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.key=``,s.value=null),e.key!=null&&e.hasOwnProperty(`key`)&&(s.key=e.key),e.value!=null&&e.hasOwnProperty(`value`)&&(s.value=E.opentelemetry.proto.common.v1.AnyValue.toObject(e.value,t)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.KeyValue`},e})(),e.InstrumentationScope=(function(){function e(e){if(this.attributes=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.name=null,e.prototype.version=null,e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.name!=null&&Object.hasOwnProperty.call(e,`name`)&&t.uint32(10).string(e.name),e.version!=null&&Object.hasOwnProperty.call(e,`version`)&&t.uint32(18).string(e.version),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(26).fork()).ldelim();return e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(32).uint32(e.droppedAttributesCount),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.InstrumentationScope;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.name=e.string();break;case 2:w.version=e.string();break;case 3:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 4:w.droppedAttributesCount=e.uint32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.name!=null&&e.hasOwnProperty(`name`)&&!w.isString(e.name))return`name: string expected`;if(e.version!=null&&e.hasOwnProperty(`version`)&&!w.isString(e.version))return`version: string expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount)?`droppedAttributesCount: integer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.InstrumentationScope)return e;var t=new E.opentelemetry.proto.common.v1.InstrumentationScope;if(e.name!=null&&(t.name=String(e.name)),e.version!=null&&(t.version=String(e.version)),e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.common.v1.InstrumentationScope.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.common.v1.InstrumentationScope.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}return e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[]),t.defaults&&(s.name=``,s.version=``,s.droppedAttributesCount=0),e.name!=null&&e.hasOwnProperty(`name`)&&(s.name=e.name),e.version!=null&&e.hasOwnProperty(`version`)&&(s.version=e.version),e.attributes&&e.attributes.length){s.attributes=[];for(var g=0;g<e.attributes.length;++g)s.attributes[g]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[g],t)}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.InstrumentationScope`},e})(),e.EntityRef=(function(){function e(e){if(this.idKeys=[],this.descriptionKeys=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.schemaUrl=null,e.prototype.type=null,e.prototype.idKeys=w.emptyArray,e.prototype.descriptionKeys=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(10).string(e.schemaUrl),e.type!=null&&Object.hasOwnProperty.call(e,`type`)&&t.uint32(18).string(e.type),e.idKeys!=null&&e.idKeys.length)for(var s=0;s<e.idKeys.length;++s)t.uint32(26).string(e.idKeys[s]);if(e.descriptionKeys!=null&&e.descriptionKeys.length)for(var s=0;s<e.descriptionKeys.length;++s)t.uint32(34).string(e.descriptionKeys[s]);return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.common.v1.EntityRef;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.schemaUrl=e.string();break;case 2:w.type=e.string();break;case 3:w.idKeys&&w.idKeys.length||(w.idKeys=[]),w.idKeys.push(e.string());break;case 4:w.descriptionKeys&&w.descriptionKeys.length||(w.descriptionKeys=[]),w.descriptionKeys.push(e.string());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl))return`schemaUrl: string expected`;if(e.type!=null&&e.hasOwnProperty(`type`)&&!w.isString(e.type))return`type: string expected`;if(e.idKeys!=null&&e.hasOwnProperty(`idKeys`)){if(!Array.isArray(e.idKeys))return`idKeys: array expected`;for(var t=0;t<e.idKeys.length;++t)if(!w.isString(e.idKeys[t]))return`idKeys: string[] expected`}if(e.descriptionKeys!=null&&e.hasOwnProperty(`descriptionKeys`)){if(!Array.isArray(e.descriptionKeys))return`descriptionKeys: array expected`;for(var t=0;t<e.descriptionKeys.length;++t)if(!w.isString(e.descriptionKeys[t]))return`descriptionKeys: string[] expected`}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.common.v1.EntityRef)return e;var t=new E.opentelemetry.proto.common.v1.EntityRef;if(e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),e.type!=null&&(t.type=String(e.type)),e.idKeys){if(!Array.isArray(e.idKeys))throw TypeError(`.opentelemetry.proto.common.v1.EntityRef.idKeys: array expected`);t.idKeys=[];for(var s=0;s<e.idKeys.length;++s)t.idKeys[s]=String(e.idKeys[s])}if(e.descriptionKeys){if(!Array.isArray(e.descriptionKeys))throw TypeError(`.opentelemetry.proto.common.v1.EntityRef.descriptionKeys: array expected`);t.descriptionKeys=[];for(var s=0;s<e.descriptionKeys.length;++s)t.descriptionKeys[s]=String(e.descriptionKeys[s])}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.idKeys=[],s.descriptionKeys=[]),t.defaults&&(s.schemaUrl=``,s.type=``),e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),e.type!=null&&e.hasOwnProperty(`type`)&&(s.type=e.type),e.idKeys&&e.idKeys.length){s.idKeys=[];for(var g=0;g<e.idKeys.length;++g)s.idKeys[g]=e.idKeys[g]}if(e.descriptionKeys&&e.descriptionKeys.length){s.descriptionKeys=[];for(var g=0;g<e.descriptionKeys.length;++g)s.descriptionKeys[g]=e.descriptionKeys[g]}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.common.v1.EntityRef`},e})(),e})(),e})(),e.resource=(function(){var e={};return e.v1=(function(){var e={};return e.Resource=(function(){function e(e){if(this.attributes=[],this.entityRefs=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.prototype.entityRefs=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(10).fork()).ldelim();if(e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(16).uint32(e.droppedAttributesCount),e.entityRefs!=null&&e.entityRefs.length)for(var s=0;s<e.entityRefs.length;++s)E.opentelemetry.proto.common.v1.EntityRef.encode(e.entityRefs[s],t.uint32(26).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.resource.v1.Resource;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.droppedAttributesCount=e.uint32();break;case 3:w.entityRefs&&w.entityRefs.length||(w.entityRefs=[]),w.entityRefs.push(E.opentelemetry.proto.common.v1.EntityRef.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}if(e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount))return`droppedAttributesCount: integer expected`;if(e.entityRefs!=null&&e.hasOwnProperty(`entityRefs`)){if(!Array.isArray(e.entityRefs))return`entityRefs: array expected`;for(var t=0;t<e.entityRefs.length;++t){var s=E.opentelemetry.proto.common.v1.EntityRef.verify(e.entityRefs[t]);if(s)return`entityRefs.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.resource.v1.Resource)return e;var t=new E.opentelemetry.proto.resource.v1.Resource;if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.resource.v1.Resource.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.resource.v1.Resource.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),e.entityRefs){if(!Array.isArray(e.entityRefs))throw TypeError(`.opentelemetry.proto.resource.v1.Resource.entityRefs: array expected`);t.entityRefs=[];for(var s=0;s<e.entityRefs.length;++s){if(typeof e.entityRefs[s]!=`object`)throw TypeError(`.opentelemetry.proto.resource.v1.Resource.entityRefs: object expected`);t.entityRefs[s]=E.opentelemetry.proto.common.v1.EntityRef.fromObject(e.entityRefs[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[],s.entityRefs=[]),t.defaults&&(s.droppedAttributesCount=0),e.attributes&&e.attributes.length){s.attributes=[];for(var g=0;g<e.attributes.length;++g)s.attributes[g]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[g],t)}if(e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),e.entityRefs&&e.entityRefs.length){s.entityRefs=[];for(var g=0;g<e.entityRefs.length;++g)s.entityRefs[g]=E.opentelemetry.proto.common.v1.EntityRef.toObject(e.entityRefs[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.resource.v1.Resource`},e})(),e})(),e})(),e.trace=(function(){var e={};return e.v1=(function(){var e={};return e.TracesData=(function(){function e(e){if(this.resourceSpans=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceSpans=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceSpans!=null&&e.resourceSpans.length)for(var s=0;s<e.resourceSpans.length;++s)E.opentelemetry.proto.trace.v1.ResourceSpans.encode(e.resourceSpans[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.TracesData;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceSpans&&w.resourceSpans.length||(w.resourceSpans=[]),w.resourceSpans.push(E.opentelemetry.proto.trace.v1.ResourceSpans.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceSpans!=null&&e.hasOwnProperty(`resourceSpans`)){if(!Array.isArray(e.resourceSpans))return`resourceSpans: array expected`;for(var t=0;t<e.resourceSpans.length;++t){var s=E.opentelemetry.proto.trace.v1.ResourceSpans.verify(e.resourceSpans[t]);if(s)return`resourceSpans.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.TracesData)return e;var t=new E.opentelemetry.proto.trace.v1.TracesData;if(e.resourceSpans){if(!Array.isArray(e.resourceSpans))throw TypeError(`.opentelemetry.proto.trace.v1.TracesData.resourceSpans: array expected`);t.resourceSpans=[];for(var s=0;s<e.resourceSpans.length;++s){if(typeof e.resourceSpans[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.TracesData.resourceSpans: object expected`);t.resourceSpans[s]=E.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(e.resourceSpans[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceSpans=[]),e.resourceSpans&&e.resourceSpans.length){s.resourceSpans=[];for(var g=0;g<e.resourceSpans.length;++g)s.resourceSpans[g]=E.opentelemetry.proto.trace.v1.ResourceSpans.toObject(e.resourceSpans[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.TracesData`},e})(),e.ResourceSpans=(function(){function e(e){if(this.scopeSpans=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resource=null,e.prototype.scopeSpans=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resource!=null&&Object.hasOwnProperty.call(e,`resource`)&&E.opentelemetry.proto.resource.v1.Resource.encode(e.resource,t.uint32(10).fork()).ldelim(),e.scopeSpans!=null&&e.scopeSpans.length)for(var s=0;s<e.scopeSpans.length;++s)E.opentelemetry.proto.trace.v1.ScopeSpans.encode(e.scopeSpans[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.ResourceSpans;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resource=E.opentelemetry.proto.resource.v1.Resource.decode(e,e.uint32());break;case 2:w.scopeSpans&&w.scopeSpans.length||(w.scopeSpans=[]),w.scopeSpans.push(E.opentelemetry.proto.trace.v1.ScopeSpans.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resource!=null&&e.hasOwnProperty(`resource`)){var t=E.opentelemetry.proto.resource.v1.Resource.verify(e.resource);if(t)return`resource.`+t}if(e.scopeSpans!=null&&e.hasOwnProperty(`scopeSpans`)){if(!Array.isArray(e.scopeSpans))return`scopeSpans: array expected`;for(var s=0;s<e.scopeSpans.length;++s){var t=E.opentelemetry.proto.trace.v1.ScopeSpans.verify(e.scopeSpans[s]);if(t)return`scopeSpans.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.ResourceSpans)return e;var t=new E.opentelemetry.proto.trace.v1.ResourceSpans;if(e.resource!=null){if(typeof e.resource!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.ResourceSpans.resource: object expected`);t.resource=E.opentelemetry.proto.resource.v1.Resource.fromObject(e.resource)}if(e.scopeSpans){if(!Array.isArray(e.scopeSpans))throw TypeError(`.opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: array expected`);t.scopeSpans=[];for(var s=0;s<e.scopeSpans.length;++s){if(typeof e.scopeSpans[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: object expected`);t.scopeSpans[s]=E.opentelemetry.proto.trace.v1.ScopeSpans.fromObject(e.scopeSpans[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.scopeSpans=[]),t.defaults&&(s.resource=null,s.schemaUrl=``),e.resource!=null&&e.hasOwnProperty(`resource`)&&(s.resource=E.opentelemetry.proto.resource.v1.Resource.toObject(e.resource,t)),e.scopeSpans&&e.scopeSpans.length){s.scopeSpans=[];for(var g=0;g<e.scopeSpans.length;++g)s.scopeSpans[g]=E.opentelemetry.proto.trace.v1.ScopeSpans.toObject(e.scopeSpans[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.ResourceSpans`},e})(),e.ScopeSpans=(function(){function e(e){if(this.spans=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.scope=null,e.prototype.spans=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.scope!=null&&Object.hasOwnProperty.call(e,`scope`)&&E.opentelemetry.proto.common.v1.InstrumentationScope.encode(e.scope,t.uint32(10).fork()).ldelim(),e.spans!=null&&e.spans.length)for(var s=0;s<e.spans.length;++s)E.opentelemetry.proto.trace.v1.Span.encode(e.spans[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.ScopeSpans;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.decode(e,e.uint32());break;case 2:w.spans&&w.spans.length||(w.spans=[]),w.spans.push(E.opentelemetry.proto.trace.v1.Span.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.scope!=null&&e.hasOwnProperty(`scope`)){var t=E.opentelemetry.proto.common.v1.InstrumentationScope.verify(e.scope);if(t)return`scope.`+t}if(e.spans!=null&&e.hasOwnProperty(`spans`)){if(!Array.isArray(e.spans))return`spans: array expected`;for(var s=0;s<e.spans.length;++s){var t=E.opentelemetry.proto.trace.v1.Span.verify(e.spans[s]);if(t)return`spans.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.ScopeSpans)return e;var t=new E.opentelemetry.proto.trace.v1.ScopeSpans;if(e.scope!=null){if(typeof e.scope!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.ScopeSpans.scope: object expected`);t.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(e.scope)}if(e.spans){if(!Array.isArray(e.spans))throw TypeError(`.opentelemetry.proto.trace.v1.ScopeSpans.spans: array expected`);t.spans=[];for(var s=0;s<e.spans.length;++s){if(typeof e.spans[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.ScopeSpans.spans: object expected`);t.spans[s]=E.opentelemetry.proto.trace.v1.Span.fromObject(e.spans[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.spans=[]),t.defaults&&(s.scope=null,s.schemaUrl=``),e.scope!=null&&e.hasOwnProperty(`scope`)&&(s.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.toObject(e.scope,t)),e.spans&&e.spans.length){s.spans=[];for(var g=0;g<e.spans.length;++g)s.spans[g]=E.opentelemetry.proto.trace.v1.Span.toObject(e.spans[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.ScopeSpans`},e})(),e.Span=(function(){function e(e){if(this.attributes=[],this.events=[],this.links=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.traceId=null,e.prototype.spanId=null,e.prototype.traceState=null,e.prototype.parentSpanId=null,e.prototype.flags=null,e.prototype.name=null,e.prototype.kind=null,e.prototype.startTimeUnixNano=null,e.prototype.endTimeUnixNano=null,e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.prototype.events=w.emptyArray,e.prototype.droppedEventsCount=null,e.prototype.links=w.emptyArray,e.prototype.droppedLinksCount=null,e.prototype.status=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.traceId!=null&&Object.hasOwnProperty.call(e,`traceId`)&&t.uint32(10).bytes(e.traceId),e.spanId!=null&&Object.hasOwnProperty.call(e,`spanId`)&&t.uint32(18).bytes(e.spanId),e.traceState!=null&&Object.hasOwnProperty.call(e,`traceState`)&&t.uint32(26).string(e.traceState),e.parentSpanId!=null&&Object.hasOwnProperty.call(e,`parentSpanId`)&&t.uint32(34).bytes(e.parentSpanId),e.name!=null&&Object.hasOwnProperty.call(e,`name`)&&t.uint32(42).string(e.name),e.kind!=null&&Object.hasOwnProperty.call(e,`kind`)&&t.uint32(48).int32(e.kind),e.startTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`startTimeUnixNano`)&&t.uint32(57).fixed64(e.startTimeUnixNano),e.endTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`endTimeUnixNano`)&&t.uint32(65).fixed64(e.endTimeUnixNano),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(74).fork()).ldelim();if(e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(80).uint32(e.droppedAttributesCount),e.events!=null&&e.events.length)for(var s=0;s<e.events.length;++s)E.opentelemetry.proto.trace.v1.Span.Event.encode(e.events[s],t.uint32(90).fork()).ldelim();if(e.droppedEventsCount!=null&&Object.hasOwnProperty.call(e,`droppedEventsCount`)&&t.uint32(96).uint32(e.droppedEventsCount),e.links!=null&&e.links.length)for(var s=0;s<e.links.length;++s)E.opentelemetry.proto.trace.v1.Span.Link.encode(e.links[s],t.uint32(106).fork()).ldelim();return e.droppedLinksCount!=null&&Object.hasOwnProperty.call(e,`droppedLinksCount`)&&t.uint32(112).uint32(e.droppedLinksCount),e.status!=null&&Object.hasOwnProperty.call(e,`status`)&&E.opentelemetry.proto.trace.v1.Status.encode(e.status,t.uint32(122).fork()).ldelim(),e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(133).fixed32(e.flags),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.Span;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.traceId=e.bytes();break;case 2:w.spanId=e.bytes();break;case 3:w.traceState=e.string();break;case 4:w.parentSpanId=e.bytes();break;case 16:w.flags=e.fixed32();break;case 5:w.name=e.string();break;case 6:w.kind=e.int32();break;case 7:w.startTimeUnixNano=e.fixed64();break;case 8:w.endTimeUnixNano=e.fixed64();break;case 9:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 10:w.droppedAttributesCount=e.uint32();break;case 11:w.events&&w.events.length||(w.events=[]),w.events.push(E.opentelemetry.proto.trace.v1.Span.Event.decode(e,e.uint32()));break;case 12:w.droppedEventsCount=e.uint32();break;case 13:w.links&&w.links.length||(w.links=[]),w.links.push(E.opentelemetry.proto.trace.v1.Span.Link.decode(e,e.uint32()));break;case 14:w.droppedLinksCount=e.uint32();break;case 15:w.status=E.opentelemetry.proto.trace.v1.Status.decode(e,e.uint32());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.traceId!=null&&e.hasOwnProperty(`traceId`)&&!(e.traceId&&typeof e.traceId.length==`number`||w.isString(e.traceId)))return`traceId: buffer expected`;if(e.spanId!=null&&e.hasOwnProperty(`spanId`)&&!(e.spanId&&typeof e.spanId.length==`number`||w.isString(e.spanId)))return`spanId: buffer expected`;if(e.traceState!=null&&e.hasOwnProperty(`traceState`)&&!w.isString(e.traceState))return`traceState: string expected`;if(e.parentSpanId!=null&&e.hasOwnProperty(`parentSpanId`)&&!(e.parentSpanId&&typeof e.parentSpanId.length==`number`||w.isString(e.parentSpanId)))return`parentSpanId: buffer expected`;if(e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags))return`flags: integer expected`;if(e.name!=null&&e.hasOwnProperty(`name`)&&!w.isString(e.name))return`name: string expected`;if(e.kind!=null&&e.hasOwnProperty(`kind`))switch(e.kind){default:return`kind: enum value expected`;case 0:case 1:case 2:case 3:case 4:case 5:break}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&!w.isInteger(e.startTimeUnixNano)&&!(e.startTimeUnixNano&&w.isInteger(e.startTimeUnixNano.low)&&w.isInteger(e.startTimeUnixNano.high)))return`startTimeUnixNano: integer|Long expected`;if(e.endTimeUnixNano!=null&&e.hasOwnProperty(`endTimeUnixNano`)&&!w.isInteger(e.endTimeUnixNano)&&!(e.endTimeUnixNano&&w.isInteger(e.endTimeUnixNano.low)&&w.isInteger(e.endTimeUnixNano.high)))return`endTimeUnixNano: integer|Long expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}if(e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount))return`droppedAttributesCount: integer expected`;if(e.events!=null&&e.hasOwnProperty(`events`)){if(!Array.isArray(e.events))return`events: array expected`;for(var t=0;t<e.events.length;++t){var s=E.opentelemetry.proto.trace.v1.Span.Event.verify(e.events[t]);if(s)return`events.`+s}}if(e.droppedEventsCount!=null&&e.hasOwnProperty(`droppedEventsCount`)&&!w.isInteger(e.droppedEventsCount))return`droppedEventsCount: integer expected`;if(e.links!=null&&e.hasOwnProperty(`links`)){if(!Array.isArray(e.links))return`links: array expected`;for(var t=0;t<e.links.length;++t){var s=E.opentelemetry.proto.trace.v1.Span.Link.verify(e.links[t]);if(s)return`links.`+s}}if(e.droppedLinksCount!=null&&e.hasOwnProperty(`droppedLinksCount`)&&!w.isInteger(e.droppedLinksCount))return`droppedLinksCount: integer expected`;if(e.status!=null&&e.hasOwnProperty(`status`)){var s=E.opentelemetry.proto.trace.v1.Status.verify(e.status);if(s)return`status.`+s}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.Span)return e;var t=new E.opentelemetry.proto.trace.v1.Span;switch(e.traceId!=null&&(typeof e.traceId==`string`?w.base64.decode(e.traceId,t.traceId=w.newBuffer(w.base64.length(e.traceId)),0):e.traceId.length>=0&&(t.traceId=e.traceId)),e.spanId!=null&&(typeof e.spanId==`string`?w.base64.decode(e.spanId,t.spanId=w.newBuffer(w.base64.length(e.spanId)),0):e.spanId.length>=0&&(t.spanId=e.spanId)),e.traceState!=null&&(t.traceState=String(e.traceState)),e.parentSpanId!=null&&(typeof e.parentSpanId==`string`?w.base64.decode(e.parentSpanId,t.parentSpanId=w.newBuffer(w.base64.length(e.parentSpanId)),0):e.parentSpanId.length>=0&&(t.parentSpanId=e.parentSpanId)),e.flags!=null&&(t.flags=e.flags>>>0),e.name!=null&&(t.name=String(e.name)),e.kind){default:if(typeof e.kind==`number`){t.kind=e.kind;break}break;case`SPAN_KIND_UNSPECIFIED`:case 0:t.kind=0;break;case`SPAN_KIND_INTERNAL`:case 1:t.kind=1;break;case`SPAN_KIND_SERVER`:case 2:t.kind=2;break;case`SPAN_KIND_CLIENT`:case 3:t.kind=3;break;case`SPAN_KIND_PRODUCER`:case 4:t.kind=4;break;case`SPAN_KIND_CONSUMER`:case 5:t.kind=5;break}if(e.startTimeUnixNano!=null&&(w.Long?(t.startTimeUnixNano=w.Long.fromValue(e.startTimeUnixNano)).unsigned=!1:typeof e.startTimeUnixNano==`string`?t.startTimeUnixNano=parseInt(e.startTimeUnixNano,10):typeof e.startTimeUnixNano==`number`?t.startTimeUnixNano=e.startTimeUnixNano:typeof e.startTimeUnixNano==`object`&&(t.startTimeUnixNano=new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber())),e.endTimeUnixNano!=null&&(w.Long?(t.endTimeUnixNano=w.Long.fromValue(e.endTimeUnixNano)).unsigned=!1:typeof e.endTimeUnixNano==`string`?t.endTimeUnixNano=parseInt(e.endTimeUnixNano,10):typeof e.endTimeUnixNano==`number`?t.endTimeUnixNano=e.endTimeUnixNano:typeof e.endTimeUnixNano==`object`&&(t.endTimeUnixNano=new w.LongBits(e.endTimeUnixNano.low>>>0,e.endTimeUnixNano.high>>>0).toNumber())),e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.trace.v1.Span.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),e.events){if(!Array.isArray(e.events))throw TypeError(`.opentelemetry.proto.trace.v1.Span.events: array expected`);t.events=[];for(var s=0;s<e.events.length;++s){if(typeof e.events[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.events: object expected`);t.events[s]=E.opentelemetry.proto.trace.v1.Span.Event.fromObject(e.events[s])}}if(e.droppedEventsCount!=null&&(t.droppedEventsCount=e.droppedEventsCount>>>0),e.links){if(!Array.isArray(e.links))throw TypeError(`.opentelemetry.proto.trace.v1.Span.links: array expected`);t.links=[];for(var s=0;s<e.links.length;++s){if(typeof e.links[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.links: object expected`);t.links[s]=E.opentelemetry.proto.trace.v1.Span.Link.fromObject(e.links[s])}}if(e.droppedLinksCount!=null&&(t.droppedLinksCount=e.droppedLinksCount>>>0),e.status!=null){if(typeof e.status!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.status: object expected`);t.status=E.opentelemetry.proto.trace.v1.Status.fromObject(e.status)}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[],s.events=[],s.links=[]),t.defaults){if(t.bytes===String?s.traceId=``:(s.traceId=[],t.bytes!==Array&&(s.traceId=w.newBuffer(s.traceId))),t.bytes===String?s.spanId=``:(s.spanId=[],t.bytes!==Array&&(s.spanId=w.newBuffer(s.spanId))),s.traceState=``,t.bytes===String?s.parentSpanId=``:(s.parentSpanId=[],t.bytes!==Array&&(s.parentSpanId=w.newBuffer(s.parentSpanId))),s.name=``,s.kind=t.enums===String?`SPAN_KIND_UNSPECIFIED`:0,w.Long){var g=new w.Long(0,0,!1);s.startTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.startTimeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.endTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.endTimeUnixNano=t.longs===String?`0`:0;s.droppedAttributesCount=0,s.droppedEventsCount=0,s.droppedLinksCount=0,s.status=null,s.flags=0}if(e.traceId!=null&&e.hasOwnProperty(`traceId`)&&(s.traceId=t.bytes===String?w.base64.encode(e.traceId,0,e.traceId.length):t.bytes===Array?Array.prototype.slice.call(e.traceId):e.traceId),e.spanId!=null&&e.hasOwnProperty(`spanId`)&&(s.spanId=t.bytes===String?w.base64.encode(e.spanId,0,e.spanId.length):t.bytes===Array?Array.prototype.slice.call(e.spanId):e.spanId),e.traceState!=null&&e.hasOwnProperty(`traceState`)&&(s.traceState=e.traceState),e.parentSpanId!=null&&e.hasOwnProperty(`parentSpanId`)&&(s.parentSpanId=t.bytes===String?w.base64.encode(e.parentSpanId,0,e.parentSpanId.length):t.bytes===Array?Array.prototype.slice.call(e.parentSpanId):e.parentSpanId),e.name!=null&&e.hasOwnProperty(`name`)&&(s.name=e.name),e.kind!=null&&e.hasOwnProperty(`kind`)&&(s.kind=t.enums===String?E.opentelemetry.proto.trace.v1.Span.SpanKind[e.kind]===void 0?e.kind:E.opentelemetry.proto.trace.v1.Span.SpanKind[e.kind]:e.kind),e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&(typeof e.startTimeUnixNano==`number`?s.startTimeUnixNano=t.longs===String?String(e.startTimeUnixNano):e.startTimeUnixNano:s.startTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.startTimeUnixNano):t.longs===Number?new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber():e.startTimeUnixNano),e.endTimeUnixNano!=null&&e.hasOwnProperty(`endTimeUnixNano`)&&(typeof e.endTimeUnixNano==`number`?s.endTimeUnixNano=t.longs===String?String(e.endTimeUnixNano):e.endTimeUnixNano:s.endTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.endTimeUnixNano):t.longs===Number?new w.LongBits(e.endTimeUnixNano.low>>>0,e.endTimeUnixNano.high>>>0).toNumber():e.endTimeUnixNano),e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}if(e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),e.events&&e.events.length){s.events=[];for(var S=0;S<e.events.length;++S)s.events[S]=E.opentelemetry.proto.trace.v1.Span.Event.toObject(e.events[S],t)}if(e.droppedEventsCount!=null&&e.hasOwnProperty(`droppedEventsCount`)&&(s.droppedEventsCount=e.droppedEventsCount),e.links&&e.links.length){s.links=[];for(var S=0;S<e.links.length;++S)s.links[S]=E.opentelemetry.proto.trace.v1.Span.Link.toObject(e.links[S],t)}return e.droppedLinksCount!=null&&e.hasOwnProperty(`droppedLinksCount`)&&(s.droppedLinksCount=e.droppedLinksCount),e.status!=null&&e.hasOwnProperty(`status`)&&(s.status=E.opentelemetry.proto.trace.v1.Status.toObject(e.status,t)),e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.Span`},e.SpanKind=(function(){var e={},t=Object.create(e);return t[e[0]=`SPAN_KIND_UNSPECIFIED`]=0,t[e[1]=`SPAN_KIND_INTERNAL`]=1,t[e[2]=`SPAN_KIND_SERVER`]=2,t[e[3]=`SPAN_KIND_CLIENT`]=3,t[e[4]=`SPAN_KIND_PRODUCER`]=4,t[e[5]=`SPAN_KIND_CONSUMER`]=5,t})(),e.Event=(function(){function e(e){if(this.attributes=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.timeUnixNano=null,e.prototype.name=null,e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(9).fixed64(e.timeUnixNano),e.name!=null&&Object.hasOwnProperty.call(e,`name`)&&t.uint32(18).string(e.name),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(26).fork()).ldelim();return e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(32).uint32(e.droppedAttributesCount),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.Span.Event;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.timeUnixNano=e.fixed64();break;case 2:w.name=e.string();break;case 3:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 4:w.droppedAttributesCount=e.uint32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.name!=null&&e.hasOwnProperty(`name`)&&!w.isString(e.name))return`name: string expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount)?`droppedAttributesCount: integer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.Span.Event)return e;var t=new E.opentelemetry.proto.trace.v1.Span.Event;if(e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.name!=null&&(t.name=String(e.name)),e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.trace.v1.Span.Event.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.Event.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}return e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;s.name=``,s.droppedAttributesCount=0}if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.name!=null&&e.hasOwnProperty(`name`)&&(s.name=e.name),e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.Span.Event`},e})(),e.Link=(function(){function e(e){if(this.attributes=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.traceId=null,e.prototype.spanId=null,e.prototype.traceState=null,e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.prototype.flags=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.traceId!=null&&Object.hasOwnProperty.call(e,`traceId`)&&t.uint32(10).bytes(e.traceId),e.spanId!=null&&Object.hasOwnProperty.call(e,`spanId`)&&t.uint32(18).bytes(e.spanId),e.traceState!=null&&Object.hasOwnProperty.call(e,`traceState`)&&t.uint32(26).string(e.traceState),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(34).fork()).ldelim();return e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(40).uint32(e.droppedAttributesCount),e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(53).fixed32(e.flags),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.Span.Link;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.traceId=e.bytes();break;case 2:w.spanId=e.bytes();break;case 3:w.traceState=e.string();break;case 4:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 5:w.droppedAttributesCount=e.uint32();break;case 6:w.flags=e.fixed32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.traceId!=null&&e.hasOwnProperty(`traceId`)&&!(e.traceId&&typeof e.traceId.length==`number`||w.isString(e.traceId)))return`traceId: buffer expected`;if(e.spanId!=null&&e.hasOwnProperty(`spanId`)&&!(e.spanId&&typeof e.spanId.length==`number`||w.isString(e.spanId)))return`spanId: buffer expected`;if(e.traceState!=null&&e.hasOwnProperty(`traceState`)&&!w.isString(e.traceState))return`traceState: string expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount)?`droppedAttributesCount: integer expected`:e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags)?`flags: integer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.Span.Link)return e;var t=new E.opentelemetry.proto.trace.v1.Span.Link;if(e.traceId!=null&&(typeof e.traceId==`string`?w.base64.decode(e.traceId,t.traceId=w.newBuffer(w.base64.length(e.traceId)),0):e.traceId.length>=0&&(t.traceId=e.traceId)),e.spanId!=null&&(typeof e.spanId==`string`?w.base64.decode(e.spanId,t.spanId=w.newBuffer(w.base64.length(e.spanId)),0):e.spanId.length>=0&&(t.spanId=e.spanId)),e.traceState!=null&&(t.traceState=String(e.traceState)),e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.trace.v1.Span.Link.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.trace.v1.Span.Link.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}return e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),e.flags!=null&&(t.flags=e.flags>>>0),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[]),t.defaults&&(t.bytes===String?s.traceId=``:(s.traceId=[],t.bytes!==Array&&(s.traceId=w.newBuffer(s.traceId))),t.bytes===String?s.spanId=``:(s.spanId=[],t.bytes!==Array&&(s.spanId=w.newBuffer(s.spanId))),s.traceState=``,s.droppedAttributesCount=0,s.flags=0),e.traceId!=null&&e.hasOwnProperty(`traceId`)&&(s.traceId=t.bytes===String?w.base64.encode(e.traceId,0,e.traceId.length):t.bytes===Array?Array.prototype.slice.call(e.traceId):e.traceId),e.spanId!=null&&e.hasOwnProperty(`spanId`)&&(s.spanId=t.bytes===String?w.base64.encode(e.spanId,0,e.spanId.length):t.bytes===Array?Array.prototype.slice.call(e.spanId):e.spanId),e.traceState!=null&&e.hasOwnProperty(`traceState`)&&(s.traceState=e.traceState),e.attributes&&e.attributes.length){s.attributes=[];for(var g=0;g<e.attributes.length;++g)s.attributes[g]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[g],t)}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.Span.Link`},e})(),e})(),e.Status=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.message=null,e.prototype.code=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.message!=null&&Object.hasOwnProperty.call(e,`message`)&&t.uint32(18).string(e.message),e.code!=null&&Object.hasOwnProperty.call(e,`code`)&&t.uint32(24).int32(e.code),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.trace.v1.Status;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 2:w.message=e.string();break;case 3:w.code=e.int32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.message!=null&&e.hasOwnProperty(`message`)&&!w.isString(e.message))return`message: string expected`;if(e.code!=null&&e.hasOwnProperty(`code`))switch(e.code){default:return`code: enum value expected`;case 0:case 1:case 2:break}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.trace.v1.Status)return e;var t=new E.opentelemetry.proto.trace.v1.Status;switch(e.message!=null&&(t.message=String(e.message)),e.code){default:if(typeof e.code==`number`){t.code=e.code;break}break;case`STATUS_CODE_UNSET`:case 0:t.code=0;break;case`STATUS_CODE_OK`:case 1:t.code=1;break;case`STATUS_CODE_ERROR`:case 2:t.code=2;break}return t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.message=``,s.code=t.enums===String?`STATUS_CODE_UNSET`:0),e.message!=null&&e.hasOwnProperty(`message`)&&(s.message=e.message),e.code!=null&&e.hasOwnProperty(`code`)&&(s.code=t.enums===String?E.opentelemetry.proto.trace.v1.Status.StatusCode[e.code]===void 0?e.code:E.opentelemetry.proto.trace.v1.Status.StatusCode[e.code]:e.code),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.trace.v1.Status`},e.StatusCode=(function(){var e={},t=Object.create(e);return t[e[0]=`STATUS_CODE_UNSET`]=0,t[e[1]=`STATUS_CODE_OK`]=1,t[e[2]=`STATUS_CODE_ERROR`]=2,t})(),e})(),e.SpanFlags=(function(){var e={},t=Object.create(e);return t[e[0]=`SPAN_FLAGS_DO_NOT_USE`]=0,t[e[255]=`SPAN_FLAGS_TRACE_FLAGS_MASK`]=255,t[e[256]=`SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK`]=256,t[e[512]=`SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK`]=512,t})(),e})(),e})(),e.collector=(function(){var e={};return e.trace=(function(){var e={};return e.v1=(function(){var e={};return e.TraceService=(function(){function e(e,t,g){s.rpc.Service.call(this,e,t,g)}return(e.prototype=Object.create(s.rpc.Service.prototype)).constructor=e,e.create=function(e,t,s){return new this(e,t,s)},Object.defineProperty(e.prototype.export=function e(t,s){return this.rpcCall(e,E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest,E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse,t,s)},`name`,{value:`Export`}),e})(),e.ExportTraceServiceRequest=(function(){function e(e){if(this.resourceSpans=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceSpans=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceSpans!=null&&e.resourceSpans.length)for(var s=0;s<e.resourceSpans.length;++s)E.opentelemetry.proto.trace.v1.ResourceSpans.encode(e.resourceSpans[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceSpans&&w.resourceSpans.length||(w.resourceSpans=[]),w.resourceSpans.push(E.opentelemetry.proto.trace.v1.ResourceSpans.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceSpans!=null&&e.hasOwnProperty(`resourceSpans`)){if(!Array.isArray(e.resourceSpans))return`resourceSpans: array expected`;for(var t=0;t<e.resourceSpans.length;++t){var s=E.opentelemetry.proto.trace.v1.ResourceSpans.verify(e.resourceSpans[t]);if(s)return`resourceSpans.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest)return e;var t=new E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest;if(e.resourceSpans){if(!Array.isArray(e.resourceSpans))throw TypeError(`.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: array expected`);t.resourceSpans=[];for(var s=0;s<e.resourceSpans.length;++s){if(typeof e.resourceSpans[s]!=`object`)throw TypeError(`.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: object expected`);t.resourceSpans[s]=E.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(e.resourceSpans[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceSpans=[]),e.resourceSpans&&e.resourceSpans.length){s.resourceSpans=[];for(var g=0;g<e.resourceSpans.length;++g)s.resourceSpans[g]=E.opentelemetry.proto.trace.v1.ResourceSpans.toObject(e.resourceSpans[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest`},e})(),e.ExportTraceServiceResponse=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.partialSuccess=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.partialSuccess!=null&&Object.hasOwnProperty.call(e,`partialSuccess`)&&E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.encode(e.partialSuccess,t.uint32(10).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.partialSuccess=E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.decode(e,e.uint32());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)){var t=E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify(e.partialSuccess);if(t)return`partialSuccess.`+t}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse)return e;var t=new E.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse;if(e.partialSuccess!=null){if(typeof e.partialSuccess!=`object`)throw TypeError(`.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.partialSuccess: object expected`);t.partialSuccess=E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.fromObject(e.partialSuccess)}return t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.partialSuccess=null),e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)&&(s.partialSuccess=E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.toObject(e.partialSuccess,t)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse`},e})(),e.ExportTracePartialSuccess=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.rejectedSpans=null,e.prototype.errorMessage=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.rejectedSpans!=null&&Object.hasOwnProperty.call(e,`rejectedSpans`)&&t.uint32(8).int64(e.rejectedSpans),e.errorMessage!=null&&Object.hasOwnProperty.call(e,`errorMessage`)&&t.uint32(18).string(e.errorMessage),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.rejectedSpans=e.int64();break;case 2:w.errorMessage=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){return typeof e!=`object`||!e?`object expected`:e.rejectedSpans!=null&&e.hasOwnProperty(`rejectedSpans`)&&!w.isInteger(e.rejectedSpans)&&!(e.rejectedSpans&&w.isInteger(e.rejectedSpans.low)&&w.isInteger(e.rejectedSpans.high))?`rejectedSpans: integer|Long expected`:e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&!w.isString(e.errorMessage)?`errorMessage: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess)return e;var t=new E.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess;return e.rejectedSpans!=null&&(w.Long?(t.rejectedSpans=w.Long.fromValue(e.rejectedSpans)).unsigned=!1:typeof e.rejectedSpans==`string`?t.rejectedSpans=parseInt(e.rejectedSpans,10):typeof e.rejectedSpans==`number`?t.rejectedSpans=e.rejectedSpans:typeof e.rejectedSpans==`object`&&(t.rejectedSpans=new w.LongBits(e.rejectedSpans.low>>>0,e.rejectedSpans.high>>>0).toNumber())),e.errorMessage!=null&&(t.errorMessage=String(e.errorMessage)),t},e.toObject=function(e,t){t||={};var s={};if(t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.rejectedSpans=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.rejectedSpans=t.longs===String?`0`:0;s.errorMessage=``}return e.rejectedSpans!=null&&e.hasOwnProperty(`rejectedSpans`)&&(typeof e.rejectedSpans==`number`?s.rejectedSpans=t.longs===String?String(e.rejectedSpans):e.rejectedSpans:s.rejectedSpans=t.longs===String?w.Long.prototype.toString.call(e.rejectedSpans):t.longs===Number?new w.LongBits(e.rejectedSpans.low>>>0,e.rejectedSpans.high>>>0).toNumber():e.rejectedSpans),e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&(s.errorMessage=e.errorMessage),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess`},e})(),e})(),e})(),e.metrics=(function(){var e={};return e.v1=(function(){var e={};return e.MetricsService=(function(){function e(e,t,g){s.rpc.Service.call(this,e,t,g)}return(e.prototype=Object.create(s.rpc.Service.prototype)).constructor=e,e.create=function(e,t,s){return new this(e,t,s)},Object.defineProperty(e.prototype.export=function e(t,s){return this.rpcCall(e,E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest,E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse,t,s)},`name`,{value:`Export`}),e})(),e.ExportMetricsServiceRequest=(function(){function e(e){if(this.resourceMetrics=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceMetrics=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceMetrics!=null&&e.resourceMetrics.length)for(var s=0;s<e.resourceMetrics.length;++s)E.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(e.resourceMetrics[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceMetrics&&w.resourceMetrics.length||(w.resourceMetrics=[]),w.resourceMetrics.push(E.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceMetrics!=null&&e.hasOwnProperty(`resourceMetrics`)){if(!Array.isArray(e.resourceMetrics))return`resourceMetrics: array expected`;for(var t=0;t<e.resourceMetrics.length;++t){var s=E.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(e.resourceMetrics[t]);if(s)return`resourceMetrics.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest)return e;var t=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest;if(e.resourceMetrics){if(!Array.isArray(e.resourceMetrics))throw TypeError(`.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: array expected`);t.resourceMetrics=[];for(var s=0;s<e.resourceMetrics.length;++s){if(typeof e.resourceMetrics[s]!=`object`)throw TypeError(`.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: object expected`);t.resourceMetrics[s]=E.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(e.resourceMetrics[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceMetrics=[]),e.resourceMetrics&&e.resourceMetrics.length){s.resourceMetrics=[];for(var g=0;g<e.resourceMetrics.length;++g)s.resourceMetrics[g]=E.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(e.resourceMetrics[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest`},e})(),e.ExportMetricsServiceResponse=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.partialSuccess=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.partialSuccess!=null&&Object.hasOwnProperty.call(e,`partialSuccess`)&&E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.encode(e.partialSuccess,t.uint32(10).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.partialSuccess=E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.decode(e,e.uint32());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)){var t=E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify(e.partialSuccess);if(t)return`partialSuccess.`+t}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse)return e;var t=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse;if(e.partialSuccess!=null){if(typeof e.partialSuccess!=`object`)throw TypeError(`.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.partialSuccess: object expected`);t.partialSuccess=E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.fromObject(e.partialSuccess)}return t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.partialSuccess=null),e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)&&(s.partialSuccess=E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.toObject(e.partialSuccess,t)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse`},e})(),e.ExportMetricsPartialSuccess=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.rejectedDataPoints=null,e.prototype.errorMessage=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.rejectedDataPoints!=null&&Object.hasOwnProperty.call(e,`rejectedDataPoints`)&&t.uint32(8).int64(e.rejectedDataPoints),e.errorMessage!=null&&Object.hasOwnProperty.call(e,`errorMessage`)&&t.uint32(18).string(e.errorMessage),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.rejectedDataPoints=e.int64();break;case 2:w.errorMessage=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){return typeof e!=`object`||!e?`object expected`:e.rejectedDataPoints!=null&&e.hasOwnProperty(`rejectedDataPoints`)&&!w.isInteger(e.rejectedDataPoints)&&!(e.rejectedDataPoints&&w.isInteger(e.rejectedDataPoints.low)&&w.isInteger(e.rejectedDataPoints.high))?`rejectedDataPoints: integer|Long expected`:e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&!w.isString(e.errorMessage)?`errorMessage: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess)return e;var t=new E.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess;return e.rejectedDataPoints!=null&&(w.Long?(t.rejectedDataPoints=w.Long.fromValue(e.rejectedDataPoints)).unsigned=!1:typeof e.rejectedDataPoints==`string`?t.rejectedDataPoints=parseInt(e.rejectedDataPoints,10):typeof e.rejectedDataPoints==`number`?t.rejectedDataPoints=e.rejectedDataPoints:typeof e.rejectedDataPoints==`object`&&(t.rejectedDataPoints=new w.LongBits(e.rejectedDataPoints.low>>>0,e.rejectedDataPoints.high>>>0).toNumber())),e.errorMessage!=null&&(t.errorMessage=String(e.errorMessage)),t},e.toObject=function(e,t){t||={};var s={};if(t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.rejectedDataPoints=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.rejectedDataPoints=t.longs===String?`0`:0;s.errorMessage=``}return e.rejectedDataPoints!=null&&e.hasOwnProperty(`rejectedDataPoints`)&&(typeof e.rejectedDataPoints==`number`?s.rejectedDataPoints=t.longs===String?String(e.rejectedDataPoints):e.rejectedDataPoints:s.rejectedDataPoints=t.longs===String?w.Long.prototype.toString.call(e.rejectedDataPoints):t.longs===Number?new w.LongBits(e.rejectedDataPoints.low>>>0,e.rejectedDataPoints.high>>>0).toNumber():e.rejectedDataPoints),e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&(s.errorMessage=e.errorMessage),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess`},e})(),e})(),e})(),e.logs=(function(){var e={};return e.v1=(function(){var e={};return e.LogsService=(function(){function e(e,t,g){s.rpc.Service.call(this,e,t,g)}return(e.prototype=Object.create(s.rpc.Service.prototype)).constructor=e,e.create=function(e,t,s){return new this(e,t,s)},Object.defineProperty(e.prototype.export=function e(t,s){return this.rpcCall(e,E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest,E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse,t,s)},`name`,{value:`Export`}),e})(),e.ExportLogsServiceRequest=(function(){function e(e){if(this.resourceLogs=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceLogs=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceLogs!=null&&e.resourceLogs.length)for(var s=0;s<e.resourceLogs.length;++s)E.opentelemetry.proto.logs.v1.ResourceLogs.encode(e.resourceLogs[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceLogs&&w.resourceLogs.length||(w.resourceLogs=[]),w.resourceLogs.push(E.opentelemetry.proto.logs.v1.ResourceLogs.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceLogs!=null&&e.hasOwnProperty(`resourceLogs`)){if(!Array.isArray(e.resourceLogs))return`resourceLogs: array expected`;for(var t=0;t<e.resourceLogs.length;++t){var s=E.opentelemetry.proto.logs.v1.ResourceLogs.verify(e.resourceLogs[t]);if(s)return`resourceLogs.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest)return e;var t=new E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest;if(e.resourceLogs){if(!Array.isArray(e.resourceLogs))throw TypeError(`.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: array expected`);t.resourceLogs=[];for(var s=0;s<e.resourceLogs.length;++s){if(typeof e.resourceLogs[s]!=`object`)throw TypeError(`.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: object expected`);t.resourceLogs[s]=E.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(e.resourceLogs[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceLogs=[]),e.resourceLogs&&e.resourceLogs.length){s.resourceLogs=[];for(var g=0;g<e.resourceLogs.length;++g)s.resourceLogs[g]=E.opentelemetry.proto.logs.v1.ResourceLogs.toObject(e.resourceLogs[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest`},e})(),e.ExportLogsServiceResponse=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.partialSuccess=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.partialSuccess!=null&&Object.hasOwnProperty.call(e,`partialSuccess`)&&E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.encode(e.partialSuccess,t.uint32(10).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.partialSuccess=E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.decode(e,e.uint32());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)){var t=E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify(e.partialSuccess);if(t)return`partialSuccess.`+t}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse)return e;var t=new E.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse;if(e.partialSuccess!=null){if(typeof e.partialSuccess!=`object`)throw TypeError(`.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.partialSuccess: object expected`);t.partialSuccess=E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.fromObject(e.partialSuccess)}return t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.partialSuccess=null),e.partialSuccess!=null&&e.hasOwnProperty(`partialSuccess`)&&(s.partialSuccess=E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.toObject(e.partialSuccess,t)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse`},e})(),e.ExportLogsPartialSuccess=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.rejectedLogRecords=null,e.prototype.errorMessage=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.rejectedLogRecords!=null&&Object.hasOwnProperty.call(e,`rejectedLogRecords`)&&t.uint32(8).int64(e.rejectedLogRecords),e.errorMessage!=null&&Object.hasOwnProperty.call(e,`errorMessage`)&&t.uint32(18).string(e.errorMessage),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.rejectedLogRecords=e.int64();break;case 2:w.errorMessage=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){return typeof e!=`object`||!e?`object expected`:e.rejectedLogRecords!=null&&e.hasOwnProperty(`rejectedLogRecords`)&&!w.isInteger(e.rejectedLogRecords)&&!(e.rejectedLogRecords&&w.isInteger(e.rejectedLogRecords.low)&&w.isInteger(e.rejectedLogRecords.high))?`rejectedLogRecords: integer|Long expected`:e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&!w.isString(e.errorMessage)?`errorMessage: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess)return e;var t=new E.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess;return e.rejectedLogRecords!=null&&(w.Long?(t.rejectedLogRecords=w.Long.fromValue(e.rejectedLogRecords)).unsigned=!1:typeof e.rejectedLogRecords==`string`?t.rejectedLogRecords=parseInt(e.rejectedLogRecords,10):typeof e.rejectedLogRecords==`number`?t.rejectedLogRecords=e.rejectedLogRecords:typeof e.rejectedLogRecords==`object`&&(t.rejectedLogRecords=new w.LongBits(e.rejectedLogRecords.low>>>0,e.rejectedLogRecords.high>>>0).toNumber())),e.errorMessage!=null&&(t.errorMessage=String(e.errorMessage)),t},e.toObject=function(e,t){t||={};var s={};if(t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.rejectedLogRecords=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.rejectedLogRecords=t.longs===String?`0`:0;s.errorMessage=``}return e.rejectedLogRecords!=null&&e.hasOwnProperty(`rejectedLogRecords`)&&(typeof e.rejectedLogRecords==`number`?s.rejectedLogRecords=t.longs===String?String(e.rejectedLogRecords):e.rejectedLogRecords:s.rejectedLogRecords=t.longs===String?w.Long.prototype.toString.call(e.rejectedLogRecords):t.longs===Number?new w.LongBits(e.rejectedLogRecords.low>>>0,e.rejectedLogRecords.high>>>0).toNumber():e.rejectedLogRecords),e.errorMessage!=null&&e.hasOwnProperty(`errorMessage`)&&(s.errorMessage=e.errorMessage),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess`},e})(),e})(),e})(),e})(),e.metrics=(function(){var e={};return e.v1=(function(){var e={};return e.MetricsData=(function(){function e(e){if(this.resourceMetrics=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceMetrics=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceMetrics!=null&&e.resourceMetrics.length)for(var s=0;s<e.resourceMetrics.length;++s)E.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(e.resourceMetrics[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.MetricsData;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceMetrics&&w.resourceMetrics.length||(w.resourceMetrics=[]),w.resourceMetrics.push(E.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceMetrics!=null&&e.hasOwnProperty(`resourceMetrics`)){if(!Array.isArray(e.resourceMetrics))return`resourceMetrics: array expected`;for(var t=0;t<e.resourceMetrics.length;++t){var s=E.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(e.resourceMetrics[t]);if(s)return`resourceMetrics.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.MetricsData)return e;var t=new E.opentelemetry.proto.metrics.v1.MetricsData;if(e.resourceMetrics){if(!Array.isArray(e.resourceMetrics))throw TypeError(`.opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: array expected`);t.resourceMetrics=[];for(var s=0;s<e.resourceMetrics.length;++s){if(typeof e.resourceMetrics[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: object expected`);t.resourceMetrics[s]=E.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(e.resourceMetrics[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceMetrics=[]),e.resourceMetrics&&e.resourceMetrics.length){s.resourceMetrics=[];for(var g=0;g<e.resourceMetrics.length;++g)s.resourceMetrics[g]=E.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(e.resourceMetrics[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.MetricsData`},e})(),e.ResourceMetrics=(function(){function e(e){if(this.scopeMetrics=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resource=null,e.prototype.scopeMetrics=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resource!=null&&Object.hasOwnProperty.call(e,`resource`)&&E.opentelemetry.proto.resource.v1.Resource.encode(e.resource,t.uint32(10).fork()).ldelim(),e.scopeMetrics!=null&&e.scopeMetrics.length)for(var s=0;s<e.scopeMetrics.length;++s)E.opentelemetry.proto.metrics.v1.ScopeMetrics.encode(e.scopeMetrics[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.ResourceMetrics;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resource=E.opentelemetry.proto.resource.v1.Resource.decode(e,e.uint32());break;case 2:w.scopeMetrics&&w.scopeMetrics.length||(w.scopeMetrics=[]),w.scopeMetrics.push(E.opentelemetry.proto.metrics.v1.ScopeMetrics.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resource!=null&&e.hasOwnProperty(`resource`)){var t=E.opentelemetry.proto.resource.v1.Resource.verify(e.resource);if(t)return`resource.`+t}if(e.scopeMetrics!=null&&e.hasOwnProperty(`scopeMetrics`)){if(!Array.isArray(e.scopeMetrics))return`scopeMetrics: array expected`;for(var s=0;s<e.scopeMetrics.length;++s){var t=E.opentelemetry.proto.metrics.v1.ScopeMetrics.verify(e.scopeMetrics[s]);if(t)return`scopeMetrics.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.ResourceMetrics)return e;var t=new E.opentelemetry.proto.metrics.v1.ResourceMetrics;if(e.resource!=null){if(typeof e.resource!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ResourceMetrics.resource: object expected`);t.resource=E.opentelemetry.proto.resource.v1.Resource.fromObject(e.resource)}if(e.scopeMetrics){if(!Array.isArray(e.scopeMetrics))throw TypeError(`.opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: array expected`);t.scopeMetrics=[];for(var s=0;s<e.scopeMetrics.length;++s){if(typeof e.scopeMetrics[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: object expected`);t.scopeMetrics[s]=E.opentelemetry.proto.metrics.v1.ScopeMetrics.fromObject(e.scopeMetrics[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.scopeMetrics=[]),t.defaults&&(s.resource=null,s.schemaUrl=``),e.resource!=null&&e.hasOwnProperty(`resource`)&&(s.resource=E.opentelemetry.proto.resource.v1.Resource.toObject(e.resource,t)),e.scopeMetrics&&e.scopeMetrics.length){s.scopeMetrics=[];for(var g=0;g<e.scopeMetrics.length;++g)s.scopeMetrics[g]=E.opentelemetry.proto.metrics.v1.ScopeMetrics.toObject(e.scopeMetrics[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.ResourceMetrics`},e})(),e.ScopeMetrics=(function(){function e(e){if(this.metrics=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.scope=null,e.prototype.metrics=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.scope!=null&&Object.hasOwnProperty.call(e,`scope`)&&E.opentelemetry.proto.common.v1.InstrumentationScope.encode(e.scope,t.uint32(10).fork()).ldelim(),e.metrics!=null&&e.metrics.length)for(var s=0;s<e.metrics.length;++s)E.opentelemetry.proto.metrics.v1.Metric.encode(e.metrics[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.ScopeMetrics;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.decode(e,e.uint32());break;case 2:w.metrics&&w.metrics.length||(w.metrics=[]),w.metrics.push(E.opentelemetry.proto.metrics.v1.Metric.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.scope!=null&&e.hasOwnProperty(`scope`)){var t=E.opentelemetry.proto.common.v1.InstrumentationScope.verify(e.scope);if(t)return`scope.`+t}if(e.metrics!=null&&e.hasOwnProperty(`metrics`)){if(!Array.isArray(e.metrics))return`metrics: array expected`;for(var s=0;s<e.metrics.length;++s){var t=E.opentelemetry.proto.metrics.v1.Metric.verify(e.metrics[s]);if(t)return`metrics.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.ScopeMetrics)return e;var t=new E.opentelemetry.proto.metrics.v1.ScopeMetrics;if(e.scope!=null){if(typeof e.scope!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ScopeMetrics.scope: object expected`);t.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(e.scope)}if(e.metrics){if(!Array.isArray(e.metrics))throw TypeError(`.opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: array expected`);t.metrics=[];for(var s=0;s<e.metrics.length;++s){if(typeof e.metrics[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: object expected`);t.metrics[s]=E.opentelemetry.proto.metrics.v1.Metric.fromObject(e.metrics[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.metrics=[]),t.defaults&&(s.scope=null,s.schemaUrl=``),e.scope!=null&&e.hasOwnProperty(`scope`)&&(s.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.toObject(e.scope,t)),e.metrics&&e.metrics.length){s.metrics=[];for(var g=0;g<e.metrics.length;++g)s.metrics[g]=E.opentelemetry.proto.metrics.v1.Metric.toObject(e.metrics[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.ScopeMetrics`},e})(),e.Metric=(function(){function e(e){if(this.metadata=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.name=null,e.prototype.description=null,e.prototype.unit=null,e.prototype.gauge=null,e.prototype.sum=null,e.prototype.histogram=null,e.prototype.exponentialHistogram=null,e.prototype.summary=null,e.prototype.metadata=w.emptyArray;var t;return Object.defineProperty(e.prototype,`data`,{get:w.oneOfGetter(t=[`gauge`,`sum`,`histogram`,`exponentialHistogram`,`summary`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.name!=null&&Object.hasOwnProperty.call(e,`name`)&&t.uint32(10).string(e.name),e.description!=null&&Object.hasOwnProperty.call(e,`description`)&&t.uint32(18).string(e.description),e.unit!=null&&Object.hasOwnProperty.call(e,`unit`)&&t.uint32(26).string(e.unit),e.gauge!=null&&Object.hasOwnProperty.call(e,`gauge`)&&E.opentelemetry.proto.metrics.v1.Gauge.encode(e.gauge,t.uint32(42).fork()).ldelim(),e.sum!=null&&Object.hasOwnProperty.call(e,`sum`)&&E.opentelemetry.proto.metrics.v1.Sum.encode(e.sum,t.uint32(58).fork()).ldelim(),e.histogram!=null&&Object.hasOwnProperty.call(e,`histogram`)&&E.opentelemetry.proto.metrics.v1.Histogram.encode(e.histogram,t.uint32(74).fork()).ldelim(),e.exponentialHistogram!=null&&Object.hasOwnProperty.call(e,`exponentialHistogram`)&&E.opentelemetry.proto.metrics.v1.ExponentialHistogram.encode(e.exponentialHistogram,t.uint32(82).fork()).ldelim(),e.summary!=null&&Object.hasOwnProperty.call(e,`summary`)&&E.opentelemetry.proto.metrics.v1.Summary.encode(e.summary,t.uint32(90).fork()).ldelim(),e.metadata!=null&&e.metadata.length)for(var s=0;s<e.metadata.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.metadata[s],t.uint32(98).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Metric;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.name=e.string();break;case 2:w.description=e.string();break;case 3:w.unit=e.string();break;case 5:w.gauge=E.opentelemetry.proto.metrics.v1.Gauge.decode(e,e.uint32());break;case 7:w.sum=E.opentelemetry.proto.metrics.v1.Sum.decode(e,e.uint32());break;case 9:w.histogram=E.opentelemetry.proto.metrics.v1.Histogram.decode(e,e.uint32());break;case 10:w.exponentialHistogram=E.opentelemetry.proto.metrics.v1.ExponentialHistogram.decode(e,e.uint32());break;case 11:w.summary=E.opentelemetry.proto.metrics.v1.Summary.decode(e,e.uint32());break;case 12:w.metadata&&w.metadata.length||(w.metadata=[]),w.metadata.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.name!=null&&e.hasOwnProperty(`name`)&&!w.isString(e.name))return`name: string expected`;if(e.description!=null&&e.hasOwnProperty(`description`)&&!w.isString(e.description))return`description: string expected`;if(e.unit!=null&&e.hasOwnProperty(`unit`)&&!w.isString(e.unit))return`unit: string expected`;if(e.gauge!=null&&e.hasOwnProperty(`gauge`)){t.data=1;var s=E.opentelemetry.proto.metrics.v1.Gauge.verify(e.gauge);if(s)return`gauge.`+s}if(e.sum!=null&&e.hasOwnProperty(`sum`)){if(t.data===1)return`data: multiple values`;t.data=1;var s=E.opentelemetry.proto.metrics.v1.Sum.verify(e.sum);if(s)return`sum.`+s}if(e.histogram!=null&&e.hasOwnProperty(`histogram`)){if(t.data===1)return`data: multiple values`;t.data=1;var s=E.opentelemetry.proto.metrics.v1.Histogram.verify(e.histogram);if(s)return`histogram.`+s}if(e.exponentialHistogram!=null&&e.hasOwnProperty(`exponentialHistogram`)){if(t.data===1)return`data: multiple values`;t.data=1;var s=E.opentelemetry.proto.metrics.v1.ExponentialHistogram.verify(e.exponentialHistogram);if(s)return`exponentialHistogram.`+s}if(e.summary!=null&&e.hasOwnProperty(`summary`)){if(t.data===1)return`data: multiple values`;t.data=1;var s=E.opentelemetry.proto.metrics.v1.Summary.verify(e.summary);if(s)return`summary.`+s}if(e.metadata!=null&&e.hasOwnProperty(`metadata`)){if(!Array.isArray(e.metadata))return`metadata: array expected`;for(var g=0;g<e.metadata.length;++g){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.metadata[g]);if(s)return`metadata.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Metric)return e;var t=new E.opentelemetry.proto.metrics.v1.Metric;if(e.name!=null&&(t.name=String(e.name)),e.description!=null&&(t.description=String(e.description)),e.unit!=null&&(t.unit=String(e.unit)),e.gauge!=null){if(typeof e.gauge!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.gauge: object expected`);t.gauge=E.opentelemetry.proto.metrics.v1.Gauge.fromObject(e.gauge)}if(e.sum!=null){if(typeof e.sum!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.sum: object expected`);t.sum=E.opentelemetry.proto.metrics.v1.Sum.fromObject(e.sum)}if(e.histogram!=null){if(typeof e.histogram!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.histogram: object expected`);t.histogram=E.opentelemetry.proto.metrics.v1.Histogram.fromObject(e.histogram)}if(e.exponentialHistogram!=null){if(typeof e.exponentialHistogram!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.exponentialHistogram: object expected`);t.exponentialHistogram=E.opentelemetry.proto.metrics.v1.ExponentialHistogram.fromObject(e.exponentialHistogram)}if(e.summary!=null){if(typeof e.summary!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.summary: object expected`);t.summary=E.opentelemetry.proto.metrics.v1.Summary.fromObject(e.summary)}if(e.metadata){if(!Array.isArray(e.metadata))throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.metadata: array expected`);t.metadata=[];for(var s=0;s<e.metadata.length;++s){if(typeof e.metadata[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Metric.metadata: object expected`);t.metadata[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.metadata[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.metadata=[]),t.defaults&&(s.name=``,s.description=``,s.unit=``),e.name!=null&&e.hasOwnProperty(`name`)&&(s.name=e.name),e.description!=null&&e.hasOwnProperty(`description`)&&(s.description=e.description),e.unit!=null&&e.hasOwnProperty(`unit`)&&(s.unit=e.unit),e.gauge!=null&&e.hasOwnProperty(`gauge`)&&(s.gauge=E.opentelemetry.proto.metrics.v1.Gauge.toObject(e.gauge,t),t.oneofs&&(s.data=`gauge`)),e.sum!=null&&e.hasOwnProperty(`sum`)&&(s.sum=E.opentelemetry.proto.metrics.v1.Sum.toObject(e.sum,t),t.oneofs&&(s.data=`sum`)),e.histogram!=null&&e.hasOwnProperty(`histogram`)&&(s.histogram=E.opentelemetry.proto.metrics.v1.Histogram.toObject(e.histogram,t),t.oneofs&&(s.data=`histogram`)),e.exponentialHistogram!=null&&e.hasOwnProperty(`exponentialHistogram`)&&(s.exponentialHistogram=E.opentelemetry.proto.metrics.v1.ExponentialHistogram.toObject(e.exponentialHistogram,t),t.oneofs&&(s.data=`exponentialHistogram`)),e.summary!=null&&e.hasOwnProperty(`summary`)&&(s.summary=E.opentelemetry.proto.metrics.v1.Summary.toObject(e.summary,t),t.oneofs&&(s.data=`summary`)),e.metadata&&e.metadata.length){s.metadata=[];for(var g=0;g<e.metadata.length;++g)s.metadata[g]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.metadata[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Metric`},e})(),e.Gauge=(function(){function e(e){if(this.dataPoints=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.dataPoints=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.dataPoints!=null&&e.dataPoints.length)for(var s=0;s<e.dataPoints.length;++s)E.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(e.dataPoints[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Gauge;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.dataPoints&&w.dataPoints.length||(w.dataPoints=[]),w.dataPoints.push(E.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.dataPoints!=null&&e.hasOwnProperty(`dataPoints`)){if(!Array.isArray(e.dataPoints))return`dataPoints: array expected`;for(var t=0;t<e.dataPoints.length;++t){var s=E.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(e.dataPoints[t]);if(s)return`dataPoints.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Gauge)return e;var t=new E.opentelemetry.proto.metrics.v1.Gauge;if(e.dataPoints){if(!Array.isArray(e.dataPoints))throw TypeError(`.opentelemetry.proto.metrics.v1.Gauge.dataPoints: array expected`);t.dataPoints=[];for(var s=0;s<e.dataPoints.length;++s){if(typeof e.dataPoints[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Gauge.dataPoints: object expected`);t.dataPoints[s]=E.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(e.dataPoints[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.dataPoints=[]),e.dataPoints&&e.dataPoints.length){s.dataPoints=[];for(var g=0;g<e.dataPoints.length;++g)s.dataPoints[g]=E.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(e.dataPoints[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Gauge`},e})(),e.Sum=(function(){function e(e){if(this.dataPoints=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.dataPoints=w.emptyArray,e.prototype.aggregationTemporality=null,e.prototype.isMonotonic=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.dataPoints!=null&&e.dataPoints.length)for(var s=0;s<e.dataPoints.length;++s)E.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(e.dataPoints[s],t.uint32(10).fork()).ldelim();return e.aggregationTemporality!=null&&Object.hasOwnProperty.call(e,`aggregationTemporality`)&&t.uint32(16).int32(e.aggregationTemporality),e.isMonotonic!=null&&Object.hasOwnProperty.call(e,`isMonotonic`)&&t.uint32(24).bool(e.isMonotonic),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Sum;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.dataPoints&&w.dataPoints.length||(w.dataPoints=[]),w.dataPoints.push(E.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(e,e.uint32()));break;case 2:w.aggregationTemporality=e.int32();break;case 3:w.isMonotonic=e.bool();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.dataPoints!=null&&e.hasOwnProperty(`dataPoints`)){if(!Array.isArray(e.dataPoints))return`dataPoints: array expected`;for(var t=0;t<e.dataPoints.length;++t){var s=E.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(e.dataPoints[t]);if(s)return`dataPoints.`+s}}if(e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`))switch(e.aggregationTemporality){default:return`aggregationTemporality: enum value expected`;case 0:case 1:case 2:break}return e.isMonotonic!=null&&e.hasOwnProperty(`isMonotonic`)&&typeof e.isMonotonic!=`boolean`?`isMonotonic: boolean expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Sum)return e;var t=new E.opentelemetry.proto.metrics.v1.Sum;if(e.dataPoints){if(!Array.isArray(e.dataPoints))throw TypeError(`.opentelemetry.proto.metrics.v1.Sum.dataPoints: array expected`);t.dataPoints=[];for(var s=0;s<e.dataPoints.length;++s){if(typeof e.dataPoints[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Sum.dataPoints: object expected`);t.dataPoints[s]=E.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(e.dataPoints[s])}}switch(e.aggregationTemporality){default:if(typeof e.aggregationTemporality==`number`){t.aggregationTemporality=e.aggregationTemporality;break}break;case`AGGREGATION_TEMPORALITY_UNSPECIFIED`:case 0:t.aggregationTemporality=0;break;case`AGGREGATION_TEMPORALITY_DELTA`:case 1:t.aggregationTemporality=1;break;case`AGGREGATION_TEMPORALITY_CUMULATIVE`:case 2:t.aggregationTemporality=2;break}return e.isMonotonic!=null&&(t.isMonotonic=!!e.isMonotonic),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.dataPoints=[]),t.defaults&&(s.aggregationTemporality=t.enums===String?`AGGREGATION_TEMPORALITY_UNSPECIFIED`:0,s.isMonotonic=!1),e.dataPoints&&e.dataPoints.length){s.dataPoints=[];for(var g=0;g<e.dataPoints.length;++g)s.dataPoints[g]=E.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(e.dataPoints[g],t)}return e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`)&&(s.aggregationTemporality=t.enums===String?E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]===void 0?e.aggregationTemporality:E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]:e.aggregationTemporality),e.isMonotonic!=null&&e.hasOwnProperty(`isMonotonic`)&&(s.isMonotonic=e.isMonotonic),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Sum`},e})(),e.Histogram=(function(){function e(e){if(this.dataPoints=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.dataPoints=w.emptyArray,e.prototype.aggregationTemporality=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.dataPoints!=null&&e.dataPoints.length)for(var s=0;s<e.dataPoints.length;++s)E.opentelemetry.proto.metrics.v1.HistogramDataPoint.encode(e.dataPoints[s],t.uint32(10).fork()).ldelim();return e.aggregationTemporality!=null&&Object.hasOwnProperty.call(e,`aggregationTemporality`)&&t.uint32(16).int32(e.aggregationTemporality),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Histogram;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.dataPoints&&w.dataPoints.length||(w.dataPoints=[]),w.dataPoints.push(E.opentelemetry.proto.metrics.v1.HistogramDataPoint.decode(e,e.uint32()));break;case 2:w.aggregationTemporality=e.int32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.dataPoints!=null&&e.hasOwnProperty(`dataPoints`)){if(!Array.isArray(e.dataPoints))return`dataPoints: array expected`;for(var t=0;t<e.dataPoints.length;++t){var s=E.opentelemetry.proto.metrics.v1.HistogramDataPoint.verify(e.dataPoints[t]);if(s)return`dataPoints.`+s}}if(e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`))switch(e.aggregationTemporality){default:return`aggregationTemporality: enum value expected`;case 0:case 1:case 2:break}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Histogram)return e;var t=new E.opentelemetry.proto.metrics.v1.Histogram;if(e.dataPoints){if(!Array.isArray(e.dataPoints))throw TypeError(`.opentelemetry.proto.metrics.v1.Histogram.dataPoints: array expected`);t.dataPoints=[];for(var s=0;s<e.dataPoints.length;++s){if(typeof e.dataPoints[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Histogram.dataPoints: object expected`);t.dataPoints[s]=E.opentelemetry.proto.metrics.v1.HistogramDataPoint.fromObject(e.dataPoints[s])}}switch(e.aggregationTemporality){default:if(typeof e.aggregationTemporality==`number`){t.aggregationTemporality=e.aggregationTemporality;break}break;case`AGGREGATION_TEMPORALITY_UNSPECIFIED`:case 0:t.aggregationTemporality=0;break;case`AGGREGATION_TEMPORALITY_DELTA`:case 1:t.aggregationTemporality=1;break;case`AGGREGATION_TEMPORALITY_CUMULATIVE`:case 2:t.aggregationTemporality=2;break}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.dataPoints=[]),t.defaults&&(s.aggregationTemporality=t.enums===String?`AGGREGATION_TEMPORALITY_UNSPECIFIED`:0),e.dataPoints&&e.dataPoints.length){s.dataPoints=[];for(var g=0;g<e.dataPoints.length;++g)s.dataPoints[g]=E.opentelemetry.proto.metrics.v1.HistogramDataPoint.toObject(e.dataPoints[g],t)}return e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`)&&(s.aggregationTemporality=t.enums===String?E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]===void 0?e.aggregationTemporality:E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]:e.aggregationTemporality),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Histogram`},e})(),e.ExponentialHistogram=(function(){function e(e){if(this.dataPoints=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.dataPoints=w.emptyArray,e.prototype.aggregationTemporality=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.dataPoints!=null&&e.dataPoints.length)for(var s=0;s<e.dataPoints.length;++s)E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.encode(e.dataPoints[s],t.uint32(10).fork()).ldelim();return e.aggregationTemporality!=null&&Object.hasOwnProperty.call(e,`aggregationTemporality`)&&t.uint32(16).int32(e.aggregationTemporality),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.ExponentialHistogram;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.dataPoints&&w.dataPoints.length||(w.dataPoints=[]),w.dataPoints.push(E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.decode(e,e.uint32()));break;case 2:w.aggregationTemporality=e.int32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.dataPoints!=null&&e.hasOwnProperty(`dataPoints`)){if(!Array.isArray(e.dataPoints))return`dataPoints: array expected`;for(var t=0;t<e.dataPoints.length;++t){var s=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify(e.dataPoints[t]);if(s)return`dataPoints.`+s}}if(e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`))switch(e.aggregationTemporality){default:return`aggregationTemporality: enum value expected`;case 0:case 1:case 2:break}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.ExponentialHistogram)return e;var t=new E.opentelemetry.proto.metrics.v1.ExponentialHistogram;if(e.dataPoints){if(!Array.isArray(e.dataPoints))throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: array expected`);t.dataPoints=[];for(var s=0;s<e.dataPoints.length;++s){if(typeof e.dataPoints[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: object expected`);t.dataPoints[s]=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.fromObject(e.dataPoints[s])}}switch(e.aggregationTemporality){default:if(typeof e.aggregationTemporality==`number`){t.aggregationTemporality=e.aggregationTemporality;break}break;case`AGGREGATION_TEMPORALITY_UNSPECIFIED`:case 0:t.aggregationTemporality=0;break;case`AGGREGATION_TEMPORALITY_DELTA`:case 1:t.aggregationTemporality=1;break;case`AGGREGATION_TEMPORALITY_CUMULATIVE`:case 2:t.aggregationTemporality=2;break}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.dataPoints=[]),t.defaults&&(s.aggregationTemporality=t.enums===String?`AGGREGATION_TEMPORALITY_UNSPECIFIED`:0),e.dataPoints&&e.dataPoints.length){s.dataPoints=[];for(var g=0;g<e.dataPoints.length;++g)s.dataPoints[g]=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.toObject(e.dataPoints[g],t)}return e.aggregationTemporality!=null&&e.hasOwnProperty(`aggregationTemporality`)&&(s.aggregationTemporality=t.enums===String?E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]===void 0?e.aggregationTemporality:E.opentelemetry.proto.metrics.v1.AggregationTemporality[e.aggregationTemporality]:e.aggregationTemporality),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.ExponentialHistogram`},e})(),e.Summary=(function(){function e(e){if(this.dataPoints=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.dataPoints=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.dataPoints!=null&&e.dataPoints.length)for(var s=0;s<e.dataPoints.length;++s)E.opentelemetry.proto.metrics.v1.SummaryDataPoint.encode(e.dataPoints[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Summary;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.dataPoints&&w.dataPoints.length||(w.dataPoints=[]),w.dataPoints.push(E.opentelemetry.proto.metrics.v1.SummaryDataPoint.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.dataPoints!=null&&e.hasOwnProperty(`dataPoints`)){if(!Array.isArray(e.dataPoints))return`dataPoints: array expected`;for(var t=0;t<e.dataPoints.length;++t){var s=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.verify(e.dataPoints[t]);if(s)return`dataPoints.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Summary)return e;var t=new E.opentelemetry.proto.metrics.v1.Summary;if(e.dataPoints){if(!Array.isArray(e.dataPoints))throw TypeError(`.opentelemetry.proto.metrics.v1.Summary.dataPoints: array expected`);t.dataPoints=[];for(var s=0;s<e.dataPoints.length;++s){if(typeof e.dataPoints[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Summary.dataPoints: object expected`);t.dataPoints[s]=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.fromObject(e.dataPoints[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.dataPoints=[]),e.dataPoints&&e.dataPoints.length){s.dataPoints=[];for(var g=0;g<e.dataPoints.length;++g)s.dataPoints[g]=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.toObject(e.dataPoints[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Summary`},e})(),e.AggregationTemporality=(function(){var e={},t=Object.create(e);return t[e[0]=`AGGREGATION_TEMPORALITY_UNSPECIFIED`]=0,t[e[1]=`AGGREGATION_TEMPORALITY_DELTA`]=1,t[e[2]=`AGGREGATION_TEMPORALITY_CUMULATIVE`]=2,t})(),e.DataPointFlags=(function(){var e={},t=Object.create(e);return t[e[0]=`DATA_POINT_FLAGS_DO_NOT_USE`]=0,t[e[1]=`DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK`]=1,t})(),e.NumberDataPoint=(function(){function e(e){if(this.attributes=[],this.exemplars=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.attributes=w.emptyArray,e.prototype.startTimeUnixNano=null,e.prototype.timeUnixNano=null,e.prototype.asDouble=null,e.prototype.asInt=null,e.prototype.exemplars=w.emptyArray,e.prototype.flags=null;var t;return Object.defineProperty(e.prototype,`value`,{get:w.oneOfGetter(t=[`asDouble`,`asInt`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.startTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`startTimeUnixNano`)&&t.uint32(17).fixed64(e.startTimeUnixNano),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(25).fixed64(e.timeUnixNano),e.asDouble!=null&&Object.hasOwnProperty.call(e,`asDouble`)&&t.uint32(33).double(e.asDouble),e.exemplars!=null&&e.exemplars.length)for(var s=0;s<e.exemplars.length;++s)E.opentelemetry.proto.metrics.v1.Exemplar.encode(e.exemplars[s],t.uint32(42).fork()).ldelim();if(e.asInt!=null&&Object.hasOwnProperty.call(e,`asInt`)&&t.uint32(49).sfixed64(e.asInt),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(58).fork()).ldelim();return e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(64).uint32(e.flags),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.NumberDataPoint;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 7:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.startTimeUnixNano=e.fixed64();break;case 3:w.timeUnixNano=e.fixed64();break;case 4:w.asDouble=e.double();break;case 6:w.asInt=e.sfixed64();break;case 5:w.exemplars&&w.exemplars.length||(w.exemplars=[]),w.exemplars.push(E.opentelemetry.proto.metrics.v1.Exemplar.decode(e,e.uint32()));break;case 8:w.flags=e.uint32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var s=0;s<e.attributes.length;++s){var g=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[s]);if(g)return`attributes.`+g}}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&!w.isInteger(e.startTimeUnixNano)&&!(e.startTimeUnixNano&&w.isInteger(e.startTimeUnixNano.low)&&w.isInteger(e.startTimeUnixNano.high)))return`startTimeUnixNano: integer|Long expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.asDouble!=null&&e.hasOwnProperty(`asDouble`)&&(t.value=1,typeof e.asDouble!=`number`))return`asDouble: number expected`;if(e.asInt!=null&&e.hasOwnProperty(`asInt`)){if(t.value===1)return`value: multiple values`;if(t.value=1,!w.isInteger(e.asInt)&&!(e.asInt&&w.isInteger(e.asInt.low)&&w.isInteger(e.asInt.high)))return`asInt: integer|Long expected`}if(e.exemplars!=null&&e.hasOwnProperty(`exemplars`)){if(!Array.isArray(e.exemplars))return`exemplars: array expected`;for(var s=0;s<e.exemplars.length;++s){var g=E.opentelemetry.proto.metrics.v1.Exemplar.verify(e.exemplars[s]);if(g)return`exemplars.`+g}}return e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags)?`flags: integer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.NumberDataPoint)return e;var t=new E.opentelemetry.proto.metrics.v1.NumberDataPoint;if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.startTimeUnixNano!=null&&(w.Long?(t.startTimeUnixNano=w.Long.fromValue(e.startTimeUnixNano)).unsigned=!1:typeof e.startTimeUnixNano==`string`?t.startTimeUnixNano=parseInt(e.startTimeUnixNano,10):typeof e.startTimeUnixNano==`number`?t.startTimeUnixNano=e.startTimeUnixNano:typeof e.startTimeUnixNano==`object`&&(t.startTimeUnixNano=new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber())),e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.asDouble!=null&&(t.asDouble=Number(e.asDouble)),e.asInt!=null&&(w.Long?(t.asInt=w.Long.fromValue(e.asInt)).unsigned=!1:typeof e.asInt==`string`?t.asInt=parseInt(e.asInt,10):typeof e.asInt==`number`?t.asInt=e.asInt:typeof e.asInt==`object`&&(t.asInt=new w.LongBits(e.asInt.low>>>0,e.asInt.high>>>0).toNumber())),e.exemplars){if(!Array.isArray(e.exemplars))throw TypeError(`.opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: array expected`);t.exemplars=[];for(var s=0;s<e.exemplars.length;++s){if(typeof e.exemplars[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: object expected`);t.exemplars[s]=E.opentelemetry.proto.metrics.v1.Exemplar.fromObject(e.exemplars[s])}}return e.flags!=null&&(t.flags=e.flags>>>0),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.exemplars=[],s.attributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.startTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.startTimeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;s.flags=0}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&(typeof e.startTimeUnixNano==`number`?s.startTimeUnixNano=t.longs===String?String(e.startTimeUnixNano):e.startTimeUnixNano:s.startTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.startTimeUnixNano):t.longs===Number?new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber():e.startTimeUnixNano),e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.asDouble!=null&&e.hasOwnProperty(`asDouble`)&&(s.asDouble=t.json&&!isFinite(e.asDouble)?String(e.asDouble):e.asDouble,t.oneofs&&(s.value=`asDouble`)),e.exemplars&&e.exemplars.length){s.exemplars=[];for(var S=0;S<e.exemplars.length;++S)s.exemplars[S]=E.opentelemetry.proto.metrics.v1.Exemplar.toObject(e.exemplars[S],t)}if(e.asInt!=null&&e.hasOwnProperty(`asInt`)&&(typeof e.asInt==`number`?s.asInt=t.longs===String?String(e.asInt):e.asInt:s.asInt=t.longs===String?w.Long.prototype.toString.call(e.asInt):t.longs===Number?new w.LongBits(e.asInt.low>>>0,e.asInt.high>>>0).toNumber():e.asInt,t.oneofs&&(s.value=`asInt`)),e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}return e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.NumberDataPoint`},e})(),e.HistogramDataPoint=(function(){function e(e){if(this.attributes=[],this.bucketCounts=[],this.explicitBounds=[],this.exemplars=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.attributes=w.emptyArray,e.prototype.startTimeUnixNano=null,e.prototype.timeUnixNano=null,e.prototype.count=null,e.prototype.sum=null,e.prototype.bucketCounts=w.emptyArray,e.prototype.explicitBounds=w.emptyArray,e.prototype.exemplars=w.emptyArray,e.prototype.flags=null,e.prototype.min=null,e.prototype.max=null;var t;return Object.defineProperty(e.prototype,`_sum`,{get:w.oneOfGetter(t=[`sum`]),set:w.oneOfSetter(t)}),Object.defineProperty(e.prototype,`_min`,{get:w.oneOfGetter(t=[`min`]),set:w.oneOfSetter(t)}),Object.defineProperty(e.prototype,`_max`,{get:w.oneOfGetter(t=[`max`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.startTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`startTimeUnixNano`)&&t.uint32(17).fixed64(e.startTimeUnixNano),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(25).fixed64(e.timeUnixNano),e.count!=null&&Object.hasOwnProperty.call(e,`count`)&&t.uint32(33).fixed64(e.count),e.sum!=null&&Object.hasOwnProperty.call(e,`sum`)&&t.uint32(41).double(e.sum),e.bucketCounts!=null&&e.bucketCounts.length){t.uint32(50).fork();for(var s=0;s<e.bucketCounts.length;++s)t.fixed64(e.bucketCounts[s]);t.ldelim()}if(e.explicitBounds!=null&&e.explicitBounds.length){t.uint32(58).fork();for(var s=0;s<e.explicitBounds.length;++s)t.double(e.explicitBounds[s]);t.ldelim()}if(e.exemplars!=null&&e.exemplars.length)for(var s=0;s<e.exemplars.length;++s)E.opentelemetry.proto.metrics.v1.Exemplar.encode(e.exemplars[s],t.uint32(66).fork()).ldelim();if(e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(74).fork()).ldelim();return e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(80).uint32(e.flags),e.min!=null&&Object.hasOwnProperty.call(e,`min`)&&t.uint32(89).double(e.min),e.max!=null&&Object.hasOwnProperty.call(e,`max`)&&t.uint32(97).double(e.max),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.HistogramDataPoint;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 9:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.startTimeUnixNano=e.fixed64();break;case 3:w.timeUnixNano=e.fixed64();break;case 4:w.count=e.fixed64();break;case 5:w.sum=e.double();break;case 6:if(w.bucketCounts&&w.bucketCounts.length||(w.bucketCounts=[]),(D&7)==2)for(var O=e.uint32()+e.pos;e.pos<O;)w.bucketCounts.push(e.fixed64());else w.bucketCounts.push(e.fixed64());break;case 7:if(w.explicitBounds&&w.explicitBounds.length||(w.explicitBounds=[]),(D&7)==2)for(var O=e.uint32()+e.pos;e.pos<O;)w.explicitBounds.push(e.double());else w.explicitBounds.push(e.double());break;case 8:w.exemplars&&w.exemplars.length||(w.exemplars=[]),w.exemplars.push(E.opentelemetry.proto.metrics.v1.Exemplar.decode(e,e.uint32()));break;case 10:w.flags=e.uint32();break;case 11:w.min=e.double();break;case 12:w.max=e.double();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var s=0;s<e.attributes.length;++s){var g=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[s]);if(g)return`attributes.`+g}}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&!w.isInteger(e.startTimeUnixNano)&&!(e.startTimeUnixNano&&w.isInteger(e.startTimeUnixNano.low)&&w.isInteger(e.startTimeUnixNano.high)))return`startTimeUnixNano: integer|Long expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.count!=null&&e.hasOwnProperty(`count`)&&!w.isInteger(e.count)&&!(e.count&&w.isInteger(e.count.low)&&w.isInteger(e.count.high)))return`count: integer|Long expected`;if(e.sum!=null&&e.hasOwnProperty(`sum`)&&(t._sum=1,typeof e.sum!=`number`))return`sum: number expected`;if(e.bucketCounts!=null&&e.hasOwnProperty(`bucketCounts`)){if(!Array.isArray(e.bucketCounts))return`bucketCounts: array expected`;for(var s=0;s<e.bucketCounts.length;++s)if(!w.isInteger(e.bucketCounts[s])&&!(e.bucketCounts[s]&&w.isInteger(e.bucketCounts[s].low)&&w.isInteger(e.bucketCounts[s].high)))return`bucketCounts: integer|Long[] expected`}if(e.explicitBounds!=null&&e.hasOwnProperty(`explicitBounds`)){if(!Array.isArray(e.explicitBounds))return`explicitBounds: array expected`;for(var s=0;s<e.explicitBounds.length;++s)if(typeof e.explicitBounds[s]!=`number`)return`explicitBounds: number[] expected`}if(e.exemplars!=null&&e.hasOwnProperty(`exemplars`)){if(!Array.isArray(e.exemplars))return`exemplars: array expected`;for(var s=0;s<e.exemplars.length;++s){var g=E.opentelemetry.proto.metrics.v1.Exemplar.verify(e.exemplars[s]);if(g)return`exemplars.`+g}}return e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags)?`flags: integer expected`:e.min!=null&&e.hasOwnProperty(`min`)&&(t._min=1,typeof e.min!=`number`)?`min: number expected`:e.max!=null&&e.hasOwnProperty(`max`)&&(t._max=1,typeof e.max!=`number`)?`max: number expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.HistogramDataPoint)return e;var t=new E.opentelemetry.proto.metrics.v1.HistogramDataPoint;if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.startTimeUnixNano!=null&&(w.Long?(t.startTimeUnixNano=w.Long.fromValue(e.startTimeUnixNano)).unsigned=!1:typeof e.startTimeUnixNano==`string`?t.startTimeUnixNano=parseInt(e.startTimeUnixNano,10):typeof e.startTimeUnixNano==`number`?t.startTimeUnixNano=e.startTimeUnixNano:typeof e.startTimeUnixNano==`object`&&(t.startTimeUnixNano=new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber())),e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.count!=null&&(w.Long?(t.count=w.Long.fromValue(e.count)).unsigned=!1:typeof e.count==`string`?t.count=parseInt(e.count,10):typeof e.count==`number`?t.count=e.count:typeof e.count==`object`&&(t.count=new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber())),e.sum!=null&&(t.sum=Number(e.sum)),e.bucketCounts){if(!Array.isArray(e.bucketCounts))throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.bucketCounts: array expected`);t.bucketCounts=[];for(var s=0;s<e.bucketCounts.length;++s)w.Long?(t.bucketCounts[s]=w.Long.fromValue(e.bucketCounts[s])).unsigned=!1:typeof e.bucketCounts[s]==`string`?t.bucketCounts[s]=parseInt(e.bucketCounts[s],10):typeof e.bucketCounts[s]==`number`?t.bucketCounts[s]=e.bucketCounts[s]:typeof e.bucketCounts[s]==`object`&&(t.bucketCounts[s]=new w.LongBits(e.bucketCounts[s].low>>>0,e.bucketCounts[s].high>>>0).toNumber())}if(e.explicitBounds){if(!Array.isArray(e.explicitBounds))throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.explicitBounds: array expected`);t.explicitBounds=[];for(var s=0;s<e.explicitBounds.length;++s)t.explicitBounds[s]=Number(e.explicitBounds[s])}if(e.exemplars){if(!Array.isArray(e.exemplars))throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: array expected`);t.exemplars=[];for(var s=0;s<e.exemplars.length;++s){if(typeof e.exemplars[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: object expected`);t.exemplars[s]=E.opentelemetry.proto.metrics.v1.Exemplar.fromObject(e.exemplars[s])}}return e.flags!=null&&(t.flags=e.flags>>>0),e.min!=null&&(t.min=Number(e.min)),e.max!=null&&(t.max=Number(e.max)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.bucketCounts=[],s.explicitBounds=[],s.exemplars=[],s.attributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.startTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.startTimeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.count=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.count=t.longs===String?`0`:0;s.flags=0}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&(typeof e.startTimeUnixNano==`number`?s.startTimeUnixNano=t.longs===String?String(e.startTimeUnixNano):e.startTimeUnixNano:s.startTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.startTimeUnixNano):t.longs===Number?new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber():e.startTimeUnixNano),e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.count!=null&&e.hasOwnProperty(`count`)&&(typeof e.count==`number`?s.count=t.longs===String?String(e.count):e.count:s.count=t.longs===String?w.Long.prototype.toString.call(e.count):t.longs===Number?new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber():e.count),e.sum!=null&&e.hasOwnProperty(`sum`)&&(s.sum=t.json&&!isFinite(e.sum)?String(e.sum):e.sum,t.oneofs&&(s._sum=`sum`)),e.bucketCounts&&e.bucketCounts.length){s.bucketCounts=[];for(var S=0;S<e.bucketCounts.length;++S)typeof e.bucketCounts[S]==`number`?s.bucketCounts[S]=t.longs===String?String(e.bucketCounts[S]):e.bucketCounts[S]:s.bucketCounts[S]=t.longs===String?w.Long.prototype.toString.call(e.bucketCounts[S]):t.longs===Number?new w.LongBits(e.bucketCounts[S].low>>>0,e.bucketCounts[S].high>>>0).toNumber():e.bucketCounts[S]}if(e.explicitBounds&&e.explicitBounds.length){s.explicitBounds=[];for(var S=0;S<e.explicitBounds.length;++S)s.explicitBounds[S]=t.json&&!isFinite(e.explicitBounds[S])?String(e.explicitBounds[S]):e.explicitBounds[S]}if(e.exemplars&&e.exemplars.length){s.exemplars=[];for(var S=0;S<e.exemplars.length;++S)s.exemplars[S]=E.opentelemetry.proto.metrics.v1.Exemplar.toObject(e.exemplars[S],t)}if(e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}return e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),e.min!=null&&e.hasOwnProperty(`min`)&&(s.min=t.json&&!isFinite(e.min)?String(e.min):e.min,t.oneofs&&(s._min=`min`)),e.max!=null&&e.hasOwnProperty(`max`)&&(s.max=t.json&&!isFinite(e.max)?String(e.max):e.max,t.oneofs&&(s._max=`max`)),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.HistogramDataPoint`},e})(),e.ExponentialHistogramDataPoint=(function(){function e(e){if(this.attributes=[],this.exemplars=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.attributes=w.emptyArray,e.prototype.startTimeUnixNano=null,e.prototype.timeUnixNano=null,e.prototype.count=null,e.prototype.sum=null,e.prototype.scale=null,e.prototype.zeroCount=null,e.prototype.positive=null,e.prototype.negative=null,e.prototype.flags=null,e.prototype.exemplars=w.emptyArray,e.prototype.min=null,e.prototype.max=null,e.prototype.zeroThreshold=null;var t;return Object.defineProperty(e.prototype,`_sum`,{get:w.oneOfGetter(t=[`sum`]),set:w.oneOfSetter(t)}),Object.defineProperty(e.prototype,`_min`,{get:w.oneOfGetter(t=[`min`]),set:w.oneOfSetter(t)}),Object.defineProperty(e.prototype,`_max`,{get:w.oneOfGetter(t=[`max`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(10).fork()).ldelim();if(e.startTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`startTimeUnixNano`)&&t.uint32(17).fixed64(e.startTimeUnixNano),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(25).fixed64(e.timeUnixNano),e.count!=null&&Object.hasOwnProperty.call(e,`count`)&&t.uint32(33).fixed64(e.count),e.sum!=null&&Object.hasOwnProperty.call(e,`sum`)&&t.uint32(41).double(e.sum),e.scale!=null&&Object.hasOwnProperty.call(e,`scale`)&&t.uint32(48).sint32(e.scale),e.zeroCount!=null&&Object.hasOwnProperty.call(e,`zeroCount`)&&t.uint32(57).fixed64(e.zeroCount),e.positive!=null&&Object.hasOwnProperty.call(e,`positive`)&&E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(e.positive,t.uint32(66).fork()).ldelim(),e.negative!=null&&Object.hasOwnProperty.call(e,`negative`)&&E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(e.negative,t.uint32(74).fork()).ldelim(),e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(80).uint32(e.flags),e.exemplars!=null&&e.exemplars.length)for(var s=0;s<e.exemplars.length;++s)E.opentelemetry.proto.metrics.v1.Exemplar.encode(e.exemplars[s],t.uint32(90).fork()).ldelim();return e.min!=null&&Object.hasOwnProperty.call(e,`min`)&&t.uint32(97).double(e.min),e.max!=null&&Object.hasOwnProperty.call(e,`max`)&&t.uint32(105).double(e.max),e.zeroThreshold!=null&&Object.hasOwnProperty.call(e,`zeroThreshold`)&&t.uint32(113).double(e.zeroThreshold),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.startTimeUnixNano=e.fixed64();break;case 3:w.timeUnixNano=e.fixed64();break;case 4:w.count=e.fixed64();break;case 5:w.sum=e.double();break;case 6:w.scale=e.sint32();break;case 7:w.zeroCount=e.fixed64();break;case 8:w.positive=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(e,e.uint32());break;case 9:w.negative=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(e,e.uint32());break;case 10:w.flags=e.uint32();break;case 11:w.exemplars&&w.exemplars.length||(w.exemplars=[]),w.exemplars.push(E.opentelemetry.proto.metrics.v1.Exemplar.decode(e,e.uint32()));break;case 12:w.min=e.double();break;case 13:w.max=e.double();break;case 14:w.zeroThreshold=e.double();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var s=0;s<e.attributes.length;++s){var g=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[s]);if(g)return`attributes.`+g}}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&!w.isInteger(e.startTimeUnixNano)&&!(e.startTimeUnixNano&&w.isInteger(e.startTimeUnixNano.low)&&w.isInteger(e.startTimeUnixNano.high)))return`startTimeUnixNano: integer|Long expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.count!=null&&e.hasOwnProperty(`count`)&&!w.isInteger(e.count)&&!(e.count&&w.isInteger(e.count.low)&&w.isInteger(e.count.high)))return`count: integer|Long expected`;if(e.sum!=null&&e.hasOwnProperty(`sum`)&&(t._sum=1,typeof e.sum!=`number`))return`sum: number expected`;if(e.scale!=null&&e.hasOwnProperty(`scale`)&&!w.isInteger(e.scale))return`scale: integer expected`;if(e.zeroCount!=null&&e.hasOwnProperty(`zeroCount`)&&!w.isInteger(e.zeroCount)&&!(e.zeroCount&&w.isInteger(e.zeroCount.low)&&w.isInteger(e.zeroCount.high)))return`zeroCount: integer|Long expected`;if(e.positive!=null&&e.hasOwnProperty(`positive`)){var g=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(e.positive);if(g)return`positive.`+g}if(e.negative!=null&&e.hasOwnProperty(`negative`)){var g=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(e.negative);if(g)return`negative.`+g}if(e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags))return`flags: integer expected`;if(e.exemplars!=null&&e.hasOwnProperty(`exemplars`)){if(!Array.isArray(e.exemplars))return`exemplars: array expected`;for(var s=0;s<e.exemplars.length;++s){var g=E.opentelemetry.proto.metrics.v1.Exemplar.verify(e.exemplars[s]);if(g)return`exemplars.`+g}}return e.min!=null&&e.hasOwnProperty(`min`)&&(t._min=1,typeof e.min!=`number`)?`min: number expected`:e.max!=null&&e.hasOwnProperty(`max`)&&(t._max=1,typeof e.max!=`number`)?`max: number expected`:e.zeroThreshold!=null&&e.hasOwnProperty(`zeroThreshold`)&&typeof e.zeroThreshold!=`number`?`zeroThreshold: number expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint)return e;var t=new E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint;if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.startTimeUnixNano!=null&&(w.Long?(t.startTimeUnixNano=w.Long.fromValue(e.startTimeUnixNano)).unsigned=!1:typeof e.startTimeUnixNano==`string`?t.startTimeUnixNano=parseInt(e.startTimeUnixNano,10):typeof e.startTimeUnixNano==`number`?t.startTimeUnixNano=e.startTimeUnixNano:typeof e.startTimeUnixNano==`object`&&(t.startTimeUnixNano=new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber())),e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.count!=null&&(w.Long?(t.count=w.Long.fromValue(e.count)).unsigned=!1:typeof e.count==`string`?t.count=parseInt(e.count,10):typeof e.count==`number`?t.count=e.count:typeof e.count==`object`&&(t.count=new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber())),e.sum!=null&&(t.sum=Number(e.sum)),e.scale!=null&&(t.scale=e.scale|0),e.zeroCount!=null&&(w.Long?(t.zeroCount=w.Long.fromValue(e.zeroCount)).unsigned=!1:typeof e.zeroCount==`string`?t.zeroCount=parseInt(e.zeroCount,10):typeof e.zeroCount==`number`?t.zeroCount=e.zeroCount:typeof e.zeroCount==`object`&&(t.zeroCount=new w.LongBits(e.zeroCount.low>>>0,e.zeroCount.high>>>0).toNumber())),e.positive!=null){if(typeof e.positive!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.positive: object expected`);t.positive=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(e.positive)}if(e.negative!=null){if(typeof e.negative!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.negative: object expected`);t.negative=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(e.negative)}if(e.flags!=null&&(t.flags=e.flags>>>0),e.exemplars){if(!Array.isArray(e.exemplars))throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: array expected`);t.exemplars=[];for(var s=0;s<e.exemplars.length;++s){if(typeof e.exemplars[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: object expected`);t.exemplars[s]=E.opentelemetry.proto.metrics.v1.Exemplar.fromObject(e.exemplars[s])}}return e.min!=null&&(t.min=Number(e.min)),e.max!=null&&(t.max=Number(e.max)),e.zeroThreshold!=null&&(t.zeroThreshold=Number(e.zeroThreshold)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[],s.exemplars=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.startTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.startTimeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.count=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.count=t.longs===String?`0`:0;if(s.scale=0,w.Long){var g=new w.Long(0,0,!1);s.zeroCount=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.zeroCount=t.longs===String?`0`:0;s.positive=null,s.negative=null,s.flags=0,s.zeroThreshold=0}if(e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&(typeof e.startTimeUnixNano==`number`?s.startTimeUnixNano=t.longs===String?String(e.startTimeUnixNano):e.startTimeUnixNano:s.startTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.startTimeUnixNano):t.longs===Number?new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber():e.startTimeUnixNano),e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.count!=null&&e.hasOwnProperty(`count`)&&(typeof e.count==`number`?s.count=t.longs===String?String(e.count):e.count:s.count=t.longs===String?w.Long.prototype.toString.call(e.count):t.longs===Number?new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber():e.count),e.sum!=null&&e.hasOwnProperty(`sum`)&&(s.sum=t.json&&!isFinite(e.sum)?String(e.sum):e.sum,t.oneofs&&(s._sum=`sum`)),e.scale!=null&&e.hasOwnProperty(`scale`)&&(s.scale=e.scale),e.zeroCount!=null&&e.hasOwnProperty(`zeroCount`)&&(typeof e.zeroCount==`number`?s.zeroCount=t.longs===String?String(e.zeroCount):e.zeroCount:s.zeroCount=t.longs===String?w.Long.prototype.toString.call(e.zeroCount):t.longs===Number?new w.LongBits(e.zeroCount.low>>>0,e.zeroCount.high>>>0).toNumber():e.zeroCount),e.positive!=null&&e.hasOwnProperty(`positive`)&&(s.positive=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(e.positive,t)),e.negative!=null&&e.hasOwnProperty(`negative`)&&(s.negative=E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(e.negative,t)),e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),e.exemplars&&e.exemplars.length){s.exemplars=[];for(var S=0;S<e.exemplars.length;++S)s.exemplars[S]=E.opentelemetry.proto.metrics.v1.Exemplar.toObject(e.exemplars[S],t)}return e.min!=null&&e.hasOwnProperty(`min`)&&(s.min=t.json&&!isFinite(e.min)?String(e.min):e.min,t.oneofs&&(s._min=`min`)),e.max!=null&&e.hasOwnProperty(`max`)&&(s.max=t.json&&!isFinite(e.max)?String(e.max):e.max,t.oneofs&&(s._max=`max`)),e.zeroThreshold!=null&&e.hasOwnProperty(`zeroThreshold`)&&(s.zeroThreshold=t.json&&!isFinite(e.zeroThreshold)?String(e.zeroThreshold):e.zeroThreshold),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint`},e.Buckets=(function(){function e(e){if(this.bucketCounts=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.offset=null,e.prototype.bucketCounts=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.offset!=null&&Object.hasOwnProperty.call(e,`offset`)&&t.uint32(8).sint32(e.offset),e.bucketCounts!=null&&e.bucketCounts.length){t.uint32(18).fork();for(var s=0;s<e.bucketCounts.length;++s)t.uint64(e.bucketCounts[s]);t.ldelim()}return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.offset=e.sint32();break;case 2:if(w.bucketCounts&&w.bucketCounts.length||(w.bucketCounts=[]),(D&7)==2)for(var O=e.uint32()+e.pos;e.pos<O;)w.bucketCounts.push(e.uint64());else w.bucketCounts.push(e.uint64());break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.offset!=null&&e.hasOwnProperty(`offset`)&&!w.isInteger(e.offset))return`offset: integer expected`;if(e.bucketCounts!=null&&e.hasOwnProperty(`bucketCounts`)){if(!Array.isArray(e.bucketCounts))return`bucketCounts: array expected`;for(var t=0;t<e.bucketCounts.length;++t)if(!w.isInteger(e.bucketCounts[t])&&!(e.bucketCounts[t]&&w.isInteger(e.bucketCounts[t].low)&&w.isInteger(e.bucketCounts[t].high)))return`bucketCounts: integer|Long[] expected`}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets)return e;var t=new E.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets;if(e.offset!=null&&(t.offset=e.offset|0),e.bucketCounts){if(!Array.isArray(e.bucketCounts))throw TypeError(`.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.bucketCounts: array expected`);t.bucketCounts=[];for(var s=0;s<e.bucketCounts.length;++s)w.Long?(t.bucketCounts[s]=w.Long.fromValue(e.bucketCounts[s])).unsigned=!0:typeof e.bucketCounts[s]==`string`?t.bucketCounts[s]=parseInt(e.bucketCounts[s],10):typeof e.bucketCounts[s]==`number`?t.bucketCounts[s]=e.bucketCounts[s]:typeof e.bucketCounts[s]==`object`&&(t.bucketCounts[s]=new w.LongBits(e.bucketCounts[s].low>>>0,e.bucketCounts[s].high>>>0).toNumber(!0))}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.bucketCounts=[]),t.defaults&&(s.offset=0),e.offset!=null&&e.hasOwnProperty(`offset`)&&(s.offset=e.offset),e.bucketCounts&&e.bucketCounts.length){s.bucketCounts=[];for(var g=0;g<e.bucketCounts.length;++g)typeof e.bucketCounts[g]==`number`?s.bucketCounts[g]=t.longs===String?String(e.bucketCounts[g]):e.bucketCounts[g]:s.bucketCounts[g]=t.longs===String?w.Long.prototype.toString.call(e.bucketCounts[g]):t.longs===Number?new w.LongBits(e.bucketCounts[g].low>>>0,e.bucketCounts[g].high>>>0).toNumber(!0):e.bucketCounts[g]}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets`},e})(),e})(),e.SummaryDataPoint=(function(){function e(e){if(this.attributes=[],this.quantileValues=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.attributes=w.emptyArray,e.prototype.startTimeUnixNano=null,e.prototype.timeUnixNano=null,e.prototype.count=null,e.prototype.sum=null,e.prototype.quantileValues=w.emptyArray,e.prototype.flags=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.startTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`startTimeUnixNano`)&&t.uint32(17).fixed64(e.startTimeUnixNano),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(25).fixed64(e.timeUnixNano),e.count!=null&&Object.hasOwnProperty.call(e,`count`)&&t.uint32(33).fixed64(e.count),e.sum!=null&&Object.hasOwnProperty.call(e,`sum`)&&t.uint32(41).double(e.sum),e.quantileValues!=null&&e.quantileValues.length)for(var s=0;s<e.quantileValues.length;++s)E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.encode(e.quantileValues[s],t.uint32(50).fork()).ldelim();if(e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(58).fork()).ldelim();return e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(64).uint32(e.flags),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.SummaryDataPoint;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 7:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.startTimeUnixNano=e.fixed64();break;case 3:w.timeUnixNano=e.fixed64();break;case 4:w.count=e.fixed64();break;case 5:w.sum=e.double();break;case 6:w.quantileValues&&w.quantileValues.length||(w.quantileValues=[]),w.quantileValues.push(E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.decode(e,e.uint32()));break;case 8:w.flags=e.uint32();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var t=0;t<e.attributes.length;++t){var s=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[t]);if(s)return`attributes.`+s}}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&!w.isInteger(e.startTimeUnixNano)&&!(e.startTimeUnixNano&&w.isInteger(e.startTimeUnixNano.low)&&w.isInteger(e.startTimeUnixNano.high)))return`startTimeUnixNano: integer|Long expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.count!=null&&e.hasOwnProperty(`count`)&&!w.isInteger(e.count)&&!(e.count&&w.isInteger(e.count.low)&&w.isInteger(e.count.high)))return`count: integer|Long expected`;if(e.sum!=null&&e.hasOwnProperty(`sum`)&&typeof e.sum!=`number`)return`sum: number expected`;if(e.quantileValues!=null&&e.hasOwnProperty(`quantileValues`)){if(!Array.isArray(e.quantileValues))return`quantileValues: array expected`;for(var t=0;t<e.quantileValues.length;++t){var s=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify(e.quantileValues[t]);if(s)return`quantileValues.`+s}}return e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags)?`flags: integer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.SummaryDataPoint)return e;var t=new E.opentelemetry.proto.metrics.v1.SummaryDataPoint;if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}if(e.startTimeUnixNano!=null&&(w.Long?(t.startTimeUnixNano=w.Long.fromValue(e.startTimeUnixNano)).unsigned=!1:typeof e.startTimeUnixNano==`string`?t.startTimeUnixNano=parseInt(e.startTimeUnixNano,10):typeof e.startTimeUnixNano==`number`?t.startTimeUnixNano=e.startTimeUnixNano:typeof e.startTimeUnixNano==`object`&&(t.startTimeUnixNano=new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber())),e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.count!=null&&(w.Long?(t.count=w.Long.fromValue(e.count)).unsigned=!1:typeof e.count==`string`?t.count=parseInt(e.count,10):typeof e.count==`number`?t.count=e.count:typeof e.count==`object`&&(t.count=new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber())),e.sum!=null&&(t.sum=Number(e.sum)),e.quantileValues){if(!Array.isArray(e.quantileValues))throw TypeError(`.opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: array expected`);t.quantileValues=[];for(var s=0;s<e.quantileValues.length;++s){if(typeof e.quantileValues[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: object expected`);t.quantileValues[s]=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.fromObject(e.quantileValues[s])}}return e.flags!=null&&(t.flags=e.flags>>>0),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.quantileValues=[],s.attributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.startTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.startTimeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;if(w.Long){var g=new w.Long(0,0,!1);s.count=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.count=t.longs===String?`0`:0;s.sum=0,s.flags=0}if(e.startTimeUnixNano!=null&&e.hasOwnProperty(`startTimeUnixNano`)&&(typeof e.startTimeUnixNano==`number`?s.startTimeUnixNano=t.longs===String?String(e.startTimeUnixNano):e.startTimeUnixNano:s.startTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.startTimeUnixNano):t.longs===Number?new w.LongBits(e.startTimeUnixNano.low>>>0,e.startTimeUnixNano.high>>>0).toNumber():e.startTimeUnixNano),e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.count!=null&&e.hasOwnProperty(`count`)&&(typeof e.count==`number`?s.count=t.longs===String?String(e.count):e.count:s.count=t.longs===String?w.Long.prototype.toString.call(e.count):t.longs===Number?new w.LongBits(e.count.low>>>0,e.count.high>>>0).toNumber():e.count),e.sum!=null&&e.hasOwnProperty(`sum`)&&(s.sum=t.json&&!isFinite(e.sum)?String(e.sum):e.sum),e.quantileValues&&e.quantileValues.length){s.quantileValues=[];for(var S=0;S<e.quantileValues.length;++S)s.quantileValues[S]=E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.toObject(e.quantileValues[S],t)}if(e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}return e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.SummaryDataPoint`},e.ValueAtQuantile=(function(){function e(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.quantile=null,e.prototype.value=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||=S.create(),e.quantile!=null&&Object.hasOwnProperty.call(e,`quantile`)&&t.uint32(9).double(e.quantile),e.value!=null&&Object.hasOwnProperty.call(e,`value`)&&t.uint32(17).double(e.value),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.quantile=e.double();break;case 2:w.value=e.double();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){return typeof e!=`object`||!e?`object expected`:e.quantile!=null&&e.hasOwnProperty(`quantile`)&&typeof e.quantile!=`number`?`quantile: number expected`:e.value!=null&&e.hasOwnProperty(`value`)&&typeof e.value!=`number`?`value: number expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile)return e;var t=new E.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile;return e.quantile!=null&&(t.quantile=Number(e.quantile)),e.value!=null&&(t.value=Number(e.value)),t},e.toObject=function(e,t){t||={};var s={};return t.defaults&&(s.quantile=0,s.value=0),e.quantile!=null&&e.hasOwnProperty(`quantile`)&&(s.quantile=t.json&&!isFinite(e.quantile)?String(e.quantile):e.quantile),e.value!=null&&e.hasOwnProperty(`value`)&&(s.value=t.json&&!isFinite(e.value)?String(e.value):e.value),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile`},e})(),e})(),e.Exemplar=(function(){function e(e){if(this.filteredAttributes=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}e.prototype.filteredAttributes=w.emptyArray,e.prototype.timeUnixNano=null,e.prototype.asDouble=null,e.prototype.asInt=null,e.prototype.spanId=null,e.prototype.traceId=null;var t;return Object.defineProperty(e.prototype,`value`,{get:w.oneOfGetter(t=[`asDouble`,`asInt`]),set:w.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(17).fixed64(e.timeUnixNano),e.asDouble!=null&&Object.hasOwnProperty.call(e,`asDouble`)&&t.uint32(25).double(e.asDouble),e.spanId!=null&&Object.hasOwnProperty.call(e,`spanId`)&&t.uint32(34).bytes(e.spanId),e.traceId!=null&&Object.hasOwnProperty.call(e,`traceId`)&&t.uint32(42).bytes(e.traceId),e.asInt!=null&&Object.hasOwnProperty.call(e,`asInt`)&&t.uint32(49).sfixed64(e.asInt),e.filteredAttributes!=null&&e.filteredAttributes.length)for(var s=0;s<e.filteredAttributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.filteredAttributes[s],t.uint32(58).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.metrics.v1.Exemplar;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 7:w.filteredAttributes&&w.filteredAttributes.length||(w.filteredAttributes=[]),w.filteredAttributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 2:w.timeUnixNano=e.fixed64();break;case 3:w.asDouble=e.double();break;case 6:w.asInt=e.sfixed64();break;case 4:w.spanId=e.bytes();break;case 5:w.traceId=e.bytes();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;var t={};if(e.filteredAttributes!=null&&e.hasOwnProperty(`filteredAttributes`)){if(!Array.isArray(e.filteredAttributes))return`filteredAttributes: array expected`;for(var s=0;s<e.filteredAttributes.length;++s){var g=E.opentelemetry.proto.common.v1.KeyValue.verify(e.filteredAttributes[s]);if(g)return`filteredAttributes.`+g}}if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.asDouble!=null&&e.hasOwnProperty(`asDouble`)&&(t.value=1,typeof e.asDouble!=`number`))return`asDouble: number expected`;if(e.asInt!=null&&e.hasOwnProperty(`asInt`)){if(t.value===1)return`value: multiple values`;if(t.value=1,!w.isInteger(e.asInt)&&!(e.asInt&&w.isInteger(e.asInt.low)&&w.isInteger(e.asInt.high)))return`asInt: integer|Long expected`}return e.spanId!=null&&e.hasOwnProperty(`spanId`)&&!(e.spanId&&typeof e.spanId.length==`number`||w.isString(e.spanId))?`spanId: buffer expected`:e.traceId!=null&&e.hasOwnProperty(`traceId`)&&!(e.traceId&&typeof e.traceId.length==`number`||w.isString(e.traceId))?`traceId: buffer expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.metrics.v1.Exemplar)return e;var t=new E.opentelemetry.proto.metrics.v1.Exemplar;if(e.filteredAttributes){if(!Array.isArray(e.filteredAttributes))throw TypeError(`.opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: array expected`);t.filteredAttributes=[];for(var s=0;s<e.filteredAttributes.length;++s){if(typeof e.filteredAttributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: object expected`);t.filteredAttributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.filteredAttributes[s])}}return e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.asDouble!=null&&(t.asDouble=Number(e.asDouble)),e.asInt!=null&&(w.Long?(t.asInt=w.Long.fromValue(e.asInt)).unsigned=!1:typeof e.asInt==`string`?t.asInt=parseInt(e.asInt,10):typeof e.asInt==`number`?t.asInt=e.asInt:typeof e.asInt==`object`&&(t.asInt=new w.LongBits(e.asInt.low>>>0,e.asInt.high>>>0).toNumber())),e.spanId!=null&&(typeof e.spanId==`string`?w.base64.decode(e.spanId,t.spanId=w.newBuffer(w.base64.length(e.spanId)),0):e.spanId.length>=0&&(t.spanId=e.spanId)),e.traceId!=null&&(typeof e.traceId==`string`?w.base64.decode(e.traceId,t.traceId=w.newBuffer(w.base64.length(e.traceId)),0):e.traceId.length>=0&&(t.traceId=e.traceId)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.filteredAttributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;t.bytes===String?s.spanId=``:(s.spanId=[],t.bytes!==Array&&(s.spanId=w.newBuffer(s.spanId))),t.bytes===String?s.traceId=``:(s.traceId=[],t.bytes!==Array&&(s.traceId=w.newBuffer(s.traceId)))}if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.asDouble!=null&&e.hasOwnProperty(`asDouble`)&&(s.asDouble=t.json&&!isFinite(e.asDouble)?String(e.asDouble):e.asDouble,t.oneofs&&(s.value=`asDouble`)),e.spanId!=null&&e.hasOwnProperty(`spanId`)&&(s.spanId=t.bytes===String?w.base64.encode(e.spanId,0,e.spanId.length):t.bytes===Array?Array.prototype.slice.call(e.spanId):e.spanId),e.traceId!=null&&e.hasOwnProperty(`traceId`)&&(s.traceId=t.bytes===String?w.base64.encode(e.traceId,0,e.traceId.length):t.bytes===Array?Array.prototype.slice.call(e.traceId):e.traceId),e.asInt!=null&&e.hasOwnProperty(`asInt`)&&(typeof e.asInt==`number`?s.asInt=t.longs===String?String(e.asInt):e.asInt:s.asInt=t.longs===String?w.Long.prototype.toString.call(e.asInt):t.longs===Number?new w.LongBits(e.asInt.low>>>0,e.asInt.high>>>0).toNumber():e.asInt,t.oneofs&&(s.value=`asInt`)),e.filteredAttributes&&e.filteredAttributes.length){s.filteredAttributes=[];for(var S=0;S<e.filteredAttributes.length;++S)s.filteredAttributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.filteredAttributes[S],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.metrics.v1.Exemplar`},e})(),e})(),e})(),e.logs=(function(){var e={};return e.v1=(function(){var e={};return e.LogsData=(function(){function e(e){if(this.resourceLogs=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resourceLogs=w.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resourceLogs!=null&&e.resourceLogs.length)for(var s=0;s<e.resourceLogs.length;++s)E.opentelemetry.proto.logs.v1.ResourceLogs.encode(e.resourceLogs[s],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.logs.v1.LogsData;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resourceLogs&&w.resourceLogs.length||(w.resourceLogs=[]),w.resourceLogs.push(E.opentelemetry.proto.logs.v1.ResourceLogs.decode(e,e.uint32()));break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resourceLogs!=null&&e.hasOwnProperty(`resourceLogs`)){if(!Array.isArray(e.resourceLogs))return`resourceLogs: array expected`;for(var t=0;t<e.resourceLogs.length;++t){var s=E.opentelemetry.proto.logs.v1.ResourceLogs.verify(e.resourceLogs[t]);if(s)return`resourceLogs.`+s}}return null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.logs.v1.LogsData)return e;var t=new E.opentelemetry.proto.logs.v1.LogsData;if(e.resourceLogs){if(!Array.isArray(e.resourceLogs))throw TypeError(`.opentelemetry.proto.logs.v1.LogsData.resourceLogs: array expected`);t.resourceLogs=[];for(var s=0;s<e.resourceLogs.length;++s){if(typeof e.resourceLogs[s]!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.LogsData.resourceLogs: object expected`);t.resourceLogs[s]=E.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(e.resourceLogs[s])}}return t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.resourceLogs=[]),e.resourceLogs&&e.resourceLogs.length){s.resourceLogs=[];for(var g=0;g<e.resourceLogs.length;++g)s.resourceLogs[g]=E.opentelemetry.proto.logs.v1.ResourceLogs.toObject(e.resourceLogs[g],t)}return s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.logs.v1.LogsData`},e})(),e.ResourceLogs=(function(){function e(e){if(this.scopeLogs=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.resource=null,e.prototype.scopeLogs=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.resource!=null&&Object.hasOwnProperty.call(e,`resource`)&&E.opentelemetry.proto.resource.v1.Resource.encode(e.resource,t.uint32(10).fork()).ldelim(),e.scopeLogs!=null&&e.scopeLogs.length)for(var s=0;s<e.scopeLogs.length;++s)E.opentelemetry.proto.logs.v1.ScopeLogs.encode(e.scopeLogs[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.logs.v1.ResourceLogs;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.resource=E.opentelemetry.proto.resource.v1.Resource.decode(e,e.uint32());break;case 2:w.scopeLogs&&w.scopeLogs.length||(w.scopeLogs=[]),w.scopeLogs.push(E.opentelemetry.proto.logs.v1.ScopeLogs.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.resource!=null&&e.hasOwnProperty(`resource`)){var t=E.opentelemetry.proto.resource.v1.Resource.verify(e.resource);if(t)return`resource.`+t}if(e.scopeLogs!=null&&e.hasOwnProperty(`scopeLogs`)){if(!Array.isArray(e.scopeLogs))return`scopeLogs: array expected`;for(var s=0;s<e.scopeLogs.length;++s){var t=E.opentelemetry.proto.logs.v1.ScopeLogs.verify(e.scopeLogs[s]);if(t)return`scopeLogs.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.logs.v1.ResourceLogs)return e;var t=new E.opentelemetry.proto.logs.v1.ResourceLogs;if(e.resource!=null){if(typeof e.resource!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.ResourceLogs.resource: object expected`);t.resource=E.opentelemetry.proto.resource.v1.Resource.fromObject(e.resource)}if(e.scopeLogs){if(!Array.isArray(e.scopeLogs))throw TypeError(`.opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: array expected`);t.scopeLogs=[];for(var s=0;s<e.scopeLogs.length;++s){if(typeof e.scopeLogs[s]!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: object expected`);t.scopeLogs[s]=E.opentelemetry.proto.logs.v1.ScopeLogs.fromObject(e.scopeLogs[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.scopeLogs=[]),t.defaults&&(s.resource=null,s.schemaUrl=``),e.resource!=null&&e.hasOwnProperty(`resource`)&&(s.resource=E.opentelemetry.proto.resource.v1.Resource.toObject(e.resource,t)),e.scopeLogs&&e.scopeLogs.length){s.scopeLogs=[];for(var g=0;g<e.scopeLogs.length;++g)s.scopeLogs[g]=E.opentelemetry.proto.logs.v1.ScopeLogs.toObject(e.scopeLogs[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.logs.v1.ResourceLogs`},e})(),e.ScopeLogs=(function(){function e(e){if(this.logRecords=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.scope=null,e.prototype.logRecords=w.emptyArray,e.prototype.schemaUrl=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.scope!=null&&Object.hasOwnProperty.call(e,`scope`)&&E.opentelemetry.proto.common.v1.InstrumentationScope.encode(e.scope,t.uint32(10).fork()).ldelim(),e.logRecords!=null&&e.logRecords.length)for(var s=0;s<e.logRecords.length;++s)E.opentelemetry.proto.logs.v1.LogRecord.encode(e.logRecords[s],t.uint32(18).fork()).ldelim();return e.schemaUrl!=null&&Object.hasOwnProperty.call(e,`schemaUrl`)&&t.uint32(26).string(e.schemaUrl),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.logs.v1.ScopeLogs;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.decode(e,e.uint32());break;case 2:w.logRecords&&w.logRecords.length||(w.logRecords=[]),w.logRecords.push(E.opentelemetry.proto.logs.v1.LogRecord.decode(e,e.uint32()));break;case 3:w.schemaUrl=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.scope!=null&&e.hasOwnProperty(`scope`)){var t=E.opentelemetry.proto.common.v1.InstrumentationScope.verify(e.scope);if(t)return`scope.`+t}if(e.logRecords!=null&&e.hasOwnProperty(`logRecords`)){if(!Array.isArray(e.logRecords))return`logRecords: array expected`;for(var s=0;s<e.logRecords.length;++s){var t=E.opentelemetry.proto.logs.v1.LogRecord.verify(e.logRecords[s]);if(t)return`logRecords.`+t}}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&!w.isString(e.schemaUrl)?`schemaUrl: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.logs.v1.ScopeLogs)return e;var t=new E.opentelemetry.proto.logs.v1.ScopeLogs;if(e.scope!=null){if(typeof e.scope!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.ScopeLogs.scope: object expected`);t.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(e.scope)}if(e.logRecords){if(!Array.isArray(e.logRecords))throw TypeError(`.opentelemetry.proto.logs.v1.ScopeLogs.logRecords: array expected`);t.logRecords=[];for(var s=0;s<e.logRecords.length;++s){if(typeof e.logRecords[s]!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.ScopeLogs.logRecords: object expected`);t.logRecords[s]=E.opentelemetry.proto.logs.v1.LogRecord.fromObject(e.logRecords[s])}}return e.schemaUrl!=null&&(t.schemaUrl=String(e.schemaUrl)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.logRecords=[]),t.defaults&&(s.scope=null,s.schemaUrl=``),e.scope!=null&&e.hasOwnProperty(`scope`)&&(s.scope=E.opentelemetry.proto.common.v1.InstrumentationScope.toObject(e.scope,t)),e.logRecords&&e.logRecords.length){s.logRecords=[];for(var g=0;g<e.logRecords.length;++g)s.logRecords[g]=E.opentelemetry.proto.logs.v1.LogRecord.toObject(e.logRecords[g],t)}return e.schemaUrl!=null&&e.hasOwnProperty(`schemaUrl`)&&(s.schemaUrl=e.schemaUrl),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.logs.v1.ScopeLogs`},e})(),e.SeverityNumber=(function(){var e={},t=Object.create(e);return t[e[0]=`SEVERITY_NUMBER_UNSPECIFIED`]=0,t[e[1]=`SEVERITY_NUMBER_TRACE`]=1,t[e[2]=`SEVERITY_NUMBER_TRACE2`]=2,t[e[3]=`SEVERITY_NUMBER_TRACE3`]=3,t[e[4]=`SEVERITY_NUMBER_TRACE4`]=4,t[e[5]=`SEVERITY_NUMBER_DEBUG`]=5,t[e[6]=`SEVERITY_NUMBER_DEBUG2`]=6,t[e[7]=`SEVERITY_NUMBER_DEBUG3`]=7,t[e[8]=`SEVERITY_NUMBER_DEBUG4`]=8,t[e[9]=`SEVERITY_NUMBER_INFO`]=9,t[e[10]=`SEVERITY_NUMBER_INFO2`]=10,t[e[11]=`SEVERITY_NUMBER_INFO3`]=11,t[e[12]=`SEVERITY_NUMBER_INFO4`]=12,t[e[13]=`SEVERITY_NUMBER_WARN`]=13,t[e[14]=`SEVERITY_NUMBER_WARN2`]=14,t[e[15]=`SEVERITY_NUMBER_WARN3`]=15,t[e[16]=`SEVERITY_NUMBER_WARN4`]=16,t[e[17]=`SEVERITY_NUMBER_ERROR`]=17,t[e[18]=`SEVERITY_NUMBER_ERROR2`]=18,t[e[19]=`SEVERITY_NUMBER_ERROR3`]=19,t[e[20]=`SEVERITY_NUMBER_ERROR4`]=20,t[e[21]=`SEVERITY_NUMBER_FATAL`]=21,t[e[22]=`SEVERITY_NUMBER_FATAL2`]=22,t[e[23]=`SEVERITY_NUMBER_FATAL3`]=23,t[e[24]=`SEVERITY_NUMBER_FATAL4`]=24,t})(),e.LogRecordFlags=(function(){var e={},t=Object.create(e);return t[e[0]=`LOG_RECORD_FLAGS_DO_NOT_USE`]=0,t[e[255]=`LOG_RECORD_FLAGS_TRACE_FLAGS_MASK`]=255,t})(),e.LogRecord=(function(){function e(e){if(this.attributes=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return e.prototype.timeUnixNano=null,e.prototype.observedTimeUnixNano=null,e.prototype.severityNumber=null,e.prototype.severityText=null,e.prototype.body=null,e.prototype.attributes=w.emptyArray,e.prototype.droppedAttributesCount=null,e.prototype.flags=null,e.prototype.traceId=null,e.prototype.spanId=null,e.prototype.eventName=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||=S.create(),e.timeUnixNano!=null&&Object.hasOwnProperty.call(e,`timeUnixNano`)&&t.uint32(9).fixed64(e.timeUnixNano),e.severityNumber!=null&&Object.hasOwnProperty.call(e,`severityNumber`)&&t.uint32(16).int32(e.severityNumber),e.severityText!=null&&Object.hasOwnProperty.call(e,`severityText`)&&t.uint32(26).string(e.severityText),e.body!=null&&Object.hasOwnProperty.call(e,`body`)&&E.opentelemetry.proto.common.v1.AnyValue.encode(e.body,t.uint32(42).fork()).ldelim(),e.attributes!=null&&e.attributes.length)for(var s=0;s<e.attributes.length;++s)E.opentelemetry.proto.common.v1.KeyValue.encode(e.attributes[s],t.uint32(50).fork()).ldelim();return e.droppedAttributesCount!=null&&Object.hasOwnProperty.call(e,`droppedAttributesCount`)&&t.uint32(56).uint32(e.droppedAttributesCount),e.flags!=null&&Object.hasOwnProperty.call(e,`flags`)&&t.uint32(69).fixed32(e.flags),e.traceId!=null&&Object.hasOwnProperty.call(e,`traceId`)&&t.uint32(74).bytes(e.traceId),e.spanId!=null&&Object.hasOwnProperty.call(e,`spanId`)&&t.uint32(82).bytes(e.spanId),e.observedTimeUnixNano!=null&&Object.hasOwnProperty.call(e,`observedTimeUnixNano`)&&t.uint32(89).fixed64(e.observedTimeUnixNano),e.eventName!=null&&Object.hasOwnProperty.call(e,`eventName`)&&t.uint32(98).string(e.eventName),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t,s){e instanceof g||(e=g.create(e));for(var S=t===void 0?e.len:e.pos+t,w=new E.opentelemetry.proto.logs.v1.LogRecord;e.pos<S;){var D=e.uint32();if(D===s)break;switch(D>>>3){case 1:w.timeUnixNano=e.fixed64();break;case 11:w.observedTimeUnixNano=e.fixed64();break;case 2:w.severityNumber=e.int32();break;case 3:w.severityText=e.string();break;case 5:w.body=E.opentelemetry.proto.common.v1.AnyValue.decode(e,e.uint32());break;case 6:w.attributes&&w.attributes.length||(w.attributes=[]),w.attributes.push(E.opentelemetry.proto.common.v1.KeyValue.decode(e,e.uint32()));break;case 7:w.droppedAttributesCount=e.uint32();break;case 8:w.flags=e.fixed32();break;case 9:w.traceId=e.bytes();break;case 10:w.spanId=e.bytes();break;case 12:w.eventName=e.string();break;default:e.skipType(D&7);break}}return w},e.decodeDelimited=function(e){return e instanceof g||(e=new g(e)),this.decode(e,e.uint32())},e.verify=function(e){if(typeof e!=`object`||!e)return`object expected`;if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&!w.isInteger(e.timeUnixNano)&&!(e.timeUnixNano&&w.isInteger(e.timeUnixNano.low)&&w.isInteger(e.timeUnixNano.high)))return`timeUnixNano: integer|Long expected`;if(e.observedTimeUnixNano!=null&&e.hasOwnProperty(`observedTimeUnixNano`)&&!w.isInteger(e.observedTimeUnixNano)&&!(e.observedTimeUnixNano&&w.isInteger(e.observedTimeUnixNano.low)&&w.isInteger(e.observedTimeUnixNano.high)))return`observedTimeUnixNano: integer|Long expected`;if(e.severityNumber!=null&&e.hasOwnProperty(`severityNumber`))switch(e.severityNumber){default:return`severityNumber: enum value expected`;case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:case 16:case 17:case 18:case 19:case 20:case 21:case 22:case 23:case 24:break}if(e.severityText!=null&&e.hasOwnProperty(`severityText`)&&!w.isString(e.severityText))return`severityText: string expected`;if(e.body!=null&&e.hasOwnProperty(`body`)){var t=E.opentelemetry.proto.common.v1.AnyValue.verify(e.body);if(t)return`body.`+t}if(e.attributes!=null&&e.hasOwnProperty(`attributes`)){if(!Array.isArray(e.attributes))return`attributes: array expected`;for(var s=0;s<e.attributes.length;++s){var t=E.opentelemetry.proto.common.v1.KeyValue.verify(e.attributes[s]);if(t)return`attributes.`+t}}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&!w.isInteger(e.droppedAttributesCount)?`droppedAttributesCount: integer expected`:e.flags!=null&&e.hasOwnProperty(`flags`)&&!w.isInteger(e.flags)?`flags: integer expected`:e.traceId!=null&&e.hasOwnProperty(`traceId`)&&!(e.traceId&&typeof e.traceId.length==`number`||w.isString(e.traceId))?`traceId: buffer expected`:e.spanId!=null&&e.hasOwnProperty(`spanId`)&&!(e.spanId&&typeof e.spanId.length==`number`||w.isString(e.spanId))?`spanId: buffer expected`:e.eventName!=null&&e.hasOwnProperty(`eventName`)&&!w.isString(e.eventName)?`eventName: string expected`:null},e.fromObject=function(e){if(e instanceof E.opentelemetry.proto.logs.v1.LogRecord)return e;var t=new E.opentelemetry.proto.logs.v1.LogRecord;switch(e.timeUnixNano!=null&&(w.Long?(t.timeUnixNano=w.Long.fromValue(e.timeUnixNano)).unsigned=!1:typeof e.timeUnixNano==`string`?t.timeUnixNano=parseInt(e.timeUnixNano,10):typeof e.timeUnixNano==`number`?t.timeUnixNano=e.timeUnixNano:typeof e.timeUnixNano==`object`&&(t.timeUnixNano=new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber())),e.observedTimeUnixNano!=null&&(w.Long?(t.observedTimeUnixNano=w.Long.fromValue(e.observedTimeUnixNano)).unsigned=!1:typeof e.observedTimeUnixNano==`string`?t.observedTimeUnixNano=parseInt(e.observedTimeUnixNano,10):typeof e.observedTimeUnixNano==`number`?t.observedTimeUnixNano=e.observedTimeUnixNano:typeof e.observedTimeUnixNano==`object`&&(t.observedTimeUnixNano=new w.LongBits(e.observedTimeUnixNano.low>>>0,e.observedTimeUnixNano.high>>>0).toNumber())),e.severityNumber){default:if(typeof e.severityNumber==`number`){t.severityNumber=e.severityNumber;break}break;case`SEVERITY_NUMBER_UNSPECIFIED`:case 0:t.severityNumber=0;break;case`SEVERITY_NUMBER_TRACE`:case 1:t.severityNumber=1;break;case`SEVERITY_NUMBER_TRACE2`:case 2:t.severityNumber=2;break;case`SEVERITY_NUMBER_TRACE3`:case 3:t.severityNumber=3;break;case`SEVERITY_NUMBER_TRACE4`:case 4:t.severityNumber=4;break;case`SEVERITY_NUMBER_DEBUG`:case 5:t.severityNumber=5;break;case`SEVERITY_NUMBER_DEBUG2`:case 6:t.severityNumber=6;break;case`SEVERITY_NUMBER_DEBUG3`:case 7:t.severityNumber=7;break;case`SEVERITY_NUMBER_DEBUG4`:case 8:t.severityNumber=8;break;case`SEVERITY_NUMBER_INFO`:case 9:t.severityNumber=9;break;case`SEVERITY_NUMBER_INFO2`:case 10:t.severityNumber=10;break;case`SEVERITY_NUMBER_INFO3`:case 11:t.severityNumber=11;break;case`SEVERITY_NUMBER_INFO4`:case 12:t.severityNumber=12;break;case`SEVERITY_NUMBER_WARN`:case 13:t.severityNumber=13;break;case`SEVERITY_NUMBER_WARN2`:case 14:t.severityNumber=14;break;case`SEVERITY_NUMBER_WARN3`:case 15:t.severityNumber=15;break;case`SEVERITY_NUMBER_WARN4`:case 16:t.severityNumber=16;break;case`SEVERITY_NUMBER_ERROR`:case 17:t.severityNumber=17;break;case`SEVERITY_NUMBER_ERROR2`:case 18:t.severityNumber=18;break;case`SEVERITY_NUMBER_ERROR3`:case 19:t.severityNumber=19;break;case`SEVERITY_NUMBER_ERROR4`:case 20:t.severityNumber=20;break;case`SEVERITY_NUMBER_FATAL`:case 21:t.severityNumber=21;break;case`SEVERITY_NUMBER_FATAL2`:case 22:t.severityNumber=22;break;case`SEVERITY_NUMBER_FATAL3`:case 23:t.severityNumber=23;break;case`SEVERITY_NUMBER_FATAL4`:case 24:t.severityNumber=24;break}if(e.severityText!=null&&(t.severityText=String(e.severityText)),e.body!=null){if(typeof e.body!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.LogRecord.body: object expected`);t.body=E.opentelemetry.proto.common.v1.AnyValue.fromObject(e.body)}if(e.attributes){if(!Array.isArray(e.attributes))throw TypeError(`.opentelemetry.proto.logs.v1.LogRecord.attributes: array expected`);t.attributes=[];for(var s=0;s<e.attributes.length;++s){if(typeof e.attributes[s]!=`object`)throw TypeError(`.opentelemetry.proto.logs.v1.LogRecord.attributes: object expected`);t.attributes[s]=E.opentelemetry.proto.common.v1.KeyValue.fromObject(e.attributes[s])}}return e.droppedAttributesCount!=null&&(t.droppedAttributesCount=e.droppedAttributesCount>>>0),e.flags!=null&&(t.flags=e.flags>>>0),e.traceId!=null&&(typeof e.traceId==`string`?w.base64.decode(e.traceId,t.traceId=w.newBuffer(w.base64.length(e.traceId)),0):e.traceId.length>=0&&(t.traceId=e.traceId)),e.spanId!=null&&(typeof e.spanId==`string`?w.base64.decode(e.spanId,t.spanId=w.newBuffer(w.base64.length(e.spanId)),0):e.spanId.length>=0&&(t.spanId=e.spanId)),e.eventName!=null&&(t.eventName=String(e.eventName)),t},e.toObject=function(e,t){t||={};var s={};if((t.arrays||t.defaults)&&(s.attributes=[]),t.defaults){if(w.Long){var g=new w.Long(0,0,!1);s.timeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.timeUnixNano=t.longs===String?`0`:0;if(s.severityNumber=t.enums===String?`SEVERITY_NUMBER_UNSPECIFIED`:0,s.severityText=``,s.body=null,s.droppedAttributesCount=0,s.flags=0,t.bytes===String?s.traceId=``:(s.traceId=[],t.bytes!==Array&&(s.traceId=w.newBuffer(s.traceId))),t.bytes===String?s.spanId=``:(s.spanId=[],t.bytes!==Array&&(s.spanId=w.newBuffer(s.spanId))),w.Long){var g=new w.Long(0,0,!1);s.observedTimeUnixNano=t.longs===String?g.toString():t.longs===Number?g.toNumber():g}else s.observedTimeUnixNano=t.longs===String?`0`:0;s.eventName=``}if(e.timeUnixNano!=null&&e.hasOwnProperty(`timeUnixNano`)&&(typeof e.timeUnixNano==`number`?s.timeUnixNano=t.longs===String?String(e.timeUnixNano):e.timeUnixNano:s.timeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.timeUnixNano):t.longs===Number?new w.LongBits(e.timeUnixNano.low>>>0,e.timeUnixNano.high>>>0).toNumber():e.timeUnixNano),e.severityNumber!=null&&e.hasOwnProperty(`severityNumber`)&&(s.severityNumber=t.enums===String?E.opentelemetry.proto.logs.v1.SeverityNumber[e.severityNumber]===void 0?e.severityNumber:E.opentelemetry.proto.logs.v1.SeverityNumber[e.severityNumber]:e.severityNumber),e.severityText!=null&&e.hasOwnProperty(`severityText`)&&(s.severityText=e.severityText),e.body!=null&&e.hasOwnProperty(`body`)&&(s.body=E.opentelemetry.proto.common.v1.AnyValue.toObject(e.body,t)),e.attributes&&e.attributes.length){s.attributes=[];for(var S=0;S<e.attributes.length;++S)s.attributes[S]=E.opentelemetry.proto.common.v1.KeyValue.toObject(e.attributes[S],t)}return e.droppedAttributesCount!=null&&e.hasOwnProperty(`droppedAttributesCount`)&&(s.droppedAttributesCount=e.droppedAttributesCount),e.flags!=null&&e.hasOwnProperty(`flags`)&&(s.flags=e.flags),e.traceId!=null&&e.hasOwnProperty(`traceId`)&&(s.traceId=t.bytes===String?w.base64.encode(e.traceId,0,e.traceId.length):t.bytes===Array?Array.prototype.slice.call(e.traceId):e.traceId),e.spanId!=null&&e.hasOwnProperty(`spanId`)&&(s.spanId=t.bytes===String?w.base64.encode(e.spanId,0,e.spanId.length):t.bytes===Array?Array.prototype.slice.call(e.spanId):e.spanId),e.observedTimeUnixNano!=null&&e.hasOwnProperty(`observedTimeUnixNano`)&&(typeof e.observedTimeUnixNano==`number`?s.observedTimeUnixNano=t.longs===String?String(e.observedTimeUnixNano):e.observedTimeUnixNano:s.observedTimeUnixNano=t.longs===String?w.Long.prototype.toString.call(e.observedTimeUnixNano):t.longs===Number?new w.LongBits(e.observedTimeUnixNano.low>>>0,e.observedTimeUnixNano.high>>>0).toNumber():e.observedTimeUnixNano),e.eventName!=null&&e.hasOwnProperty(`eventName`)&&(s.eventName=e.eventName),s},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.getTypeUrl=function(e){return e===void 0&&(e=`type.googleapis.com`),e+`/opentelemetry.proto.logs.v1.LogRecord`},e})(),e})(),e})(),e})(),e})(),t.exports=E})),require_suppress_tracing$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isTracingSuppressed=e.unsuppressTracing=e.suppressTracing=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key SUPPRESS_TRACING`);function s(e){return e.setValue(t,!0)}e.suppressTracing=s;function g(e){return e.deleteValue(t)}e.unsuppressTracing=g;function S(e){return e.getValue(t)===!0}e.isTracingSuppressed=S})),require_constants$6=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BAGGAGE_MAX_TOTAL_LENGTH=e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=e.BAGGAGE_MAX_NAME_VALUE_PAIRS=e.BAGGAGE_HEADER=e.BAGGAGE_ITEMS_SEPARATOR=e.BAGGAGE_PROPERTIES_SEPARATOR=e.BAGGAGE_KEY_PAIR_SEPARATOR=void 0,e.BAGGAGE_KEY_PAIR_SEPARATOR=`=`,e.BAGGAGE_PROPERTIES_SEPARATOR=`;`,e.BAGGAGE_ITEMS_SEPARATOR=`,`,e.BAGGAGE_HEADER=`baggage`,e.BAGGAGE_MAX_NAME_VALUE_PAIRS=180,e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,e.BAGGAGE_MAX_TOTAL_LENGTH=8192})),require_utils$15=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_constants$6();function g(e){return e.reduce((e,t)=>{let g=`${e}${e===``?``:s.BAGGAGE_ITEMS_SEPARATOR}${t}`;return g.length>s.BAGGAGE_MAX_TOTAL_LENGTH?e:g},``)}e.serializeKeyPairs=g;function S(e){return e.getAllEntries().map(([e,t])=>{let g=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return t.metadata!==void 0&&(g+=s.BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),g})}e.getKeyPairs=S;function w(e){let g=e.split(s.BAGGAGE_PROPERTIES_SEPARATOR);if(g.length<=0)return;let S=g.shift();if(!S)return;let w=S.indexOf(s.BAGGAGE_KEY_PAIR_SEPARATOR);if(w<=0)return;let E=decodeURIComponent(S.substring(0,w).trim()),D=decodeURIComponent(S.substring(w+1).trim()),O;return g.length>0&&(O=(0,t.baggageEntryMetadataFromString)(g.join(s.BAGGAGE_PROPERTIES_SEPARATOR))),{key:E,value:D,metadata:O}}e.parsePairKeyValue=w;function E(e){let t={};return typeof e==`string`&&e.length>0&&e.split(s.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let s=w(e);s!==void 0&&s.value.length>0&&(t[s.key]=s.value)}),t}e.parseKeyPairsIntoRecord=E})),require_W3CBaggagePropagator$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$2(),g=require_constants$6(),S=require_utils$15();e.W3CBaggagePropagator=class{inject(e,w,E){let D=t.propagation.getBaggage(e);if(!D||(0,s.isTracingSuppressed)(e))return;let O=(0,S.getKeyPairs)(D).filter(e=>e.length<=g.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,g.BAGGAGE_MAX_NAME_VALUE_PAIRS),k=(0,S.serializeKeyPairs)(O);k.length>0&&E.set(w,g.BAGGAGE_HEADER,k)}extract(e,s,w){let E=w.get(s,g.BAGGAGE_HEADER),D=Array.isArray(E)?E.join(g.BAGGAGE_ITEMS_SEPARATOR):E;if(!D)return e;let O={};return D.length===0||(D.split(g.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let t=(0,S.parsePairKeyValue)(e);if(t){let e={value:t.value};t.metadata&&(e.metadata=t.metadata),O[t.key]=e}}),Object.entries(O).length===0)?e:t.propagation.setBaggage(e,t.propagation.createBaggage(O))}fields(){return[g.BAGGAGE_HEADER]}}})),require_anchored_clock$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AnchoredClock=void 0,e.AnchoredClock=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}})),require_attributes$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isAttributeValue=e.isAttributeKey=e.sanitizeAttributes=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function s(e){let s={};if(typeof e!=`object`||!e)return s;for(let[w,E]of Object.entries(e)){if(!g(w)){t.diag.warn(`Invalid attribute key: ${w}`);continue}if(!S(E)){t.diag.warn(`Invalid attribute value set for key: ${w}`);continue}Array.isArray(E)?s[w]=E.slice():s[w]=E}return s}e.sanitizeAttributes=s;function g(e){return typeof e==`string`&&e.length>0}e.isAttributeKey=g;function S(e){return e==null?!0:Array.isArray(e)?w(e):E(e)}e.isAttributeValue=S;function w(e){let t;for(let s of e)if(s!=null){if(!t){if(E(s)){t=typeof s;continue}return!1}if(typeof s!==t)return!1}return!0}function E(e){switch(typeof e){case`number`:case`boolean`:case`string`:return!0}return!1}})),require_logging_error_handler$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.loggingErrorHandler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function s(){return e=>{t.diag.error(g(e))}}e.loggingErrorHandler=s;function g(e){return typeof e==`string`?e:JSON.stringify(S(e))}function S(e){let t={},s=e;for(;s!==null;)Object.getOwnPropertyNames(s).forEach(e=>{if(t[e])return;let g=s[e];g&&(t[e]=String(g))}),s=Object.getPrototypeOf(s);return t}})),require_global_error_handler$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,require_logging_error_handler$2().loggingErrorHandler)();function s(e){t=e}e.setGlobalErrorHandler=s;function g(e){try{t(e)}catch{}}e.globalErrorHandler=g})),require_environment$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e.getNumberFromEnv=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=__require$2(`util`);function g(e){let g=process.env[e];if(g==null||g.trim()===``)return;let S=Number(g);if(isNaN(S)){t.diag.warn(`Unknown value ${(0,s.inspect)(g)} for ${e}, expected a number, using defaults`);return}return S}e.getNumberFromEnv=g;function S(e){let t=process.env[e];if(!(t==null||t.trim()===``))return t}e.getStringFromEnv=S;function w(e){let g=process.env[e]?.trim().toLowerCase();return g==null||g===``?!1:g===`true`?!0:(g===`false`||t.diag.warn(`Unknown value ${(0,s.inspect)(g)} for ${e}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}e.getBooleanFromEnv=w;function E(e){return S(e)?.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}e.getStringListFromEnv=E})),require_globalThis$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=typeof globalThis==`object`?globalThis:global})),require_performance$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=void 0,e.otperformance=__require$2(`perf_hooks`).performance})),require_version$5=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.1.0`})),require_semconv$6=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),require_sdk_info$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=require_version$5(),s=(init_esm$1(),__toCommonJS(esm_exports$1)),g=require_semconv$6();e.SDK_INFO={[s.ATTR_TELEMETRY_SDK_NAME]:`opentelemetry`,[g.ATTR_PROCESS_RUNTIME_NAME]:`node`,[s.ATTR_TELEMETRY_SDK_LANGUAGE]:s.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[s.ATTR_TELEMETRY_SDK_VERSION]:t.VERSION}})),require_timer_util$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=void 0;function t(e){e.unref()}e.unrefTimer=t})),require_node$10=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=e.SDK_INFO=e.otperformance=e._globalThis=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=void 0;var t=require_environment$2();Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}});var s=require_globalThis$2();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return s._globalThis}});var g=require_performance$2();Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return g.otperformance}});var S=require_sdk_info$2();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return S.SDK_INFO}});var w=require_timer_util$2();Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return w.unrefTimer}})})),require_platform$10=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getNumberFromEnv=e.getStringFromEnv=e.getBooleanFromEnv=e.unrefTimer=e.otperformance=e._globalThis=e.SDK_INFO=void 0;var t=require_node$10();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return t.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return t._globalThis}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return t.otperformance}}),Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return t.unrefTimer}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}})})),require_time$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.addHrTimes=e.isTimeInput=e.isTimeInputHrTime=e.hrTimeToMicroseconds=e.hrTimeToMilliseconds=e.hrTimeToNanoseconds=e.hrTimeToTimeStamp=e.hrTimeDuration=e.timeInputToHrTime=e.hrTime=e.getTimeOrigin=e.millisToHrTime=void 0;let t=require_platform$10(),s=9,g=10**6,S=10**9;function w(e){let t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*g)]}e.millisToHrTime=w;function E(){let e=t.otperformance.timeOrigin;if(typeof e!=`number`){let s=t.otperformance;e=s.timing&&s.timing.fetchStart}return e}e.getTimeOrigin=E;function D(e){return J(w(E()),w(typeof e==`number`?e:t.otperformance.now()))}e.hrTime=D;function O(e){if(H(e))return e;if(typeof e==`number`)return e<E()?D(e):w(e);if(e instanceof Date)return w(e.getTime());throw TypeError(`Invalid input type`)}e.timeInputToHrTime=O;function k(e,t){let s=t[0]-e[0],g=t[1]-e[1];return g<0&&(--s,g+=S),[s,g]}e.hrTimeDuration=k;function j(e){let t=9,s=`${`0`.repeat(9)}${e[1]}Z`,g=s.substring(s.length-9-1);return new Date(e[0]*1e3).toISOString().replace(`000Z`,g)}e.hrTimeToTimeStamp=j;function F(e){return e[0]*S+e[1]}e.hrTimeToNanoseconds=F;function L(e){return e[0]*1e3+e[1]/1e6}e.hrTimeToMilliseconds=L;function B(e){return e[0]*1e6+e[1]/1e3}e.hrTimeToMicroseconds=B;function H(e){return Array.isArray(e)&&e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`}e.isTimeInputHrTime=H;function q(e){return H(e)||typeof e==`number`||e instanceof Date}e.isTimeInput=q;function J(e,t){let s=[e[0]+t[0],e[1]+t[1]];return s[1]>=S&&(s[1]-=S,s[0]+=1),s}e.addHrTimes=J})),require_ExportResult$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExportResultCode=void 0,(function(e){e[e.SUCCESS=0]=`SUCCESS`,e[e.FAILED=1]=`FAILED`})(e.ExportResultCode||={})})),require_composite$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CompositePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));e.CompositePropagator=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>typeof e.fields==`function`?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,s,g){for(let S of this._propagators)try{S.inject(e,s,g)}catch(e){t.diag.warn(`Failed to inject with ${S.constructor.name}. Err: ${e.message}`)}}extract(e,s,g){return this._propagators.reduce((e,S)=>{try{return S.extract(e,s,g)}catch(e){t.diag.warn(`Failed to extract with ${S.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}})),require_validators$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateValue=e.validateKey=void 0;let t=`[_0-9a-z-*/]`,s=`[a-z]${t}{0,255}`,g=`[a-z0-9]${t}{0,240}@[a-z]${t}{0,13}`,S=RegExp(`^(?:${s}|${g})$`),w=/^[ -~]{0,255}[!-~]$/,E=/,|=/;function D(e){return S.test(e)}e.validateKey=D;function O(e){return w.test(e)&&!E.test(e)}e.validateValue=O})),require_TraceState$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceState=void 0;let t=require_validators$2(),s=32,g=512,S=`,`,w=`=`;e.TraceState=class e{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){let s=this._clone();return s._internalState.has(e)&&s._internalState.delete(e),s._internalState.set(e,t),s}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+`=`+this.get(t)),e),[]).join(`,`)}_parse(e){e.length>512||(this._internalState=e.split(`,`).reverse().reduce((e,s)=>{let g=s.trim(),S=g.indexOf(`=`);if(S!==-1){let w=g.slice(0,S),E=g.slice(S+1,s.length);(0,t.validateKey)(w)&&(0,t.validateValue)(E)&&e.set(w,E)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let t=new e;return t._internalState=new Map(this._internalState),t}}})),require_W3CTraceContextPropagator$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CTraceContextPropagator=e.parseTraceParent=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$2(),g=require_TraceState$2();e.TRACE_PARENT_HEADER=`traceparent`,e.TRACE_STATE_HEADER=`tracestate`;let S=`00`,w=RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`);function E(e){let t=w.exec(e);return!t||t[1]===`00`&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}}e.parseTraceParent=E,e.W3CTraceContextPropagator=class{inject(g,S,w){let E=t.trace.getSpanContext(g);if(!E||(0,s.isTracingSuppressed)(g)||!(0,t.isSpanContextValid)(E))return;let D=`00-${E.traceId}-${E.spanId}-0${Number(E.traceFlags||t.TraceFlags.NONE).toString(16)}`;w.set(S,e.TRACE_PARENT_HEADER,D),E.traceState&&w.set(S,e.TRACE_STATE_HEADER,E.traceState.serialize())}extract(s,S,w){let D=w.get(S,e.TRACE_PARENT_HEADER);if(!D)return s;let O=Array.isArray(D)?D[0]:D;if(typeof O!=`string`)return s;let k=E(O);if(!k)return s;k.isRemote=!0;let j=w.get(S,e.TRACE_STATE_HEADER);if(j){let e=Array.isArray(j)?j.join(`,`):j;k.traceState=new g.TraceState(typeof e==`string`?e:void 0)}return t.trace.setSpanContext(s,k)}fields(){return[e.TRACE_PARENT_HEADER,e.TRACE_STATE_HEADER]}}})),require_rpc_metadata$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRPCMetadata=e.deleteRPCMetadata=e.setRPCMetadata=e.RPCType=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key RPC_METADATA`);(function(e){e.HTTP=`http`})(e.RPCType||={});function s(e,s){return e.setValue(t,s)}e.setRPCMetadata=s;function g(e){return e.deleteValue(t)}e.deleteRPCMetadata=g;function S(e){return e.getValue(t)}e.getRPCMetadata=S})),require_lodash_merge$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isPlainObject=void 0;let t=`[object Object]`,s=`[object Null]`,g=`[object Undefined]`,S=Function.prototype.toString,w=S.call(Object),E=Object.getPrototypeOf,D=Object.prototype,O=D.hasOwnProperty,k=Symbol?Symbol.toStringTag:void 0,j=D.toString;function F(e){if(!L(e)||B(e)!==`[object Object]`)return!1;let t=E(e);if(t===null)return!0;let s=O.call(t,`constructor`)&&t.constructor;return typeof s==`function`&&s instanceof s&&S.call(s)===w}e.isPlainObject=F;function L(e){return typeof e==`object`&&!!e}function B(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:k&&k in Object(e)?H(e):q(e)}function H(e){let t=O.call(e,k),s=e[k],g=!1;try{e[k]=void 0,g=!0}catch{}let S=j.call(e);return g&&(t?e[k]=s:delete e[k]),S}function q(e){return j.call(e)}})),require_merge$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=require_lodash_merge$2(),s=20;function g(...e){let t=e.shift(),s=new WeakMap;for(;e.length>0;)t=w(t,e.shift(),0,s);return t}e.merge=g;function S(e){return D(e)?e.slice():e}function w(e,t,s=0,g){let L;if(!(s>20)){if(s++,j(e)||j(t)||O(t))L=S(t);else if(D(e)){if(L=e.slice(),D(t))for(let e=0,s=t.length;e<s;e++)L.push(S(t[e]));else if(k(t)){let e=Object.keys(t);for(let s=0,g=e.length;s<g;s++){let g=e[s];L[g]=S(t[g])}}}else if(k(e))if(k(t)){if(!F(e,t))return t;L=Object.assign({},e);let S=Object.keys(t);for(let D=0,O=S.length;D<O;D++){let O=S[D],F=t[O];if(j(F))F===void 0?delete L[O]:L[O]=F;else{let S=L[O],D=F;if(E(e,O,g)||E(t,O,g))delete L[O];else{if(k(S)&&k(D)){let s=g.get(S)||[],w=g.get(D)||[];s.push({obj:e,key:O}),w.push({obj:t,key:O}),g.set(S,s),g.set(D,w)}L[O]=w(L[O],F,s,g)}}}}else L=t;return L}}function E(e,t,s){let g=s.get(e[t])||[];for(let s=0,S=g.length;s<S;s++){let S=g[s];if(S.key===t&&S.obj===e)return!0}return!1}function D(e){return Array.isArray(e)}function O(e){return typeof e==`function`}function k(e){return!j(e)&&!D(e)&&!O(e)&&typeof e==`object`}function j(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===void 0||e instanceof Date||e instanceof RegExp||e===null}function F(e,s){return!(!(0,t.isPlainObject)(e)||!(0,t.isPlainObject)(s))}})),require_timeout$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callWithTimeout=e.TimeoutError=void 0;var t=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=t;function s(e,s){let g,S=new Promise(function(e,S){g=setTimeout(function(){S(new t(`Operation timed out.`))},s)});return Promise.race([e,S]).then(e=>(clearTimeout(g),e),e=>{throw clearTimeout(g),e})}e.callWithTimeout=s})),require_url$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isUrlIgnored=e.urlMatches=void 0;function t(e,t){return typeof t==`string`?e===t:!!e.match(t)}e.urlMatches=t;function s(e,s){if(!s)return!1;for(let g of s)if(t(e,g))return!0;return!1}e.isUrlIgnored=s})),require_promise$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Deferred=void 0,e.Deferred=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}})),require_callback$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BindOnceFuture=void 0;let t=require_promise$2();e.BindOnceFuture=class{_callback;_that;_isCalled=!1;_deferred=new t.Deferred;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}})),require_configuration$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.diagLogLevelFromString=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s={ALL:t.DiagLogLevel.ALL,VERBOSE:t.DiagLogLevel.VERBOSE,DEBUG:t.DiagLogLevel.DEBUG,INFO:t.DiagLogLevel.INFO,WARN:t.DiagLogLevel.WARN,ERROR:t.DiagLogLevel.ERROR,NONE:t.DiagLogLevel.NONE};function g(e){return e==null?void 0:s[e.toUpperCase()]??(t.diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(s)}, using default`),t.DiagLogLevel.INFO)}e.diagLogLevelFromString=g})),require_exporter$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._export=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$2();function g(e,g){return new Promise(S=>{t.context.with((0,s.suppressTracing)(t.context.active()),()=>{e.export(g,e=>{S(e)})})})}e._export=g})),require_src$13=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.internal=e.diagLogLevelFromString=e.BindOnceFuture=e.urlMatches=e.isUrlIgnored=e.callWithTimeout=e.TimeoutError=e.merge=e.TraceState=e.unsuppressTracing=e.suppressTracing=e.isTracingSuppressed=e.setRPCMetadata=e.getRPCMetadata=e.deleteRPCMetadata=e.RPCType=e.parseTraceParent=e.W3CTraceContextPropagator=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=e.CompositePropagator=e.unrefTimer=e.otperformance=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e._globalThis=e.SDK_INFO=e.parseKeyPairsIntoRecord=e.ExportResultCode=e.timeInputToHrTime=e.millisToHrTime=e.isTimeInputHrTime=e.isTimeInput=e.hrTimeToTimeStamp=e.hrTimeToNanoseconds=e.hrTimeToMilliseconds=e.hrTimeToMicroseconds=e.hrTimeDuration=e.hrTime=e.getTimeOrigin=e.addHrTimes=e.loggingErrorHandler=e.setGlobalErrorHandler=e.globalErrorHandler=e.sanitizeAttributes=e.isAttributeValue=e.AnchoredClock=e.W3CBaggagePropagator=void 0;var t=require_W3CBaggagePropagator$2();Object.defineProperty(e,`W3CBaggagePropagator`,{enumerable:!0,get:function(){return t.W3CBaggagePropagator}});var s=require_anchored_clock$2();Object.defineProperty(e,`AnchoredClock`,{enumerable:!0,get:function(){return s.AnchoredClock}});var g=require_attributes$2();Object.defineProperty(e,`isAttributeValue`,{enumerable:!0,get:function(){return g.isAttributeValue}}),Object.defineProperty(e,`sanitizeAttributes`,{enumerable:!0,get:function(){return g.sanitizeAttributes}});var S=require_global_error_handler$2();Object.defineProperty(e,`globalErrorHandler`,{enumerable:!0,get:function(){return S.globalErrorHandler}}),Object.defineProperty(e,`setGlobalErrorHandler`,{enumerable:!0,get:function(){return S.setGlobalErrorHandler}});var w=require_logging_error_handler$2();Object.defineProperty(e,`loggingErrorHandler`,{enumerable:!0,get:function(){return w.loggingErrorHandler}});var E=require_time$3();Object.defineProperty(e,`addHrTimes`,{enumerable:!0,get:function(){return E.addHrTimes}}),Object.defineProperty(e,`getTimeOrigin`,{enumerable:!0,get:function(){return E.getTimeOrigin}}),Object.defineProperty(e,`hrTime`,{enumerable:!0,get:function(){return E.hrTime}}),Object.defineProperty(e,`hrTimeDuration`,{enumerable:!0,get:function(){return E.hrTimeDuration}}),Object.defineProperty(e,`hrTimeToMicroseconds`,{enumerable:!0,get:function(){return E.hrTimeToMicroseconds}}),Object.defineProperty(e,`hrTimeToMilliseconds`,{enumerable:!0,get:function(){return E.hrTimeToMilliseconds}}),Object.defineProperty(e,`hrTimeToNanoseconds`,{enumerable:!0,get:function(){return E.hrTimeToNanoseconds}}),Object.defineProperty(e,`hrTimeToTimeStamp`,{enumerable:!0,get:function(){return E.hrTimeToTimeStamp}}),Object.defineProperty(e,`isTimeInput`,{enumerable:!0,get:function(){return E.isTimeInput}}),Object.defineProperty(e,`isTimeInputHrTime`,{enumerable:!0,get:function(){return E.isTimeInputHrTime}}),Object.defineProperty(e,`millisToHrTime`,{enumerable:!0,get:function(){return E.millisToHrTime}}),Object.defineProperty(e,`timeInputToHrTime`,{enumerable:!0,get:function(){return E.timeInputToHrTime}});var D=require_ExportResult$2();Object.defineProperty(e,`ExportResultCode`,{enumerable:!0,get:function(){return D.ExportResultCode}});var O=require_utils$15();Object.defineProperty(e,`parseKeyPairsIntoRecord`,{enumerable:!0,get:function(){return O.parseKeyPairsIntoRecord}});var k=require_platform$10();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return k.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return k._globalThis}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return k.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return k.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return k.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return k.getStringListFromEnv}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return k.otperformance}}),Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return k.unrefTimer}});var j=require_composite$2();Object.defineProperty(e,`CompositePropagator`,{enumerable:!0,get:function(){return j.CompositePropagator}});var F=require_W3CTraceContextPropagator$2();Object.defineProperty(e,`TRACE_PARENT_HEADER`,{enumerable:!0,get:function(){return F.TRACE_PARENT_HEADER}}),Object.defineProperty(e,`TRACE_STATE_HEADER`,{enumerable:!0,get:function(){return F.TRACE_STATE_HEADER}}),Object.defineProperty(e,`W3CTraceContextPropagator`,{enumerable:!0,get:function(){return F.W3CTraceContextPropagator}}),Object.defineProperty(e,`parseTraceParent`,{enumerable:!0,get:function(){return F.parseTraceParent}});var L=require_rpc_metadata$2();Object.defineProperty(e,`RPCType`,{enumerable:!0,get:function(){return L.RPCType}}),Object.defineProperty(e,`deleteRPCMetadata`,{enumerable:!0,get:function(){return L.deleteRPCMetadata}}),Object.defineProperty(e,`getRPCMetadata`,{enumerable:!0,get:function(){return L.getRPCMetadata}}),Object.defineProperty(e,`setRPCMetadata`,{enumerable:!0,get:function(){return L.setRPCMetadata}});var B=require_suppress_tracing$2();Object.defineProperty(e,`isTracingSuppressed`,{enumerable:!0,get:function(){return B.isTracingSuppressed}}),Object.defineProperty(e,`suppressTracing`,{enumerable:!0,get:function(){return B.suppressTracing}}),Object.defineProperty(e,`unsuppressTracing`,{enumerable:!0,get:function(){return B.unsuppressTracing}});var H=require_TraceState$2();Object.defineProperty(e,`TraceState`,{enumerable:!0,get:function(){return H.TraceState}});var q=require_merge$2();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return q.merge}});var J=require_timeout$2();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return J.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return J.callWithTimeout}});var Y=require_url$2();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return Y.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return Y.urlMatches}});var ee=require_callback$2();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return ee.BindOnceFuture}});var te=require_configuration$2();Object.defineProperty(e,`diagLogLevelFromString`,{enumerable:!0,get:function(){return te.diagLogLevelFromString}}),e.internal={_export:require_exporter$2()._export}})),require_hex_to_binary=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hexToBinary=void 0;function t(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-87:e-55}function s(e){let s=new Uint8Array(e.length/2),g=0;for(let S=0;S<e.length;S+=2){let w=t(e.charCodeAt(S)),E=t(e.charCodeAt(S+1));s[g++]=w<<4|E}return s}e.hexToBinary=s})),require_utils$14=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getOtlpEncoder=e.encodeAsString=e.encodeAsLongBits=e.toLongBits=e.hrTimeToNanos=void 0;let t=require_src$13(),s=require_hex_to_binary();function g(e){let t=BigInt(1e9);return BigInt(e[0])*t+BigInt(e[1])}e.hrTimeToNanos=g;function S(e){return{low:Number(BigInt.asUintN(32,e)),high:Number(BigInt.asUintN(32,e>>BigInt(32)))}}e.toLongBits=S;function w(e){return S(g(e))}e.encodeAsLongBits=w;function E(e){return g(e).toString()}e.encodeAsString=E;let D=typeof BigInt<`u`?E:t.hrTimeToNanoseconds;function O(e){return e}function k(e){if(e!==void 0)return(0,s.hexToBinary)(e)}let j={encodeHrTime:w,encodeSpanContext:s.hexToBinary,encodeOptionalSpanContext:k};function F(e){if(e===void 0)return j;let t=e.useLongBits??!0,g=e.useHex??!1;return{encodeHrTime:t?w:D,encodeSpanContext:g?O:s.hexToBinary,encodeOptionalSpanContext:g?O:k}}e.getOtlpEncoder=F})),require_internal$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.toAnyValue=e.toKeyValue=e.toAttributes=e.createInstrumentationScope=e.createResource=void 0;function t(e){let t={attributes:g(e.attributes),droppedAttributesCount:0},s=e.schemaUrl;return s&&s!==``&&(t.schemaUrl=s),t}e.createResource=t;function s(e){return{name:e.name,version:e.version}}e.createInstrumentationScope=s;function g(e){return Object.keys(e).map(t=>S(t,e[t]))}e.toAttributes=g;function S(e,t){return{key:e,value:w(t)}}e.toKeyValue=S;function w(e){let t=typeof e;return t===`string`?{stringValue:e}:t===`number`?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:t===`boolean`?{boolValue:e}:e instanceof Uint8Array?{bytesValue:e}:Array.isArray(e)?{arrayValue:{values:e.map(w)}}:t===`object`&&e!=null?{kvlistValue:{values:Object.entries(e).map(([e,t])=>S(e,t))}}:{}}e.toAnyValue=w})),require_internal$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.toLogAttributes=e.createExportLogsServiceRequest=void 0;let t=require_utils$14(),s=require_internal$3();function g(e,s){return{resourceLogs:w(e,(0,t.getOtlpEncoder)(s))}}e.createExportLogsServiceRequest=g;function S(e){let t=new Map;for(let s of e){let{resource:e,instrumentationScope:{name:g,version:S=``,schemaUrl:w=``}}=s,E=t.get(e);E||(E=new Map,t.set(e,E));let D=`${g}@${S}:${w}`,O=E.get(D);O||(O=[],E.set(D,O)),O.push(s)}return t}function w(e,t){let g=S(e);return Array.from(g,([e,g])=>{let S=(0,s.createResource)(e);return{resource:S,scopeLogs:Array.from(g,([,e])=>({scope:(0,s.createInstrumentationScope)(e[0].instrumentationScope),logRecords:e.map(e=>E(e,t)),schemaUrl:e[0].instrumentationScope.schemaUrl})),schemaUrl:S.schemaUrl}})}function E(e,t){return{timeUnixNano:t.encodeHrTime(e.hrTime),observedTimeUnixNano:t.encodeHrTime(e.hrTimeObserved),severityNumber:D(e.severityNumber),severityText:e.severityText,body:(0,s.toAnyValue)(e.body),eventName:e.eventName,attributes:O(e.attributes),droppedAttributesCount:e.droppedAttributesCount,flags:e.spanContext?.traceFlags,traceId:t.encodeOptionalSpanContext(e.spanContext?.traceId),spanId:t.encodeOptionalSpanContext(e.spanContext?.spanId)}}function D(e){return e}function O(e){return Object.keys(e).map(t=>(0,s.toKeyValue)(t,e[t]))}e.toLogAttributes=O})),require_logs$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufLogsSerializer=void 0;let t=require_root(),s=require_internal$2(),g=t.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse,S=t.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest;e.ProtobufLogsSerializer={serializeRequest:e=>{let t=(0,s.createExportLogsServiceRequest)(e);return S.encode(t).finish()},deserializeResponse:e=>g.decode(e)}})),require_protobuf$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ProtobufLogsSerializer=void 0;var t=require_logs$1();Object.defineProperty(e,`ProtobufLogsSerializer`,{enumerable:!0,get:function(){return t.ProtobufLogsSerializer}})})),require_AggregationTemporality$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AggregationTemporality=void 0,(function(e){e[e.DELTA=0]=`DELTA`,e[e.CUMULATIVE=1]=`CUMULATIVE`})(e.AggregationTemporality||={})})),require_MetricData$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DataPointType=e.InstrumentType=void 0,(function(e){e.COUNTER=`COUNTER`,e.GAUGE=`GAUGE`,e.HISTOGRAM=`HISTOGRAM`,e.UP_DOWN_COUNTER=`UP_DOWN_COUNTER`,e.OBSERVABLE_COUNTER=`OBSERVABLE_COUNTER`,e.OBSERVABLE_GAUGE=`OBSERVABLE_GAUGE`,e.OBSERVABLE_UP_DOWN_COUNTER=`OBSERVABLE_UP_DOWN_COUNTER`})(e.InstrumentType||={}),(function(e){e[e.HISTOGRAM=0]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=1]=`EXPONENTIAL_HISTOGRAM`,e[e.GAUGE=2]=`GAUGE`,e[e.SUM=3]=`SUM`})(e.DataPointType||={})})),require_utils$13=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.equalsCaseInsensitive=e.binarySearchUB=e.setEquals=e.FlatMap=e.isPromiseAllSettledRejectionResult=e.PromiseAllSettled=e.callWithTimeout=e.TimeoutError=e.instrumentationScopeId=e.hashAttributes=e.isNotNullish=void 0;function t(e){return e!=null}e.isNotNullish=t;function s(e){let t=Object.keys(e);return t.length===0?``:(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}e.hashAttributes=s;function g(e){return`${e.name}:${e.version??``}:${e.schemaUrl??``}`}e.instrumentationScopeId=g;var S=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=S;function w(e,t){let s,g=new Promise(function(e,g){s=setTimeout(function(){g(new S(`Operation timed out.`))},t)});return Promise.race([e,g]).then(e=>(clearTimeout(s),e),e=>{throw clearTimeout(s),e})}e.callWithTimeout=w;async function E(e){return Promise.all(e.map(async e=>{try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}))}e.PromiseAllSettled=E;function D(e){return e.status===`rejected`}e.isPromiseAllSettledRejectionResult=D;function O(e,t){let s=[];return e.forEach(e=>{s.push(...t(e))}),s}e.FlatMap=O;function k(e,t){if(e.size!==t.size)return!1;for(let s of e)if(!t.has(s))return!1;return!0}e.setEquals=k;function j(e,t){let s=0,g=e.length-1,S=e.length;for(;g>=s;){let w=s+Math.trunc((g-s)/2);e[w]<t?s=w+1:(S=w,g=w-1)}return S}e.binarySearchUB=j;function F(e,t){return e.toLowerCase()===t.toLowerCase()}e.equalsCaseInsensitive=F})),require_types$6=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AggregatorKind=void 0,(function(e){e[e.DROP=0]=`DROP`,e[e.SUM=1]=`SUM`,e[e.LAST_VALUE=2]=`LAST_VALUE`,e[e.HISTOGRAM=3]=`HISTOGRAM`,e[e.EXPONENTIAL_HISTOGRAM=4]=`EXPONENTIAL_HISTOGRAM`})(e.AggregatorKind||={})})),require_Drop$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DropAggregator=void 0;let t=require_types$6();e.DropAggregator=class{kind=t.AggregatorKind.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,s,g){}}})),require_Histogram$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.HistogramAggregator=e.HistogramAccumulation=void 0;let t=require_types$6(),s=require_MetricData$2(),g=require_utils$13();function S(e){let t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var w=class{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,s=!0,g=S(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=s,this._current=g}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);let t=(0,g.binarySearchUB)(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}};e.HistogramAccumulation=w,e.HistogramAggregator=class{_boundaries;_recordMinMax;kind=t.AggregatorKind.HISTOGRAM;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new w(e,this._boundaries,this._recordMinMax)}merge(e,t){let s=e.toPointValue(),g=t.toPointValue(),S=s.buckets.counts,E=g.buckets.counts,D=Array(S.length);for(let e=0;e<S.length;e++)D[e]=S[e]+E[e];let O=1/0,k=-1/0;return this._recordMinMax&&(s.hasMinMax&&g.hasMinMax?(O=Math.min(s.min,g.min),k=Math.max(s.max,g.max)):s.hasMinMax?(O=s.min,k=s.max):g.hasMinMax&&(O=g.min,k=g.max)),new w(e.startTime,s.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:s.buckets.boundaries,counts:D},count:s.count+g.count,sum:s.sum+g.sum,hasMinMax:this._recordMinMax&&(s.hasMinMax||g.hasMinMax),min:O,max:k})}diff(e,t){let s=e.toPointValue(),g=t.toPointValue(),S=s.buckets.counts,E=g.buckets.counts,D=Array(S.length);for(let e=0;e<S.length;e++)D[e]=E[e]-S[e];return new w(t.startTime,s.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:s.buckets.boundaries,counts:D},count:g.count-s.count,sum:g.sum-s.sum,hasMinMax:!1,min:1/0,max:-1/0})}toMetricData(e,t,g,S){return{descriptor:e,aggregationTemporality:t,dataPointType:s.DataPointType.HISTOGRAM,dataPoints:g.map(([t,g])=>{let w=g.toPointValue(),E=e.type===s.InstrumentType.GAUGE||e.type===s.InstrumentType.UP_DOWN_COUNTER||e.type===s.InstrumentType.OBSERVABLE_GAUGE||e.type===s.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:g.startTime,endTime:S,value:{min:w.hasMinMax?w.min:void 0,max:w.hasMinMax?w.max:void 0,sum:E?void 0:w.sum,buckets:w.buckets,count:w.count}}})}}}})),require_Buckets$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Buckets=void 0,e.Buckets=class e{backing;indexBase;indexStart;indexEnd;constructor(e=new t,s=0,g=0,S=0){this.backing=e,this.indexBase=s,this.indexStart=g,this.indexEnd=S}get offset(){return this.indexStart}get length(){return this.backing.length===0||this.indexEnd===this.indexStart&&this.at(0)===0?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){let t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)}incrementBucket(e,t){this.backing.increment(e,t)}decrementBucket(e,t){this.backing.decrement(e,t)}trim(){for(let e=0;e<this.length;e++)if(this.at(e)!==0){this.indexStart+=e;break}else if(e===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}for(let e=this.length-1;e>=0;e--)if(this.at(e)!==0){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();let t=1+this.indexEnd-this.indexStart,s=1<<e,g=0,S=0;for(let e=this.indexStart;e<=this.indexEnd;){let w=e%s;w<0&&(w+=s);for(let E=w;E<s&&g<t;E++)this._relocateBucket(S,g),g++,e++;S++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new e(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){let e=this.indexBase-this.indexStart;e!==0&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}};var t=class e{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,s){let g=Array(e).fill(0);g.splice(s,this._counts.length-t,...this._counts.slice(t)),g.splice(0,t,...this._counts.slice(0,t)),this._counts=g}reverse(e,t){let s=Math.floor((e+t)/2)-e;for(let g=0;g<s;g++){let s=this._counts[e+g];this._counts[e+g]=this._counts[t-g-1],this._counts[t-g-1]=s}}emptyBucket(e){let t=this._counts[e];return this._counts[e]=0,t}increment(e,t){this._counts[e]+=t}decrement(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new e([...this._counts])}}})),require_ieee754$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSignificand=e.getNormalBase2=e.MIN_VALUE=e.MAX_NORMAL_EXPONENT=e.MIN_NORMAL_EXPONENT=e.SIGNIFICAND_WIDTH=void 0,e.SIGNIFICAND_WIDTH=52;let t=2146435072,s=1048575,g=1023;e.MIN_NORMAL_EXPONENT=-g+1,e.MAX_NORMAL_EXPONENT=g,e.MIN_VALUE=2**-1022;function S(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e),((t.getUint32(0)&2146435072)>>20)-g}e.getNormalBase2=S;function w(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let s=t.getUint32(0),g=t.getUint32(4);return(s&1048575)*2**32+g}e.getSignificand=w})),require_util$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.nextGreaterSquare=e.ldexp=void 0;function t(e,t){return e===0||e===1/0||e===-1/0||Number.isNaN(e)?e:e*2**t}e.ldexp=t;function s(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e++,e}e.nextGreaterSquare=s})),require_types$5=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MappingError=void 0,e.MappingError=class extends Error{}})),require_ExponentMapping$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExponentMapping=void 0;let t=require_ieee754$2(),s=require_util$3(),g=require_types$5();e.ExponentMapping=class{_shift;constructor(e){this._shift=-e}mapToIndex(e){return e<t.MIN_VALUE?this._minNormalLowerBoundaryIndex():t.getNormalBase2(e)+this._rightShift(t.getSignificand(e)-1,t.SIGNIFICAND_WIDTH)>>this._shift}lowerBoundary(e){let t=this._minNormalLowerBoundaryIndex();if(e<t)throw new g.MappingError(`underflow: ${e} is < minimum lower boundary: ${t}`);let S=this._maxNormalLowerBoundaryIndex();if(e>S)throw new g.MappingError(`overflow: ${e} is > maximum lower boundary: ${S}`);return s.ldexp(1,e<<this._shift)}get scale(){return this._shift===0?0:-this._shift}_minNormalLowerBoundaryIndex(){let e=t.MIN_NORMAL_EXPONENT>>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return t.MAX_NORMAL_EXPONENT>>this._shift}_rightShift(e,t){return Math.floor(e*2**-t)}}})),require_LogarithmMapping$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LogarithmMapping=void 0;let t=require_ieee754$2(),s=require_util$3(),g=require_types$5();e.LogarithmMapping=class{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=s.ldexp(Math.LOG2E,e),this._inverseFactor=s.ldexp(Math.LN2,-e)}mapToIndex(e){if(e<=t.MIN_VALUE)return this._minNormalLowerBoundaryIndex()-1;if(t.getSignificand(e)===0)return(t.getNormalBase2(e)<<this._scale)-1;let s=Math.floor(Math.log(e)*this._scaleFactor),g=this._maxNormalLowerBoundaryIndex();return s>=g?g:s}lowerBoundary(e){let s=this._maxNormalLowerBoundaryIndex();if(e>=s){if(e===s)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new g.MappingError(`overflow: ${e} is > maximum lower boundary: ${s}`)}let S=this._minNormalLowerBoundaryIndex();if(e<=S){if(e===S)return t.MIN_VALUE;if(e===S-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new g.MappingError(`overflow: ${e} is < minimum lower boundary: ${S}`)}return Math.exp(e*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return t.MIN_NORMAL_EXPONENT<<this._scale}_maxNormalLowerBoundaryIndex(){return(t.MAX_NORMAL_EXPONENT+1<<this._scale)-1}}})),require_getMapping$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getMapping=void 0;let t=require_ExponentMapping$2(),s=require_LogarithmMapping$2(),g=require_types$5(),S=-10,w=20,E=Array.from({length:31},(e,g)=>g>10?new s.LogarithmMapping(g-10):new t.ExponentMapping(g-10));function D(e){if(e>20||e<-10)throw new g.MappingError(`expected scale >= -10 && <= 20, got: ${e}`);return E[e+10]}e.getMapping=D})),require_ExponentialHistogram$2=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExponentialHistogramAggregator=e.ExponentialHistogramAccumulation=void 0;let t=require_types$6(),s=require_MetricData$2(),g=(init_esm$2(),__toCommonJS(esm_exports$2)),S=require_Buckets$2(),w=require_getMapping$2(),E=require_util$3();var D=class e{low;high;static combine(t,s){return new e(Math.min(t.low,s.low),Math.max(t.high,s.high))}constructor(e,t){this.low=e,this.high=t}};let O=20,k=160,j=2;var F=class e{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e,t=160,s=!0,E=0,D=0,O=0,k=1/0,j=-1/0,F=new S.Buckets,L=new S.Buckets,B=(0,w.getMapping)(20)){this.startTime=e,this._maxSize=t,this._recordMinMax=s,this._sum=E,this._count=D,this._zeroCount=O,this._min=k,this._max=j,this._positive=F,this._negative=L,this._mapping=B,this._maxSize<2&&(g.diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \
@@ -771,14 +771,14 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
771
771
  `}){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
772
772
  `:`
773
773
  `,D=` `,{customPrettifiers:O,errorLikeObjectKeys:k,hideObject:j,levelFirst:F,levelKey:L,levelLabel:B,messageFormat:H,messageKey:q,minimumLevel:J,singleLine:Y,timestampKey:ee,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:J,objectColorizer:_e,singleLine:Y,timestampKey:ee,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 J=q[B];L(e[J],J,B,E,e,k,F),H[J]=e[J]}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 J=``,{plain:Y,errors:ee}=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(Y).length>0&&(J+=L.greyMessage(g(Y))),J+=O,J=J.replace(/\\\\/gi,`\\`)):Object.entries(Y).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});J+=`${k}${L.property(e)}:${w.startsWith(O)?``:` `}${w}${O}`}),Object.entries(ee).forEach(([e,t])=>{let s=typeof j[e]==`function`?t:g(t,null,2);s!==void 0&&(J+=w({keyName:e,lines:s,eol:O,ident:k}))}),J}})),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}}),J=D({log:t,context:this.context}),Y=k({log:t,context:this.context}),ee=``;if(this.levelFirst&&q&&(ee=`${q}`),Y&&ee===``?ee=`${Y}`:Y&&(ee=`${ee} ${Y}`),!this.levelFirst&&q&&(ee=ee.length>0?`${ee} ${q}`:q),J&&(ee=ee.length>0?`${ee} ${J}:`:J),ee.endsWith(`:`)===!1&&ee!==``&&(ee+=`:`),s!==void 0&&(ee=ee.length>0?`${ee} ${s}`:s),ee.length>0&&!this.singleLine&&(ee+=this.EOL),t.type===`Error`&&typeof t.stack==`string`){let e=S({log:t,context:this.context});this.singleLine&&(ee+=this.EOL),ee+=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)&&(ee+=` `),ee+=s}return ee}})),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 J(e){let t=B(Object.assign({},q,e));return H.bind({...t,context:t})}function Y(e={}){let t=J(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=J(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+`
774
- `)}),g(w,E,s),E},{parse:`lines`,close(e,t){s.on(`close`,()=>{t(e)})}})}t.exports=Y,t.exports.build=Y,t.exports.PinoPretty=Y,t.exports.prettyFactory=J,t.exports.colorizerFactory=E,t.exports.isColorSupported=s,t.exports.default=Y})),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.contentDir),previousPath:spansPreviousPath(e.contentDir),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.contentDir),previousPath:logsPreviousPath(e.contentDir),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}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()}buildInstance(){if(this.activeFileSink=void 0,this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));let e;try{e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`})}catch(e){if(console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),this.fileSinkOpts){let e=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=e,(0,import_pino.default)(this.options,import_pino.default.multistream([{stream:e}]))}return(0,import_pino.default)(this.options)}if(this.fileSinkOpts){let t=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=t,(0,import_pino.default)(this.options,import_pino.default.multistream([{stream:e},{stream:t}]))}return(0,import_pino.default)(this.options,e)}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()}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){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let s;return s=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,s),s}reset(){this.config={},this.loggers.clear()}async flushAllFileSinks(){let e=[];for(let t of this.loggers.values())e.push(t.flushFileSink());await Promise.all(e)}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(s=>({...s,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:s,...g}=t;return g})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let s=t.getLocalState()??{},g=e(s.agentFocus??{});t.setLocalState({...s,agentFocus:g})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}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 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}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=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}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let s=0;this.mutateAgentPresence(g=>{let S=Date.now(),w={};for(let[t,E]of Object.entries(g)){if(S-E.ts>=2e4&&t!==e){s++;continue}w[t]=E}return w[e]=t,w})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),s>0&&this.log.info({evictedCount:s,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(s=>{if(!s[e])return s;t=!0;let{[e]:g,...S}=s;return S})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let s=[],g=!1,S=this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;g=!0;let E=Date.now();return s.push({currentDoc:w.currentDoc,ts:E}),{...S,[e]:{...w,mode:t,ts:E}}}),w=s[0];S&&w?this.log.debug({agentId:e,action:`touchMode`,currentDoc:w.currentDoc,ts:w.ts,mode:t},`[agent-presence] touchMode`):g||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(s=>{let g=s[e];if(!g)return s;let S=Date.now();return t=S,{...s,[e]:{...g,ts:S}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let s=t.getLocalState()??{},g=e(s.agentPresence??{});return t.setLocalState({...s,agentPresence:g}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null,fileSpanExporter=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(e={}){let t=e.localSink!==void 0,s=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!s||tracerProvider)return noopResult();try{let g=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),S=new import_src$2.AsyncLocalStorageContextManager;context.setGlobalContextManager(S);let w=[],E=e.localSink?.attributeDenylist??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;w.push(new ScrubbingSpanProcessor({attributeDenylist:E})),t&&e.localSink!==void 0&&(fileSpanExporter=new FileSpanExporter({contentDir:e.localSink.contentDir,maxBytes:e.localSink.spansMaxBytes}),w.push(new import_src$7.SimpleSpanProcessor(fileSpanExporter))),s&&w.push(new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter));let D=new import_src$7.BasicTracerProvider({resource:g,spanProcessors:w});trace.setGlobalTracerProvider(D),tracerProvider=D;try{propagation.setGlobalPropagator(new import_src.W3CTraceContextPropagator)}catch(e){getLogger(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let O=null;s&&(O=new import_src$6.MeterProvider({resource:g,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]}),metrics.setGlobalMeterProvider(O)),meterProvider=O,getLogger(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:s,otlp_endpoint:s?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:g.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized`)}catch(e){let t=getLogger(`telemetry`);tracerProvider===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),meterProvider=null,fileSpanExporter=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),meterProvider=null)}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3,shutdownHooks=new Set;function onTelemetryShutdown(e){shutdownHooks.add(e)}async function shutdownTelemetry(){let e=getLogger(`telemetry`);for(let t of shutdownHooks)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!tracerProvider&&!meterProvider)return;let t=(fileSpanExporter?fileSpanExporter.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),s;await Promise.race([t.then(()=>(s!==void 0&&clearTimeout(s),!1)),new Promise(e=>{s=setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS),s.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,fileSpanExporter=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,s){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await s(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,s){return getTracer().startActiveSpan(e,t??{},e=>{try{return s(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,s,g){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:s,"body.bytes":t.length,"doc.name":e.guid}},()=>{let s=e.getXmlFragment(`default`),S=e.getText(`source`),w=S.toString(),{body:E}=stripFrontmatter(t),D=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":E.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(E,buildParseOpts(g))),O=schema.nodeFromJSON(D);w!==t&&applyFastDiff(S,w,t),updateYFragment(e,s,O,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,s){withSpanSync(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let g=e.getXmlFragment(`default`),S=e.getText(`source`),{body:w}=stripFrontmatter(t),E=mdManager.parseWithFallback(w,buildParseOpts(s)),D=schema.nodeFromJSON(E),O=S.toString();O!==t&&(S.delete(0,O.length),S.insert(0,t)),updateYFragment(e,g,D,{mapping:new Map,isOMark:new Map})})}function deriveFragmentFromYtext(e,t){let s=e.getXmlFragment(`default`),{body:g}=stripFrontmatter(e.getText(`source`).toString()),S=mdManager.parseWithFallback(g,buildParseOpts(t));updateYFragment(e,s,schema.nodeFromJSON(S),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(e)??0)+1;this.seqs.set(e,s);let g=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:s});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(e,s),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let g=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});s.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,s);let g=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:s,branch:e});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,s)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,g);let S=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:g,docName:e,sv:Buffer.from(t).toString(`base64`)});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,s]of this.latestDiskAckSVs)e[t]=Buffer.from(s).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g);let S=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:g,docName:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g);let S=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:g,path:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let s=extname(e).slice(1).toLowerCase();return s.length>0&&t.has(s)}function stripDocExtension(e){let t=e.toLowerCase();for(let s of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(s))return e.slice(0,-s.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let s=canonicalize(t);if(!s)throw Error(`registerDocExtension: unsupported extension "${t}"`);let g=docExtensionByName.get(e);if(!g)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let S=canonicalize(g);return S?S===s?{effective:g,changed:!1,shadowed:null}:rank(s)<rank(S)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g}):{effective:g,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$10=()=>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$10().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$10().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$10()[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$10().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$10().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$10()[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$10().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$10().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 get_conflict_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 flat mapping where each value is a string, number, boolean, or array of scalars. 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 respondFrontmatterMalformed(e,t,s){console.warn(JSON.stringify({event:`frontmatter-malformed-write-refused`,handler:s,"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$9=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$9.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$9.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$9.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$9.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$9.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 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;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 shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,s){let g=normalizeBridge(e),S=normalizeBridge(t);if(g===S){if(e!==t){let g=detectAppliedToleranceClasses(e,t);for(let e of g)shouldEmitBridgeToleranceApplied(s.site,e,s.nowMs)&&(incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:s.site,class:e})))}return!0}let w={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${g.slice(0,300)}\n frag: ${S.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(w);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let E=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(w,{verbose:E}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,s){let g={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return s&&Object.assign(g,s),g}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,s){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,s)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,s){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,s)})}function tracedAppendFileSync(e,t,s){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,s)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,s){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,s)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
774
+ `)}),g(w,E,s),E},{parse:`lines`,close(e,t){s.on(`close`,()=>{t(e)})}})}t.exports=Y,t.exports.build=Y,t.exports.PinoPretty=Y,t.exports.prettyFactory=J,t.exports.colorizerFactory=E,t.exports.isColorSupported=s,t.exports.default=Y})),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}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()}buildInstance(){if(this.activeFileSink=void 0,this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));let e;try{e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`})}catch(e){if(console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),this.fileSinkOpts){let e=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=e,(0,import_pino.default)(this.options,import_pino.default.multistream([{stream:e}]))}return(0,import_pino.default)(this.options)}if(this.fileSinkOpts){let t=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=t,(0,import_pino.default)(this.options,import_pino.default.multistream([{stream:e},{stream:t}]))}return(0,import_pino.default)(this.options,e)}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()}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){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let s;return s=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,s),s}reset(){this.config={},this.loggers.clear()}async flushAllFileSinks(){let e=[];for(let t of this.loggers.values())e.push(t.flushFileSink());await Promise.all(e)}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(s=>({...s,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:s,...g}=t;return g})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let s=t.getLocalState()??{},g=e(s.agentFocus??{});t.setLocalState({...s,agentFocus:g})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}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 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}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=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}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let s=0;this.mutateAgentPresence(g=>{let S=Date.now(),w={};for(let[t,E]of Object.entries(g)){if(S-E.ts>=2e4&&t!==e){s++;continue}w[t]=E}return w[e]=t,w})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),s>0&&this.log.info({evictedCount:s,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(s=>{if(!s[e])return s;t=!0;let{[e]:g,...S}=s;return S})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let s=[],g=!1,S=this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;g=!0;let E=Date.now();return s.push({currentDoc:w.currentDoc,ts:E}),{...S,[e]:{...w,mode:t,ts:E}}}),w=s[0];S&&w?this.log.debug({agentId:e,action:`touchMode`,currentDoc:w.currentDoc,ts:w.ts,mode:t},`[agent-presence] touchMode`):g||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(s=>{let g=s[e];if(!g)return s;let S=Date.now();return t=S,{...s,[e]:{...g,ts:S}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let s=t.getLocalState()??{},g=e(s.agentPresence??{});return t.setLocalState({...s,agentPresence:g}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null,fileSpanExporter=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(e={}){let t=e.localSink!==void 0,s=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!s||tracerProvider)return noopResult();try{let g=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),S=new import_src$2.AsyncLocalStorageContextManager;context.setGlobalContextManager(S);let w=[],E=e.localSink?.attributeDenylist??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;w.push(new ScrubbingSpanProcessor({attributeDenylist:E})),t&&e.localSink!==void 0&&(fileSpanExporter=new FileSpanExporter({projectDir:e.localSink.projectDir,maxBytes:e.localSink.spansMaxBytes}),w.push(new import_src$7.SimpleSpanProcessor(fileSpanExporter))),s&&w.push(new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter));let D=new import_src$7.BasicTracerProvider({resource:g,spanProcessors:w});trace.setGlobalTracerProvider(D),tracerProvider=D;try{propagation.setGlobalPropagator(new import_src.W3CTraceContextPropagator)}catch(e){getLogger(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let O=null;s&&(O=new import_src$6.MeterProvider({resource:g,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]}),metrics.setGlobalMeterProvider(O)),meterProvider=O,getLogger(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:s,otlp_endpoint:s?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:g.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized`)}catch(e){let t=getLogger(`telemetry`);tracerProvider===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),meterProvider=null,fileSpanExporter=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),meterProvider=null)}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3,shutdownHooks=new Set;function onTelemetryShutdown(e){shutdownHooks.add(e)}async function shutdownTelemetry(){let e=getLogger(`telemetry`);for(let t of shutdownHooks)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!tracerProvider&&!meterProvider)return;let t=(fileSpanExporter?fileSpanExporter.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),s;await Promise.race([t.then(()=>(s!==void 0&&clearTimeout(s),!1)),new Promise(e=>{s=setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS),s.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,fileSpanExporter=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,s){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await s(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,s){return getTracer().startActiveSpan(e,t??{},e=>{try{return s(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,s,g){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:s,"body.bytes":t.length,"doc.name":e.guid}},()=>{let s=e.getXmlFragment(`default`),S=e.getText(`source`),w=S.toString(),{body:E}=stripFrontmatter(t),D=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":E.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(E,buildParseOpts(g))),O=schema.nodeFromJSON(D);w!==t&&applyFastDiff(S,w,t),updateYFragment(e,s,O,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,s){withSpanSync(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let g=e.getXmlFragment(`default`),S=e.getText(`source`),{body:w}=stripFrontmatter(t),E=mdManager.parseWithFallback(w,buildParseOpts(s)),D=schema.nodeFromJSON(E),O=S.toString();O!==t&&(S.delete(0,O.length),S.insert(0,t)),updateYFragment(e,g,D,{mapping:new Map,isOMark:new Map})})}function deriveFragmentFromYtext(e,t){let s=e.getXmlFragment(`default`),{body:g}=stripFrontmatter(e.getText(`source`).toString()),S=mdManager.parseWithFallback(g,buildParseOpts(t));updateYFragment(e,s,schema.nodeFromJSON(S),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(e)??0)+1;this.seqs.set(e,s);let g=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:s});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(e,s),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let g=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});s.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,s);let g=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:s,branch:e});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,s)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,g);let S=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:g,docName:e,sv:Buffer.from(t).toString(`base64`)});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,s]of this.latestDiskAckSVs)e[t]=Buffer.from(s).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g);let S=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:g,docName:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g);let S=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:g,path:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let s=extname(e).slice(1).toLowerCase();return s.length>0&&t.has(s)}function stripDocExtension(e){let t=e.toLowerCase();for(let s of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(s))return e.slice(0,-s.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let s=canonicalize(t);if(!s)throw Error(`registerDocExtension: unsupported extension "${t}"`);let g=docExtensionByName.get(e);if(!g)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let S=canonicalize(g);return S?S===s?{effective:g,changed:!1,shadowed:null}:rank(s)<rank(S)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g}):{effective:g,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$10=()=>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$10().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$10().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$10()[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$10().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$10().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$10()[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$10().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$10().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 flat mapping where each value is a string, number, boolean, or array of scalars. 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 respondFrontmatterMalformed(e,t,s){console.warn(JSON.stringify({event:`frontmatter-malformed-write-refused`,handler:s,"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$9=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$9.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$9.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$9.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$9.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$9.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 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;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 shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,s){let g=normalizeBridge(e),S=normalizeBridge(t);if(g===S){if(e!==t){let g=detectAppliedToleranceClasses(e,t);for(let e of g)shouldEmitBridgeToleranceApplied(s.site,e,s.nowMs)&&(incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:s.site,class:e})))}return!0}let w={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${g.slice(0,300)}\n frag: ${S.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(w);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let E=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(w,{verbose:E}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,s){let g={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return s&&Object.assign(g,s),g}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,s){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,s)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,s){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,s)})}function tracedAppendFileSync(e,t,s){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,s)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,s){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,s)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
775
775
  `);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(s===CONFIG_VALIDATION_REVERT_ORIGIN)return`no-op`;let S=e.getText(`source`),w=S.toString(),E=g.lkgCache.get(t);if(w.length===0&&(t!==`__config__/okignore`||E===void 0||E===``)||E!==void 0&&w===E)return`no-op`;let D=configScopeAttr(t),O=withConfigSpanSync(`config.validate`,{"config.scope":D,"config.validation.layer":`L3`},e=>{let s=validateConfigContent(t,w);return e.setAttribute(`config.outcome`,s.ok?`success`:`rejected`),s.ok||emitSchemaInvalidIssueEvents(s.error),s});if(!O.ok)return await withConfigSpan(`config.revert`,{"config.scope":D,"config.outcome":`reverted`},async()=>{let s=E??defaultLkgFor(t);e.transact(()=>{S.length>0&&S.delete(0,S.length),S.insert(0,s)},CONFIG_VALIDATION_REVERT_ORIGIN),E===void 0&&g.lkgCache.set(t,s),t===`__config__/okignore`&&isKnownConfigError(O.error)&&okignoreRejectionCounter().add(1,{"error.code":O.error.code}),g.onConfigRejected?.(t,O.error)}),`reverted`;let k=configDocAbsPath(t,g);try{await tracedMkdir(dirname(k),{recursive:!0})}catch(e){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] could not create parent dir for ${k}: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not create parent directory for ${k}: ${s}`}),`write-failed`}try{return await withFileLock(`${k}.lock`,async()=>{let s=null;try{s=readFileSync(k,`utf-8`)}catch(e){if(e.code!==`ENOENT`){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] could not read config for reconciliation: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not read config for reconciliation at ${k}: ${s}`}),`write-failed`}}if(s!==null&&E!==void 0&&s!==E){if(validateConfigContent(t,s).ok)return e.transact(()=>{S.length>0&&S.delete(0,S.length),S.insert(0,s)},CONFIG_FILE_WATCHER_ORIGIN),g.lkgCache.set(t,s),getLogger(`config-persistence`).info({docName:t,path:k},`[config-persistence] reconciled: external writer landed; imported disk into Y.Text`),`reconciled`;getLogger(`config-persistence`).warn({docName:t,path:k},`[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write`)}try{await atomicWriteConfig(k,w)}catch(e){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] write-failed at ${k}: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Failed to persist config at ${k}: ${s}`}),`write-failed`}return g.lkgCache.set(t,w),`persisted`},{onWarn:(e,t)=>{getLogger(`config-persistence`).warn(t,`[config-persistence] ${e}`)}})}catch(e){if(e instanceof FileLockTimeoutError)return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] lock timeout at ${k}: ${e.message}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:e.message}),`write-failed`;throw e}}function applyExternalConfigChange(e,t,s,g){if(!e)return`no-op`;let S=g.lkgCache.get(t);if(S!==void 0&&S===s)return`no-op`;let w=configScopeAttr(t),E=withConfigSpanSync(`config.validate`,{"config.scope":w,"config.validation.layer":`L3`},e=>{let g=validateConfigContent(t,s);return e.setAttribute(`config.outcome`,g.ok?`success`:`rejected`),g.ok||emitSchemaInvalidIssueEvents(g.error),g});if(!E.ok)return t===`__config__/okignore`&&isKnownConfigError(E.error)&&okignoreRejectionCounter().add(1,{"error.code":E.error.code}),g.onConfigRejected?.(t,E.error),`rejected`;let D=e.getText(`source`);return e.transact(()=>{D.length>0&&D.delete(0,D.length),D.insert(0,s)},CONFIG_FILE_WATCHER_ORIGIN),g.lkgCache.set(t,s),`applied`}let pendingContributors=new Map;function recordContributor(e,t,s,g,S,w,E,D){let O=pendingContributors.get(t);if(O||(O={writerId:t,displayName:s,colorSeed:g??s,docs:new Set,subjectOverride:S,actor:w,summaries:[],previousPaths:[]},pendingContributors.set(t,O)),O.docs.add(e),S!==void 0&&(O.subjectOverride=S),w!==void 0){let e=O.actor??{};w.principalId!==void 0&&(e.principalId=w.principalId),w.agentType!==void 0&&(e.agentType=w.agentType),w.clientName!==void 0&&(e.clientName=w.clientName),w.clientVersion!==void 0&&(e.clientVersion=w.clientVersion),w.label!==void 0&&(e.label=w.label),O.actor=e}if(typeof E==`string`&&E.length>0&&O.summaries.push(E),D&&D.length>0)for(let e of D)O.previousPaths.push(e)}function swapContributors(){let e=pendingContributors;return pendingContributors=new Map,e}function restoreContributors(e){for(let[t,s]of e){let e=pendingContributors.get(t);e||(e={writerId:t,displayName:s.displayName,colorSeed:s.colorSeed,docs:new Set,actor:s.actor,summaries:[],previousPaths:[]},pendingContributors.set(t,e));for(let t of s.docs)e.docs.add(t);s.summaries.length>0&&(e.summaries=[...s.summaries,...e.summaries]),s.previousPaths.length>0&&(e.previousPaths=[...s.previousPaths,...e.previousPaths])}}function formatContributorsFrom(e){if(e.size===0)return``;let t=[``];for(let s of e.values()){let e={v:1,id:s.writerId,name:s.displayName,colorSeed:s.colorSeed,docs:[...s.docs]};s.summaries.length>0&&(e.summaries=[...s.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
776
776
  `)}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)}function acquireLock(e,t){let s=resolve(e,`lock`);if(existsSync(s)){let t=null;try{t=JSON.parse(readFileSync(s,`utf-8`))}catch{console.warn(`[shadow-lock] Corrupt lock file at ${s} — replacing`)}if(t&&!isValidLockPid(t.pid)&&(console.warn(`[shadow-lock] Invalid lock pid (${String(t.pid)}) at ${s} — replacing`),t=null),t){let s=t.hostname===hostname();if(!(s&&t.pid===process.pid)){if(s&&isProcessAlive(t.pid))throw Error(`Shadow repo at ${e} is locked by another writer (pid=${t.pid}, worktree=${t.worktreeRoot}, started=${t.startedAt}). Only one active writer instance may mutate a given shadow root at a time.`);console.warn(`[shadow-lock] Stale lock detected (pid=${t.pid}, host=${t.hostname}) — replacing`)}}}let g={pid:process.pid,hostname:hostname(),startedAt:new Date().toISOString(),worktreeRoot:t};return writeFileSync(s,JSON.stringify(g,null,2),`utf-8`),s}function releaseLock(e){let t=resolve(e,`lock`);try{unlinkSync(t)}catch{}}const GIT_TIMEOUT_MS$3=(()=>{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 shadowGit(e){return esm_default({baseDir:e.workTree,timeout:{block:GIT_TIMEOUT_MS$3}}).env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree})}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};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(`
777
777
  `).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`){return withSpan(`shadow.commitWip`,{attributes:{"shadow.writer":t.id,"shadow.branch":S}},async()=>commitWipInner(e,t,s,g,S))}async function commitWipInner(e,t,s,g,S=`main`){let w=resolve(e.gitDir,`index-wip-${t.id}`),E=`refs/wip/${S}/${t.id}`,D=shadowGit(e),O=s||`.`;try{try{let t=(await D.raw(`rev-parse`,`${E}^{tree}`)).trim();await D.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:w}).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 ${E}:`,e),e}await D.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:w}).raw(`add`,O);let s=(await D.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:w}).raw(`write-tree`)).trim(),S=null;try{S=(await D.raw(`rev-parse`,E)).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 ${E}:`,e),e}let k=[`commit-tree`,s,`-m`,g];S&&k.push(`-p`,S);let j=(await D.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(...k)).trim();return await D.raw(`update-ref`,E,j),j}finally{try{rmSync(w)}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:`Open Knowledge (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=formatCheckpointBodyLine(s.kind===`bridge-merge-loss`?{kind:`bridge-merge-loss`,docName:s.docName,size:k,metadata:s.metadata}:{kind:`external-change-rescue`,docName:s.docName,size:k,metadata:s.metadata}),F=`checkpoint: ${s.label}\n\n${j}`;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`,F)).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(`
778
778
  `).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 s.raw(`ls-tree`,`-r`,`--long`,g)).trim().split(`
779
779
  `)[0];if(e){let t=e.split(/\s+/),s=4,g=3;j===0&&(j=Number(t[3]??`0`)),k=(t[4]??``).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,maxExternalChangeRescue:50,ttlMs:720*60*60*1e3};async function gcCheckpointRefs(e,t=`main`,s=DEFAULT_CHECKPOINT_RETENTION){let g={scanned:0,deletedBridgeMergeLoss:0,deletedExternalChangeRescue: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(`
780
- `).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":[],"external-change-rescue":[]},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)=>{e.sort((e,t)=>t.timestamp-e.timestamp);for(let w=0;w<e.length;w++){let E=e[w];if(!E)continue;let O=w>=t,k=s.ttlMs>0&&E.timestamp>0&&B-E.timestamp>s.ttlMs;if(O||k){let e=D.get(E.sha);e&&(H.push(e),g[S]++)}}};q(F[`bridge-merge-loss`],s.maxBridgeMergeLoss,`deletedBridgeMergeLoss`),q(F[`external-change-rescue`],s.maxExternalChangeRescue,`deletedExternalChangeRescue`);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`){return withSpan(`shadow.saveVersion`,{attributes:{"shadow.branch":g,"shadow.writer_count":s.length}},async()=>saveVersionInner(e,t,s,g))}async function saveVersionInner(e,t,s,g=`main`){let S=shadowGit(e),w=t||`.`,E=resolve(e.gitDir,`index-checkpoint`);try{await S.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:E}).raw(`add`,w);let t=(await S.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),D=[];for(let e of[...s,GIT_UPSTREAM_WRITER])try{let t=(await S.raw(`rev-parse`,`refs/wip/${g}/${e.id}`)).trim();D.push(t)}catch{}let O=[...new Set(D)];if(O.length===0)try{let e=(await S.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${g}/`)).trim().split(`
781
- `).filter(Boolean);e[0]&&O.push(e[0])}catch{}let k={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:[]},j=[`commit-tree`,t,`-m`,`${formatCheckpointSubject(`Checkpoint version`)}\n\n${formatOkActor(k)}`];for(let e of O)j.push(`-p`,e);let F=(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(...j)).trim(),L=`refs/checkpoints/${g}/${F}`;await S.raw(`update-ref`,L,F);for(let e of s)try{await S.raw(`update-ref`,`-d`,`refs/wip/${g}/${e.id}`)}catch{}try{await S.raw(`update-ref`,`-d`,`refs/wip/${g}/${GIT_UPSTREAM_WRITER.id}`)}catch{}return{checkpointRef:L}}finally{try{rmSync(E)}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))return;let w=e.documents.get(t);if(!w)return;let E=stripFrontmatter(w.getText(`source`).toString()).frontmatter,{frontmatter:D}=stripFrontmatter(s);try{w.transact(()=>{applyDiskContentToDoc(w,s,g,t,S)},FILE_WATCHER_ORIGIN)}catch(e){throw setReconciledBase(t,w.getText(`source`).toString()),e}E!==D&&recordFrontmatterEditSurface(`file-watcher`),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 reconcileDiskBeforeAgentWrite(e,t,s,g){if(isSystemDoc(t)||isConfigDoc(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{return NOT_RECONCILED}return normalizeBridge(D)===normalizeBridge(w)?NOT_RECONCILED:(applyExternalChange(e,t,D,g),{reconciled:!0,baseBytes:Buffer.byteLength(w,`utf8`),diskBytes:Buffer.byteLength(D,`utf8`)})}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(`
780
+ `).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":[],"external-change-rescue":[]},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)=>{e.sort((e,t)=>t.timestamp-e.timestamp);for(let w=0;w<e.length;w++){let E=e[w];if(!E)continue;let O=w>=t,k=s.ttlMs>0&&E.timestamp>0&&B-E.timestamp>s.ttlMs;if(O||k){let e=D.get(E.sha);e&&(H.push(e),g[S]++)}}};q(F[`bridge-merge-loss`],s.maxBridgeMergeLoss,`deletedBridgeMergeLoss`),q(F[`external-change-rescue`],s.maxExternalChangeRescue,`deletedExternalChangeRescue`);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){return withSpan(`shadow.saveVersion`,{attributes:{"shadow.branch":g,"shadow.writer_count":s.length}},async()=>saveVersionInner(e,t,s,g,S))}async function saveVersionInner(e,t,s,g=`main`,S){let w=shadowGit(e),E=t||`.`,D=resolve(e.gitDir,`index-checkpoint`);try{await w.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:D}).raw(`add`,E);let t=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:D}).raw(`write-tree`)).trim(),O=[];for(let e of[...s,GIT_UPSTREAM_WRITER])try{let t=(await w.raw(`rev-parse`,`refs/wip/${g}/${e.id}`)).trim();O.push(t)}catch{}let k=[...new Set(O)];if(k.length===0)try{let e=(await w.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${g}/`)).trim().split(`
781
+ `).filter(Boolean);e[0]&&k.push(e[0])}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:[]},F=[`commit-tree`,t,`-m`,`${formatCheckpointSubject(S?.trim()?S.trim():`Checkpoint version`)}\n\n${formatOkActor(j)}`];for(let e of k)F.push(`-p`,e);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(),B=`refs/checkpoints/${g}/${L}`;await w.raw(`update-ref`,B,L);for(let e of s)try{await w.raw(`update-ref`,`-d`,`refs/wip/${g}/${e.id}`)}catch{}try{await w.raw(`update-ref`,`-d`,`refs/wip/${g}/${GIT_UPSTREAM_WRITER.id}`)}catch{}return{checkpointRef:B}}finally{try{rmSync(D)}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))return;let w=e.documents.get(t);if(!w)return;let E=stripFrontmatter(w.getText(`source`).toString()).frontmatter,{frontmatter:D}=stripFrontmatter(s);try{w.transact(()=>{applyDiskContentToDoc(w,s,g,t,S)},FILE_WATCHER_ORIGIN)}catch(e){throw setReconciledBase(t,w.getText(`source`).toString()),e}E!==D&&recordFrontmatterEditSurface(`file-watcher`),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 reconcileDiskBeforeAgentWrite(e,t,s,g){if(isSystemDoc(t)||isConfigDoc(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{return NOT_RECONCILED}return normalizeBridge(D)===normalizeBridge(w)?NOT_RECONCILED:(applyExternalChange(e,t,D,g),{reconciled:!0,baseBytes:Buffer.byteLength(w,`utf8`),diskBytes:Buffer.byteLength(D,`utf8`)})}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(`
782
782
  `),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(`
783
783
  `).trim()),S=[]):S.push(e)}if(S.length>0){let e=S.join(`
784
784
  `).trim();e&&g.push(e)}return g}function reconcile(e){if(isSystemDoc(e.docName)||isConfigDoc(e.docName))return{kind:`noop`};let{base:t,ours:s,theirs:g}=e;if(containsConflictMarkers(g))return{kind:`refused`,reason:`conflict-markers`};if(g===t)return{kind:`noop`};if(s===t)return{kind:`clean`,newContent:g};let S=splitMarkdownBlocks(t),w=splitMarkdownBlocks(s),E=splitMarkdownBlocks(g);return(S.length+1)*(w.length+1)>4e6||(S.length+1)*(E.length+1)>4e6?{kind:`refused`,reason:`too-large`}:mergeBlocks(S,w,E)}function mergeBlocks(e,t,s){let g=computeEditOps(e,t),S=computeEditOps(e,s),w=[],E=[];for(let t=0;t<e.length;t++){let s=e[t],D=g.get(t),O=S.get(t),k=D?.insertsBefore??[],j=O?.insertsBefore??[];w.push(...k,...j);let F=D?.action??`keep`,L=O?.action??`keep`;if(F===`keep`&&L===`keep`)w.push(s);else if(F===`keep`&&L!==`keep`)L===`modify`&&O?.newContent!==void 0&&w.push(O.newContent);else if(F!==`keep`&&L===`keep`)F===`modify`&&D?.newContent!==void 0&&w.push(D.newContent);else{let e=F===`modify`?D?.newContent:null,g=L===`modify`?O?.newContent:null;e===g||E.push({blockIndex:t,base:s,ours:e??``,theirs:g??``}),e!=null&&w.push(e)}}let D=g.get(e.length),O=S.get(e.length);D?.insertsBefore&&w.push(...D.insertsBefore),O?.insertsBefore&&w.push(...O.insertsBefore);let k=w.length>0?`${w.join(`
@@ -804,7 +804,7 @@ native-divergence-injected
804
804
  `,`
805
805
  `).replaceAll(`\r`,`
806
806
  `).split(`
807
- `))s(S)||collectHrefsFromLine(stripHtmlComments(S,g).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let s=extname(t).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(s))return null;let g=resolveAssetProjectPath(t,e.fromDocName);if(!g)return null;let S=resolve(e.contentDir,g),w,E;try{if(w=normalize(realpathSync(S)),!isWithinContentDir(w,e.contentDir))return null;E=statSync(w)}catch(t){let s=errnoCode$1(t);return s!==`ENOENT`&&s!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return E.isFile()?{absolutePath:w,relativePath:toContentRelativePath(e.contentDir,w),stat:E}:null}function toContentRelativePath(e,t){let s=normalize(realpathSync(e));return normalize(t).slice(s.length+(s.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let s=new Map;for(let[g,S]of e.fileIndex){let w=e.readMarkdown(S.canonicalPath);if(w!==null)for(let S of extractLocalAssetHrefs(w)){let w=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:g,href:S});if(!w||e.isExcluded?.(w.relativePath))continue;let E=mediaKindForAssetPath(w.absolutePath),D=s.get(w.relativePath);if(D){D.referencedBy.includes(g)||D.referencedBy.push(g);continue}s.set(w.relativePath,{kind:`asset`,path:w.relativePath,assetExt:extname(w.relativePath).toLowerCase(),mediaKind:E,size:w.stat.size,modified:w.stat.mtime.toISOString(),referencedBy:[g]})}}return[...s.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:s,inlineExtensions:g,assetExtensions:S,blocklistExtensions:w}=e;return(e,E,D)=>{let O;try{O=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return D()}let k=extname(O).slice(1).toLowerCase(),j=k===`md`||k===`mdx`;if(!O||t.isPathIgnored(O)||!j&&!S.has(k))return D();E.setHeader(`X-Content-Type-Options`,`nosniff`),j||(g.has(k)?E.setHeader(`Content-Disposition`,`inline`):E.setHeader(`Content-Disposition`,`attachment`)),k===`svg`&&E.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`),s(e,E,()=>{if(!E.headersSent){if(S.has(k)||w.has(k)){E.statusCode=404,E.end();return}D()}})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let s=resolve(e),g=resolve(s,t),S=relative(s,g);return S===``?{ok:!0,abs:g,rel:``}:S===`..`||S.startsWith(`../`)||isAbsolute(S)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:g,rel:S}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target Open Knowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`);function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const TEXT_CHANNEL_FIELD=string().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function outputSchemaWithText(e){return{text:TEXT_CHANNEL_FIELD,...e}}function textPlusStructured(e,t,s){let g={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:g,...s?{isError:!0}:{}}}const HOCUSPOCUS_NOT_RUNNING_ERROR="Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",ROLE_LABEL={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},ROLE_BEFORE={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},ROLE_AFTER={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function buildWorkflowFrame(e){return`## Where this fits
807
+ `))s(S)||collectHrefsFromLine(stripHtmlComments(S,g).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let s=extname(t).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(s))return null;let g=resolveAssetProjectPath(t,e.fromDocName);if(!g)return null;let S=resolve(e.contentDir,g),w,E;try{if(w=normalize(realpathSync(S)),!isWithinContentDir(w,e.contentDir))return null;E=statSync(w)}catch(t){let s=errnoCode$1(t);return s!==`ENOENT`&&s!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return E.isFile()?{absolutePath:w,relativePath:toContentRelativePath(e.contentDir,w),stat:E}:null}function toContentRelativePath(e,t){let s=normalize(realpathSync(e));return normalize(t).slice(s.length+(s.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let s=new Map;for(let[g,S]of e.fileIndex){let w=e.readMarkdown(S.canonicalPath);if(w!==null)for(let S of extractLocalAssetHrefs(w)){let w=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:g,href:S});if(!w||e.isExcluded?.(w.relativePath))continue;let E=mediaKindForAssetPath(w.absolutePath),D=s.get(w.relativePath);if(D){D.referencedBy.includes(g)||D.referencedBy.push(g);continue}s.set(w.relativePath,{kind:`asset`,path:w.relativePath,assetExt:extname(w.relativePath).toLowerCase(),mediaKind:E,size:w.stat.size,modified:w.stat.mtime.toISOString(),referencedBy:[g]})}}return[...s.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:s,inlineExtensions:g,assetExtensions:S,blocklistExtensions:w}=e;return(e,E,D)=>{let O;try{O=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return D()}let k=extname(O).slice(1).toLowerCase(),j=k===`md`||k===`mdx`;if(!O||t.isPathIgnored(O)||!j&&!S.has(k))return D();E.setHeader(`X-Content-Type-Options`,`nosniff`),j||(g.has(k)?E.setHeader(`Content-Disposition`,`inline`):E.setHeader(`Content-Disposition`,`attachment`)),k===`svg`&&E.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`),s(e,E,()=>{if(!E.headersSent){if(S.has(k)||w.has(k)){E.statusCode=404,E.end();return}D()}})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let s=resolve(e),g=resolve(s,t),S=relative(s,g);return S===``?{ok:!0,abs:g,rel:``}:S===`..`||S.startsWith(`../`)||isAbsolute(S)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:g,rel:S}}function agentIdentityFields(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target Open Knowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),VERSION_FIELD_DESCRIBE="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",versionInputSchema=string().length(40).regex(/^[0-9a-f]+$/i).describe(VERSION_FIELD_DESCRIBE),previewUrlOutputField=string().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),previewUrlSourceField=string().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),previousPreviewUrlField=string().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),summaryOutputSchema=object$1({value:string(),truncatedFrom:number().optional(),hint:string().optional()}).describe(`Normalized change-note summary, when one was recorded.`),looseObjectArray=array(record(string(),unknown())),previewAttachWarningField=record(string(),unknown()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),documentResultBaseShape={summary:summaryOutputSchema.optional(),contentDivergence:WriteWarningSchema.optional().describe(`Present when the converged Y.Text didn't byte-match the bytes you composed, or when an out-of-band disk edit was reconciled in before your write landed.`)};function nestDocResult(e,t,s){let g={};return e&&(g.previewUrl=e.url,g.previewUrlSource=e.source),t&&(g.warning=t),Object.keys(s).length>0&&(g.document=s),g}function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const TEXT_CHANNEL_FIELD=string().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function outputSchemaWithText(e){return{text:TEXT_CHANNEL_FIELD,...e}}function textPlusStructured(e,t,s){let g={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:g,...s?{isError:!0}:{}}}const HOCUSPOCUS_NOT_RUNNING_ERROR="Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",ROLE_LABEL={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},ROLE_BEFORE={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},ROLE_AFTER={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function buildWorkflowFrame(e){return`## Where this fits
808
808
 
809
809
  Open Knowledge accretes a persistent wiki through three workflow tools, mapped to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f):
810
810
 
@@ -812,7 +812,7 @@ Open Knowledge accretes a persistent wiki through three workflow tools, mapped t
812
812
  - **Wiki, provisional** — \`research\`
813
813
  - **Wiki, canonical** — \`consolidate\`
814
814
 
815
- (Project-level folder structure: \`ok seed\` for fresh repos with the Karpathy three-layer; \`discover\` MCP tool for existing-content repos that need conventions extracted from siblings. Neither is required — these three tools work against any folder structure the project already uses.)
815
+ (Project-level folder structure: \`ok seed\` for fresh repos with the Karpathy three-layer; \`workflow({ kind: "discover" })\` for existing-content repos that need conventions extracted from siblings. Neither is required — these three tools work against any folder structure the project already uses.)
816
816
 
817
817
  **This tool operates in the ${ROLE_LABEL[e]}.**
818
818
 
@@ -821,9 +821,9 @@ Open Knowledge accretes a persistent wiki through three workflow tools, mapped t
821
821
 
822
822
  Karpathy's insight: "The tedious part of maintaining a knowledge base is not the reading or the thinking — it's the bookkeeping." Humans abandon wikis because maintenance costs exceed perceived value. These tools exist so an agent can do the bookkeeping (fetching, summarizing, cross-linking, superseding) without fatigue. Follow the steps below faithfully — skipping the cross-linking, supersedes chains, or raw-source preservation is what turns a useful wiki back into an abandoned one.
823
823
 
824
- `}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)}}try{let e=await resolveConfig(t,g);return{ok:!0,cwd:g,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,config:E}=S;try{return{ok:!0,cwd:w,config:E,url:await resolveServerUrl(s,w)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function normalizeDocName(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: docName "${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: docName "${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,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${s.status} with non-JSON body: ${t}`}}return normalizeResponse(s,g)}async function httpPost(e,t,s){let g;if(s!==void 0)try{g=JSON.stringify(s)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}let S;try{S=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:g,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let w;try{w=await S.json()}catch(e){let t=e instanceof Error?e.message:String(e);return S.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${S.status} with non-JSON body: ${t}`}}return normalizeResponse(S,w)}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
+ `}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)}}try{let e=await resolveConfig(t,g);return{ok:!0,cwd:g,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,config:E}=S;try{return{ok:!0,cwd:w,config:E,url:await resolveServerUrl(s,w)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}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,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${s.status} with non-JSON body: ${t}`}}return normalizeResponse(s,g)}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(`
825
825
  `)){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 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(`
826
- `).map(e=>e.trim()).filter(Boolean);return D.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(D.map(e=>logOnRef(w,e,t,S,s)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s),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 s=extractFrontmatterYaml(t);if(s===null)return{};let g;try{g=(0,import_dist$1.parse)(s)}catch(t){if(!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] malformed YAML frontmatter at ${e} — title/description unavailable. Reason: ${s}`)}return{}}if(typeof g!=`object`||!g)return{};let S=g,w={};return typeof S.title==`string`&&(w.title=S.title),typeof S.description==`string`&&(w.description=S.description),w}function extractFrontmatterYaml(e){let t=e.replace(/^/,``),s=/^[ \t]*---\r?\n([\s\S]*?)\r?\n[ \t]*---(\r?\n|$)/.exec(t);return s?s[1]??null:null}const FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function parseFrontmatterRaw(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]);if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i;function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${s}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.backlinks??s.results??s.links;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e,s=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;s&&S.push({source:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let s=[...new Set(t)],g=[];for(let e=0;e<s.length;e+=BACKLINK_COUNT_CHUNK)g.push(s.slice(e,e+BACKLINK_COUNT_CHUNK));let S=await Promise.all(g.map(async t=>{let s=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return s.ok?s.counts??{}:null})),w=new Map,E=!1;for(let e of S)if(e){E=!0;for(let[t,s]of Object.entries(e))typeof s==`number`&&Number.isFinite(s)&&w.set(t,s)}return E?w:null}async function fetchForwardLinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.forwardLinks??s.links??s.results;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){S.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let s=typeof t.docName==`string`?t.docName:void 0;s&&S.push({kind:`doc`,docName:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}function liftOwnFrontmatter(e){let t=e??{};return{title:typeof t.title==`string`?t.title:void 0,description:typeof t.description==`string`?t.description:void 0,tags:Array.isArray(t.tags)?t.tags.filter(e=>typeof e==`string`):[],frontmatter:t}}async function enrichPath(e,t,s={}){let g=resolveWithinRoot(t.projectDir,e);if(!g.ok)throw Error(`enrichPath: ${g.reason}`);let S=g.rel,w=g.abs,E=t.historyDepth??5,D=s.includeRichFields===!0,O=readFrontmatter(w);if(!D){let e=liftOwnFrontmatter(await O);return{path:S,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[k,j,F,L,B]=await Promise.all([O,fetchBacklinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),readShadowLog(t.projectDir,S,E).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,S,E).catch(()=>({commits:[],source:`git`}))]),H=liftOwnFrontmatter(k);return{path:S,title:H.title,description:H.description,tags:H.tags,frontmatter:H.frontmatter,backlinkCount:j?.length??null,backlinks:j,forwardLinkCount:F?.length??null,forwardLinks:F,history:L.commits,historySource:L.source,projectHistory:B.commits,projectHistorySource:B.source}}async function scanDirectory(e,t){let s={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},g=0,S=[{path:e,depth:0}];for(;S.length>0;){let e=S.shift();if(!e)break;if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}let w;try{w=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let E of w){if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}g++;let w=E.name;if(E.isDirectory()){if(DIR_SKIP.has(w)||w.startsWith(`.`))continue;e.depth===0&&s.childDirCount++,S.push({path:`${e.path}/${w}`,depth:e.depth+1})}else if(E.isFile()&&WIKI_EXT_RE.test(w)){s.recursiveMdCount++,e.depth===0&&s.directMdCount++;let g=`${e.path}/${w}`;try{let e=await stat$1(g);(!s.mostRecent||e.mtimeMs>s.mostRecent.mtimeMs)&&(s.mostRecent={absPath:g,relPath:relative(t,g).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return s}async function enrichDirectory(e,t){let s=resolveWithinRoot(t.projectDir,e);if(!s.ok)throw Error(`enrichDirectory: ${s.reason}`);let g=s.rel,S=s.abs,w=await scanDirectory(S,t.projectDir),E;if(w.mostRecent){let e=await readFrontmatter(w.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;E={path:w.mostRecent.relPath,title:t??basename(w.mostRecent.relPath),updatedAt:new Date(w.mostRecent.mtimeMs).toISOString()}}let D={path:g,type:`directory`,directMdCount:w.directMdCount,recursiveMdCount:w.recursiveMdCount,childDirCount:w.childDirCount,mostRecentMd:E,truncated:w.truncated},O=readFolderFrontmatter(t.projectDir,g);O.title!==void 0&&(D.title=O.title),O.description!==void 0&&(D.description=O.description),(O.tags?.length??0)>0&&(D.tags=O.tags);let k=resolveTemplatesAvailable(t.projectDir,g);return k.length>0&&(D.templates_available=k),D}async function enrichDirectoryRecursive(e,t,s){let g=await enrichDirectory(e,s);if(t<=1)return g;let S=g.path,w=resolve(s.projectDir,S),E;try{E=await readdir(w,{withFileTypes:!0})}catch{return g}let D=[];for(let e of E){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let g=await enrichDirectoryRecursive(S?`${S}/${e.name}`:e.name,t-1,s);D.push(g)}return D.length>0&&(g.subfolders=D),g}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function mergePatch(e,t){let s={...e};for(let[e,g]of Object.entries(t))if(g!==void 0){if(isEmpty$1(g)){delete s[e];continue}s[e]=g}return s}function isEmpty$1(e){return isFrontmatterValueEmpty(e)}function applyNestedFolderRulesUpsert(e){if(!isAbsolute(e.projectDir))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};let t=[];for(let s of e.rules){let g=resolveTargetFolderFromMatch(s.new_match??s.match);if(!g.ok)return{ok:!1,error:{code:`MULTI_FOLDER_GLOB`,message:g.message,rule:s.match}};let S=g.folder?resolve(e.projectDir,g.folder):e.projectDir,w=resolve(e.projectDir);if(!S.startsWith(w+sep)&&S!==w)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved target folder escapes projectDir: ${S}`,rule:s.match}};let E=null,D=null;if(s.new_match!==void 0&&s.new_match!==s.match){let t=resolveTargetFolderFromMatch(s.match);if(!t.ok)return{ok:!1,error:{code:`MULTI_FOLDER_GLOB`,message:t.message,rule:s.match}};if(E=t.folder,D=t.folder?resolve(e.projectDir,t.folder):e.projectDir,!D.startsWith(w+sep)&&D!==w)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved source folder escapes projectDir: ${D}`,rule:s.match}}}t.push({targetFolder:g.folder,targetAbs:S,sourceFolder:E,sourceAbs:D,rule:s})}let s=[];for(let g of t)try{if(g.sourceAbs&&g.sourceAbs!==g.targetAbs){let t=join(g.sourceAbs,`.ok`,`frontmatter.yml`);existsSync(t)&&(unlinkSync(t),autoCleanOkDir(join(g.sourceAbs,`.ok`)),s.push({match:g.rule.match,path:relPathOf$1(e.projectDir,t),action:`deleted`}))}let t=join(g.targetAbs,`.ok`),S=join(t,`frontmatter.yml`),w=readExistingFrontmatter(S),E=Object.keys(g.rule.frontmatter).length===0?{}:mergePatch(w,g.rule.frontmatter);if(Object.keys(E).length===0){existsSync(S)&&(unlinkSync(S),autoCleanOkDir(t),s.push({match:g.rule.new_match??g.rule.match,path:relPathOf$1(e.projectDir,S),action:`deleted`}));continue}mkdirSync(t,{recursive:!0});let D=(0,import_dist$1.stringify)(E),O=`${S}.tmp.${process.pid}.${Date.now()}`;writeFileSync(O,D,`utf-8`),renameSync(O,S),s.push({match:g.rule.new_match??g.rule.match,path:relPathOf$1(e.projectDir,S),action:`written`})}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write nested frontmatter for ${g.rule.match}: ${e.message}`,rule:g.rule.match},...s.length>0?{partiallyApplied:s}:{}}}return{ok:!0,applied:s}}function resolveTargetFolderFromMatch(e){let t=e.split(`/`).filter(e=>e.length>0),s=[],g=!1;for(let S of t){let t=/[*?[\]{}]/.test(S);if(g&&!t)return{ok:!1,message:`Glob "${e}" matches multiple folders (literal segment "${S}" appears after a glob). Split it into one rule per folder, e.g. folder_config({ action: "set-rule", rules: [{ match: "specs/foo/${S}/**", ... }, ...] }).`};if(t){if(g=!0,S!==`**`&&S!==`*`)return{ok:!1,message:`Glob "${e}" uses an unsupported pattern segment "${S}". Only "*" and "**" are supported in nested folder rules.`};continue}s.push(S)}return{ok:!0,folder:s.join(`/`)}}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$1(e,t){let s=resolve(e);return t.startsWith(s+sep)?t.slice(s.length+1).split(sep).join(`/`):t}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=/^[A-Za-z0-9_-]+$/;function applyTemplateWrite(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let s=validateTitle(e.frontmatter.title);if(!s.ok)return{ok:!1,error:s.error};let g=validateSubstitutionAllowlist(e.body);if(!g.ok)return{ok:!1,error:g.error};let{templatesDir:S,filePath:w}=templatePaths(e.projectDir,t.folderRel,e.name),E=serializeFrontmatter(e.frontmatter),D=E?`---\n${E}---\n${e.body}`:e.body;try{mkdirSync(S,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${relPathOf(e.projectDir,S)}: ${t.message}`}}}let O=!existsSync(w),k=`${w}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(k,D,`utf-8`),renameSync(k,w)}catch(t){try{unlinkSync(k)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${relPathOf(e.projectDir,w)}: ${t.message}`}}}let j=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&j.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,path:relPathOf(e.projectDir,w),created:O,warnings:j}}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}`}}}let E=!1,D=!1;if(existsSync(s)&&isEmpty(s))try{rmdirSync(s),E=!0}catch{}if(existsSync(g)&&isEmpty(g))try{rmdirSync(g),D=!0}catch{}return{ok:!0,path:relPathOf(e.projectDir,S),existed:w,cleanedEmpty:{templatesDir:E,okDir:D}}}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 serializeFrontmatter(e){let t={};return e.title!==void 0&&(t.title=e.title),e.description!==void 0&&(t.description=e.description),Array.isArray(e.tags)&&e.tags.length>0&&(t.tags=e.tags),Object.keys(t).length===0?``:(0,import_dist$1.stringify)(t)}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$7=()=>getLogger(`http`);function successResponse(e,t,s,g,S={}){if(e.headersSent||e.writableEnded||e.destroyed){log$7().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$7().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$7().error({event:`api.success.unserializable-body`,bodyKeys:typeof w.data==`object`&&w.data!==null?Object.keys(w.data):null,handler:S.handler,originalStatus:t,err:s},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(E)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,s=e.now??Date.now,g=e.ttlMs??6e4;async function S(S){let w=t.get(S);if(w?.status===`resolved`&&w.expiresAt>s())return w.installed;if(w?.status===`inflight`)return w.promise;let E=(async()=>{try{let w=await e.probe(S);return t.set(S,{status:`resolved`,installed:w,expiresAt:s()+g}),w}catch{return t.set(S,{status:`resolved`,installed:!1,expiresAt:s()+g}),!1}})();return t.set(S,{status:`inflight`,promise:E}),E}async function w(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await S(e)]));return Object.fromEntries(e)}return{probeAll:w,probeWithCache:S}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let s=e.headers.origin;if(typeof s==`string`&&s.length>0)try{return isLoopbackHostname(new URL(s).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await s():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return s=>e===`darwin`?probeMacOs(s,t):e===`win32`?probeWindows(s,t):probeLinux(s,t)}function probeMacOs(e,t){let s=MACOS_APP_NAMES[e];function g(e){return new Promise(s=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}return(async()=>{for(let e of s)if(await g(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(s=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{s(!e)})})}function probeLinux(e,t){return new Promise(s=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let s=[],g=0,S=AbortSignal.timeout(t.timeoutMs),w=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));S.addEventListener(`abort`,w,{once:!0});try{for await(let S of e){if(g+=S.length,g>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);s.push(S)}return Buffer.concat(s)}finally{S.removeEventListener(`abort`,w)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,s,g={}){let S=e.safeParse(t);if(S.success)return{ok:!0,value:S.data};let w=S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(s,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:g.handler,detail:w}),{ok:!1}}function withValidation(e,t,s={}){return async(g,S)=>{if(s.method!==void 0&&g.method!==s.method){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:s.handler,extraHeaders:{Allow:s.method}});return}if(s.preBodyGate!==void 0&&!s.preBodyGate(g,S)){!S.headersSent&&!S.writableEnded&&!S.destroyed&&errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(s.skipBodyParse){let w=validateBody(e,{},S,s);if(!w.ok)return;await t(g,S,w.value);return}let w;try{w=await readRequestBody(g)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(S,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(S,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s.handler,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s.handler,cause:e});return}let E;try{E=w.length===0?{}:JSON.parse(w.toString(`utf8`))}catch(e){errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:s.handler,cause:e});return}let D=validateBody(e,E,S,s);D.ok&&await t(g,S,D.value)}}function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,s){return new Promise(g=>{let S=!1,w=e=>{S||(S=!0,g(e))},E=setTimeout(()=>w({ok:!1,reason:`timeout`}),s);try{let s=spawn(e,[...t],{detached:!0,stdio:`ignore`,shell:!1});s.once(`error`,e=>{clearTimeout(E),w(classifySpawnError(e))}),s.once(`spawn`,()=>{if(!S){try{s.unref()}catch{}clearTimeout(E),w({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(E),w(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let w=typeof S.path==`string`?S.path:``;if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(w,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let E=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!E){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let D=resolveCursorSpawnInvocation(E,w,s.platform),O=await(s.spawnDetached??spawnDetached)(D.exec,D.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(O.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(O.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(O.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let s of t){let t=s(e);try{return await access(t,constants$1.X_OK),t}catch(e){let s=e?.code;s!==`ENOENT`&&s!==`EACCES`&&s!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,s,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],{timeout:e,encoding:`utf-8`},(e,s)=>{if(e){t(null);return}let g=s.split(/\r?\n/)[0]?.trim();t(g&&g.length>0?g:null)})})}function resolveCursorSpawnInvocation(e,t,s){return s===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:{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=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:`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`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}if(s.platform!==`darwin`){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Handoff is currently macOS-only.`,{handler:HANDLER});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;if(k.type===`app-bundle`){k.quitFirst&&(await F(`/usr/bin/osascript`,[`-e`,`tell application "${k.appName}" to quit`],SPAWN_TIMEOUT_MS).catch(()=>void 0),await j(QUIT_SETTLE_MS));let e=await F(`/usr/bin/open`,[`-a`,k.appName],SPAWN_TIMEOUT_MS);if(!e.ok){emitSpawnFailure(t,E,e.reason);return}await j(APP_BUNDLE_SETTLE_MS);let s=await F(`/usr/bin/open`,[D],SPAWN_TIMEOUT_MS);if(!s.ok){emitSpawnFailure(t,E,s.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 L=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!L){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let B=resolveCursorSpawnInvocation(L,O,s.platform),H=await F(B.exec,B.args,SPAWN_TIMEOUT_MS);if(!H.ok){emitSpawnFailure(t,E,H.reason);return}await j(CURSOR_SETTLE_MS);let q=await F(`/usr/bin/open`,[D],SPAWN_TIMEOUT_MS);if(!q.ok){emitSpawnFailure(t,E,q.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}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}`}function splitFrontmatterLines(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).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}}const PANE_TARGET_FILE=`pane-target.json`,PANE_TARGET_TTL_MS=3e4;function armPaneTarget(e,t,s=Date.now()){if(!t.startsWith(`#/`))return!1;tracedMkdirSync(e,{recursive:!0});let g={route:t,armedAtMs:s};return tracedWriteFileSync(resolve(e,PANE_TARGET_FILE),JSON.stringify(g)),!0}function readArmedPaneTarget(e,t=Date.now(),s=PANE_TARGET_TTL_MS){let g=resolve(e,PANE_TARGET_FILE);if(!existsSync(g))return null;try{let e=JSON.parse(readFileSync(g,`utf-8`));return typeof e.route!=`string`||typeof e.armedAtMs!=`number`||t-e.armedAtMs>s?null:e.route}catch(e){let t=e.code;return(t===`EACCES`||t===`EPERM`||t===`EIO`)&&process.stderr.write(`[pane-target] readArmedPaneTarget failed at ${g}: ${e instanceof Error?e.message:String(e)}\n`),null}}function clearArmedPaneTarget(e){let t=resolve(e,PANE_TARGET_FILE);if(existsSync(t))try{tracedUnlinkSync(t)}catch{}}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;getLogger(`share`).info({action:`construct-url`,result:e,...s===void 0?{}:{branchExists:s},...g===void 0?{}:{kind:g}},`share action`)}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 parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let s=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return s||(s=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)||(s=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),s)||(s=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)?{owner:s[1],repo:s[2]}: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);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}: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(`
826
+ `).map(e=>e.trim()).filter(Boolean);return D.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(D.map(e=>logOnRef(w,e,t,S,s)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s),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 s=extractFrontmatterYaml(t);if(s===null)return{};let g;try{g=(0,import_dist$1.parse)(s)}catch(t){if(!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] malformed YAML frontmatter at ${e} — title/description unavailable. Reason: ${s}`)}return{}}if(typeof g!=`object`||!g)return{};let S=g,w={};return typeof S.title==`string`&&(w.title=S.title),typeof S.description==`string`&&(w.description=S.description),w}function extractFrontmatterYaml(e){let t=e.replace(/^/,``),s=/^[ \t]*---\r?\n([\s\S]*?)\r?\n[ \t]*---(\r?\n|$)/.exec(t);return s?s[1]??null:null}const FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function parseFrontmatterRaw(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]);if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i;function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${s}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.backlinks??s.results??s.links;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e,s=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;s&&S.push({source:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let s=[...new Set(t)],g=[];for(let e=0;e<s.length;e+=BACKLINK_COUNT_CHUNK)g.push(s.slice(e,e+BACKLINK_COUNT_CHUNK));let S=await Promise.all(g.map(async t=>{let s=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return s.ok?s.counts??{}:null})),w=new Map,E=!1;for(let e of S)if(e){E=!0;for(let[t,s]of Object.entries(e))typeof s==`number`&&Number.isFinite(s)&&w.set(t,s)}return E?w:null}async function fetchForwardLinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.forwardLinks??s.links??s.results;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){S.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let s=typeof t.docName==`string`?t.docName:void 0;s&&S.push({kind:`doc`,docName:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}function liftOwnFrontmatter(e){let t=e??{};return{title:typeof t.title==`string`?t.title:void 0,description:typeof t.description==`string`?t.description:void 0,tags:Array.isArray(t.tags)?t.tags.filter(e=>typeof e==`string`):[],frontmatter:t}}async function enrichPath(e,t,s={}){let g=resolveWithinRoot(t.projectDir,e);if(!g.ok)throw Error(`enrichPath: ${g.reason}`);let S=g.rel,w=g.abs,E=t.historyDepth??5,D=s.includeRichFields===!0,O=readFrontmatter(w);if(!D){let e=liftOwnFrontmatter(await O);return{path:S,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[k,j,F,L,B]=await Promise.all([O,fetchBacklinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),readShadowLog(t.projectDir,S,E).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,S,E).catch(()=>({commits:[],source:`git`}))]),H=liftOwnFrontmatter(k);return{path:S,title:H.title,description:H.description,tags:H.tags,frontmatter:H.frontmatter,backlinkCount:j?.length??null,backlinks:j,forwardLinkCount:F?.length??null,forwardLinks:F,history:L.commits,historySource:L.source,projectHistory:B.commits,projectHistorySource:B.source}}async function scanDirectory(e,t){let s={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},g=0,S=[{path:e,depth:0}];for(;S.length>0;){let e=S.shift();if(!e)break;if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}let w;try{w=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let E of w){if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}g++;let w=E.name;if(E.isDirectory()){if(DIR_SKIP.has(w)||w.startsWith(`.`))continue;e.depth===0&&s.childDirCount++,S.push({path:`${e.path}/${w}`,depth:e.depth+1})}else if(E.isFile()&&WIKI_EXT_RE.test(w)){s.recursiveMdCount++,e.depth===0&&s.directMdCount++;let g=`${e.path}/${w}`;try{let e=await stat$1(g);(!s.mostRecent||e.mtimeMs>s.mostRecent.mtimeMs)&&(s.mostRecent={absPath:g,relPath:relative(t,g).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return s}async function enrichDirectory(e,t){let s=resolveWithinRoot(t.projectDir,e);if(!s.ok)throw Error(`enrichDirectory: ${s.reason}`);let g=s.rel,S=s.abs,w=await scanDirectory(S,t.projectDir),E;if(w.mostRecent){let e=await readFrontmatter(w.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;E={path:w.mostRecent.relPath,title:t??basename(w.mostRecent.relPath),updatedAt:new Date(w.mostRecent.mtimeMs).toISOString()}}let D={path:g,type:`directory`,directMdCount:w.directMdCount,recursiveMdCount:w.recursiveMdCount,childDirCount:w.childDirCount,mostRecentMd:E,truncated:w.truncated},O=readFolderFrontmatter(t.projectDir,g);O.title!==void 0&&(D.title=O.title),O.description!==void 0&&(D.description=O.description),(O.tags?.length??0)>0&&(D.tags=O.tags);let k=resolveTemplatesAvailable(t.projectDir,g);return k.length>0&&(D.templates_available=k),D}async function enrichDirectoryRecursive(e,t,s){let g=await enrichDirectory(e,s);if(t<=1)return g;let S=g.path,w=resolve(s.projectDir,S),E;try{E=await readdir(w,{withFileTypes:!0})}catch{return g}let D=[];for(let e of E){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let g=await enrichDirectoryRecursive(S?`${S}/${e.name}`:e.name,t-1,s);D.push(g)}return D.length>0&&(g.subfolders=D),g}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function mergePatch(e,t){let s={...e};for(let[e,g]of Object.entries(t))if(g!==void 0){if(isEmpty$1(g)){delete s[e];continue}s[e]=g}return s}function dropEmpties(e){let t={};for(let[s,g]of Object.entries(e))g!=null&&(typeof g==`string`&&g===``||Array.isArray(g)&&g.length===0||(t[s]=g));return t}function isEmpty$1(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$1(t,w),action:`deleted`}):{ok:!0,path:relPathOf$1(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$1(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$1(e,t){return t.startsWith(e+sep)?t.slice(e.length+1).split(sep).join(`/`):t}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=/^[A-Za-z0-9_-]+$/;function applyTemplateWrite(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let s=validateTitle(e.frontmatter.title);if(!s.ok)return{ok:!1,error:s.error};let g=validateSubstitutionAllowlist(e.body);if(!g.ok)return{ok:!1,error:g.error};let{templatesDir:S,filePath:w}=templatePaths(e.projectDir,t.folderRel,e.name),E=serializeFrontmatter(e.frontmatter),D=E?`---\n${E}---\n${e.body}`:e.body;try{mkdirSync(S,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${relPathOf(e.projectDir,S)}: ${t.message}`}}}let O=!existsSync(w),k=`${w}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(k,D,`utf-8`),renameSync(k,w)}catch(t){try{unlinkSync(k)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${relPathOf(e.projectDir,w)}: ${t.message}`}}}let j=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&j.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,path:relPathOf(e.projectDir,w),created:O,warnings:j}}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 serializeFrontmatter(e){let t={};return e.title!==void 0&&(t.title=e.title),e.description!==void 0&&(t.description=e.description),Array.isArray(e.tags)&&e.tags.length>0&&(t.tags=e.tags),Object.keys(t).length===0?``:(0,import_dist$1.stringify)(t)}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$7=()=>getLogger(`http`);function successResponse(e,t,s,g,S={}){if(e.headersSent||e.writableEnded||e.destroyed){log$7().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$7().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$7().error({event:`api.success.unserializable-body`,bodyKeys:typeof w.data==`object`&&w.data!==null?Object.keys(w.data):null,handler:S.handler,originalStatus:t,err:s},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(E)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,s=e.now??Date.now,g=e.ttlMs??6e4;async function S(S){let w=t.get(S);if(w?.status===`resolved`&&w.expiresAt>s())return w.installed;if(w?.status===`inflight`)return w.promise;let E=(async()=>{try{let w=await e.probe(S);return t.set(S,{status:`resolved`,installed:w,expiresAt:s()+g}),w}catch{return t.set(S,{status:`resolved`,installed:!1,expiresAt:s()+g}),!1}})();return t.set(S,{status:`inflight`,promise:E}),E}async function w(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await S(e)]));return Object.fromEntries(e)}return{probeAll:w,probeWithCache:S}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let s=e.headers.origin;if(typeof s==`string`&&s.length>0)try{return isLoopbackHostname(new URL(s).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await s():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return s=>e===`darwin`?probeMacOs(s,t):e===`win32`?probeWindows(s,t):probeLinux(s,t)}function probeMacOs(e,t){let s=MACOS_APP_NAMES[e];function g(e){return new Promise(s=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}return(async()=>{for(let e of s)if(await g(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(s=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{s(!e)})})}function probeLinux(e,t){return new Promise(s=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let s=[],g=0,S=AbortSignal.timeout(t.timeoutMs),w=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));S.addEventListener(`abort`,w,{once:!0});try{for await(let S of e){if(g+=S.length,g>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);s.push(S)}return Buffer.concat(s)}finally{S.removeEventListener(`abort`,w)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,s,g={}){let S=e.safeParse(t);if(S.success)return{ok:!0,value:S.data};let w=S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(s,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:g.handler,detail:w}),{ok:!1}}function withValidation(e,t,s={}){return async(g,S)=>{if(s.method!==void 0&&g.method!==s.method){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:s.handler,extraHeaders:{Allow:s.method}});return}if(s.preBodyGate!==void 0&&!s.preBodyGate(g,S)){!S.headersSent&&!S.writableEnded&&!S.destroyed&&errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(s.skipBodyParse){let w=validateBody(e,{},S,s);if(!w.ok)return;await t(g,S,w.value);return}let w;try{w=await readRequestBody(g)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(S,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(S,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s.handler,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s.handler,cause:e});return}let E;try{E=w.length===0?{}:JSON.parse(w.toString(`utf8`))}catch(e){errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:s.handler,cause:e});return}let D=validateBody(e,E,S,s);D.ok&&await t(g,S,D.value)}}function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,s){return new Promise(g=>{let S=!1,w=e=>{S||(S=!0,g(e))},E=setTimeout(()=>w({ok:!1,reason:`timeout`}),s);try{let s=spawn(e,[...t],{detached:!0,stdio:`ignore`,shell:!1});s.once(`error`,e=>{clearTimeout(E),w(classifySpawnError(e))}),s.once(`spawn`,()=>{if(!S){try{s.unref()}catch{}clearTimeout(E),w({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(E),w(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let w=typeof S.path==`string`?S.path:``;if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(w,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let E=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!E){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let D=resolveCursorSpawnInvocation(E,w,s.platform),O=await(s.spawnDetached??spawnDetached)(D.exec,D.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(O.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(O.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(O.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let s of t){let t=s(e);try{return await access(t,constants$1.X_OK),t}catch(e){let s=e?.code;s!==`ENOENT`&&s!==`EACCES`&&s!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,s,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],{timeout:e,encoding:`utf-8`},(e,s)=>{if(e){t(null);return}let g=s.split(/\r?\n/)[0]?.trim();t(g&&g.length>0?g:null)})})}function resolveCursorSpawnInvocation(e,t,s){return s===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:{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=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:`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`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}if(s.platform!==`darwin`){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Handoff is currently macOS-only.`,{handler:HANDLER});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;if(k.type===`app-bundle`){k.quitFirst&&(await F(`/usr/bin/osascript`,[`-e`,`tell application "${k.appName}" to quit`],SPAWN_TIMEOUT_MS).catch(()=>void 0),await j(QUIT_SETTLE_MS));let e=await F(`/usr/bin/open`,[`-a`,k.appName],SPAWN_TIMEOUT_MS);if(!e.ok){emitSpawnFailure(t,E,e.reason);return}await j(APP_BUNDLE_SETTLE_MS);let s=await F(`/usr/bin/open`,[D],SPAWN_TIMEOUT_MS);if(!s.ok){emitSpawnFailure(t,E,s.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 L=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!L){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let B=resolveCursorSpawnInvocation(L,O,s.platform),H=await F(B.exec,B.args,SPAWN_TIMEOUT_MS);if(!H.ok){emitSpawnFailure(t,E,H.reason);return}await j(CURSOR_SETTLE_MS);let q=await F(`/usr/bin/open`,[D],SPAWN_TIMEOUT_MS);if(!q.ok){emitSpawnFailure(t,E,q.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}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}`}function splitFrontmatterLines(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).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}}const PANE_TARGET_FILE=`pane-target.json`,PANE_TARGET_TTL_MS=3e4;function armPaneTarget(e,t,s=Date.now()){if(!t.startsWith(`#/`))return!1;tracedMkdirSync(e,{recursive:!0});let g={route:t,armedAtMs:s};return tracedWriteFileSync(resolve(e,PANE_TARGET_FILE),JSON.stringify(g)),!0}function readArmedPaneTarget(e,t=Date.now(),s=PANE_TARGET_TTL_MS){let g=resolve(e,PANE_TARGET_FILE);if(!existsSync(g))return null;try{let e=JSON.parse(readFileSync(g,`utf-8`));return typeof e.route!=`string`||typeof e.armedAtMs!=`number`||t-e.armedAtMs>s?null:e.route}catch(e){let t=e.code;return(t===`EACCES`||t===`EPERM`||t===`EIO`)&&process.stderr.write(`[pane-target] readArmedPaneTarget failed at ${g}: ${e instanceof Error?e.message:String(e)}\n`),null}}function clearArmedPaneTarget(e){let t=resolve(e,PANE_TARGET_FILE);if(existsSync(t))try{tracedUnlinkSync(t)}catch{}}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;getLogger(`share`).info({action:`construct-url`,result:e,...s===void 0?{}:{branchExists:s},...g===void 0?{}:{kind:g}},`share action`)}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 parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let s=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return s||(s=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)||(s=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),s)||(s=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)?{owner:s[1],repo:s[2]}: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);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}: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(`
827
827
  `).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 MAX_ZIP_BYTES=102400,BUNDLE_SKILL_NAME={discovery:`open-knowledge-discovery`,project:`open-knowledge`},DESKTOP_SKILLS_REL=`Open Knowledge.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 t=e.indexOf(`
828
828
  ---`,4);if(!e.startsWith(`---
829
829
  `)||t<0)return;let s=e.slice(4,t),g=s.search(/^metadata:/m);if(g<0)return;let S=s.slice(g).split(`
@@ -1691,29 +1691,77 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
1691
1691
  `,t-1)),S=[e.indexOf(`.`,s),e.indexOf(`?`,s),e.indexOf(`!`,s),e.indexOf(`
1692
1692
  `,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(e.slice(w,E));return k?`${D}${k}${O}`:null}function matchFence(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(e,t){let s=e.trimStart();if(e.length-s.length>3)return!1;let g=0;for(;s[g]===t.char;)g+=1;return g<t.length?!1:s.slice(g).trim().length===0}function leadingMarkdownPrefixLength(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode(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+=1;continue}let t=0;for(;e[S+t]==="`";)t+=1;if(t===s)return{text:e.slice(g,S),nextIndex:S+s};S+=t}return{text:e.slice(t,g),nextIndex:g}}function readWikiLink(e,t){WIKI_LINK_RE.lastIndex=t;let s=WIKI_LINK_RE.exec(e);if(!s)return null;let g=s[1]??``,S=g.trim(),w=s[2]?.trim()||null,E=s[3]??null,D=E?.trim()||null;if(!S)return null;let O=D??S,k=D?E:g,j=D?s[0].lastIndexOf(E??``):2,F=k?.indexOf(O)??0;return{target:S,alias:D,anchor:w,label:O,labelStart:t+j+Math.max(F,0),nextIndex:t+s[0].length}}function normalizeMarkdownHref(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function readMarkdownLink(e,t){MD_LINK_RE.lastIndex=t;let s=MD_LINK_RE.exec(e);return s?{text:s[1]??``,href:normalizeMarkdownHref(s[2]??``),nextIndex:t+s[0].length}:null}function readMarkdownImage(e,t){MD_IMAGE_RE.lastIndex=t;let s=MD_IMAGE_RE.exec(e);return s?{alt:s[1]??``,nextIndex:t+s[0].length}:null}function isWordBoundaryChar(e){return!e||!WORD_CHAR_RE.test(e)}function hasWholeWordBoundaries(e,t,s){return isWordBoundaryChar(e[t-1])&&isWordBoundaryChar(e[s])}function prepareSearchLabels(e){let t=[],s=new Set;for(let g of e.matchLabels){let e=g.trim();if(!e)continue;let S=e.toLocaleLowerCase();s.has(S)||(s.add(S),t.push({raw:e,lower:S,length:e.length}))}return t.sort((e,t)=>t.length===e.length?e.raw.localeCompare(t.raw):t.length-e.length)}function findSegmentMatches(e,t){let s=e.toLocaleLowerCase(),g=[];for(let S of t){let t=0;for(;t<=s.length-S.length;){let w=s.indexOf(S.lower,t);if(w===-1)break;let E=w+S.length;hasWholeWordBoundaries(e,w,E)&&g.push({start:w,end:E}),t=w+1}}g.sort((e,t)=>{if(e.start!==t.start)return e.start-t.start;let s=e.end-e.start,g=t.end-t.start;return g===s?e.end-t.end:g-s});let S=[],w=null;for(let e of g)w&&e.start<w.end||(S.push(e),w=e);return S}function contiguousOffsets(e,t){let s=[];for(let g=0;g<t.length;g+=1)s.push(e+g);return s}function wikiLinkResolvesToTarget(e,t){let s=e.trim();return s?s===t||toWikiLinkSlug(s)===t:!1}function scanLineForMentions(e,t,s,g,S){let w=``,E=[],D=``,O=[];function k(){D&&(E.push({flatStart:w.length,text:D,sourceOffsets:O}),w+=D,D=``,O=[])}function j(e,t){D+=e,O.push(t)}function F(e){k(),w+=e}function L(e,t){k(),e&&(E.push({flatStart:w.length,text:e,sourceOffsets:t}),w+=e)}let B=leadingMarkdownPrefixLength(e);for(;B<e.length;){if(e[B]===`\\`&&B+1<e.length){j(e[B+1]??``,t+B+1),B+=2;continue}if(e[B]==="`"){let t=readInlineCode(e,B);if(t){F(t.text),B=t.nextIndex;continue}}if(e[B]===`!`&&e[B+1]===`[`){let t=readMarkdownImage(e,B);if(t){F(t.alt),B=t.nextIndex;continue}}if(e[B]===`[`&&e[B+1]===`[`){let s=readWikiLink(e,B);if(s){let e=s.label;wikiLinkResolvesToTarget(s.target,g)?F(e):L(e,contiguousOffsets(t+s.labelStart,e)),B=s.nextIndex;continue}}if(e[B]===`[`&&e[B-1]!==`!`){let S=readMarkdownLink(e,B);if(S){resolveInternalHref(S.href,s)?.docName===g?F(S.text):L(S.text,contiguousOffsets(t+B+1,S.text)),B=S.nextIndex;continue}}j(e[B]??``,t+B),B+=1}k();let H=[];for(let e of E){let t=findSegmentMatches(e.text,S);for(let s of t){let t=e.flatStart+s.start,g=e.flatStart+s.end,S=snippetAround(w,t,g)??e.text.slice(s.start,s.end),E=e.sourceOffsets[s.start];typeof E==`number`&&H.push({excerpt:S,offset:E})}}return H}function scanMarkdownForMentions(e,t,s,g){let{frontmatter:S,body:w}=stripFrontmatter(e),E=S.length,D=[],O=null,k=0,j=0;for(;j<=w.length;){let e=w[j];if(!(j===w.length||e===`
1693
1693
  `||e===`\r`)){j+=1;continue}let S=w.slice(k,j);if(O)isFenceClose(S,O)&&(O=null);else{let e=matchFence(S);e?O=e:D.push(...scanLineForMentions(S,E+k,t,s,g))}if(j===w.length)break;if(e===`\r`&&w[j+1]===`
1694
- `){j+=2,k=j;continue}j+=1,k=j}return D}function serializeLiveDocument$1(e){return e.getText(`source`).toString()}async function readDocumentMarkdown(e,t,s){let g=e.documents.get(t);if(g)try{return serializeLiveDocument$1(g)}catch(e){return log$5.warn({docName:t,err:e},`[suggest-links] Failed live serialization, falling back to live source text`),g.getText(`source`).toString()}return await readFile$1(s.canonicalPath,`utf-8`)}function toPublicTarget(e){return{docName:e.docName,title:e.title,aliases:e.aliases}}async function suggestLinks(e){let{hocuspocus:t,fileIndex:s,docName:g,scanBudgetMs:S=500,now:w=()=>Date.now(),onComplete:E}=e,D=w(),O=s.get(g);if(!O)throw new SuggestLinksTargetNotFoundError(g);let k=extractPageIdentity(await readDocumentMarkdown(t,g,O),g),j=prepareSearchLabels(k),F=[...s.keys()].filter(e=>e!==g).sort((e,t)=>e.localeCompare(t)),L=new Map,B=!1;for(let e of F){if(w()-D>S){B=!0;break}let E=s.get(e);if(!E)continue;let O;try{O=await readDocumentMarkdown(t,e,E)}catch(t){log$5.warn({docName:e,err:t},`[suggest-links] Failed to read source doc`);continue}let k=scanMarkdownForMentions(O,e,g,j).map(t=>({source:e,excerpt:t.excerpt,offset:t.offset}));k.length>0&&L.set(e,k)}let H=[...L.entries()].sort(([e,t],[s,g])=>g.length===t.length?e===s?(t[0]?.offset??2**53-1)-(g[0]?.offset??2**53-1):e.localeCompare(s):g.length-t.length).flatMap(([,e])=>e),q=w()-D,J={durationMs:q,corpusDocCount:F.length,candidateCount:H.length,truncated:B};return log$5.info({docName:g,durationMs:q,corpusDocCount:F.length,candidateCount:H.length,truncated:B,labelCount:j.length,normalizedTarget:toWikiLinkSlug(k.title)},`[suggest-links] scan completed`),E?.(J),{target:toPublicTarget(k),mentions:H,truncated:B}}const GIT_LOG_FORMAT=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,EMPTY={entries:[],total:0,hasMore:!1};function classifyType(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`import:`)||e.startsWith(`upstream:`)?`upstream`:e.startsWith(`park:`)?`park`:`wip`}function parseGitLogOutput(e){return e.trim()?e.split(``).map(e=>{let t=e.trimStart();if(!t)return null;let[s=``,g=``,S=``,w=``,E=``,D=``]=t.split(`\0`),O=classifyType(E);return{sha:s.trim(),timestamp:g,author:S,authorEmail:w,type:O,message:E,contributors:readContributors(D),checkpoint:O===`checkpoint`?parseCheckpoint(D):null,rawBody:D}}).filter(e=>e!==null&&e.sha.length===40):[]}function toArray(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}let _chainDepthHist=null;function chainDepthHist(){return _chainDepthHist||=getMeter().createHistogram(`rename.predecessor_chain_depth_histogram`,{description:`Predecessor chain depth observed per timeline query`}),_chainDepthHist}let _transientSkipCounter=null;function transientSkipCounter(){return _transientSkipCounter||=getMeter().createCounter(`rename.transient_skip_total`,{description:`Count of empty-commitSha entries encountered (lazy-population transient skip)`}),_transientSkipCounter}function matchesAuthor(e,t){return t.length===0?!0:t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}function filterEntriesByOkActorDocs(e,t,s){return e.length===0||t.length===0?e:e.filter(e=>{let g=parseOkActors(e.rawBody);if(g.length===0)return!0;let S=new Set;for(let e of g){for(let t of e.docs)S.add(t);if(e.previous_paths)for(let t of e.previous_paths)S.add(t.from),S.add(t.to)}if(S.size===0)return!0;for(let g=0;g<t.length;g++){let w=t[g],E=s[g];if(!(E!==null&&!E.has(e.sha))&&S.has(w.path))return!0}return!1})}async function filterEntriesByChain(e,t,s,g,S,w,E){if(t.length===0||s.length===0)return t;let D=await Promise.all(s.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,g,E);return s.length===0?new Set:buildAncestorShaSet(e,s,g,w)})),O=[];for(let e=0;e<t.length;e++){let g=t[e];for(let t=0;t<s.length;t++){let w=s[t],E=D[t];E!==null&&!E.has(g.sha)||O.push({entryIdx:e,sha:g.sha,path:S(w.path)})}}if(O.length===0)return[];let k=await batchCheckExistence(e,O.map(e=>({sha:e.sha,path:e.path}))),j=new Set;for(let e=0;e<O.length;e++)k[e]&&j.add(O[e].entryIdx);return t.filter((e,t)=>j.has(t))}async function getDocumentHistory(e,t,s=`.`,g){if(!existsSync(e.workTree)||!existsSync(e.gitDir)||t.docName&&(t.docName.includes(`..`)||t.docName.includes(`\0`)))return EMPTY;let S=t.branch??`main`,w=Math.max(1,t.limit??50),E=Math.max(0,t.offset??0),D=toArray(t.type),O=toArray(t.author),k=toArray(t.excludeAuthor),j=s===`.`?``:s.replace(/^\.\//,``),F=e=>j?`${j}/${e}${getDocExtension(e)}`:`${e}${getDocExtension(e)}`,L=t.docName?F(t.docName):void 0;try{let s=g?.renameLogIndex??getOrLoadRenameLogIndex(e.gitDir),{chain:j,skipped:B}=await withSpan(`rename.expandPredecessors`,void 0,async()=>t.docName?expandPredecessors(t.docName,S,s):{chain:[],skipped:0}),H=j.length>1;t.docName&&chainDepthHist().record(j.length),B>0&&transientSkipCounter().add(B);let q=createSeedsCache(),J=createAncestorShaSetCache(),Y=shadowGit(e);if(D.length===1&&D[0]===`checkpoint`){let t=(await Y.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${S}/`)).trim().split(`
1694
+ `){j+=2,k=j;continue}j+=1,k=j}return D}function serializeLiveDocument$1(e){return e.getText(`source`).toString()}async function readDocumentMarkdown(e,t,s){let g=e.documents.get(t);if(g)try{return serializeLiveDocument$1(g)}catch(e){return log$5.warn({docName:t,err:e},`[suggest-links] Failed live serialization, falling back to live source text`),g.getText(`source`).toString()}return await readFile$1(s.canonicalPath,`utf-8`)}function toPublicTarget(e){return{docName:e.docName,title:e.title,aliases:e.aliases}}async function suggestLinks(e){let{hocuspocus:t,fileIndex:s,docName:g,scanBudgetMs:S=500,now:w=()=>Date.now(),onComplete:E}=e,D=w(),O=s.get(g);if(!O)throw new SuggestLinksTargetNotFoundError(g);let k=extractPageIdentity(await readDocumentMarkdown(t,g,O),g),j=prepareSearchLabels(k),F=[...s.keys()].filter(e=>e!==g).sort((e,t)=>e.localeCompare(t)),L=new Map,B=!1;for(let e of F){if(w()-D>S){B=!0;break}let E=s.get(e);if(!E)continue;let O;try{O=await readDocumentMarkdown(t,e,E)}catch(t){log$5.warn({docName:e,err:t},`[suggest-links] Failed to read source doc`);continue}let k=scanMarkdownForMentions(O,e,g,j).map(t=>({source:e,excerpt:t.excerpt,offset:t.offset}));k.length>0&&L.set(e,k)}let H=[...L.entries()].sort(([e,t],[s,g])=>g.length===t.length?e===s?(t[0]?.offset??2**53-1)-(g[0]?.offset??2**53-1):e.localeCompare(s):g.length-t.length).flatMap(([,e])=>e),q=w()-D,J={durationMs:q,corpusDocCount:F.length,candidateCount:H.length,truncated:B};return log$5.info({docName:g,durationMs:q,corpusDocCount:F.length,candidateCount:H.length,truncated:B,labelCount:j.length,normalizedTarget:toWikiLinkSlug(k.title)},`[suggest-links] scan completed`),E?.(J),{target:toPublicTarget(k),mentions:H,truncated:B}}const GIT_LOG_FORMAT=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,EMPTY={entries:[],total:0,hasMore:!1},FOLDER_ARTIFACT_SUBJECT_RE=/^(template-(create|edit|rename|move|delete)|folder-frontmatter-(edit|delete)|folder-create): /;function isFolderArtifactSubject(e){return FOLDER_ARTIFACT_SUBJECT_RE.test(e)}function classifyType(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`import:`)||e.startsWith(`upstream:`)?`upstream`:e.startsWith(`park:`)?`park`:`wip`}function parseGitLogOutput(e){return e.trim()?e.split(``).map(e=>{let t=e.trimStart();if(!t)return null;let[s=``,g=``,S=``,w=``,E=``,D=``]=t.split(`\0`),O=classifyType(E);return{sha:s.trim(),timestamp:g,author:S,authorEmail:w,type:O,message:E,contributors:readContributors(D),checkpoint:O===`checkpoint`?parseCheckpoint(D):null,rawBody:D}}).filter(e=>e!==null&&e.sha.length===40):[]}function toArray(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}let _chainDepthHist=null;function chainDepthHist(){return _chainDepthHist||=getMeter().createHistogram(`rename.predecessor_chain_depth_histogram`,{description:`Predecessor chain depth observed per timeline query`}),_chainDepthHist}let _transientSkipCounter=null;function transientSkipCounter(){return _transientSkipCounter||=getMeter().createCounter(`rename.transient_skip_total`,{description:`Count of empty-commitSha entries encountered (lazy-population transient skip)`}),_transientSkipCounter}function matchesAuthor(e,t){return t.length===0?!0:t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}function filterEntriesByOkActorDocs(e,t,s){return e.length===0||t.length===0?e:e.filter(e=>{let g=parseOkActors(e.rawBody);if(g.length===0)return!0;let S=new Set;for(let e of g){for(let t of e.docs)S.add(t);if(e.previous_paths)for(let t of e.previous_paths)S.add(t.from),S.add(t.to)}if(S.size===0)return!0;for(let g=0;g<t.length;g++){let w=t[g],E=s[g];if(!(E!==null&&!E.has(e.sha))&&S.has(w.path))return!0}return!1})}async function filterEntriesByChain(e,t,s,g,S,w,E){if(t.length===0||s.length===0)return t;let D=await Promise.all(s.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,g,E);return s.length===0?new Set:buildAncestorShaSet(e,s,g,w)})),O=[];for(let e=0;e<t.length;e++){let g=t[e];for(let t=0;t<s.length;t++){let w=s[t],E=D[t];E!==null&&!E.has(g.sha)||O.push({entryIdx:e,sha:g.sha,path:S(w.path)})}}if(O.length===0)return[];let k=await batchCheckExistence(e,O.map(e=>({sha:e.sha,path:e.path}))),j=new Set;for(let e=0;e<O.length;e++)k[e]&&j.add(O[e].entryIdx);return t.filter((e,t)=>j.has(t))}async function getDocumentHistory(e,t,s=`.`,g){if(!existsSync(e.workTree)||!existsSync(e.gitDir)||t.docName&&(t.docName.includes(`..`)||t.docName.includes(`\0`)))return EMPTY;let S=t.branch??`main`,w=Math.max(1,t.limit??50),E=Math.max(0,t.offset??0),D=toArray(t.type),O=toArray(t.author),k=toArray(t.excludeAuthor),j=s===`.`?``:s.replace(/^\.\//,``),F=e=>j?`${j}/${e}${getDocExtension(e)}`:`${e}${getDocExtension(e)}`,L=t.docName?F(t.docName):void 0;try{let s=g?.renameLogIndex??getOrLoadRenameLogIndex(e.gitDir),{chain:j,skipped:B}=await withSpan(`rename.expandPredecessors`,void 0,async()=>t.docName?expandPredecessors(t.docName,S,s):{chain:[],skipped:0}),H=j.length>1;t.docName&&chainDepthHist().record(j.length),B>0&&transientSkipCounter().add(B);let q=createSeedsCache(),J=createAncestorShaSetCache(),Y=shadowGit(e);if(D.length===1&&D[0]===`checkpoint`){let t=(await Y.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${S}/`)).trim().split(`
1695
1695
  `).filter(e=>e.length===40),s=[];if(S!==`main`)try{s=(await Y.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
1696
1696
  `).filter(e=>e.length===40)}catch{}let g=[...t,...s];if(g.length===0)return EMPTY;let D=parseGitLogOutput(await Y.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...g)).map(e=>({...e,type:`checkpoint`}));if(L){let t=createAncestorShaSetCache();D=await filterEntriesByChain(e,D,j,S,F,t,q)}if(S!==`main`&&t.length>0&&s.length>0){let e=new Set(t),s=D.filter(t=>e.has(t.sha)),g=D.filter(t=>!e.has(t.sha)),S=s.reduce((e,t)=>Math.min(e,new Date(t.timestamp).getTime()),1/0);D=[...s,...g.filter(e=>new Date(e.timestamp).getTime()<S)]}let B=D.filter(e=>matchesAuthor(e,O)&&(k.length===0||!matchesAuthor(e,k))),H=B.length;return{entries:B.slice(E,E+w).map(({rawBody:e,...t})=>t),total:H,hasMore:E+w<H}}let ee=[],te=[],ne=S!==`main`;try{let e=(await Y.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${S}/`)).trim().split(`
1697
1697
  `).filter(e=>e.length===40);ee.push(...e)}catch{}let ae=[];if(ne)try{ae=(await Y.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
1698
1698
  `).filter(e=>e.length===40)}catch{}try{let e=(await Y.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/${S}/`)).trim().split(`
1699
1699
  `).filter(Boolean);te.push(...e)}catch{}if(ne&&te.length===0)try{let e=(await Y.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/main/`)).trim().split(`
1700
- `).filter(Boolean);te.push(...e)}catch{}if(te.length===0&&ee.length===0&&ae.length===0)return EMPTY;let oe=[...ee,...ae],se=[];if(oe.length>0){let t=parseGitLogOutput(await Y.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...oe)).map(e=>({...e,type:`checkpoint`}));if(L&&(t=await filterEntriesByChain(e,t,j,S,F,J,q)),ne&&ee.length>0&&ae.length>0){let e=new Set(ee),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);se=[...s,...g.filter(e=>new Date(e.timestamp).getTime()<S)]}else se=t}let ce=[...te];for(let e of oe)ce.push(e);let ue=[];if(ce.length>0&&(ue=parseGitLogOutput(await Y.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...ce,...L?[`--`,L]:[])),H))for(let t=0;t<j.length-1;t++){let s=j[t];if(s.renameCommit!==null)try{let t=await buildSeeds(e,s.renameCommit,S,q);if(t.length===0)continue;let g=F(s.path),w=await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`],t,g);ue=[...ue,...parseGitLogOutput(w)]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${s.path}); skipping:`,e)}}let de=[...se,...ue],fe=new Set,me=[];for(let e of de)fe.has(e.sha)||(fe.add(e.sha),me.push(e));let ge=me;me.length>0&&j.length>0&&(ge=filterEntriesByOkActorDocs(me,j,await Promise.all(j.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,S,q);return s.length===0?new Set:buildAncestorShaSet(e,s,S,J)})))),ge.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let _e=ge;_e=_e.filter(e=>e.type!==`park`),D.length>0&&(_e=_e.filter(e=>D.includes(e.type))),O.length>0&&(_e=_e.filter(e=>matchesAuthor(e,O))),k.length>0&&(_e=_e.filter(e=>!matchesAuthor(e,k)));let ve=_e.length;return{entries:_e.slice(E,E+w).map(({rawBody:e,...t})=>t),total:ve,hasMore:E+w<ve}}catch(e){return console.warn(`[timeline] getDocumentHistory 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}function recordContentDivergenceGate(e,t){agentWriteGateFiredCounter().add(1,{handler:e}),t!==void 0&&agentWriteContentDivergenceCounter().add(1,{handler:e,divergence_type:t.divergenceType})}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$4=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=getDocExtension(e);return{path:s?`${s}/${e}${g}`:`${e}${g}`}}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=!1,L=(e,t)=>{if(!w){if(w=!0,k)try{unlinkSync(k)}catch{}g(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},B=classifyUploadErrno;S.on(`field`,(e,t)=>{e===`parentDocName`&&(O=t)}),S.on(`file`,(e,g,S)=>{F=!0,E=S.filename||`upload`,D=S.mimeType||``;let H;try{H=mintTempUploadPath(t)}catch(e){L(B(e),e),g.resume();return}k=H;let q=new HashingPassThrough;pipeline(g,q,createWriteStream(H)).then(()=>{w||(w=!0,s({filename:E,mimeType:D,parentDocName:O,tempPath:H,sha:q.digest(),byteLength:q.byteLength()}))}).catch(e=>{j=e,L(B(e),e)})}),S.on(`error`,e=>{L(`urn:ok:error:malformed-upload`,e)}),S.on(`close`,()=>{w||j||F||(w=!0,s({filename:``,mimeType:``,parentDocName:O,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{w||j||e.complete||L(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(S)})}function safeSubdir(e,t){let s=resolve(e,t);if(s!==e&&!s.startsWith(`${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}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,getDocExtension:S,maxEntries:w,signal:E}=e,D=e.maxDepth??1/0;showAllWalkInvocations+=1;let O=0,k=!1,j=!1,F=e=>g?e===g||e.startsWith(`${g}/`):!0,L;try{L=await realpath(t)}catch{L=t}let B=e=>e===L?!0:e.startsWith(`${L}/`);async function H(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,{bypassFilters:!0}))continue;try{if(!B(await realpath(`${e}/${S.name}`)))continue}catch{continue}return!0}if(S.isFile()&&!s.isExcluded(g,{bypassFilters:!0}))return!0}return!1}async function*q(e,t,g){let L;try{L=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[document-list][showAll] readdir failed for ${e}:`,t);return}for(let J of L){if(E?.aborted){j=!0;return}if(O>=w){k=!0;return}let L=t?`${t}/${J.name}`:J.name;if(J.isDirectory()){if(s.isDirExcluded(L,{bypassFilters:!0}))continue;let t=`${e}/${J.name}`,S;try{S=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!B(S)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${S}`);continue}if(F(L)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}O+=1;let s=g>=D?await H(t,L):void 0;yield{kind:`folder`,path:L,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...s===void 0?{}:{hasChildren:s}}}g<D&&(yield*q(t,L,g+1));continue}if(!J.isFile()||s.isExcluded(L,{bypassFilters:!0})||!F(L))continue;let Y=null;try{Y=await stat$1(`${e}/${J.name}`)}catch(t){console.warn(`[document-list][showAll] stat failed for ${e}/${J.name}:`,t);continue}if(isSupportedDocFile(J.name)){let e=L.replace(/\.(md|mdx)$/i,``),t=S(e);O+=1,yield{kind:`document`,docName:e,docExt:t,size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let ee=synthesizeShowAllAssetExt(J.name),te=ASSET_EXTENSIONS.has(ee)?mediaKindForSidebarAssetExtension(ee):null;O+=1,yield{kind:`asset`,docName:L,docExt:ee,path:L,assetExt:ee,mediaKind:te,referencedBy:[],size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}return yield*q(g?`${t}/${g}`:t,g??``,1),j&&(showAllWalkAborts+=1),{truncated:k}}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===`.ok`||e.startsWith(`.ok/`)||e===`.git`||e.startsWith(`.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`?isSupportedDocFile(s)?s:`${s}${getDocExtension(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 SUPPORTED_DOC_EXTENSIONS.some(s=>existsSync(resolve(e,`${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(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){S(w,E);continue}!s.isFile()||!isSupportedDocFile(E)||g.push({docName:stripDocExtension(E),fullPath:w,content:readFileSync(w,`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);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 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 t=e;if(e.startsWith(`---
1700
+ `).filter(Boolean);te.push(...e)}catch{}if(te.length===0&&ee.length===0&&ae.length===0)return EMPTY;let oe=[...ee,...ae],se=[];if(oe.length>0){let t=parseGitLogOutput(await Y.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...oe)).map(e=>({...e,type:`checkpoint`}));if(L&&(t=await filterEntriesByChain(e,t,j,S,F,J,q)),ne&&ee.length>0&&ae.length>0){let e=new Set(ee),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);se=[...s,...g.filter(e=>new Date(e.timestamp).getTime()<S)]}else se=t}let ce=[...te];for(let e of oe)ce.push(e);let ue=[];if(ce.length>0&&(ue=parseGitLogOutput(await Y.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...ce,...L?[`--`,L]:[])),H))for(let t=0;t<j.length-1;t++){let s=j[t];if(s.renameCommit!==null)try{let t=await buildSeeds(e,s.renameCommit,S,q);if(t.length===0)continue;let g=F(s.path),w=await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`],t,g);ue=[...ue,...parseGitLogOutput(w)]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${s.path}); skipping:`,e)}}let de=[...se,...ue],fe=new Set,me=[];for(let e of de)fe.has(e.sha)||(fe.add(e.sha),me.push(e));let ge=me;me.length>0&&j.length>0&&(ge=filterEntriesByOkActorDocs(me,j,await Promise.all(j.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,S,q);return s.length===0?new Set:buildAncestorShaSet(e,s,S,J)})))),ge.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let _e=ge;_e=_e.filter(e=>e.type!==`park`),D.length>0&&(_e=_e.filter(e=>D.includes(e.type))),O.length>0&&(_e=_e.filter(e=>matchesAuthor(e,O))),k.length>0&&(_e=_e.filter(e=>!matchesAuthor(e,k)));let ve=_e.length;return{entries:_e.slice(E,E+w).map(({rawBody:e,...t})=>t),total:ve,hasMore:E+w<ve}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),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(`
1701
+ `).filter(Boolean);e.push(...s)}catch{}if(e.length===0)return EMPTY;let t=await j.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...e,`--`,k),s=O?`${O}/.ok/`:`.ok/`,g=new Set,D=[];for(let e of parseGitLogOutput(t)){if(g.has(e.sha)||!isFolderArtifactSubject(e.message)||!e.contributors.some(e=>e.docs.some(e=>e.startsWith(s))))continue;g.add(e.sha);let{rawBody:t,...S}=e;D.push(S)}let F=D.length;return{entries:D.slice(E,E+w),total:F,hasMore:E+w<F}}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}function recordContentDivergenceGate(e,t){agentWriteGateFiredCounter().add(1,{handler:e}),t!==void 0&&agentWriteContentDivergenceCounter().add(1,{handler:e,divergence_type:t.divergenceType})}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$4=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=getDocExtension(e);return{path:s?`${s}/${e}${g}`:`${e}${g}`}}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=!1,L=(e,t)=>{if(!w){if(w=!0,k)try{unlinkSync(k)}catch{}g(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},B=classifyUploadErrno;S.on(`field`,(e,t)=>{e===`parentDocName`&&(O=t)}),S.on(`file`,(e,g,S)=>{F=!0,E=S.filename||`upload`,D=S.mimeType||``;let H;try{H=mintTempUploadPath(t)}catch(e){L(B(e),e),g.resume();return}k=H;let q=new HashingPassThrough;pipeline(g,q,createWriteStream(H)).then(()=>{w||(w=!0,s({filename:E,mimeType:D,parentDocName:O,tempPath:H,sha:q.digest(),byteLength:q.byteLength()}))}).catch(e=>{j=e,L(B(e),e)})}),S.on(`error`,e=>{L(`urn:ok:error:malformed-upload`,e)}),S.on(`close`,()=>{w||j||F||(w=!0,s({filename:``,mimeType:``,parentDocName:O,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{w||j||e.complete||L(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(S)})}function safeSubdir(e,t){let s=resolve(e,t);if(s!==e&&!s.startsWith(`${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}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,getDocExtension:S,maxEntries:w,signal:E}=e,D=e.maxDepth??1/0;showAllWalkInvocations+=1;let O=0,k=!1,j=!1,F=e=>g?e===g||e.startsWith(`${g}/`):!0,L;try{L=await realpath(t)}catch{L=t}let B=e=>e===L?!0:e.startsWith(`${L}/`);async function H(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,{bypassFilters:!0}))continue;try{if(!B(await realpath(`${e}/${S.name}`)))continue}catch{continue}return!0}if(S.isFile()&&!s.isExcluded(g,{bypassFilters:!0}))return!0}return!1}async function*q(e,t,g){let L;try{L=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[document-list][showAll] readdir failed for ${e}:`,t);return}for(let J of L){if(E?.aborted){j=!0;return}if(O>=w){k=!0;return}let L=t?`${t}/${J.name}`:J.name;if(J.isDirectory()){if(s.isDirExcluded(L,{bypassFilters:!0}))continue;let t=`${e}/${J.name}`,S;try{S=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!B(S)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${S}`);continue}if(F(L)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}O+=1;let s=g>=D?await H(t,L):void 0;yield{kind:`folder`,path:L,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...s===void 0?{}:{hasChildren:s}}}g<D&&(yield*q(t,L,g+1));continue}if(!J.isFile()||s.isExcluded(L,{bypassFilters:!0})||!F(L))continue;let Y=null;try{Y=await stat$1(`${e}/${J.name}`)}catch(t){console.warn(`[document-list][showAll] stat failed for ${e}/${J.name}:`,t);continue}if(isSupportedDocFile(J.name)){let e=L.replace(/\.(md|mdx)$/i,``),t=S(e);O+=1,yield{kind:`document`,docName:e,docExt:t,size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let ee=synthesizeShowAllAssetExt(J.name),te=ASSET_EXTENSIONS.has(ee)?mediaKindForSidebarAssetExtension(ee):null;O+=1,yield{kind:`asset`,docName:L,docExt:ee,path:L,assetExt:ee,mediaKind:te,referencedBy:[],size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}return yield*q(g?`${t}/${g}`:t,g??``,1),j&&(showAllWalkAborts+=1),{truncated:k}}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===`.ok`||e.startsWith(`.ok/`)||e===`.git`||e.startsWith(`.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`?isSupportedDocFile(s)?s:`${s}${getDocExtension(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 SUPPORTED_DOC_EXTENSIONS.some(s=>existsSync(resolve(e,`${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(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;if(s.isDirectory()){S(w,E);continue}!s.isFile()||!isSupportedDocFile(E)||g.push({docName:stripDocExtension(E),fullPath:w,content:readFileSync(w,`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);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 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 t=e;if(e.startsWith(`---
1701
1702
  `)||e.startsWith(`---\r
1702
1703
  `)){let s=e.indexOf(`
1703
1704
  ---`,3);s!==-1&&(t=e.slice(s+4))}let s=[],g=new Map,S=createCodeFenceTracker();for(let e of t.split(`
1704
1705
  `)){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 createApiExtension(e){let{hocuspocus:t,sessionManager:s,contentDir:g,serverInstanceId:S,getFileIndex:w,getFolderIndex:E,onReferencedAssetsCacheInvalidator:D,getAliasMap:O,rescanFiles:k,enableTestRoutes:j=!1,shadowRef:F,flushGitCommit:L,flushContributors:B,takeStoreFailure:H,takeStoreDivergence:q,markAgentWriteStore:J,getCurrentBranch:Y,getDiskAckSVs:ee,contentRoot:te,backlinkIndex:ne,tagIndex:ae,signalChannel:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,onAgentWrite:ue,getSyncEngine:de,localOpCliArgs:fe=[`open-knowledge`],projectDir:me,getPrincipal:ge,contentFilter:_e,installedAgentsProbe:ve,forceUnloadDocument:ye,ready:Ce,recentlyRemovedDocs:we,serializeDoc:Te}=e,De=createConcurrencyGuard(),je=new Map,Me=null;function Pe(){let e=E?.();return e instanceof Map?e:null}function Ie(e){let t=Pe();if(t)try{upsertFolderIndexEntry(t,g,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function Re(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)Ie(resolve(g,t.slice(0,e).join(`/`)))}function ze(e){let t=Pe();t&&removeFolderIndexEntries(t,e)}function Be(e,t){let s=Pe();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)&&Ie(e);return}for(let[e,t]of S)s.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(g,e)})}function Ve(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
1705
- `)}function Ue(){Me=null}D?.(Ue);let We=createInstalledAgentsProbe({probe:ve??createOsProbe(process.platform)});function Ge(e){if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,`${e}${getDocExtension(e)}`);return!s.startsWith(`${t}/`)&&s!==t?null:s}function Ke(e){let t=Ge(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Xe(e,t){return t.has(e)?Ke(e):e}let $e={cluster:void 0,category:void 0,tags:void 0};function nt(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;return Array.isArray(e.tags)?g=e.tags.length>0?e.tags:void 0:typeof e.tags==`string`&&e.tags&&(g=[e.tags]),{cluster:t,category:s,tags:g}}}}catch{}try{let t=Ge(e);if(!t||!existsSync(t))return $e;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):$e}catch{return $e}}function rt(e,t){return t.has(e)?nt(e):$e}function it(e){if(ne)try{if(ne.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$4.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 at(e){return O?.().get(e)??e}function st(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 Tt(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>L?.()).catch(e=>{log$4.warn({err:e},`[${s}] post-write flush failed`)})}async function Et(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(J?.(e),await t.debouncer.executeNow(s));let g=H?.(e)??null;return g?{kind:`failure`,failure:g}:q?.(e)?{kind:`divergence`}:null}function Dt(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 jt(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 Mt(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,hint:'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 Ft(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}return e}function It(){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 Lt=It(),Rt=e=>e.endsWith(`.`)?e:`${e}.`;function zt(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Rt(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Rt(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Rt(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Rt(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Rt(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Rt(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Rt(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 Bt(e){let g=new Map;for(let s of e){let e=t.documents.get(s);e&&g.set(s,e.getText(`source`).toString())}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),e&&(t.closeConnections(s),await(ye??t.unloadDocument.bind(t))(e))}return g}function Vt(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&tracedWriteFileSync(e,w,`utf-8`);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&&registerWrite(e,contentHash(E))}}function Ht(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 Ut(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 Wt(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),tracedWriteFileSync(s,t,`utf-8`),registerWrite(s,contentHash(t)),setReconciledBase(e,t);let S=w();S instanceof Map&&updateFileIndex({kind:`update`,path:s,docName:e,content:t},S)}function Kt(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=en(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 $t(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 en(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=$t(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=$t(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Mr(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=Ut(g);if(typeof s!=`string`)continue;let S=$t(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Fr(e){let s=de?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=`${s}${getDocExtension(s)}`,w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Ir(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?jr(S.docName,s):S;e.rewrites!==0&&(Wt(S.docName,e.markdown),ne?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Lr(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,ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function zr(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(_e?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||_e?.isExcluded(E))continue;let D=stripDocExtension(E);registerDocExtension(D,extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Br(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(_e?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||_e?.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 Vr(e,t){return Lt(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ne)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isSupportedDocFile(e)||isSupportedDocFile(S))throw new ManagedRenameInvalidRequestError(`Asset operations do not support markdown documents.`);if(!isSupportedAssetFile(e,ASSET_EXTENSIONS)||!isSupportedAssetFile(S,ASSET_EXTENSIONS))throw new ManagedRenameInvalidRequestError(`Asset operations require supported asset extensions.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(_e?.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=Mr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Fr(O.map(e=>e.docName)),await renameTrackedPathInGit(me,w,E)||renamePathOnDisk(w,E);let k=Ir(O,D);return ne.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),oe?.(`files`),k.length>0&&(oe?.(`backlinks`),oe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Hr(e,s,S,E){return Lt(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ne)throw new BacklinkIndexRequiredError;let O=resolveContentEntryPath(g,S,e),k=resolveContentEntryPath(g,S,s);if(O===k)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(O))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(k)&&!isCaseOnlySelfCollision(O,k))throw new ManagedRenameDestinationExistsError;let j=statSync(O);if(S===`file`&&!j.isFile()||S===`folder`&&!j.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Br(O,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[stripDocExtension(e)]:zr(O)).map(t=>({from:t,to:S===`file`?stripDocExtension(s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Mr(L);Fr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(me,O,k)||renamePathOnDisk(O,k),Be(e,s),oe?.(`files`)),g.push(...Ir(t,L)),g.length>0&&(ne.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),oe?.(`backlinks`),oe?.(`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 ne.getBacklinks(e))H.has(t.source)||J.add(t.source);let ee=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ae=new Set,se=new Set,ce=[];for(let e of[...H.keys(),...ee]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){ce.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Ut(e);typeof s==`string`?(te.set(e,s),H.has(e)||ae.add(e)):H.has(e)||ce.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)??Ut(t);typeof e==`string`&&en(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),se.add(t),H.has(t)||ae.add(t))}}Fr(se);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ue=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Ht([...te.keys()],te)}),de=[],fe=[...ae].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(me??g,ue,async()=>{for(let e of ce)ne.deleteDocument(e);for(let e of fe){let s=t.documents.get(e)?Kt(e,H,L):en(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Wt(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ne.updateDocumentFromMarkdown(e,s.markdown)}if(we)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(we.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let D=resolveContentEntryPath(g,S,e),O=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(me,D,O)||renamePathOnDisk(D,O),S===`folder`&&Be(e,s);let k=await Bt([...H.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(F?.current){let e=F.current;withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},t=>{let s=randomUUID(),g=new Date().toISOString(),w=Y?.()??`main`,D=getOrLoadRenameLogIndex(e.gitDir),O=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},k=0;for(let{from:t,to:j}of B){let F={v:1,from:t,to:j,at:g,commitSha:``,branch:w,groupId:s,kind:S,actor:O};appendRenameLogEntry(e.gitDir,F,D,e),k+=1,E?.actor?recordContributor(j,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(t,j),E.actor.actorMetadata,void 0,[{from:t,to:j}]):recordContributor(j,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(t,j),void 0,void 0,[{from:t,to:j}])}t.setAttribute(`rename.entries_appended`,k)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let q=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of q){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),E=en(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Vt([{fromDocName:e,toDocName:t}],new Map([[e,E.markdown]])),setReconciledBase(t,E.markdown);let D=w();D instanceof Map&&updateFileIndex({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:E.markdown},D),ne.renameDocument(e,t,E.markdown),E.rewrites>0&&de.push({docName:t,rewrites:E.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`)}),ne.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),oe?.(`files`),oe?.(`backlinks`),oe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Ur(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 Wr(e){return{principalId:ge?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Gr(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 Kr(e){return{value:e.value}}function qr(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Jr(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=Gr(S),E=g||!w.response?w.response:Kr(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(),qr(S,!g);for(let{docName:e}of s)Tt(e,`rename-path`);return E}case`principal`:{let t=Gr(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)}qr(e.summary,!1);for(let{docName:e}of s)Tt(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)}`)}}}let Yr=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=at(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Ur(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}),J=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),Y=new Date().toISOString(),ee=typeof E.content==`string`?E.content:`Hello from the agent! ${Y}`,{response:te,stored:ne}=Gr(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ce?.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,`${ee}\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}): ${ee.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,Wr({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),qr(H)}finally{ce?.touchMode(O,`idle`)}let ae=await Et(D);if(ae?.kind===`failure`){Dt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){jt(w,`agent-write`);return}Tt(D,`agent-write`),ue?.();let oe=Mt(J);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:Y,...te?{summary:te}:{},...oe?{warning: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$4.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`}),Xr=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=at(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Ur(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:J,stored:Y}=Gr(q),ee=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);ce?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(ee.dc.document.getText(`source`),k,F,L),ee.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(ee.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),ee.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},ee.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,Wr({clientName:L,clientVersion:B,label:H}),Y),incrementAgentWriteCalls(),qr(q)}finally{ce?.touchMode(k,`idle`)}let oe=await Et(O);if(oe?.kind===`failure`){Dt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){jt(w,`agent-write-md`);return}Tt(O,`agent-write-md`),se?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),ue?.();let de=it(O),fe=st(O),me=vt();me===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let ge=Mt(te);successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:fe,systemSubscriberCount:me,...de?{hints:de}:{},...J?{summary:J}:{},...ae===void 0?ge?{warning:ge}:{}:{warning:toContentDivergenceWarning(ae)}},{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$4.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`}),Zr=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=at(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Ur(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),J=normalizeSummary(E.summary),{response:Y,stored:ee}=Gr(J),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,de=!1,fe=!1,me=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ce?.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))me.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
1706
+ `)}function Ue(){Me=null}D?.(Ue);let We=createInstalledAgentsProbe({probe:ve??createOsProbe(process.platform)});function Ge(e){if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,`${e}${getDocExtension(e)}`);return!s.startsWith(`${t}/`)&&s!==t?null:s}function Ke(e){let t=Ge(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Xe(e,t){return t.has(e)?Ke(e):e}let $e={cluster:void 0,category:void 0,tags:void 0};function nt(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;return Array.isArray(e.tags)?g=e.tags.length>0?e.tags:void 0:typeof e.tags==`string`&&e.tags&&(g=[e.tags]),{cluster:t,category:s,tags:g}}}}catch{}try{let t=Ge(e);if(!t||!existsSync(t))return $e;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):$e}catch{return $e}}function rt(e,t){return t.has(e)?nt(e):$e}function it(e){if(ne)try{if(ne.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$4.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 at(e){return O?.().get(e)??e}function st(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 Tt(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>L?.()).catch(e=>{log$4.warn({err:e},`[${s}] post-write flush failed`)})}async function Et(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(J?.(e),await t.debouncer.executeNow(s));let g=H?.(e)??null;return g?{kind:`failure`,failure:g}:q?.(e)?{kind:`divergence`}:null}function Dt(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 jt(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 Mt(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,hint:'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 Ft(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}return e}function It(){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 Lt=It(),Rt=e=>e.endsWith(`.`)?e:`${e}.`;function zt(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Rt(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Rt(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Rt(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Rt(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Rt(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Rt(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Rt(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 Bt(e){let g=new Map;for(let s of e){let e=t.documents.get(s);e&&g.set(s,e.getText(`source`).toString())}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),e&&(t.closeConnections(s),await(ye??t.unloadDocument.bind(t))(e))}return g}function Vt(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&tracedWriteFileSync(e,w,`utf-8`);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&&registerWrite(e,contentHash(E))}}function Ht(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 Ut(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 Wt(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),tracedWriteFileSync(s,t,`utf-8`),registerWrite(s,contentHash(t)),setReconciledBase(e,t);let S=w();S instanceof Map&&updateFileIndex({kind:`update`,path:s,docName:e,content:t},S)}function Kt(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=en(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 $t(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 en(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=$t(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=$t(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Mr(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=Ut(g);if(typeof s!=`string`)continue;let S=$t(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Fr(e){let s=de?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=`${s}${getDocExtension(s)}`,w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Ir(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?jr(S.docName,s):S;e.rewrites!==0&&(Wt(S.docName,e.markdown),ne?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Lr(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,ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function zr(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(_e?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||_e?.isExcluded(E))continue;let D=stripDocExtension(E);registerDocExtension(D,extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Br(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(_e?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||_e?.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 Vr(e,t){return Lt(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ne)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isSupportedDocFile(e)||isSupportedDocFile(S))throw new ManagedRenameInvalidRequestError(`Asset operations do not support markdown documents.`);if(!isSupportedAssetFile(e,ASSET_EXTENSIONS)||!isSupportedAssetFile(S,ASSET_EXTENSIONS))throw new ManagedRenameInvalidRequestError(`Asset operations require supported asset extensions.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(_e?.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=Mr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Fr(O.map(e=>e.docName)),await renameTrackedPathInGit(me,w,E)||renamePathOnDisk(w,E);let k=Ir(O,D);return ne.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),oe?.(`files`),k.length>0&&(oe?.(`backlinks`),oe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Hr(e,s,S,E){return Lt(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ne)throw new BacklinkIndexRequiredError;let O=resolveContentEntryPath(g,S,e),k=resolveContentEntryPath(g,S,s);if(O===k)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(O))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(k)&&!isCaseOnlySelfCollision(O,k))throw new ManagedRenameDestinationExistsError;let j=statSync(O);if(S===`file`&&!j.isFile()||S===`folder`&&!j.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Br(O,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[stripDocExtension(e)]:zr(O)).map(t=>({from:t,to:S===`file`?stripDocExtension(s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Mr(L);Fr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(me,O,k)||renamePathOnDisk(O,k),Be(e,s),oe?.(`files`)),g.push(...Ir(t,L)),g.length>0&&(ne.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),oe?.(`backlinks`),oe?.(`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 ne.getBacklinks(e))H.has(t.source)||J.add(t.source);let ee=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ae=new Set,se=new Set,ce=[];for(let e of[...H.keys(),...ee]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){ce.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Ut(e);typeof s==`string`?(te.set(e,s),H.has(e)||ae.add(e)):H.has(e)||ce.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)??Ut(t);typeof e==`string`&&en(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),se.add(t),H.has(t)||ae.add(t))}}Fr(se);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ue=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Ht([...te.keys()],te)}),de=[],fe=[...ae].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(me??g,ue,async()=>{for(let e of ce)ne.deleteDocument(e);for(let e of fe){let s=t.documents.get(e)?Kt(e,H,L):en(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Wt(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ne.updateDocumentFromMarkdown(e,s.markdown)}if(we)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(we.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let D=resolveContentEntryPath(g,S,e),O=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(me,D,O)||renamePathOnDisk(D,O),S===`folder`&&Be(e,s);let k=await Bt([...H.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(F?.current){let e=F.current;withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},t=>{let s=randomUUID(),g=new Date().toISOString(),w=Y?.()??`main`,D=getOrLoadRenameLogIndex(e.gitDir),O=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},k=0;for(let{from:t,to:j}of B){let F={v:1,from:t,to:j,at:g,commitSha:``,branch:w,groupId:s,kind:S,actor:O};appendRenameLogEntry(e.gitDir,F,D,e),k+=1,E?.actor?recordContributor(j,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(t,j),E.actor.actorMetadata,void 0,[{from:t,to:j}]):recordContributor(j,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(t,j),void 0,void 0,[{from:t,to:j}])}t.setAttribute(`rename.entries_appended`,k)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let q=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of q){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),E=en(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Vt([{fromDocName:e,toDocName:t}],new Map([[e,E.markdown]])),setReconciledBase(t,E.markdown);let D=w();D instanceof Map&&updateFileIndex({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:E.markdown},D),ne.renameDocument(e,t,E.markdown),E.rewrites>0&&de.push({docName:t,rewrites:E.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`)}),ne.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),oe?.(`files`),oe?.(`backlinks`),oe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Ur(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 Wr(e){return{principalId:ge?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Gr(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 Kr(e){return{value:e.value}}function qr(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Jr(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=Gr(S),E=g||!w.response?w.response:Kr(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(),qr(S,!g);for(let{docName:e}of s)Tt(e,`rename-path`);return E}case`principal`:{let t=Gr(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)}qr(e.summary,!1);for(let{docName:e}of s)Tt(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 Yr(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function Xr(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=Gr(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Zr(e){if(B)try{await B()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let Qr=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=at(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Ur(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}),J=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),Y=new Date().toISOString(),ee=typeof E.content==`string`?E.content:`Hello from the agent! ${Y}`,{response:te,stored:ne}=Gr(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ce?.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,`${ee}\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}): ${ee.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,Wr({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),qr(H)}finally{ce?.touchMode(O,`idle`)}let ae=await Et(D);if(ae?.kind===`failure`){Dt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){jt(w,`agent-write`);return}Tt(D,`agent-write`),ue?.();let oe=Mt(J);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:Y,...te?{summary:te}:{},...oe?{warning: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$4.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`}),ji=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=at(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Ur(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:J,stored:Y}=Gr(q),ee=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);ce?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(ee.dc.document.getText(`source`),k,F,L),ee.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(ee.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),ee.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},ee.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,Wr({clientName:L,clientVersion:B,label:H}),Y),incrementAgentWriteCalls(),qr(q)}finally{ce?.touchMode(k,`idle`)}let oe=await Et(O);if(oe?.kind===`failure`){Dt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){jt(w,`agent-write-md`);return}Tt(O,`agent-write-md`),se?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),ue?.();let de=it(O),fe=st(O),me=vt();me===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let ge=Mt(te);successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:fe,systemSubscriberCount:me,...de?{hints:de}:{},...J?{summary:J}:{},...ae===void 0?ge?{warning:ge}:{}:{warning:toContentDivergenceWarning(ae)}},{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$4.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`}),Hi=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=at(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Ur(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),J=normalizeSummary(E.summary),{response:Y,stored:ee}=Gr(J),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,de=!1,fe=!1,me=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ce?.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))me.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
1706
1707
  `),S=s.nextFenced+(g?`
1707
- `:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),fe=!0}de=!0},te.origin)})}finally{ce?.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;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(de&&me.length>0){if(recordContributor(D,O,k,j,void 0,Wr({clientName:F,clientVersion:L,label:B}),ee),incrementAgentWriteCalls(),qr(J),fe){let e=await Et(D);if(e?.kind===`failure`){Dt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){jt(w,`frontmatter-patch`);return}}Tt(D,`frontmatter-patch`)}se?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),ue?.();let ge=st(D),_e=vt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Mt(ne);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:ge,systemSubscriberCount:_e,appliedKeys:me,...Y?{summary:Y}:{},...ve?{warning:ve}:{}},{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$4.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 Qr(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 ji=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=at(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:Qr(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:Qr(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}),Hi=withValidation(EmptyRequestSchema,async(e,t)=>{try{Ce&&await Ce.catch(e=>{log$4.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`),D=s.searchParams.get(`showAll`)===`true`,O=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(D&&_e&&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:_e,dirFilter:S,getDocExtension,maxEntries:t,maxDepth: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:k}=D.value;k&&log$4.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:k,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$4.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(D&&_e){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=je.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:_e,dirFilter:S,documents:e,getDocExtension,maxEntries:s,maxDepth: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$4.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;je.set(e,E),w.finally(()=>{je.get(e)===E&&je.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(),je.get(e)===w&&je.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 k=w(),j=E?.()??new Map,F=[];for(let[e,t]of j)S&&!e.startsWith(`${S}/`)&&e!==S||F.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let[e,t]of k){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);F.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=relative(g,t.canonicalPath);F.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}}let L=[];try{let e=Ve(k);Me?.signature!==e&&(Me={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:_e?e=>_e.isPathIgnored(e):void 0})}),L=Me?.assets??[]}catch(e){Me=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}for(let e of L)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||F.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});F.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:F},{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}),Ui=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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:ne.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:Ke(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}),Gi=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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]=ne.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}),Ki=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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=Ft();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ne.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Xe(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}),Yi=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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}=ne.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ne.getLinkGraph());let D=Ft();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=rt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Xe(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}),Xi=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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:ne.getOrphans([...w().keys()],s).map(e=>({docName:e,title:Ke(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}),Zi=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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=Ft();successResponse(t,200,HubsSuccessSchema,{hubs:ne.getHubs(S).map(e=>({docName:e.docName,title:Xe(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}),ka=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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=>at(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ne.getDeadLinks(Ft(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Ke(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}),_s=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=at(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:J}=Ur(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 edit_document. Use write_document with position:"replace" to rewrite the 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 Y=normalizeSummary(E.summary),ee=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,de=!1,fe;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ce?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(ee.dc.document.getText(`source`),F,B,H),ee.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(ee.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){de=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));fe=applyAgentMarkdownWrite(ee.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),ee.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},ee.origin),fe!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:fe.intendedBytes,actualBytes:fe.actualBytes,byteDelta:fe.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!de){let{stored:e}=Gr(Y);recordContributor(j,F,L,B,void 0,Wr({clientName:H,clientVersion:q,label:J}),e),incrementAgentWriteCalls(),qr(Y),recordContentDivergenceGate(`agent-patch`,fe)}}finally{ce?.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(de){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}let me=await Et(j);if(me?.kind===`failure`){Dt(w,me.failure,`agent-patch`);return}if(me?.kind===`divergence`){jt(w,`agent-patch`);return}Tt(j,`agent-patch`),se?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),ue?.();let ge=st(j),_e=vt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=Gr(Y),ye=Mt(te);successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:ge,systemSubscriberCount:_e,...ve?{summary:ve}:{},...fe===void 0?ye?{warning:ye}:{}:{warning:toContentDivergenceWarning(fe)}},{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$4.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`}),xs=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=at(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Ur(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);ce?.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,Wr({clientName:k,clientVersion:j,label:F}))}finally{ce?.touchMode(E,`idle`)}if(q){let e=await Et(w);if(e?.kind===`failure`){Dt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){jt(g,`agent-undo`);return}Tt(w,`agent-undo`)}se?.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$4.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`}),Cs=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$4.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}),Ts=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=at(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$4.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}),Ds=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=at(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$4.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(ye??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ne&&(ne.deleteDocument(E),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),oe?.(`backlinks`),oe?.(`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`),_e&&await _e.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}oe?.(`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}),Os=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ne.rebuildFromDisk(),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),oe?.(`backlinks`),oe?.(`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}),ks=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!k){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}k(),oe?.(`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}),As=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Ur(s),E=F?.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=[];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}O.length===0&&(O=e===void 0?[SERVICE_WRITER]:[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}]);let k=await saveVersion(E,te??`.`,O);getLogger(`history`).info({checkpointRef:k.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:k.checkpointRef},{handler:`save-version`})}catch(e){log$4.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`}),Ns=withValidation(EmptyRequestSchema,async(e,t)=>{let s=F?.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(`branch`)??Y?.()??`main`;if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName query parameter is required.`,{handler:`history`});return}if(w.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}let E=te??`.`,D=safeDocPath(S,E);if(`error`in D){errorResponse(t,400,`urn:ok:error:invalid-request`,D.error,{handler:`history`});return}let O=Number(g.searchParams.get(`limit`)??`50`),k=Number(g.searchParams.get(`offset`)??`0`),j=Math.min(200,Number.isFinite(O)?O:50),L=Number.isFinite(k)?k:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=Date.now();try{let e=await getDocumentHistory(s,{docName:S,branch:w,limit:j,offset:L,type:B,author:H,excludeAuthor:q},E),g=Date.now()-J;getLogger(`timeline`).info({docName:S,entries:e.entries.length,durationMs:g},`query`),successResponse(t,200,HistorySuccessSchema,{...e},{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 Ps(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=F?.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=te??`.`,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=Y?.()??`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 Is=withValidation(EmptyRequestSchema,async(e,s)=>{let g=F?.current;if(!g){errorResponse(s,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`diff`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),w=S.searchParams.get(`docName`)??``,E=S.searchParams.get(`from`)??``,D=S.searchParams.get(`to`)??``;if(!D||!/^[0-9a-f]{40}$/i.test(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`'to' must be a valid 40-char commit SHA.`,{handler:`diff`});return}let O=te??`.`,k=safeDocPath(w,O);if(`error`in k){errorResponse(s,400,`urn:ok:error:invalid-request`,k.error,{handler:`diff`});return}let j=shadowGit(g),L=Y?.()??`main`,B=getOrLoadRenameLogIndex(g.gitDir),H=createAncestorShaSetCache(),q=e=>{let t=safeDocPath(e,O);return`error`in t?`${e}.md`:t.path};try{let e=await resolveDocPathAtCommit(g,w,D,L,B,q,H);if(e===null){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document did not exist at the target version.`,{handler:`diff`});return}let S=await j.raw(`show`,`${D}:${e}`),O;if(E&&/^[0-9a-f]{40}$/i.test(E)){let e=await resolveDocPathAtCommit(g,w,E,L,B,q,H);if(e===null){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document did not exist at the source version.`,{handler:`diff`});return}O=await j.raw(`show`,`${E}:${e}`)}else{let e=t.documents.get(w);if(!e){errorResponse(s,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`diff`});return}O=e.getText(`source`).toString()}let k=stripFrontmatter(O).body,F=stripFrontmatter(S).body,J=diffLines(k,F),Y=[],ee=0,te=0;for(let e of J){let t=e.value.replace(/\n$/,``).split(`
1708
- `),s=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)Y.push({type:s,text:e});e.added&&(ee+=t.length),e.removed&&(te+=t.length)}successResponse(s,200,DiffSuccessSchema,{lines:Y,additions:ee,deletions:te},{handler:`diff`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`diff`,cause:e})}},{handler:`diff`,method:`GET`,skipBodyParse:!0}),Rs=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,ge);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:`${S.docName}${getDocExtension(S.docName)}`}),`rollback`);return}let D=F?.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=te??`.`,L=safeDocPath(O,j);if(`error`in L){errorResponse(g,400,`urn:ok:error:invalid-request`,L.error,{handler:`rollback`});return}let B=shadowGit(D),H=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,Y?.()??`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 B.raw(`show`,`${k}:${E}`),L=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 J=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,ee;q.transact(()=>{replaceRawBody(q,F,J),ee=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),ee!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:ee.intendedBytes,actualBytes:ee.actualBytes,byteDelta:ee.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,ee);let te;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=Gr(s);te=t||!g.response?g.response:Kr(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),qr(s,!t);break}case`principal`:{let e=Gr(w.summary);te=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),qr(w.summary,!1);break}case`anonymous`:log$4.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 ne=await Et(O);if(ne?.kind===`failure`){Dt(g,ne.failure,`rollback`);return}if(ne?.kind===`divergence`){jt(g,`rollback`);return}Tt(O,`rollback`);let ae=Date.now()-H;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ae},`rollback`),w.kind===`agent`&&se?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()}),successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:L,...te?{summary:te}:{},...ee===void 0?{}:{warning:toContentDivergenceWarning(ee)}},{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`}),$s=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$4.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}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$4.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}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Ce&&await Ce.catch(e=>{log$4.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=ee?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s}},{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 nc(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=ge?.()??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 rc(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=ce?.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$4.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 ic(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 ac(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 oc=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(_e?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`&&(F[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`),t.writeHead(200,F);try{await pipeline(createReadStream(O),t)}catch(e){log$4.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}),sc=1048576,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-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>sc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${sc}-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}),lc=1440*60*1e3,uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!F?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(F.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>lc){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$4.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=Y?.()??`main`,t=await listRescueCheckpoints(F.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$4.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});async function dc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`rescue-get`,extraHeaders:{Allow:`GET`}});return}if(!F?.current){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`rescue-get`});return}let g=resolve(F.current.gitDir,`rescue`),S=resolve(g,`${s}${getDocExtension(s)}`);if(!S.startsWith(`${g}/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid document name.`,{handler:`rescue-get`});return}if(existsSync(S)){let e=statSync(S);if(Date.now()-e.mtimeMs>lc)try{unlinkSync(S)}catch{}else{let e=readFileSync(S,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=Y?.()??`main`,g=(await listRescueCheckpoints(F.current,e)).filter(e=>e.docName===s).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(g){let e=shadowGit(F.current),s=((await e.raw(`ls-tree`,`-r`,g.sha)).trim().split(`
1709
- `)[0]??``).split(/\s+/)[2];if(s){let g=await e.raw(`cat-file`,`-p`,s);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(g);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`rescue-get`})}let fc=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,ge);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 E=resolve(g),D=resolve(E,S);if(!D.startsWith(`${E}/`)&&D!==E){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let O=stripDocExtension(S);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`create-page`});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(E,s),w=g.find(e=>e.name===k);if(!w){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(E,w.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${w.path}.`,{handler:`create-page`,cause:e});return}let{body:L}=stripFrontmatter(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=w.scope}mkdirSync(dirname(D),{recursive:!0});try{writeFileSync(D,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(we?.delete(L),_e&&_e.incrementMdDir(dirname(L)),registerWrite(D,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)}`)}let B=typeof w==`function`?w():null;B instanceof Map&&updateFileIndex({kind:`create`,path:D,docName:L,content:j},B),ne&&(ne.updateDocumentFromMarkdown(L,j),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),oe?.(`backlinks`),oe?.(`graph`)),oe?.(`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`}),pc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,ge).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(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(_e?.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}),Re(e),oe?.(`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,ge);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:E}=S,D=E===`file`?stripDocExtension(S.path):S.path;if(!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(D===`.ok`||D.startsWith(`.ok/`)||E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||E===`folder`&&isReservedSyntheticFolderPath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}E===`file`&&probeAndRegisterSourceFileExtension(g,D);let O=resolveContentEntryPath(g,E,D);if(!existsSync(O)){if(E===`file`){let e=resolveContentEntryPath(g,`folder`,D);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${E}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${E} does not exist.`,{handler:`duplicate-path`});return}let k=statSync(O);if(E===`file`&&!k.isFile()||E===`folder`&&!k.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${E}.`,{handler:`duplicate-path`});return}let j=E===`file`?[D]:zr(resolveContentEntryPath(g,`folder`,D)),F=de?.(),L=new Set(F?F.getConflicts().map(e=>e.file):[]);for(let e of j){let g=stripDocExtension(e),S=t.documents.get(g),w=`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),D=L.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let B=typeof w==`function`?w():null,H,q=[];if(E===`file`){let e=extname(O);if(H=nextAvailableDuplicateDocName(g,D).docName,isSystemDoc(H)||isConfigDoc(H)||_e?.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(O,`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 k=!1;try{registerDocExtension(H,e),we?.delete(H),_e&&(_e.incrementMdDir(dirname(H)),k=!0),registerWrite(t,contentHash(S)),B instanceof Map&&updateFileIndex({kind:`create`,path:t,docName:H,content:S},B),ne?.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),_e&&k&&_e.decrementMdDir(dirname(H)),B instanceof Map&&updateFileIndex({kind:`delete`,path:t,docName:H},B),e}}else{if(H=nextAvailableDuplicateFolderPath(g,D).folderPath,_e?.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(O,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))Re(e);let e=collectMarkdownCopies(g,H);q=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),we?.delete(t.docName),_e&&_e.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),B instanceof Map&&updateFileIndex({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content},B),ne?.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)}`)}ne&&q.length>0&&(ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),oe?.(`backlinks`),oe?.(`graph`)),oe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:E,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`}),hc=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=Ge(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}),gc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,ge);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(E===`.ok`||E.startsWith(`.ok/`)||D===`.ok`||D.startsWith(`.ok/`)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}if(w===`asset`){let t;try{t=await Vr(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=zt(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=Jr(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$4.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}),B)try{await B()}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}let O=w===`file`?[stripDocExtension(E)]:zr(resolveContentEntryPath(g,`folder`,E)),k=de?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]);for(let e of O){let g=stripDocExtension(e),S=t.documents.get(g),D=w===`file`?E:`${g}${getDocExtension(e)}`,O=S!==void 0&&isDocInConflict(S),k=j.has(D);if(O||k){respondDocInConflict(s,new DocInConflictError({file:D}),`rename-path`);return}}if(w===`file`&&probeAndRegisterSourceFileExtension(g,E),_e&&(w===`file`?_e.isExcluded(isSupportedDocFile(D)?D:`${D}${getDocExtension(E)}`):_e.isDirExcluded(D))){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${w===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let F=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,L;try{L=await Hr(E,D,w,F?{actor:F}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Rt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(L.renamed.length===0&&L.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}L.renamedAssets.length>0&&Ue();let H;if(L.renamed.length>0&&(H=Jr(e,`Renamed ${E} → ${D}`,L.renamed.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$4.debug({kind:w,fromPath:E,toPath:D,affectedDocs:L.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${w}`,attribution_kind:e.kind}),B)try{await B()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:L.renamed,renamedAssets:L.renamedAssets,rewrittenDocs:L.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=zt(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),_c=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Ur(S);let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let D=e===`asset`?Lr(E):{path:E,ambiguous:!1};if(D.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let O=D.path;if(e===`asset`&&(isSupportedDocFile(O)||isReservedProjectStatePath(O))){errorResponse(s,400,isReservedProjectStatePath(O)?`urn:ok:error:reserved-doc-name`:`urn:ok:error:invalid-request`,isReservedProjectStatePath(O)?`.ok and .git are reserved directories.`:`Asset operations do not support markdown documents.`,{handler:`delete-path`});return}let k=e===`asset`?resolveContentEntryPath(g,`folder`,O):resolveContentEntryPath(g,e,O);if(!existsSync(k)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${e} does not exist.`,{handler:`delete-path`});return}let j=statSync(k);if(e===`file`&&!j.isFile()||e===`asset`&&!j.isFile()||e===`folder`&&!j.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${e}.`,{handler:`delete-path`});return}let F=e===`asset`?[]:e===`file`?[E]:zr(resolveContentEntryPath(g,`folder`,E)),L=de?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let g of F){let S=stripDocExtension(g),w=t.documents.get(S),E=e===`file`?g:`${S}${getDocExtension(S)}`,D=w!==void 0&&isDocInConflict(w),O=B.has(E);if(D||O){respondDocInConflict(s,new DocInConflictError({file:E}),`delete-path`);return}}if(await Bt(F),we)for(let e of F)isSystemDoc(e)||isConfigDoc(e)||(we.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));e===`file`||e===`asset`?tracedUnlinkSync(k):(tracedRmSync(k,{recursive:!0,force:!1}),ze(E)),Ue();let H=w();if(H instanceof Map)for(let e of F)updateFileIndex({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e},H);oe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:F},{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`}),vc=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,ge).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===`folder`&&isReservedSyntheticFolderPath(S),D=e===`asset`&&isReservedProjectStatePath(S),O=e===`asset`&&isSupportedDocFile(S);if(e===`file`&&(isSystemDoc(S)||isConfigDoc(S))||E||D||O){errorResponse(t,400,O?`urn:ok:error:invalid-request`:`urn:ok:error:reserved-doc-name`,O?`Asset operations do not support markdown documents.`:`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(e===`asset`){Ue(),oe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let k=w(),j=e===`file`?k.has(S)?[S]:[]:listAffectedDocNames(k,e,S);if(Ue(),j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Bt(j),we)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(we.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));let F=w();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e},F);e===`folder`&&ze(S),oe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:j},{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`}),yc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=t,w,E=getDocExtension(t);try{let s=readFileSync(resolve(g,`${t}${E}`),`utf-8`);e=extractPageTitle(s,t),w=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}s.push({docName:t,title:e,docExt:E,size:S.size,modified:S.modified,icon:w})}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}),bc=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 xc(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,me??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:E,byteLength:D,parentDocName:O}=s,k=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},j=validateBody(UploadRequestSchema,{parentDocName:O},t,{handler:`upload-asset`});if(!j.ok){k();return}let{parentDocName:F}=j.value,{agentId:L,agentName:B}=Ur(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(D===0){k(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(F.includes(`\0`)||F.includes(`..`)||F.startsWith(`/`)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let H=resolve(g),q=resolveUploadDestDir(F,`./`,H);if(!isWithinContentDir(q,H)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(q,H)}catch(e){if(k(),(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$4.error({err:e,destDir:q},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(q,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){k();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(q),s;try{s=realpathSync(H)}catch{s=H}if(!isWithinContentDir(e,s)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let J=await fileTypeFromFile(w),Y=J?.mime,ee=J?.ext;if(!Y){let e=readTempFileHead(w,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(Y=`image/svg+xml`,ee=`svg`)}{let s=await findDuplicateAsset(q,E,D);if(s){k();let S=relative(g,resolve(q,s));log$4.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,dedup:!0,mime:Y??null,size:D,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let te;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=ee??t??``;te=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else te=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,q,te),S=relative(g,resolve(q,s));log$4.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,dedup:!1,mime:Y??null,size:D,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$4.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,filename:te,size:D,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Sc=`/api/local-op/clone`,Cc=`/api/local-op/open`,wc=`/api/local-op/ok-init`,Tc=600*1e3,Ec=45e3,Dc=`local-op-clone`,Oc=withValidation(LocalOpCloneRequestSchema,kc,{handler:Dc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Dc})});async function kc(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:Dc,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:Dc,cause:Error(`dir=${S}`)});return}if(!De.tryAcquire(Sc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Dc,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,Dc),D=null,O=runCloneSubprocess({cliArgs:fe,url:g,dir:S,branch:w,timeoutMs:Tc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$4.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 Ac(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$4.error({err:e,handler:Dc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),De.release(Sc)}})(),t.on(`close`,()=>{O.cancel()})}async function Ac(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]=fe,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),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$4.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/open] 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$4.error({cwd:s,cliCmd:e,err:t.message},`[local-op/open] 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 jc=`local-op-open`,Mc=withValidation(LocalOpOpenRequestSchema,async(e,t,s)=>{let{dir:g,port:S}=s;if(!isSafeLocalPath(g)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:jc,cause:Error(`dir=${g}`)});return}if(!De.tryAcquire(Cc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:jc,extraHeaders:{"Retry-After":`5`}});return}try{let e=await Ac(g,S);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:jc}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:jc,cause:Error(e.error)})}finally{De.release(Cc)}},{handler:jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:jc})}),Nc=`local-op-ok-init`,Pc=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:Nc,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:Nc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Nc,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:Nc});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:Nc});return}if(!De.tryAcquire(wc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Nc,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:Nc})}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:Nc})}finally{De.release(wc)}},{handler:Nc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Nc})}),Fc=`/api/local-op/auth/login`,Ic=`/api/local-op/auth/status`,Lc=`/api/local-op/auth/repos`,Rc=`/api/local-op/auth/signout`,zc=`/api/local-op/auth/pat`,Bc=null,Vc=`local-op-auth-login`,Hc=withValidation(LocalOpAuthHostRequestSchema,Uc,{handler:Vc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Vc})});async function Uc(e,t,s){let g=s.host??`github.com`;if(!De.tryAcquire(Fc)){let e=Bc;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:Vc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Bc=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,Vc),w=runDeviceFlowSubprocess({cliArgs:fe,host:g,timeoutMs:Tc,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(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Bc=w;let E=()=>{w.cancel(),Bc===w&&(Bc=null,De.release(Fc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Bc===w&&(Bc=null,De.release(Fc))})}let Wc=`local-op-auth-status`,Gc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!De.tryAcquire(Ic)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Wc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,{stdio:[`ignore`,`pipe`,`pipe`],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(`
1710
- `).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:Wc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:Wc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Wc,cause:e})}finally{De.release(Ic)}},{handler:Wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Wc})}),Kc=`local-op-auth-repos`,qc=withValidation(LocalOpAuthHostRequestSchema,Jc,{handler:Kc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Kc})});async function Jc(e,t,s){let g=s.host??`github.com`;if(!De.tryAcquire(Lc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Kc,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,Kc),[w,...E]=fe,D=[...E,`auth`,`repos`,`--json`,`--host`,g],O=!1,k=``,j=spawn(w,D,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),F=setTimeout(()=>{j.kill(`SIGTERM`)},Tc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
1711
- `);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$4.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(),De.release(Lc))}),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()),De.release(Lc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),De.release(Lc))})}let Yc=`local-op-auth-signout`,Xc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!De.tryAcquire(Rc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Yc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,{stdio:`ignore`,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:Yc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Yc,cause:e})}finally{De.release(Rc)}},{handler:Yc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Yc})}),Zc=`local-op-auth-pat`,Qc=withValidation(LocalOpAuthPatRequestSchema,async(e,t,s)=>{let{pat:g,host:S}=s,w=S??`github.com`;if(!De.tryAcquire(zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:Zc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`pat`,`--json`,`--host`,w],E=(await new Promise((t,s)=>{let w=spawn(e,S,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),E=setTimeout(()=>{w.kill(`SIGTERM`)},3e4);w.stdin.write(`${g}\n`),w.stdin.end();let D=[];w.stdout.on(`data`,e=>D.push(e)),w.on(`close`,e=>{clearTimeout(E),e===0?t(Buffer.concat(D).toString(`utf-8`)):s(Error(`auth pat exited with code ${e}`))}),w.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
1712
- `).map(e=>e.trim()).filter(Boolean),D=null;for(let e=E.length-1;e>=0;e--)try{D=JSON.parse(E[e]);break}catch{}D===null?successResponse(t,200,LocalOpAuthPatSuccessSchema,{},{handler:Zc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,D,{handler:Zc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:Zc,cause:e})}finally{De.release(zc)}},{handler:Zc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Zc})}),$c=`local-op-auth-identity`;async function nl(e,t){if(checkLocalOpSecurity(e,t,{handler:$c})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:$c,extraHeaders:{Allow:`GET`}});return}if(!me){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:$c});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(me)},{handler:$c})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:$c,cause:e})}}}let il=`/api/local-op/auth/set-identity`,al=`local-op-auth-set-identity`,cl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!me){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:al});return}if(!De.tryAcquire(il)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:al,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(me,g,S),de?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:al})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:al,cause:e})}finally{De.release(il)}},{handler:al,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:al})});async function ll(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=de?.();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 ul=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=de?.();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`})?de?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function dl(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=de?.();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 fl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=de?.();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`})?de?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function pl(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(!me){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=de?.(),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:me,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=Te?Te(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 ml(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 gl(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 _l=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 vl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,We.probeAll)}catch(e){t.headersSent||(log$4.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}))}}async function yl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-abort-merge`}))return;if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-abort-merge`,extraHeaders:{Allow:`POST`}});return}let s=de?.();if(!s){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-abort-merge`});return}try{await s.abortMerge(),successResponse(t,200,SyncAbortMergeSuccessSchema,{},{handler:`sync-abort-merge`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to abort merge.`,{handler:`sync-abort-merge`,cause:e})}}let xl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ae){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:ae.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 Cl(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(!ae){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=ae.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:Ke(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 Tl(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 El=/^[A-Za-z0-9_-]+$/;function Dl(e,t,s=`template`){return!e||!El.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 Ol(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 kl(e,t){if(e.method===`GET`)return jl(e,t);if(e.method===`PUT`)return Ml(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let jl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Tl(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}),Ml=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{let e=Tl(s.path,t,`path`,`folder-config-put`);if(!e)return;let g=e.folderRel===``?`**`:`${e.folderRel}/**`,S=[];if(s.frontmatter!==void 0){let w=applyNestedFolderRulesUpsert({projectDir:e.resolvedContentDir,rules:[{match:g,frontmatter:Ol(s.frontmatter)}]});if(!w.ok){let e=w.error.code===`WRITE_ERROR`||w.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 write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push(...w.applied)}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 Pl(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}let Fl=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 Il(e,t){if(e.method===`GET`)return zl(e,t);if(e.method===`PUT`)return Bl(e,t);if(e.method===`DELETE`)return Vl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Ll=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Rl=e=>{let t=e.match(Ll),s={},g=e;if(t){try{let e=(0,import_dist$1.parse)(t[1]??``);e&&typeof e==`object`&&!Array.isArray(e)&&(s=e)}catch{}g=e.slice(t[0].length)}return{frontmatter:s,body:g}},zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Dl(g,t,`template-get`))return;let S=Tl(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=w===``?[]:w.split(`/`),O=null,k=null,j=null;for(let e=D.length;e>=0;e--){let t=e===0?``:D.slice(0,e).join(`/`),s=t===``?E:resolve(E,t);if(s!==E&&!s.startsWith(`${E}${sep}`))continue;let S=resolve(s,`.ok`,`templates`,`${g}.md`);if(existsSync(S)){O=S,k=t,j=e===D.length?`local`:`inherited`;break}}if(!O||k===null||j===null){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{frontmatter:F,body:L}=Rl(await readFile$1(O,`utf-8`)),B=relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`);successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:B,frontmatter:F,body:L}},{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}),Bl=withValidation(TemplatePutRequestSchema,async(e,t,s)=>{try{let e=s.name;if(!Dl(e,t,`template-put`))return;let g=Tl(s.folder,t,`folder`,`template-put`);if(!g||Pl(g.folderRel,e,`template-put`,t))return;let S=applyTemplateWrite({projectDir:g.resolvedContentDir,folder:g.folderRel,name:e,body:typeof s.body==`string`?s.body:``,frontmatter:Ol(s.frontmatter)});if(!S.ok){let e=S.error.code===`WRITE_ERROR`||S.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 write template.`:`Invalid template request.`,{handler:`template-put`,detail:S.error.code,cause:Error(S.error.message)});return}successResponse(t,200,TemplatePutSuccessSchema,{path:S.path,created:S.created,warnings:S.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`}),Vl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Dl(g,t,`template-delete`))return;let S=Tl(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S||Pl(S.folderRel,g,`template-delete`,t))return;let w=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});if(!w.ok){let e=w.error.code===`WRITE_ERROR`||w.error.code===`UNLINK_FAILED`||w.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:w.error.code,cause:Error(w.error.message)});return}successResponse(t,200,TemplateDeleteSuccessSchema,{existed:w.existed,path:w.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});function Hl(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 Ul(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}`}function Wl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Gl(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`);return s.length>0?s:void 0}async function Kl(){let e=[];for(let[t,s]of w()){if(isSystemDoc(t)||isConfigDoc(t))continue;let g=``,S=t;try{g=await readFile$1(s.canonicalPath,`utf-8`),S=extractPageTitle(g,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:S,content:g,modifiedTs:Date.parse(s.modified)}))}return[...e,...Hl(e)]}function ql(){return[...w()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function Jl(){let e=`${g}${me??``}`,t=ql(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return s.corpus;if(s?.fingerprint===t&&s.pending)return s.pending;let S=Kl().then(e=>createWorkspaceSearchCorpus(e));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}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function Yl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Jl().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}Yl();async function Xl(e,t){if(e.method===`GET`)return Zl(e,t);if(e.method===`POST`)return Ql(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let Zl=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Wl(s.searchParams.get(`intent`)),E=Gl(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),D=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{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:S,intent:w,results:searchWorkspaceCorpus(await Jl(),S,{intent:w,scopes:E,limit:D}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Ul(e.document.content,S):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{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}),Ql=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Wl(s.intent),w=Gl(s.scopes??s.scope),E=typeof s.limit==`number`?s.limit:void 0;if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:g,intent:S,results:searchWorkspaceCorpus(await Jl(),g,{intent:S,scopes:w,limit:E}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Ul(e.document.content,g):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{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`}),$l=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 eu(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$4.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 tu(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$4.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 nu=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!me){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidSharePath(s.kind===`doc`?s.docPath:s.folderPath,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 e=readGitHeadBranch(me);if(e===null){if(readOriginGitHubRepo(me).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 S=readOriginGitHubRepo(me);if(S.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(S.kind===`non-github`){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(me,e)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=toGitRelativePath(me,g);if(w===null)throw Error(`content dir is not contained within the project dir`);let E=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;w!==``&&E&&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 D;if(s.kind===`doc`)D=buildGitHubBlobUrl(S.owner,S.repo,e,s.docPath);else{let t=s.folderPath===``?w:s.folderPath;D=buildGitHubTreeUrl(S.owner,S.repo,e,t)}let O=`${SHARE_BASE_URL}${encodeShareUrl(D)}`;emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:O,sharedUrl:D,branch:e},{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})}),ru=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!me){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(me,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}),iu=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,ge).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!me){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(me,s.branch)),{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 au(e){let[t,...s]=fe,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,{stdio:[`ignore`,`pipe`,`pipe`],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 ou=withValidation(EmptyRequestSchema,async(e,t)=>{if(!De.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 au([`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{De.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})}),su=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(!De.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 au([`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{De.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})}),cu=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!me){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(!De.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`,me,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await au(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&de?.()?.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{De.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),lu=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`})}),uu=me?getLocalDir(me):null;async function du(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}uu&&clearArmedPaneTarget(uu),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:uu?readServerLock(uu)?.port??0:0,paneTarget:uu?readArmedPaneTarget(uu):null};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, DELETE`}})}let fu={"/api/config":du,"/api/asset":oc,"/api/asset-text":cc,"/api/document":ji,"/api/documents":Hi,"/api/backlinks":Ui,"/api/backlink-counts":Gi,"/api/forward-links":Ki,"/api/link-graph":Yi,"/api/dead-links":ka,"/api/orphans":Xi,"/api/hubs":Zi,"/api/tags":xl,"/api/pages":yc,"/api/folder-config":kl,"/api/template":Il,"/api/templates":Fl,"/api/search":Xl,"/api/suggest-links":bc,"/api/page-headings":hc,"/api/create-page":fc,"/api/create-folder":pc,"/api/duplicate-path":mc,"/api/rename-path":gc,"/api/delete-path":_c,"/api/trash/cleanup":vc,"/api/upload":xc,"/api/agent-write":Yr,"/api/agent-write-md":Xr,"/api/frontmatter-patch":Zr,"/api/agent-patch":_s,"/api/agent-undo":xs,"/api/agent-activity":Cs,"/api/agent-burst-diff":Ts,"/api/save-version":As,"/api/history":Ns,"/api/diff":Is,"/api/rollback":Rs,"/api/metrics/reconciliation":$s,"/api/metrics/parse-health":ec,"/api/metrics/agent-presence":rc,"/api/__embed-detect":ic,"/api/server-info":tc,"/api/share/construct-url":nu,"/api/git/branch-info":ru,"/api/git/checkout":iu,"/api/share/publish/owners":ou,"/api/share/publish/name-check":su,"/api/share/publish":cu,"/api/principal":nc,"/api/rescue":uc,"/api/workspace":ac,"/api/sync/status":ll,"/api/sync/trigger":ul,"/api/sync/conflicts":dl,"/api/sync/conflict-content":pl,"/api/sync/resolve-conflict":fl,"/api/sync/abort-merge":yl,"/api/local-op/clone":Oc,"/api/local-op/open":Mc,"/api/local-op/ok-init":Pc,"/api/local-op/auth/login":Hc,"/api/local-op/auth/status":Gc,"/api/local-op/auth/repos":qc,"/api/local-op/auth/signout":Xc,"/api/local-op/auth/pat":Qc,"/api/local-op/auth/identity":nl,"/api/local-op/auth/set-identity":cl,"/api/installed-agents":vl,"/api/spawn-cursor":tu,"/api/handoff":eu,"/api/install-skill":_l,"/api/skill/install-state":$l,"/api/seed/plan":ml,"/api/seed/apply":hl,"/api/seed/packs":gl,"/api/client-logs":lu};j&&(fu[`/api/test-reset`]=Ds,fu[`/api/test-rescan-backlinks`]=Os,fu[`/api/test-rescan-files`]=ks);let pu=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/sync/abort-merge./api/git/checkout./api/test-reset./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/seed/apply./api/client-logs`.split(`.`)),mu=[`/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(pu.has(s)||mu.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(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/rescue/`)?E=`/api/rescue/:docName`:s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:fu[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=fu[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/rescue/`)){let g=decodeURIComponent(s.slice(12));g&&(E=!0,await dc(e,t,g))}else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await Ps(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Cl(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 isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedBasenameIndex(e){let t=e.contentDir,s=new Set;function g(S){let w;try{w=readdirSync(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=relative(t,w);if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=lstatSync(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=realpathSync(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=statSync(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()?g(S):E.isFile()&&isSupportedAssetFile(w,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),g(w);continue}O.isFile()&&isSupportedAssetFile(w,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}g(t)}const HocuspocusAuthTokenSchema=object$1({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch: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`];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 log$3=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$3.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$3.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$3.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-CvT4CaVU-BJSxTfe_.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(g!==t&&!g.startsWith(`${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$3.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
1708
+ `:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),fe=!0}de=!0},te.origin)})}finally{ce?.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;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(de&&me.length>0){if(recordContributor(D,O,k,j,void 0,Wr({clientName:F,clientVersion:L,label:B}),ee),incrementAgentWriteCalls(),qr(J),fe){let e=await Et(D);if(e?.kind===`failure`){Dt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){jt(w,`frontmatter-patch`);return}}Tt(D,`frontmatter-patch`)}se?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),ue?.();let ge=st(D),_e=vt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Mt(ne);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:ge,systemSubscriberCount:_e,appliedKeys:me,...Y?{summary:Y}:{},...ve?{warning:ve}:{}},{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$4.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 Ui(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 Gi=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=at(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:Ui(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:Ui(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}),Ki=withValidation(EmptyRequestSchema,async(e,t)=>{try{Ce&&await Ce.catch(e=>{log$4.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`),D=s.searchParams.get(`showAll`)===`true`,O=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(D&&_e&&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:_e,dirFilter:S,getDocExtension,maxEntries:t,maxDepth: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:k}=D.value;k&&log$4.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:k,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$4.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(D&&_e){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=je.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:_e,dirFilter:S,documents:e,getDocExtension,maxEntries:s,maxDepth: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$4.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;je.set(e,E),w.finally(()=>{je.get(e)===E&&je.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(),je.get(e)===w&&je.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 k=w(),j=E?.()??new Map,F=[];for(let[e,t]of j)S&&!e.startsWith(`${S}/`)&&e!==S||F.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let[e,t]of k){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);F.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=relative(g,t.canonicalPath);F.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}}let L=[];try{let e=Ve(k);Me?.signature!==e&&(Me={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:_e?e=>_e.isPathIgnored(e):void 0})}),L=Me?.assets??[]}catch(e){Me=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}for(let e of L)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||F.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});F.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:F},{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}),Yi=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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:ne.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:Ke(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}),Xi=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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]=ne.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}),Zi=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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=Ft();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ne.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Xe(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}),ka=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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}=ne.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ne.getLinkGraph());let D=Ft();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=rt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Xe(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}),_s=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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:ne.getOrphans([...w().keys()],s).map(e=>({docName:e,title:Ke(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}),xs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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=Ft();successResponse(t,200,HubsSuccessSchema,{hubs:ne.getHubs(S).map(e=>({docName:e.docName,title:Xe(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}),Cs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){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=>at(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ne.getDeadLinks(Ft(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Ke(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}),Ts=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=at(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:J}=Ur(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 Y=normalizeSummary(E.summary),ee=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,de=!1,fe;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ce?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(ee.dc.document.getText(`source`),F,B,H),ee.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(ee.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){de=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));fe=applyAgentMarkdownWrite(ee.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),ee.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},ee.origin),fe!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:fe.intendedBytes,actualBytes:fe.actualBytes,byteDelta:fe.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!de){let{stored:e}=Gr(Y);recordContributor(j,F,L,B,void 0,Wr({clientName:H,clientVersion:q,label:J}),e),incrementAgentWriteCalls(),qr(Y),recordContentDivergenceGate(`agent-patch`,fe)}}finally{ce?.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(de){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 me=await Et(j);if(me?.kind===`failure`){Dt(w,me.failure,`agent-patch`);return}if(me?.kind===`divergence`){jt(w,`agent-patch`);return}Tt(j,`agent-patch`),se?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),ue?.();let ge=st(j),_e=vt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=Gr(Y),ye=Mt(te);successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:ge,systemSubscriberCount:_e,...ve?{summary:ve}:{},...fe===void 0?ye?{warning:ye}:{}:{warning:toContentDivergenceWarning(fe)}},{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$4.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`}),Ds=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=at(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Ur(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);ce?.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,Wr({clientName:k,clientVersion:j,label:F}))}finally{ce?.touchMode(E,`idle`)}if(q){let e=await Et(w);if(e?.kind===`failure`){Dt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){jt(g,`agent-undo`);return}Tt(w,`agent-undo`)}se?.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$4.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`}),Os=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$4.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}),ks=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=at(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$4.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}),As=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=at(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$4.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(ye??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ne&&(ne.deleteDocument(E),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),oe?.(`backlinks`),oe?.(`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`),_e&&await _e.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}oe?.(`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}),Ns=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ne){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ne.rebuildFromDisk(),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),oe?.(`backlinks`),oe?.(`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}),Ps=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!k){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}k(),oe?.(`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}),Is=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Ur(s),E=F?.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=[];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}O.length===0&&(O=e===void 0?[SERVICE_WRITER]:[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}]);let k=te??`.`,j=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),L=await saveVersion(E,k,O,`main`,j.kind===`value`?j.value:void 0);getLogger(`history`).info({checkpointRef:L.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:L.checkpointRef},{handler:`save-version`})}catch(e){log$4.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`}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{let s=F?.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`)??Y?.()??`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=Ol(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);successResponse(t,200,HistorySuccessSchema,{...await getFolderTimeline(s,e.folderRel,te??`.`,{branch:E,limit:D,offset:k})},{handler:`history`});return}let D=te??`.`,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`),L=Math.min(200,Number.isFinite(k)?k:50),B=Number.isFinite(j)?j:0,H=g.searchParams.get(`type`)??void 0,q=g.searchParams.get(`author`)??void 0,J=g.searchParams.get(`excludeAuthor`)??void 0,ee=Date.now();try{let e=await getDocumentHistory(s,{docName:S,branch:E,limit:L,offset:B,type:H,author:q,excludeAuthor:J},D),g=Date.now()-ee;getLogger(`timeline`).info({docName:S,entries:e.entries.length,durationMs:g},`query`),successResponse(t,200,HistorySuccessSchema,{...e},{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 $s(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=F?.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=te??`.`,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=Y?.()??`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 ec=withValidation(EmptyRequestSchema,async(e,s)=>{let g=F?.current;if(!g){errorResponse(s,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`diff`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),w=S.searchParams.get(`docName`)??``,E=S.searchParams.get(`from`)??``,D=S.searchParams.get(`to`)??``;if(!D||!/^[0-9a-f]{40}$/i.test(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`'to' must be a valid 40-char commit SHA.`,{handler:`diff`});return}let O=te??`.`,k=safeDocPath(w,O);if(`error`in k){errorResponse(s,400,`urn:ok:error:invalid-request`,k.error,{handler:`diff`});return}let j=shadowGit(g),L=Y?.()??`main`,B=getOrLoadRenameLogIndex(g.gitDir),H=createAncestorShaSetCache(),q=e=>{let t=safeDocPath(e,O);return`error`in t?`${e}.md`:t.path};try{let e=await resolveDocPathAtCommit(g,w,D,L,B,q,H);if(e===null){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document did not exist at the target version.`,{handler:`diff`});return}let S=await j.raw(`show`,`${D}:${e}`),O;if(E&&/^[0-9a-f]{40}$/i.test(E)){let e=await resolveDocPathAtCommit(g,w,E,L,B,q,H);if(e===null){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document did not exist at the source version.`,{handler:`diff`});return}O=await j.raw(`show`,`${E}:${e}`)}else{let e=t.documents.get(w);if(!e){errorResponse(s,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`diff`});return}O=e.getText(`source`).toString()}let k=stripFrontmatter(O).body,F=stripFrontmatter(S).body,J=diffLines(k,F),Y=[],ee=0,te=0;for(let e of J){let t=e.value.replace(/\n$/,``).split(`
1709
+ `),s=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)Y.push({type:s,text:e});e.added&&(ee+=t.length),e.removed&&(te+=t.length)}successResponse(s,200,DiffSuccessSchema,{lines:Y,additions:ee,deletions:te},{handler:`diff`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`diff`,cause:e})}},{handler:`diff`,method:`GET`,skipBodyParse:!0}),tc=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,ge);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:`${S.docName}${getDocExtension(S.docName)}`}),`rollback`);return}let D=F?.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=te??`.`,L=safeDocPath(O,j);if(`error`in L){errorResponse(g,400,`urn:ok:error:invalid-request`,L.error,{handler:`rollback`});return}let B=shadowGit(D),H=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,Y?.()??`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 B.raw(`show`,`${k}:${E}`),L=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 J=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,ee;q.transact(()=>{replaceRawBody(q,F,J),ee=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),ee!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:ee.intendedBytes,actualBytes:ee.actualBytes,byteDelta:ee.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,ee);let te;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=Gr(s);te=t||!g.response?g.response:Kr(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),qr(s,!t);break}case`principal`:{let e=Gr(w.summary);te=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),qr(w.summary,!1);break}case`anonymous`:log$4.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 ne=await Et(O);if(ne?.kind===`failure`){Dt(g,ne.failure,`rollback`);return}if(ne?.kind===`divergence`){jt(g,`rollback`);return}Tt(O,`rollback`);let ae=Date.now()-H;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ae},`rollback`),w.kind===`agent`&&se?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()}),successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:L,...te?{summary:te}:{},...ee===void 0?{}:{warning:toContentDivergenceWarning(ee)}},{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`}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$4.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}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$4.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}),ic=withValidation(EmptyRequestSchema,async(e,t)=>{try{Ce&&await Ce.catch(e=>{log$4.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=ee?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s}},{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 ac(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=ge?.()??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 oc(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=ce?.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$4.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 sc(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 cc(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 lc=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(_e?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`&&(F[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`),t.writeHead(200,F);try{await pipeline(createReadStream(O),t)}catch(e){log$4.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}),uc=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>uc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${uc}-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}),fc=1440*60*1e3,pc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!F?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(F.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>fc){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$4.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=Y?.()??`main`,t=await listRescueCheckpoints(F.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$4.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});async function mc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`rescue-get`,extraHeaders:{Allow:`GET`}});return}if(!F?.current){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`rescue-get`});return}let g=resolve(F.current.gitDir,`rescue`),S=resolve(g,`${s}${getDocExtension(s)}`);if(!S.startsWith(`${g}/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid document name.`,{handler:`rescue-get`});return}if(existsSync(S)){let e=statSync(S);if(Date.now()-e.mtimeMs>fc)try{unlinkSync(S)}catch{}else{let e=readFileSync(S,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=Y?.()??`main`,g=(await listRescueCheckpoints(F.current,e)).filter(e=>e.docName===s).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(g){let e=shadowGit(F.current),s=((await e.raw(`ls-tree`,`-r`,g.sha)).trim().split(`
1710
+ `)[0]??``).split(/\s+/)[2];if(s){let g=await e.raw(`cat-file`,`-p`,s);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(g);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`rescue-get`})}let hc=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,ge);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 E=resolve(g),D=resolve(E,S);if(!D.startsWith(`${E}/`)&&D!==E){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let O=stripDocExtension(S);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`create-page`});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(E,s),w=g.find(e=>e.name===k);if(!w){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(E,w.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${w.path}.`,{handler:`create-page`,cause:e});return}let{body:L}=stripFrontmatter(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=w.scope}mkdirSync(dirname(D),{recursive:!0});try{writeFileSync(D,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(we?.delete(L),_e&&_e.incrementMdDir(dirname(L)),registerWrite(D,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)}`)}let B=typeof w==`function`?w():null;B instanceof Map&&updateFileIndex({kind:`create`,path:D,docName:L,content:j},B),ne&&(ne.updateDocumentFromMarkdown(L,j),ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),oe?.(`backlinks`),oe?.(`graph`)),oe?.(`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`}),gc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,ge).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(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(_e?.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}),Re(e),oe?.(`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`}),_c=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,ge);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:E}=S,D=E===`file`?stripDocExtension(S.path):S.path;if(!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(D===`.ok`||D.startsWith(`.ok/`)||E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||E===`folder`&&isReservedSyntheticFolderPath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}E===`file`&&probeAndRegisterSourceFileExtension(g,D);let O=resolveContentEntryPath(g,E,D);if(!existsSync(O)){if(E===`file`){let e=resolveContentEntryPath(g,`folder`,D);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${E}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${E} does not exist.`,{handler:`duplicate-path`});return}let k=statSync(O);if(E===`file`&&!k.isFile()||E===`folder`&&!k.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${E}.`,{handler:`duplicate-path`});return}let j=E===`file`?[D]:zr(resolveContentEntryPath(g,`folder`,D)),F=de?.(),L=new Set(F?F.getConflicts().map(e=>e.file):[]);for(let e of j){let g=stripDocExtension(e),S=t.documents.get(g),w=`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),D=L.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let B=typeof w==`function`?w():null,H,q=[];if(E===`file`){let e=extname(O);if(H=nextAvailableDuplicateDocName(g,D).docName,isSystemDoc(H)||isConfigDoc(H)||_e?.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(O,`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 k=!1;try{registerDocExtension(H,e),we?.delete(H),_e&&(_e.incrementMdDir(dirname(H)),k=!0),registerWrite(t,contentHash(S)),B instanceof Map&&updateFileIndex({kind:`create`,path:t,docName:H,content:S},B),ne?.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),_e&&k&&_e.decrementMdDir(dirname(H)),B instanceof Map&&updateFileIndex({kind:`delete`,path:t,docName:H},B),e}}else{if(H=nextAvailableDuplicateFolderPath(g,D).folderPath,_e?.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(O,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))Re(e);let e=collectMarkdownCopies(g,H);q=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),we?.delete(t.docName),_e&&_e.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),B instanceof Map&&updateFileIndex({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content},B),ne?.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)}`)}ne&&q.length>0&&(ne.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),oe?.(`backlinks`),oe?.(`graph`)),oe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:E,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`}),vc=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=Ge(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}),yc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,ge);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(E===`.ok`||E.startsWith(`.ok/`)||D===`.ok`||D.startsWith(`.ok/`)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}if(w===`asset`){let t;try{t=await Vr(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=zt(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=Jr(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$4.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}),B)try{await B()}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}let O=w===`file`?[stripDocExtension(E)]:zr(resolveContentEntryPath(g,`folder`,E)),k=de?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]);for(let e of O){let g=stripDocExtension(e),S=t.documents.get(g),D=w===`file`?E:`${g}${getDocExtension(e)}`,O=S!==void 0&&isDocInConflict(S),k=j.has(D);if(O||k){respondDocInConflict(s,new DocInConflictError({file:D}),`rename-path`);return}}if(w===`file`&&probeAndRegisterSourceFileExtension(g,E),_e&&(w===`file`?_e.isExcluded(isSupportedDocFile(D)?D:`${D}${getDocExtension(E)}`):_e.isDirExcluded(D))){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${w===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let F=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,L;try{L=await Hr(E,D,w,F?{actor:F}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Rt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(L.renamed.length===0&&L.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}L.renamedAssets.length>0&&Ue();let H;if(L.renamed.length>0&&(H=Jr(e,`Renamed ${E} → ${D}`,L.renamed.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$4.debug({kind:w,fromPath:E,toPath:D,affectedDocs:L.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${w}`,attribution_kind:e.kind}),B)try{await B()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:L.renamed,renamedAssets:L.renamedAssets,rewrittenDocs:L.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=zt(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),bc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Ur(S);let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let D=e===`asset`?Lr(E):{path:E,ambiguous:!1};if(D.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let O=D.path;if(e===`asset`&&(isSupportedDocFile(O)||isReservedProjectStatePath(O))){errorResponse(s,400,isReservedProjectStatePath(O)?`urn:ok:error:reserved-doc-name`:`urn:ok:error:invalid-request`,isReservedProjectStatePath(O)?`.ok and .git are reserved directories.`:`Asset operations do not support markdown documents.`,{handler:`delete-path`});return}let k=e===`asset`?resolveContentEntryPath(g,`folder`,O):resolveContentEntryPath(g,e,O);if(!existsSync(k)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${e} does not exist.`,{handler:`delete-path`});return}let j=statSync(k);if(e===`file`&&!j.isFile()||e===`asset`&&!j.isFile()||e===`folder`&&!j.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${e}.`,{handler:`delete-path`});return}let F=e===`asset`?[]:e===`file`?[E]:zr(resolveContentEntryPath(g,`folder`,E)),L=de?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let g of F){let S=stripDocExtension(g),w=t.documents.get(S),E=e===`file`?g:`${S}${getDocExtension(S)}`,D=w!==void 0&&isDocInConflict(w),O=B.has(E);if(D||O){respondDocInConflict(s,new DocInConflictError({file:E}),`delete-path`);return}}if(await Bt(F),we)for(let e of F)isSystemDoc(e)||isConfigDoc(e)||(we.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));e===`file`||e===`asset`?tracedUnlinkSync(k):(tracedRmSync(k,{recursive:!0,force:!1}),ze(E)),Ue();let H=w();if(H instanceof Map)for(let e of F)updateFileIndex({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e},H);oe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:F},{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`}),xc=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,ge).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===`folder`&&isReservedSyntheticFolderPath(S),D=e===`asset`&&isReservedProjectStatePath(S),O=e===`asset`&&isSupportedDocFile(S);if(e===`file`&&(isSystemDoc(S)||isConfigDoc(S))||E||D||O){errorResponse(t,400,O?`urn:ok:error:invalid-request`:`urn:ok:error:reserved-doc-name`,O?`Asset operations do not support markdown documents.`:`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(e===`asset`){Ue(),oe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let k=w(),j=e===`file`?k.has(S)?[S]:[]:listAffectedDocNames(k,e,S);if(Ue(),j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Bt(j),we)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(we.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));let F=w();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e},F);e===`folder`&&ze(S),oe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:j},{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`}),Sc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=t,w,E=getDocExtension(t);try{let s=readFileSync(resolve(g,`${t}${E}`),`utf-8`);e=extractPageTitle(s,t),w=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}s.push({docName:t,title:e,docExt:E,size:S.size,modified:S.modified,icon:w})}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}),Cc=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 wc(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,me??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:E,byteLength:D,parentDocName:O}=s,k=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},j=validateBody(UploadRequestSchema,{parentDocName:O},t,{handler:`upload-asset`});if(!j.ok){k();return}let{parentDocName:F}=j.value,{agentId:L,agentName:B}=Ur(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(D===0){k(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(F.includes(`\0`)||F.includes(`..`)||F.startsWith(`/`)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let H=resolve(g),q=resolveUploadDestDir(F,`./`,H);if(!isWithinContentDir(q,H)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(q,H)}catch(e){if(k(),(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$4.error({err:e,destDir:q},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(q,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){k();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(q),s;try{s=realpathSync(H)}catch{s=H}if(!isWithinContentDir(e,s)){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){k(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let J=await fileTypeFromFile(w),Y=J?.mime,ee=J?.ext;if(!Y){let e=readTempFileHead(w,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(Y=`image/svg+xml`,ee=`svg`)}{let s=await findDuplicateAsset(q,E,D);if(s){k();let S=relative(g,resolve(q,s));log$4.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,dedup:!0,mime:Y??null,size:D,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let te;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=ee??t??``;te=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else te=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,q,te),S=relative(g,resolve(q,s));log$4.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,dedup:!1,mime:Y??null,size:D,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$4.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:L,agentName:B,filename:te,size:D,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Tc=`/api/local-op/clone`,Ec=`/api/local-op/open`,Dc=`/api/local-op/ok-init`,Oc=600*1e3,kc=45e3,Ac=`local-op-clone`,jc=withValidation(LocalOpCloneRequestSchema,Mc,{handler:Ac,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ac})});async function Mc(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:Ac,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:Ac,cause:Error(`dir=${S}`)});return}if(!De.tryAcquire(Tc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Ac,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,Ac),D=null,O=runCloneSubprocess({cliArgs:fe,url:g,dir:S,branch:w,timeoutMs:Oc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$4.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 Nc(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$4.error({err:e,handler:Ac},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),De.release(Tc)}})(),t.on(`close`,()=>{O.cancel()})}async function Nc(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]=fe,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),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$4.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/open] 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$4.error({cwd:s,cliCmd:e,err:t.message},`[local-op/open] 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 Pc=`local-op-open`,Fc=withValidation(LocalOpOpenRequestSchema,async(e,t,s)=>{let{dir:g,port:S}=s;if(!isSafeLocalPath(g)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:Pc,cause:Error(`dir=${g}`)});return}if(!De.tryAcquire(Ec)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:Pc,extraHeaders:{"Retry-After":`5`}});return}try{let e=await Nc(g,S);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:Pc}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:Pc,cause:Error(e.error)})}finally{De.release(Ec)}},{handler:Pc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Pc})}),Ic=`local-op-ok-init`,Lc=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:Ic,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:Ic});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Ic,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:Ic});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:Ic});return}if(!De.tryAcquire(Dc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Ic,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:Ic})}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:Ic})}finally{De.release(Dc)}},{handler:Ic,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ic})}),Rc=`/api/local-op/auth/login`,zc=`/api/local-op/auth/status`,Bc=`/api/local-op/auth/repos`,Vc=`/api/local-op/auth/signout`,Hc=`/api/local-op/auth/pat`,Uc=null,Wc=`local-op-auth-login`,Gc=withValidation(LocalOpAuthHostRequestSchema,Kc,{handler:Wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Wc})});async function Kc(e,t,s){let g=s.host??`github.com`;if(!De.tryAcquire(Rc)){let e=Uc;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:Wc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Uc=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,Wc),w=runDeviceFlowSubprocess({cliArgs:fe,host:g,timeoutMs:Oc,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(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Uc=w;let E=()=>{w.cancel(),Uc===w&&(Uc=null,De.release(Rc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Uc===w&&(Uc=null,De.release(Rc))})}let qc=`local-op-auth-status`,Jc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!De.tryAcquire(zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:qc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,{stdio:[`ignore`,`pipe`,`pipe`],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(`
1711
+ `).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:qc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:qc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:qc,cause:e})}finally{De.release(zc)}},{handler:qc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:qc})}),Yc=`local-op-auth-repos`,Xc=withValidation(LocalOpAuthHostRequestSchema,Zc,{handler:Yc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Yc})});async function Zc(e,t,s){let g=s.host??`github.com`;if(!De.tryAcquire(Bc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Yc,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,Yc),[w,...E]=fe,D=[...E,`auth`,`repos`,`--json`,`--host`,g],O=!1,k=``,j=spawn(w,D,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),F=setTimeout(()=>{j.kill(`SIGTERM`)},Oc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
1712
+ `);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$4.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(),De.release(Bc))}),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()),De.release(Bc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),De.release(Bc))})}let Qc=`local-op-auth-signout`,$c=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!De.tryAcquire(Vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Qc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,{stdio:`ignore`,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:Qc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Qc,cause:e})}finally{De.release(Vc)}},{handler:Qc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Qc})}),nl=`local-op-auth-pat`,il=withValidation(LocalOpAuthPatRequestSchema,async(e,t,s)=>{let{pat:g,host:S}=s,w=S??`github.com`;if(!De.tryAcquire(Hc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:nl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`pat`,`--json`,`--host`,w],E=(await new Promise((t,s)=>{let w=spawn(e,S,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),E=setTimeout(()=>{w.kill(`SIGTERM`)},3e4);w.stdin.write(`${g}\n`),w.stdin.end();let D=[];w.stdout.on(`data`,e=>D.push(e)),w.on(`close`,e=>{clearTimeout(E),e===0?t(Buffer.concat(D).toString(`utf-8`)):s(Error(`auth pat exited with code ${e}`))}),w.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
1713
+ `).map(e=>e.trim()).filter(Boolean),D=null;for(let e=E.length-1;e>=0;e--)try{D=JSON.parse(E[e]);break}catch{}D===null?successResponse(t,200,LocalOpAuthPatSuccessSchema,{},{handler:nl}):successResponse(t,200,LocalOpAuthPatSuccessSchema,D,{handler:nl})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:nl,cause:e})}finally{De.release(Hc)}},{handler:nl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:nl})}),al=`local-op-auth-identity`;async function cl(e,t){if(checkLocalOpSecurity(e,t,{handler:al})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:al,extraHeaders:{Allow:`GET`}});return}if(!me){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:al});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(me)},{handler:al})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:al,cause:e})}}}let ll=`/api/local-op/auth/set-identity`,ul=`local-op-auth-set-identity`,dl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!me){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:ul});return}if(!De.tryAcquire(ll)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:ul,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(me,g,S),de?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:ul})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:ul,cause:e})}finally{De.release(ll)}},{handler:ul,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ul})});async function fl(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=de?.();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 pl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=de?.();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`})?de?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function ml(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=de?.();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 hl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=de?.();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`})?de?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function gl(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(!me){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=de?.(),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:me,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=Te?Te(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 _l(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 vl=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 yl(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 xl=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 Cl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,We.probeAll)}catch(e){t.headersSent||(log$4.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}))}}async function Tl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-abort-merge`}))return;if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-abort-merge`,extraHeaders:{Allow:`POST`}});return}let s=de?.();if(!s){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-abort-merge`});return}try{await s.abortMerge(),successResponse(t,200,SyncAbortMergeSuccessSchema,{},{handler:`sync-abort-merge`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to abort merge.`,{handler:`sync-abort-merge`,cause:e})}}let El=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ae){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:ae.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 Dl(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(!ae){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=ae.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:Ke(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 Ol(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 kl=/^[A-Za-z0-9_-]+$/;function jl(e,t,s=`template`){return!e||!kl.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 Ml(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 Pl(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 Fl(e,t){if(e.method===`GET`)return Il(e,t);if(e.method===`PUT`)return Ll(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Il=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Ol(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}),Ll=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,ge);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=Ol(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`&&(Xr(e,Yr(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Zr(`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 Rl(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}let zl=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 Bl(e,t){if(e.method===`GET`)return Ul(e,t);if(e.method===`PUT`)return Wl(e,t);if(e.method===`POST`)return Kl(e,t);if(e.method===`DELETE`)return Gl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Vl=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Hl=e=>{let t=e.match(Vl),s={},g=e;if(t){try{let e=(0,import_dist$1.parse)(t[1]??``);e&&typeof e==`object`&&!Array.isArray(e)&&(s=e)}catch{}g=e.slice(t[0].length)}return{frontmatter:s,body:g}},Ul=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=Ol(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Ml(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,{frontmatter:F,body:L}=Hl(await readFile$1(O,`utf-8`));successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:F,body:L}},{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}),Wl=withValidation(TemplatePutRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,ge);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let g=s.name;if(!jl(g,t,`template-put`))return;let S=Ol(s.folder,t,`folder`,`template-put`);if(!S||Rl(S.folderRel,g,`template-put`,t))return;let w=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g,body:typeof s.body==`string`?s.body:``,frontmatter:Pl(s.frontmatter)});if(!w.ok){let e=w.error.code===`WRITE_ERROR`||w.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 write template.`:`Invalid template request.`,{handler:`template-put`,detail:w.error.code,cause:Error(w.error.message)});return}Xr(e,Yr(`template`,S.folderRel,g),`${w.created?`template-create`:`template-edit`}: ${w.path}`),await Zr(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:w.path,created:w.created,warnings:w.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`}),Gl=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=Ol(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},ge);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Rl(S.folderRel,g,`template-delete`,t))return;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&&(Xr(E,Yr(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Zr(`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}),Kl=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,ge);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=Ol(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Ol(s.toFolder,t,`folder`,`template-move`);if(!S||Rl(g.folderRel,s.fromName,`template-move`,t))return;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(me,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=Ml(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=Hl(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`)).body}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:Pl(s.frontmatter)});t.ok||(E=t.error)}}if(Xr(e,Yr(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Zr(`template-move`),oe?.(`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`});function ql(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 Jl(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}`}function Yl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Xl(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`);return s.length>0?s:void 0}async function Zl(){let e=[];for(let[t,s]of w()){if(isSystemDoc(t)||isConfigDoc(t))continue;let g=``,S=t;try{g=await readFile$1(s.canonicalPath,`utf-8`),S=extractPageTitle(g,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:S,content:g,modifiedTs:Date.parse(s.modified)}))}return[...e,...ql(e)]}function Ql(){return[...w()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function $l(){let e=`${g}${me??``}`,t=Ql(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return s.corpus;if(s?.fingerprint===t&&s.pending)return s.pending;let S=Zl().then(e=>createWorkspaceSearchCorpus(e));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}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function eu(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{$l().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}eu();async function tu(e,t){if(e.method===`GET`)return nu(e,t);if(e.method===`POST`)return ru(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let nu=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Yl(s.searchParams.get(`intent`)),E=Xl(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),D=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{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:S,intent:w,results:searchWorkspaceCorpus(await $l(),S,{intent:w,scopes:E,limit:D}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Jl(e.document.content,S):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{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}),ru=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Yl(s.intent),w=Xl(s.scopes??s.scope),E=typeof s.limit==`number`?s.limit:void 0;if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:g,intent:S,results:searchWorkspaceCorpus(await $l(),g,{intent:S,scopes:w,limit:E}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Jl(e.document.content,g):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{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`}),iu=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 au(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$4.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 ou(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$4.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 su=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!me){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidSharePath(s.kind===`doc`?s.docPath:s.folderPath,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 e=readGitHeadBranch(me);if(e===null){if(readOriginGitHubRepo(me).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 S=readOriginGitHubRepo(me);if(S.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(S.kind===`non-github`){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(me,e)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=toGitRelativePath(me,g);if(w===null)throw Error(`content dir is not contained within the project dir`);let E=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;w!==``&&E&&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 D;if(s.kind===`doc`)D=buildGitHubBlobUrl(S.owner,S.repo,e,s.docPath);else{let t=s.folderPath===``?w:s.folderPath;D=buildGitHubTreeUrl(S.owner,S.repo,e,t)}let O=`${SHARE_BASE_URL}${encodeShareUrl(D)}`;emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:O,sharedUrl:D,branch:e},{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})}),cu=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!me){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(me,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}),lu=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,ge).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!me){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(me,s.branch)),{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 uu(e){let[t,...s]=fe,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,{stdio:[`ignore`,`pipe`,`pipe`],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 du=withValidation(EmptyRequestSchema,async(e,t)=>{if(!De.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 uu([`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{De.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})}),fu=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(!De.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 uu([`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{De.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})}),pu=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!me){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(!De.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`,me,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await uu(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&de?.()?.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{De.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),mu=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`})}),hu=me?getLocalDir(me):null;async function gu(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}hu&&clearArmedPaneTarget(hu),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:hu?readServerLock(hu)?.port??0:0,paneTarget:hu?readArmedPaneTarget(hu):null};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, DELETE`}})}let _u={"/api/config":gu,"/api/asset":lc,"/api/asset-text":dc,"/api/document":Gi,"/api/documents":Ki,"/api/backlinks":Yi,"/api/backlink-counts":Xi,"/api/forward-links":Zi,"/api/link-graph":ka,"/api/dead-links":Cs,"/api/orphans":_s,"/api/hubs":xs,"/api/tags":El,"/api/pages":Sc,"/api/folder-config":Fl,"/api/template":Bl,"/api/templates":zl,"/api/search":tu,"/api/suggest-links":Cc,"/api/page-headings":vc,"/api/create-page":hc,"/api/create-folder":gc,"/api/duplicate-path":_c,"/api/rename-path":yc,"/api/delete-path":bc,"/api/trash/cleanup":xc,"/api/upload":wc,"/api/agent-write":Qr,"/api/agent-write-md":ji,"/api/frontmatter-patch":Hi,"/api/agent-patch":Ts,"/api/agent-undo":Ds,"/api/agent-activity":Os,"/api/agent-burst-diff":ks,"/api/save-version":Is,"/api/history":Rs,"/api/diff":ec,"/api/rollback":tc,"/api/metrics/reconciliation":nc,"/api/metrics/parse-health":rc,"/api/metrics/agent-presence":oc,"/api/__embed-detect":sc,"/api/server-info":ic,"/api/share/construct-url":su,"/api/git/branch-info":cu,"/api/git/checkout":lu,"/api/share/publish/owners":du,"/api/share/publish/name-check":fu,"/api/share/publish":pu,"/api/principal":ac,"/api/rescue":pc,"/api/workspace":cc,"/api/sync/status":fl,"/api/sync/trigger":pl,"/api/sync/conflicts":ml,"/api/sync/conflict-content":gl,"/api/sync/resolve-conflict":hl,"/api/sync/abort-merge":Tl,"/api/local-op/clone":jc,"/api/local-op/open":Fc,"/api/local-op/ok-init":Lc,"/api/local-op/auth/login":Gc,"/api/local-op/auth/status":Jc,"/api/local-op/auth/repos":Xc,"/api/local-op/auth/signout":$c,"/api/local-op/auth/pat":il,"/api/local-op/auth/identity":cl,"/api/local-op/auth/set-identity":dl,"/api/installed-agents":Cl,"/api/spawn-cursor":ou,"/api/handoff":au,"/api/install-skill":xl,"/api/skill/install-state":iu,"/api/seed/plan":_l,"/api/seed/apply":vl,"/api/seed/packs":yl,"/api/client-logs":mu};j&&(_u[`/api/test-reset`]=As,_u[`/api/test-rescan-backlinks`]=Ns,_u[`/api/test-rescan-files`]=Ps);let vu=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/sync/abort-merge./api/git/checkout./api/test-reset./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/seed/apply./api/client-logs`.split(`.`)),yu=[`/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(vu.has(s)||yu.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(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/rescue/`)?E=`/api/rescue/:docName`:s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:_u[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=_u[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/rescue/`)){let g=decodeURIComponent(s.slice(12));g&&(E=!0,await mc(e,t,g))}else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await $s(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Dl(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 isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedBasenameIndex(e){let t=e.contentDir,s=new Set;function g(S){let w;try{w=readdirSync(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=relative(t,w);if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=lstatSync(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=realpathSync(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=statSync(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()?g(S):E.isFile()&&isSupportedAssetFile(w,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),g(w);continue}O.isFile()&&isSupportedAssetFile(w,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}g(t)}const HocuspocusAuthTokenSchema=object$1({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch: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`];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 log$3=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$3.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$3.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$3.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-CvT4CaVU-BJSxTfe_.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(g!==t&&!g.startsWith(`${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$3.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
1713
1714
  `).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:s});g=e.length>0}catch(e){log$3.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$3.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 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`],{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],{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}`],{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(`Open Knowledge 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 Open Knowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
1714
1715
  `)}function buildTooOldMessage(e,t,s,g){let S=[];if(S.push(`Open Knowledge 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 Open Knowledge.`),S.push("Run `ok diagnose health --check git` to verify your installation."),S.join(`
1715
- `)}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}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 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:{contentDir:e.contentDir,spansMaxBytes:g,attributeDenylist:w},logs:{contentDir:e.contentDir,maxBytes:S}}}const MCP_SERVER_NAME=`open-knowledge`,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 buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `exec("ls -A <dir>")`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut` — pipes OK) and returns raw stdout plus enriched metadata per file.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment.\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir, the folder\'s own `title`/`description`/`tags` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, or to land them on a finished deliverable (see below) — not to re-check your own edits.\n\n**End a turn on the deliverable, not your scratch space.** Keep the preview steady *during* a multi-doc task — don\'t yank it around to re-check your own edits. But when a turn created or substantially changed user-facing docs, navigate the preview to the primary deliverable before you hand back: the hub / overview / index page when you created several docs, or the changed doc when you changed one. Don\'t step the user through every supporting source card — the user is watching, so leave them on the result.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session. If a tool can navigate to a URL, it counts as an in-app browser — match on the capability, not on what your host is called.\n\n- **You have `preview_*` tools** (e.g. `preview_start` + `preview_eval`) → **First open of the session:** to land directly on a doc, arm it first with `get_preview_url({ armPaneTarget: true, docName })` (or `folder`), then `preview_start("open-knowledge-ui")` — `ok ui` redirects the base-open straight to the armed route, so the pane opens on the doc, not root. Plain `preview_start` (no arm) opens at root. **Moving between docs once the pane is open: do it in one `preview_eval` step — set `window.location.hash` to the target\'s route fragment from the response `previewUrl`, the part from `#` on (e.g. `window.location.hash = \'#/specs/foo/SPEC\'`).** That drives the SPA router directly. Arm + `preview_start` only redirects a *fresh* open; it can\'t move an already-open pane (`preview_start` reuses the live process without reloading), so use `preview_eval` there. Don\'t read or edit `.claude/launch.json` — host-managed; the OK lock-collision proxy handles the UI-already-running case. If `preview_start` fails, report it; don\'t "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** — Codex\'s built-in browser, or any host tool that navigates to a URL (`browser`, `view_url`, `open_url`, `web.browse`, etc.) → call `get_preview_url` once for the **exact** target (`docName` for a doc, `folder` for a folder) and navigate your **in-app browser** straight to the returned `url`. Open that deep URL directly — never the root then navigate. Omit both args only for the root.\n- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all, e.g. the Claude Code CLI) → for an "open `<doc>`/`<folder>`" request, run **`ok open <doc>`** (`--folder` for a folder) — opens the doc in OK Desktop via deep link (folders in the browser), with browser fallback; an action, not a URL to print. No `ok` on PATH or no shell → `get_preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly. The system browser is the fallback, never the default.\n- **Honor `autoOpen`** (on `get_preview_url`, or on `warning` for write tools). If `false`, do not open or refresh any preview UI; surface the URL only if asked.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `get_preview_url` → in-app browser).\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the three attach-warning tools: `write_document` / `edit_document` / `edit_frontmatter`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete_document` / `rename` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `get_preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed. (Navigating the pane with `preview_eval` by setting `window.location.hash` is fine — that drives the view, it is not a read-back verification loop.)\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `get_config({ path: [\'content\', \'dir\'] })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. A folder\'s own metadata + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If substantial folders have no frontmatter of their own and no `templates_available`, the project isn\'t onboarded — invoke `discover` (Workflow tools table) before writing.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}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 loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,s={}){let g=t?{error:t instanceof Error?t.message:String(t),...s}:s;this.emit(`error`,e,g)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,s){let g={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...s},S=`${JSON.stringify(g)}\n`;process.stderr.write(S);let w=process.env.OK_LOG_FILE;if(w)try{appendFileSync(w,S)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
1716
- `).length};let s=e===`command`?240:120;return t.length<=s?t:{type:`string`,length:t.length,preview:`${t.slice(0,s)}...`}}function summarizeArgValue(e,t){if(t===null)return null;if(typeof t==`string`)return summarizeStringForLog(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(isPlainObject(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function summarizeArgsForLog(e,t){return isPlainObject(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,summarizeArgValue(e,t)])):summarizeArgValue(e,t)}function summarizeStructuredContentForLog(e){let t={structuredKeys:Object.keys(e).sort()};for(let s of COMMON_SCALAR_KEYS)s in e&&(t[s]=e[s]);for(let s of COMMON_ARRAY_KEYS){let g=e[s];Array.isArray(g)&&(t[`${s}Count`]=g.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),typeof e.stdout==`string`&&(t.stdoutChars=e.stdout.length),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),isPlainObject(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),t}function summarizeToolResultForLog(e){if(!isPlainObject(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>isPlainObject(t)&&typeof t.text==`string`?e+t.text.length:e,0)),isPlainObject(e.structuredContent)&&Object.assign(t,summarizeStructuredContentForLog(e.structuredContent)),t}function summarizeIdentityForLog(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{}}}function splitInvocationArgs(e){let t=e.at(-1);return isToolExtraLike(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function wrapToolHandlerForLogging(e,t,s){let g=s.logger;return g?async(...S)=>{let w=g.child(),E=Date.now(),{toolArgs:D,extra:O}=splitInvocationArgs(S);w.info(`tool start`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},...O?.sessionId?{transportSessionId:O.sessionId}:{},...s.identityRef?.current?{agent:summarizeIdentityForLog(s.identityRef.current)}:{},...D===void 0?{}:{args:summarizeArgsForLog(e,D)}});try{let s=await runWithMcpLogger(w,async()=>await t(...S));return w.info(`tool finish`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E,result:summarizeToolResultForLog(s)}),s}catch(t){throw w.error(`tool error`,t,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E}),t}}:t}function createLoggedServer(e,t){if(!t.logger)return e;let s=e.tool.bind(e),g=e.registerTool,S=typeof g==`function`?g.bind(e):void 0,w=Object.create(e);return w.tool=((...e)=>{let g=String(e[0]),S=e.at(-1);if(typeof S!=`function`)return s(...e);let w=[...e];return w[w.length-1]=wrapToolHandlerForLogging(g,S,t),s(...w)}),S&&(w.registerTool=((e,s,g)=>typeof g==`function`?S(e,s,wrapToolHandlerForLogging(e,g,t)):S(e,s,g))),w}function buildBody$2(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** the output is the source of truth for future agents.
1716
+ `)}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}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 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_SERVER_NAME=`open-knowledge`,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 buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `exec("ls -A <dir>")`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut`) and returns raw stdout plus enriched metadata per file. One command or a pipe (`|`) per call — it is NOT a shell, so `&&` / `;` / redirects are rejected; list several dirs with `ls -A a b c` or make separate calls.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment.\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir, the folder\'s own `title`/`description`/`tags` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, or to land them on a finished deliverable (see below) — not to re-check your own edits.\n\n**End a turn on the deliverable, not your scratch space.** Keep the preview steady *during* a multi-doc task — don\'t yank it around to re-check your own edits. But when a turn created or substantially changed user-facing docs, navigate the preview to the primary deliverable before you hand back: the hub / overview / index page when you created several docs, or the changed doc when you changed one. Don\'t step the user through every supporting source card — the user is watching, so leave them on the result.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session. If a tool can navigate to a URL, it counts as an in-app browser — match on the capability, not on what your host is called.\n\n- **You have `preview_*` tools** (e.g. `preview_start` + `preview_eval`) → **First open of the session:** to land directly on a doc, arm it first with `preview_url({ armPaneTarget: true, document })` (or `folder`), then `preview_start("open-knowledge-ui")` — `ok ui` redirects the base-open straight to the armed route, so the pane opens on the doc, not root. Plain `preview_start` (no arm) opens at root. **Moving between docs once the pane is open: do it in one `preview_eval` step — set `window.location.hash` to the target\'s route fragment from the response `previewUrl`, the part from `#` on (e.g. `window.location.hash = \'#/specs/foo/SPEC\'`).** That drives the SPA router directly. Arm + `preview_start` only redirects a *fresh* open; it can\'t move an already-open pane (`preview_start` reuses the live process without reloading), so use `preview_eval` there. Don\'t read or edit `.claude/launch.json` — host-managed; the OK lock-collision proxy handles the UI-already-running case. If `preview_start` fails, report it; don\'t "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** — Codex\'s built-in browser, or any host tool that navigates to a URL (`browser`, `view_url`, `open_url`, `web.browse`, etc.) → call `preview_url` once for the **exact** target (`document` for a doc, `folder` for a folder) and navigate your **in-app browser** straight to the returned `url`. Open that deep URL directly — never the root then navigate. Omit both args only for the root.\n- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all, e.g. the Claude Code CLI) → for an "open `<doc>`/`<folder>`" request, run **`ok open <doc>`** (`--folder` for a folder) — opens the doc in OK Desktop via deep link (folders in the browser), with browser fallback; an action, not a URL to print. No `ok` on PATH or no shell → `preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly. The system browser is the fallback, never the default.\n- **Honor `autoOpen`** (on `preview_url`, or on `warning` for write tools). If `false`, do not open or refresh any preview UI; surface the URL only if asked.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `preview_url` → in-app browser).\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the two attach-warning tools: `write` / `edit`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete` / `move` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed. (Navigating the pane with `preview_eval` by setting `window.location.hash` is fine — that drives the view, it is not a read-back verification loop.)\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `config({ key: \'content.dir\' })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. A folder\'s own metadata + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If substantial folders have no frontmatter of their own and no `templates_available`, the project isn\'t onboarded — invoke `workflow({ kind: \'discover\' })` before writing.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}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 loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,s={}){let g=t?{error:t instanceof Error?t.message:String(t),...s}:s;this.emit(`error`,e,g)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,s){let g={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...s},S=`${JSON.stringify(g)}\n`;process.stderr.write(S);let w=process.env.OK_LOG_FILE;if(w)try{appendFileSync(w,S)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
1717
+ `).length};let s=e===`command`?240:120;return t.length<=s?t:{type:`string`,length:t.length,preview:`${t.slice(0,s)}...`}}function summarizeArgValue(e,t){if(t===null)return null;if(typeof t==`string`)return summarizeStringForLog(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(isPlainObject(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function summarizeArgsForLog(e,t){return isPlainObject(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,summarizeArgValue(e,t)])):summarizeArgValue(e,t)}function summarizeStructuredContentForLog(e){let t={structuredKeys:Object.keys(e).sort()};for(let s of COMMON_SCALAR_KEYS)s in e&&(t[s]=e[s]);for(let s of COMMON_ARRAY_KEYS){let g=e[s];Array.isArray(g)&&(t[`${s}Count`]=g.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),typeof e.stdout==`string`&&(t.stdoutChars=e.stdout.length),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),isPlainObject(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),t}function summarizeToolResultForLog(e){if(!isPlainObject(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>isPlainObject(t)&&typeof t.text==`string`?e+t.text.length:e,0)),isPlainObject(e.structuredContent)&&Object.assign(t,summarizeStructuredContentForLog(e.structuredContent)),t}function summarizeIdentityForLog(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{}}}function splitInvocationArgs(e){let t=e.at(-1);return isToolExtraLike(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function wrapToolHandlerForLogging(e,t,s){let g=s.logger;return g?async(...S)=>{let w=g.child(),E=Date.now(),{toolArgs:D,extra:O}=splitInvocationArgs(S);w.info(`tool start`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},...O?.sessionId?{transportSessionId:O.sessionId}:{},...s.identityRef?.current?{agent:summarizeIdentityForLog(s.identityRef.current)}:{},...D===void 0?{}:{args:summarizeArgsForLog(e,D)}});try{let s=await runWithMcpLogger(w,async()=>await t(...S));return w.info(`tool finish`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E,result:summarizeToolResultForLog(s)}),s}catch(t){throw w.error(`tool error`,t,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E}),t}}:t}function createLoggedServer(e,t){if(!t.logger)return e;let s=e.tool.bind(e),g=e.registerTool,S=typeof g==`function`?g.bind(e):void 0,w=Object.create(e);return w.tool=((...e)=>{let g=String(e[0]),S=e.at(-1);if(typeof S!=`function`)return s(...e);let w=[...e];return w[w.length-1]=wrapToolHandlerForLogging(g,S,t),s(...w)}),S&&(w.registerTool=((e,s,g)=>typeof g==`function`?S(e,s,wrapToolHandlerForLogging(e,g,t)):S(e,s,g))),w}const DESCRIPTION$16=[`[Requires: Hocuspocus server] Save a project-wide checkpoint of every document — a single restore point you can return to.`,``,`**Parameters:**`,'- `summary` — Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Appears as the checkpoint subject in `history`. Avoid secrets or PII — persisted to git history.',``,"Returns `{ version }` — the 40-char checkpoint SHA. Find checkpoints later via `history`; restore a single doc with `restore_version({ document, version })`."].join(`
1718
+ `);function register$16(e,t){e.registerTool(`checkpoint`,{description:DESCRIPTION$16,inputSchema:{summary:summaryArgSchema.describe(`Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({version:string().describe(VERSION_FIELD_DESCRIBE),previewUrl:previewUrlOutputField.describe(`Always null — a checkpoint is project-wide, not scoped to one doc.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=t.identityRef?.current,w=await httpPost(g,`/api/save-version`,{...e.summary===void 0?{}:{summary:e.summary},...S?{writers:[{id:`agent-${S.connectionId}`,name:S.displayName,email:`agent-${S.connectionId}@openknowledge.local`}]}:{}});if(!w.ok)return textResult(`Error: ${w.error}`,!0);let E=typeof w.checkpointRef==`string`?w.checkpointRef:``,D=E.split(`/`).pop()??``;return/^[0-9a-f]{40}$/i.test(D)?textPlusStructured(`Checkpoint saved. Version: ${D}`,{version:D,previewUrl:null}):textResult(`Error: checkpoint committed but the server returned no usable version ref ("${E}"). Find the latest checkpoint via \`history\`.`,!0)})}const DESCRIPTION$15=[`[Operates on disk; no running OK server required] Read the effective merged Open Knowledge config (defaults → user → project).`,``,`Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.`,``,"Read returns the FULL merged config or a sub-tree when `key` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, and `github.*` config sub-trees, plus `preview.baseUrl`, were removed; their values are now built-in constants in `@inkeep/open-knowledge-core`. Reading those keys returns `exists: false`. (`preview.scriptSrc` and `appearance.preview.autoOpen` are still live keys.)",``,`**Parameters:**`,'- `key` (optional) — Dotted config key. `"content"` returns the content sub-tree; `"appearance.theme"` returns just that leaf. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
1719
+ `),InputSchema$3={key:string().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$5=outputSchemaWithText({value:unknown().describe(`Resolved config value at the requested path (or full config).`),exists:boolean().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:string().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)});function readConfigPath(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s)return;s=s[e]}return s}function register$15(e,t){e.registerTool(`config`,{description:DESCRIPTION$15,inputSchema:InputSchema$3,outputSchema:OutputSchema$5,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=e.key?e.key.split(`.`).filter(e=>e.length>0):[],S=g.length>0?readConfigPath(s.config,g):s.config;return g.length>0&&S===void 0?textPlusStructured(`(no value at ${e.key})`,{value:null,exists:!1,...e.key?{key:e.key}:{}}):textPlusStructured(JSON.stringify(S,null,2),{value:S,exists:!0,...e.key?{key:e.key}:{}})})}const DESCRIPTION$14=["[Requires: Hocuspocus server] Read GitHub-sync merge conflicts. Dispatches on `kind`:",``,'- `kind: "list"` — enumerate every doc currently tracked in a merge-conflict state. Returns `{ list: [{ file, detectedAt, ... }] }` (empty when none). The entry point to the resolve flow.','- `kind: "content"` — fetch the three merge stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, lifecycleStatus } }`. `ours` reflects the live Y.Text (what the human sees) when the doc is loaded server-side.',``,`**Parameters:**`,"- `kind` — `list` | `content`.",'- `file` — Required for `kind: "content"`. Relative path WITH the `.md`/`.mdx` extension (e.g. `notes/sso.md`) — git stages key on the exact path, so do NOT strip the extension.',``,"The `shape` field discriminates the conflict: `both-modified` (both sides edited), `delete-modify` (you deleted, they edited — `ours` empty), or `modify-delete` (you edited, they deleted — `theirs` empty). Use it to pick the `resolve_conflict` strategy."].join(`
1720
+ `);function register$14(e,t){e.registerTool(`conflicts`,{description:DESCRIPTION$14,inputSchema:{kind:_enum([`list`,`content`]).describe("`list` enumerates tracked conflicts; `content` fetches one file's stages."),file:string().min(1).optional().describe('Required when `kind: "content"`. Conflicted file WITH extension (e.g. `notes/sso.md`) — git stages key on the exact path, so keep the extension (DD2).'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({list:looseObjectArray.optional().describe('`kind: "list"` — every tracked conflict (`{ file, detectedAt, ... }`).'),content:object$1({file:string().describe(`The conflicted file.`),base:string().describe(`Merge-base stage content.`),ours:string().describe(`Our stage (live Y.Text when loaded server-side).`),theirs:string().describe(`Their stage content.`),shape:_enum([`both-modified`,`delete-modify`,`modify-delete`]).describe("Conflict shape — pick the `resolve_conflict` strategy from it."),lifecycleStatus:string().nullable().describe(`The doc's lifecycle status, or null.`)}).optional().describe('`kind: "content"` — the three merge stages + shape + lifecycle.')}),annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.kind===`content`){if(!e.file)return textResult('Error: `kind: "content"` requires `file` — the conflicted file WITH extension, e.g. conflicts({ kind: "content", file: "notes/sso.md" }).',!0);let t=await httpGet(g,`/api/sync/conflict-content${`?file=${encodeURIComponent(e.file)}&source=ytext`}`);if(!t.ok){let e=t.error,s=typeof t.detail==`string`?t.detail:void 0;return textResult(`Error: ${s?`${e} — ${s}`:e}`,!0)}let s=t,S=typeof s.file==`string`?s.file:e.file,w=typeof s.base==`string`?s.base:``,E=typeof s.ours==`string`?s.ours:``,D=typeof s.theirs==`string`?s.theirs:``,O=s.kind===`delete-modify`||s.kind===`modify-delete`?s.kind:`both-modified`,k=typeof s.lifecycleStatus==`string`?s.lifecycleStatus:null;return textPlusStructured(`Conflict stages for ${S} (shape: ${O})${k?` (lifecycle: ${k})`:``}:\n--- base ---\n${w}\n--- ours ---\n${E}\n--- theirs ---\n${D}`,{content:{file:S,base:w,ours:E,theirs:D,shape:O,lifecycleStatus:k}})}let S=await httpGet(g,`/api/sync/conflicts`);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let w=S.conflicts,E=Array.isArray(w)?w:[];return textPlusStructured(E.length===0?`No conflicts tracked.`:`Tracked conflicts (${E.length}):\n${E.map(e=>`- ${e&&typeof e==`object`&&`file`in e?String(e.file??``):``}`).join(`
1721
+ `)}`,{list:E})})}const PREVIEW_URL_SOURCES=[`lock`];function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function encodeFolderRoute(e){let t=e.replace(/^\/+|\/+$/g,``);return t?`${encodeDocName(t)}/`:``}const START_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',ATTACH_PREVIEW_ONCE_MESSAGE=`No browser is attached to the preview. Open it with preview_start, or call preview_url for the URL.`;function buildPreviewAttachWarning(e,t){return e?{action:`attach-preview-once`,previewUrl:e.url,message:ATTACH_PREVIEW_ONCE_MESSAGE,autoOpen:t}:{action:`start-ui`,previewUrl:null,message:START_UI_MESSAGE,autoOpen:t}}const START_UI_TEXT_HINT=START_UI_MESSAGE;async function resolvePreviewUrlForTool(e,t,s){return resolvePreviewUrl(e,{lockDir:resolveLockDir(s??await t.resolveCwd())})}function resolveUiInfo(e){try{let t=readUiLock(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while resolving ui info: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null}}async function buildListResolver(e,t){let s={lockDir:resolveLockDir(t??await e.resolveCwd())};return{resolve:e=>resolvePreviewUrl(e,s)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let s=`/#/${encodeDocName(e)}`;try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:s,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const FrontmatterPatchValue=union([FrontmatterValueSchema,_null()]),FrontmatterArg=record(string(),FrontmatterPatchValue).describe(`Metadata as a flat key→value map (string | number | boolean | string[]). Merge-patch: include a key to set it, set a key to null to delete it; keys you omit are unchanged. Example: { title: "Q3 Planning", tags: ["planning"], status: "draft" }.`),PositionArg=_enum([`append`,`prepend`,`replace`]).describe(`Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). append / prepend = add to the end / start.`);function splitTargetPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),s=t.lastIndexOf(`/`);return s===-1?{folder:``,name:t}:{folder:t.slice(0,s),name:t.slice(s+1)}}const TEMPLATE_NAME_REGEX=/^[A-Za-z0-9_-]+$/,TEMPLATE_PATH_DESCRIBE='Template path = `<folder>/<name>` (e.g. "fishing-log/trip-log"). The slashes are the folder it belongs to; the final segment is the template name (letters, digits, `_`, `-` only — no dots/spaces). Stored at `<folder>/.ok/templates/<name>.md`.',TEMPLATE_CONTENT_DESCRIBE="Template Markdown body. Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time.";function resolveTemplatePath(e){let{folder:t,name:s}=splitTargetPath(e);return TEMPLATE_NAME_REGEX.test(s)?{ok:!0,folder:t,name:s}:{ok:!1,error:`the final segment of a template path is its name — "${s}" must be letters, digits, \`_\`, \`-\` only (no dots/spaces). e.g. { template: { path: "fishing-log/trip-log" } }.`}}function exactlyOneTargetError(e,t){let s=t.filter(t=>e[t]!==void 0);if(s.length===1)return null;let g=t.map(e=>`\`${e}\``).join(`, `);return s.length===0?`Name exactly one of ${g} — the one thing you are addressing. Nest that target's fields under its key (e.g. \`{ document: { path, … } }\`); see this tool's parameter docs for which fields each target takes.`:`You named ${s.map(e=>`\`${e}\``).join(` and `)} — name exactly ONE target.`}const DESCRIPTION$13=["Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, or `asset`.",``,"- `document` — Doc path(s) to delete (a single path or an array). Inbound links become redlinks. Irreversible. [Requires: Hocuspocus server]","- `folder` — Folder path to delete (recursive). [Requires: Hocuspocus server]",'- `template` — `{ path: "<folder>/<name>" }` — a template to delete (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]','- `asset` — `{ path: "<folder>/<file.ext>" }` — a binary asset to delete. [Requires: Hocuspocus server]',``,'Call `links({ kind: "backlinks", document })` BEFORE deleting a doc to see what links here.'].join(`
1722
+ `);function parseDeletedDocNames(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}async function deleteOneDoc(e,t,s,g){let S=normalizeDocName(e);if(!S.ok)return{docName:e,ok:!1,error:S.error.replace(/^Error:\s*/,``)};let w=await httpPost(t,`/api/delete-path`,{kind:`file`,path:S.docName,...agentIdentityFields(g.identityRef?.current)});if(!w.ok)return{docName:S.docName,ok:!1,error:w.error};let E=parseDeletedDocNames(w.deletedDocNames),D=await resolvePreviewUrlForTool(S.docName,{config:g.config,resolveCwd:g.resolveCwd},s);return{docName:S.docName,ok:!0,deletedDocNames:E.length>0?E:[S.docName],...D?{previousPreviewUrl:D.url}:{}}}function register$13(e,t){e.registerTool(`delete`,{description:DESCRIPTION$13,inputSchema:{document:union([string(),array(string()).min(1),object$1({path:union([string(),array(string()).min(1)])})]).optional().describe("Doc path(s) to delete — a string, an array, or `{ path }`. Inbound links become redlinks. Irreversible."),folder:union([string(),object$1({path:string()})]).optional().describe("Folder path to delete (recursive) — a string or `{ path }`."),template:object$1({path:string().describe("Template path = `<folder>/<name>`.")}).optional().describe(`A template to delete.`),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are its folder. Example: "images/diagram.png".`)}).optional().describe(`A binary asset to delete.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({ok:boolean(),deletedDocNames:array(string()).optional().describe(`The single docName removed (a document delete never cascades to descendants).`),error:string().optional().describe("Present when `ok` is false.")}).optional().describe(`Single-document delete result.`),folder:object$1({ok:boolean(),deletedDocNames:array(string())}).optional().describe(`Folder delete result (docNames removed).`),template:object$1({ok:boolean(),existed:boolean()}).optional().describe(`Template delete result.`),asset:object$1({ok:boolean(),path:string()}).optional().describe(`Asset delete result.`),documents:looseObjectArray.optional().describe(`Batch doc delete: per-doc result records.`),previousPreviewUrl:previousPreviewUrlField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s,w=typeof e.folder==`object`?e.folder.path:e.folder,E=e.document&&typeof e.document==`object`&&!Array.isArray(e.document)?e.document.path:e.document,D=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`]);if(D)return textResult(`Error: ${D}`,!0);if(e.template!==void 0){let s=resolveTemplatePath(e.template.path);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{folder:g,name:w}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=new URLSearchParams({folder:g,name:w});for(let[e,s]of Object.entries(agentIdentityFields(t.identityRef?.current)))typeof s==`string`&&s.length>0&&E.set(e,s);let D=await httpDelete(S,`/api/template?${E.toString()}`);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.existed===!0;return textPlusStructured(O?`Deleted template "${w}" from ${g||`(root)`}.`:`Template "${w}" did not exist in ${g||`(root)`} — nothing to delete.`,{template:{ok:!0,existed:O}})}if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.folder!==void 0){let e=await httpPost(S,`/api/delete-path`,{kind:`folder`,path:w,...agentIdentityFields(t.identityRef?.current)});if(!e.ok)return textResult(`Error: ${e.error}`,!0);let s=parseDeletedDocNames(e.deletedDocNames);return textPlusStructured(`Deleted folder ${w}${s.length?` (${s.length} doc(s))`:``}.`,{folder:{ok:!0,deletedDocNames:s}})}if(e.asset!==void 0){let s=e.asset.path.replace(/^\/+/,``).replace(/\/+$/,``),g=await httpPost(S,`/api/delete-path`,{kind:`asset`,path:s,...agentIdentityFields(t.identityRef?.current)});return g.ok?textPlusStructured(`Deleted asset ${s}.`,{asset:{ok:!0,path:s}}):textResult(`Error: ${g.error}`,!0)}let O=E;if(Array.isArray(O)){let e=await Promise.all(O.map(e=>deleteOneDoc(e,S,g,t))),s=e.filter(e=>e.ok).length,w=s===e.length,E=e.map(e=>e.ok?`Deleted ${e.docName}.`:`Failed ${e.docName}: ${e.error}`);return textPlusStructured(`${s}/${e.length} deleted.\n${E.join(`
1723
+ `)}`,{documents:e},!w)}let k=await deleteOneDoc(O,S,g,t);if(!k.ok)return textPlusStructured(`Error: ${k.error??`unknown error`}`,{document:{ok:!1,error:k.error}},!0);let j=k.deletedDocNames??[k.docName];return textPlusStructured(j.length===1?`Deleted ${j[0]}.`:`Deleted ${j.length} documents: ${j.join(`, `)}.`,{document:{ok:!0,deletedDocNames:j},...k.previousPreviewUrl?{previousPreviewUrl:k.previousPreviewUrl}:{}})})}function parseContentDivergence(e){let t=WriteWarningSchema.safeParse(e);return t.success?t.data:void 0}function formatContentDivergenceLine(e){return e.kind===`content-divergence`?`⚠ Content divergence: ${e.actualBytes} actual bytes vs ${e.intendedBytes} intended (byteDelta=${e.byteDelta}). ${e.hint??`currentState carries the converged content (re-read only if it is truncated).`}`:`⚠ ${e.hint??`An out-of-band edit was reconciled into this document before your edit landed on top — re-read for the combined result.`}`}function formatContentDivergenceBrief(e){return e.kind===`content-divergence`?`⚠ Content divergence: ${e.actualBytes} actual vs ${e.intendedBytes} intended (byteDelta=${e.byteDelta}).`:`⚠ Out-of-band disk edit reconciled before this write — re-read for the combined result.`}const DESCRIPTION$12=`${["Edit one thing in place. Pass EXACTLY ONE of `document`, `folder`, or `template`. Within each: a body edit (`find` + `replace`) OR a `frontmatter` merge-patch — not both in one call.",``,"- `document` — Edit a doc [Requires: Hocuspocus server]. Body: `{ path, find, replace, occurrence? }` (occurrence = which match, 1 = first). Metadata: `{ path, frontmatter }` (merge-patch; `null` deletes a key). Body find/replace is body-only; frontmatter-intersecting finds are rejected.","- `folder` — Edit a folder (folders have no body): `{ path, frontmatter }` (merge-patch).",'- `template` — Edit a template: `{ path: "<folder>/<name>", ... }`; body `find`/`replace`/`occurrence?` or metadata `frontmatter`.',"- `summary` — Optional one-line user-outcome (≤80 chars) recorded in the timeline for any `document`, `folder`, or `template` edit. Avoid secrets or PII — persisted to git history.",``,'Responses may include `structuredContent.document.contentDivergence` when the converged Y.Text doesn\'t match the bytes your edit composed to. The edit still landed; re-read the doc with `exec("cat <path>")` to see what converged.'].join(`
1724
+ `)}\n${renderInventoryFooter()}`;function bodyOrFrontmatterError(e,t){let s=e.find!==void 0||e.replace!==void 0,g=e.frontmatter!==void 0;return e.find!==void 0&&e.replace===void 0?`\`find\` needs a \`replace\`. Body edit: { ${t}: { …, find, replace } }.`:e.replace!==void 0&&e.find===void 0?`\`replace\` needs a \`find\`. Body edit: { ${t}: { …, find, replace } }.`:s&&g?`Pick ONE: edit body text (find+replace) OR metadata (frontmatter), not both in one call.`:!s&&!g?`Provide either a body edit (find+replace) or a frontmatter patch for { ${t} }.`:null}function readDocFullText(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=resolveWithinRoot(e,`${t}${s}`);if(g.ok&&existsSync(g.abs))try{return readFileSync(g.abs,`utf-8`)}catch(e){if(e?.code===`ENOENT`)return null;throw e}}return null}function nthOccurrenceOffset(e,t,s){let g=0;for(let S=0;S<s;S++){let w=e.indexOf(t,g);if(w===-1)return-1;if(S===s-1)return w;g=w+Math.max(1,t.length)}return-1}async function handleDocBody(e,t,s,g,S,w,E){let D=normalizeDocName(e.path);if(!D.ok)return textResult(D.error,!0);let O=w.identityRef?.current,k,j=e.occurrence??1;if(j>1){let t;try{t=readDocFullText(g,D.docName)}catch(e){return textResult(`Error: cannot read "${D.docName}" to resolve occurrence ${j}: ${e instanceof Error?e.message:String(e)}.`,!0)}if(t===null)return textResult(`Error: cannot resolve occurrence ${j} — "${D.docName}" is not on disk yet. Retry with the first match (omit \`occurrence\`).`,!0);let s=nthOccurrenceOffset(t,e.find,j);if(s===-1)return textResult(`Error: \`find\` occurs fewer than ${j} times in "${D.docName}".`,!0);k=s}let F=await httpPost(S,`/api/agent-patch`,{docName:D.docName,find:e.find,replace:e.replace,...k===void 0?{}:{offset:k},...t.summary===void 0?{}:{summary:t.summary},...agentIdentityFields(O)});if(!F.ok){let e=typeof F.detail==`string`&&F.detail.length>0?F.detail:``;return textResult(e?`Error: ${F.error} (${e})`:`Error: ${F.error}`,!0)}return composeWritePreviewResult(F,D.docName,s,E,`Edit applied successfully.`)}async function handleDocFrontmatter(e,t,s,g,S,w){let E=normalizeDocName(e.path);if(!E.ok)return textResult(E.error,!0);let D=S.identityRef?.current,O=await httpPost(g,`/api/frontmatter-patch`,{docName:E.docName,patch:e.frontmatter,...t.summary===void 0?{}:{summary:t.summary},...agentIdentityFields(D)});if(!O.ok){let e=O.error,t=O.fieldErrors&&typeof O.fieldErrors==`object`?O.fieldErrors:void 0;return textResult(t?`Error: ${e}\n${Object.entries(t).map(([e,t])=>` ${e}: ${t}`).join(`
1725
+ `)}`:`Error: ${e}`,!0)}let k=[],j=[];for(let[t,s]of Object.entries(e.frontmatter))s===null?j.push(t):k.push(t);let F=[k.length?`${k.length} set`:``,j.length?`${j.length} deleted`:``].filter(Boolean).join(`, `);return composeWritePreviewResult(O,E.docName,s,w,`Frontmatter patched (${F||`${Object.keys(e.frontmatter).length} key(s)`}).`)}function composeWritePreviewResult(e,t,s,g,S){let w=resolvePreviewUrl(t,{lockDir:resolveLockDir(s)}),E=typeof e.subscriberCount==`number`?e.subscriberCount:void 0,D=(typeof e.systemSubscriberCount==`number`?e.systemSubscriberCount:void 0)===0,O=E===0,k=e.summary&&typeof e.summary==`object`?e.summary:void 0,j=typeof k?.hint==`string`?k.hint:void 0,F=parseContentDivergence(e.warning),L=[S];D&&!w&&L.push(START_UI_TEXT_HINT),j&&L.push(j),F&&L.push(formatContentDivergenceLine(F));let B=L.join(`
1726
+ `);if(!w&&!D&&!O&&!k&&!F)return textResult(B);let H={};return k&&(H.summary=k),F&&(H.contentDivergence=F),textPlusStructured(B,nestDocResult(w,D?buildPreviewAttachWarning(w,g):void 0,H))}function templateFilePath(e,t,s){let g=resolveWithinRoot(e,`${t.replace(/\/+$/,``)}/.ok/templates/${s}.md`);return g.ok?{ok:!0,abs:g.abs}:{ok:!1}}function parseTemplateFrontmatter(e){let t=e.replace(/^---\r?\n/,``).replace(/\r?\n?---\r?\n?$/,``).trim();if(t===``)return{title:``};let s=(0,import_dist$1.parse)(t);if(typeof s!=`object`||!s||Array.isArray(s))return{title:``};let g=s;return{title:typeof g.title==`string`?g.title:``,...typeof g.description==`string`?{description:g.description}:{},...Array.isArray(g.tags)?{tags:g.tags.map(e=>String(e))}:{}}}async function handleTemplate$1(e,t,s,g,S){let w=bodyOrFrontmatterError(e,`template`);if(w)return textResult(`Error: ${w}`,!0);let E=resolveTemplatePath(e.path);if(!E.ok)return textResult(`Error: ${E.error}`,!0);let{folder:D,name:O}=E;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let k=templateFilePath(s,D,O);if(!k.ok||!existsSync(k.abs))return textResult(`Error: template "${O}" not found in ${D||`(root)`}. Create it with \`write({ template })\` first.`,!0);let j;try{j=readFileSync(k.abs,`utf-8`)}catch(e){return textResult(`Error: could not read template: ${e.message}`,!0)}let{frontmatter:F,body:L}=stripFrontmatter(j),B=parseTemplateFrontmatter(F);if(e.frontmatter!==void 0){let s=await httpPut(g,`/api/template`,{folder:D,name:O,body:L,frontmatter:mergePatch(B,e.frontmatter),...t===void 0?{}:{summary:t},...agentIdentityFields(S.identityRef?.current)});if(!s.ok)return textResult(`Error: ${s.error}`,!0);let w=typeof s.path==`string`?s.path:void 0;return textPlusStructured(`Patched template "${O}" frontmatter${w?` (${w})`:``}.`,{template:{ok:!0,path:w}})}let H=e.occurrence??1,q=nthOccurrenceOffset(L,e.find,H);if(q===-1)return textResult(`Error: \`find\` occurs fewer than ${H} time(s) in template "${O}".`,!0);let J=await httpPut(g,`/api/template`,{folder:D,name:O,body:L.slice(0,q)+e.replace+L.slice(q+e.find.length),frontmatter:B,...t===void 0?{}:{summary:t},...agentIdentityFields(S.identityRef?.current)});if(!J.ok)return textResult(`Error: ${J.error}`,!0);let Y=typeof J.path==`string`?J.path:void 0;return textPlusStructured(`Edited template "${O}"${Y?` (${Y})`:``}.`,{template:{ok:!0,path:Y}})}async function handleFolder$1(e,t,s,g){if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=await httpPut(s,`/api/folder-config`,{path:e.path,frontmatter:e.frontmatter,...t===void 0?{}:{summary:t},...agentIdentityFields(g.identityRef?.current)});if(!S.ok)return textResult(`Error: ${S.error}`,!0);let w=(Array.isArray(S.applied)?S.applied:[])[0]??{},E=w.action??`written`;return textPlusStructured(`${E===`deleted`?`Cleared`:E===`noop`?`No change to`:`Updated`} folder properties for ${e.path}.`,{folder:{ok:!0,path:w.path??`${e.path}/.ok/frontmatter.yml`,action:E}})}function register$12(e,t){let s={find:string().optional().describe("Exact BODY text to find. Use WITH `replace`. For metadata, use `frontmatter` instead — not this."),replace:string().optional().describe("Replacement for the `find` match."),occurrence:number().int().positive().optional().describe(`Which match to edit (1 = first). Default: first.`)};e.registerTool(`edit`,{description:DESCRIPTION$12,inputSchema:{document:object$1({path:string().describe(`Document path, no extension — the slashes are its folder. Example: "meetings/standup".`),...s,frontmatter:FrontmatterArg.optional().describe("Metadata merge-patch (set keys; `null` deletes a key). Use INSTEAD of find/replace.")}).optional().describe(`Edit a DOCUMENT: its body (find+replace) OR its frontmatter (patch). Body: { document: { path, find, replace } }. Metadata: { document: { path, frontmatter } }.`),folder:object$1({path:string().describe(`Folder path.`),frontmatter:FrontmatterArg.describe("Update the folder's own title/description/tags (merge-patch; `null` deletes).")}).optional().describe(`Edit a FOLDER: only its frontmatter (folders have no body). Example: { folder: { path: "meetings", frontmatter: { description: "All-hands" } } }`),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),...s,frontmatter:FrontmatterArg.optional().describe(`Template metadata merge-patch.`)}).optional().describe(`Edit a TEMPLATE: body (find+replace) or frontmatter (patch).`),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1(documentResultBaseShape).optional().describe(`Document edit result (present when there is a doc-specific signal).`),folder:object$1({ok:boolean(),path:string(),action:string().describe("`written` (created/updated) | `deleted` (cleared) | `noop`.")}).optional().describe(`Folder frontmatter edit result.`),template:object$1({ok:boolean(),path:string()}).optional().describe(`Template edit result.`),previewUrl:previewUrlOutputField.optional(),previewUrlSource:previewUrlSourceField,warning:previewAttachWarningField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s,E=resolveContentDir(S,g),D=S.appearance.preview.autoOpen,O=exactlyOneTargetError(e,[`document`,`folder`,`template`]);if(O)return textResult(`Error: ${O}`,!0);if(e.document!==void 0){let s=bodyOrFrontmatterError(e.document,`document`);return s?textResult(`Error: ${s}`,!0):w?e.document.frontmatter===void 0?handleDocBody(e.document,e,g,E,w,t,D):handleDocFrontmatter({path:e.document.path,frontmatter:e.document.frontmatter},e,g,w,t,D):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}return e.folder===void 0?handleTemplate$1(e.template,e.summary,g,w,t):handleFolder$1(e.folder,e.summary,w,t)})}const PRODUCER_COMMANDS=new Set([`cat`,`ls`,`grep`,`find`]),PATH_FALLBACK_RE=/\b[\w./-]+\.(md|mdx)\b/g;function isWikiPath(e){return/\.(md|mdx)$/.test(e)}function normalize$1(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function argsOf(e){return e.args.slice(1)}function nonFlagArgs(e){return e.filter(e=>!e.startsWith(`-`))}function extractFromCat(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function extractFromLs(e,t){let s=nonFlagArgs(argsOf(t)),g=s.length>0?s[s.length-1]:``,S=g&&g!==`.`?normalize$1(g):``,w=[];S&&w.push(S);for(let t of e.split(`
1727
+ `)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!isWikiPath(e))continue;let s=S?`${S}/${e}`:e;w.push(s)}return w}function extractFromGrep(e){let t=[];for(let s of e.split(`
1728
+ `)){if(!s)continue;let e=s.indexOf(`:`);if(e<0)continue;let g=normalize$1(s.slice(0,e));isWikiPath(g)&&t.push(g)}return t}function extractFromFind(e){let t=[];for(let s of e.split(`
1729
+ `)){let e=normalize$1(s);e&&isWikiPath(e)&&t.push(e)}return t}function extractFromHeadTail(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function headTailActsAsProducer(e){return nonFlagArgs(argsOf(e)).length>0}function fallback(e){let t=[],s=e.matchAll(PATH_FALLBACK_RE);for(let e of s)t.push(normalize$1(e[0]));return t}function extractReferencedPaths(e,t){let s=null;for(let e=t.length-1;e>=0;e--){let g=t[e];if(PRODUCER_COMMANDS.has(g.command)){s=g;break}if((g.command===`head`||g.command===`tail`)&&headTailActsAsProducer(g)){s=g;break}}let g;if(!s)g=fallback(e);else{switch(s.command){case`cat`:g=extractFromCat(s);break;case`ls`:g=extractFromLs(e,s);break;case`grep`:g=extractFromGrep(e);break;case`find`:g=extractFromFind(e);break;case`head`:case`tail`:g=extractFromHeadTail(s);break;default:g=fallback(e)}g.length===0&&(g=fallback(e))}let S=new Set,w=[];for(let e of g){let t=normalize$1(e);!t||S.has(t)||(S.add(t),w.push(t))}return w}function shellEscape(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const MAX_STDOUT_BYTES=16*1024*1024;var StdoutOverflowError=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,s){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=s}};function createBashInstance(e){if(!isAbsolute(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new xt({cwd:`/`,fs:new Ss({root:resolve(e),allowSymlinks:!1})})}async function execBash(e,t){let s=await e.exec(t);if(s.stdout.length>MAX_STDOUT_BYTES)throw new StdoutOverflowError(MAX_STDOUT_BYTES,s.stdout.length,{stdout:s.stdout.slice(0,MAX_STDOUT_BYTES),stderr:s.stderr,exitCode:s.exitCode});return{stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode}}const SCAN_CAP=1e3,SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function snapshotMtimes(e){let t=resolve(e),s=new Map,g=0,S=!1;async function w(e){if(S)return;let E;try{E=await readdir(e,{withFileTypes:!0})}catch{return}for(let D of E){if(S)return;if(D.isDirectory()&&SKIP_DIRS.has(D.name))continue;let E=resolve(e,D.name);if(D.isDirectory()){await w(E);continue}if(D.isFile()){if(g>=SCAN_CAP){S=!0;return}try{let e=await stat$1(E);s.set(relative(t,E),e.mtimeMs),g++}catch{}}}}return await w(t),{snapshot:s,truncated:S}}function diffMtimes(e,t){let s=[];for(let[g,S]of t){let t=e.get(g);(t===void 0||t!==S)&&s.push(g)}for(let[g]of e)t.has(g)||s.push(g);return{changed:s}}const WIKI_EXCLUDE_DIRS=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];function isRecursiveGrepFlag(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const STRATEGIES=[{command:`grep`,applies:e=>e.slice(1).some(isRecursiveGrepFlag),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let s of e)t.push(`-not`,`-path`,`*/${s}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function augmentStagesWithExcludes(e){return e.map(e=>{let t=STRATEGIES.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let s=t.buildExcludeArgs(WIKI_EXCLUDE_DIRS),g=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,g),...s,...e.args.slice(g)]}})}function serializeStages(e){return e.map(e=>e.args.map(shellEscape).join(` `)).join(` | `)}const ALLOWLIST=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),ALLOWLIST_HINT=`cat, ls, grep, find, head, tail, wc, sort, uniq, cut`,WRITE_OPS=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),SHELL_CONSTRUCT_OPS=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),UNIVERSAL_FLAG_DENY=new Set([`-o`,`--output-file`,`--output`]),UNIVERSAL_FLAG_PREFIX_DENY=[`-o=`,`--output-file=`,`--output=`],FIND_FLAG_DENY=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),SUSPICIOUS_STRING_RE=/[`]|\$\(|\$\{|\$'/;function isOpToken(e){return typeof e==`object`&&!!e&&`op`in e}function opTokenError(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return WRITE_OPS.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use the \`write\` or \`edit\` tool.`}:SHELL_CONSTRUCT_OPS.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported — exec runs ONE command or a pipe (|), not a shell. Run separate exec calls, or pass multiple paths to one command (e.g. \`ls -A a b c\`, \`cat a b c\`).`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function buildStageArgs(e){let t=[];for(let s of e){if(typeof s==`string`){if(SUSPICIOUS_STRING_RE.test(s))return{error:{category:`shell_construct_blocked`,message:`Argument '${s}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(s);continue}if(!isOpToken(s))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(s.op===`glob`&&typeof s.pattern==`string`){t.push(s.pattern);continue}return typeof s.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:opTokenError(s)}}return{args:t}}function checkStage(e){if(!ALLOWLIST.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: ${ALLOWLIST_HINT}.`};for(let t of e.args.slice(1)){if(UNIVERSAL_FLAG_DENY.has(t)||UNIVERSAL_FLAG_PREFIX_DENY.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use the \`write\` or \`edit\` tool.`};if(e.command===`find`&&FIND_FLAG_DENY.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function parseCommand(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let s;try{s=import_shell_quote.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let g=[],S=[];for(let e of s){if(isOpToken(e)&&e.op===`|`){g.push(S),S=[];continue}S.push(e)}g.push(S);let w=[];for(let e of g){let t=buildStageArgs(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let s={command:t.args[0],args:t.args},g=checkStage(s);if(g)return{error:g};w.push(s)}return{stages:w}}const SOFT_CAP_LINES=500,SOFT_CAP_BYTES=50*1024,BINARY_EXT_RE=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,DESCRIPTION$11=["**STOP — when the project has `.ok/`, do NOT use native `Read`/`Grep`/`Glob` on in-scope `.md`/`.mdx`; use `exec` (this tool).** Native tools skip the frontmatter, backlinks, shadow-repo activity, and git history `exec` returns per wiki file. Reserve native tools for source code, non-markdown, and projects without `.ok/`. (Full rule + escape hatch: the `open-knowledge` skill / MCP `instructions`.)",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,"Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or a pipe (|) per call — NOT a shell: `&&`, `;`, redirections, subshells, and writes are rejected. To do several things, make separate exec calls or pass multiple paths to one command (e.g. `ls -A a b c`, `cat a b c`).",``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
1730
+ `);function applySoftCap(e){let t=e.split(`
1731
+ `),s=t[t.length-1]===``?t.length-1:t.length;if(s<=SOFT_CAP_LINES&&e.length<=SOFT_CAP_BYTES)return{text:e,truncated:!1,omittedLines:0};let g=Math.min(s,SOFT_CAP_LINES),S=0,w=0;for(let e=0;e<g;e++){let s=t[e];if(S+=s.length+1,S>SOFT_CAP_BYTES)break;w++}let E=t.slice(0,w).join(`
1732
+ `),D=s-w;return{text:`${E}\n<truncated: ${D} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:D}}function detectBinaryArgs(e){let t=[];for(let s of e)if(s.command===`cat`)for(let e of s.args.slice(1))e.startsWith(`-`)||BINARY_EXT_RE.test(e)&&t.push(e);return t}function extractHeadTailLimit(e){for(let t=1;t<e.length;t++){let s=e[t],g=s.match(/^--lines=(\d+)$/);if(g)return Number(g[1]);if(s===`--lines`&&t+1<e.length){let s=Number(e[t+1]);if(Number.isFinite(s))return s}if(s===`-n`&&t+1<e.length){let s=Number(e[t+1]);if(Number.isFinite(s))return s}let S=s.match(/^-n(\d+)$/);if(S)return Number(S[1]);let w=s.match(/^-(\d+)$/);if(w)return Number(w[1])}return 10}function detectHeadTailTruncation(e,t){if(e.length<2)return null;let s=e[e.length-1];if(s.command!==`head`&&s.command!==`tail`)return null;let g=extractHeadTailLimit(s.args),S=t.split(`
1733
+ `),w=S[S.length-1]===``?S.length-1:S.length;if(w<g)return null;let E=S.slice(0,w),D=new Set(E.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,O=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${s.command} -${g}\` cap (${w} lines, ${D} unique file${D===1?``:`s`}). The \`${O}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${s.command}\` or widen the cap.`}}function isDirectoryMeta(e){return e.type===`directory`}function formatDirectoryEntry(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`);let s=[];return s.push(`${e.recursiveMdCount} md file${e.recursiveMdCount===1?``:`s`}`),e.childDirCount>0&&s.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(s.join(`, `)),e.mostRecentMd&&t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path})`),e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function formatFileEntry(e){let t=[`**${e.title??e.path}** (${e.path})`];if(e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.backlinkCount!==null&&t.push(`backlinks: ${e.backlinkCount}`),e.forwardLinkCount!==null&&t.push(`forward links: ${e.forwardLinkCount}`),e.history&&e.history.length>0){let s=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${s.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let s=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${s.join(` · `)}`)}return`- ${t.join(` — `)}`}function buildStdoutProvenance(e,t,s){let g=null;for(let t=e.length-1;t>=0;t--){let s=e[t],S=s.command;if(S===`ls`||S===`cat`){g=s;break}if((S===`head`||S===`tail`)&&nonFlagArgs(argsOf(s)).length>0){g=s;break}}if(!g)return``;let S=nonFlagArgs(argsOf(g));if(g.command===`ls`){let e=S[S.length-1];if(!e||e===`.`)return``;let s=e.replace(/\/+/g,`/`);return s.startsWith(`./`)&&(s=s.slice(2)),s.endsWith(`/`)&&(s=s.slice(0,-1)),!s||!t.has(s)?``:`${s}/:\n`}let w=S.filter(e=>/\.(md|mdx)$/.test(e)&&s.has(e));return w.length===1?`==> ${w[0]} <==\n`:``}function formatEnrichedBlock(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let s of e)t.push(isDirectoryMeta(s)?formatDirectoryEntry(s):formatFileEntry(s));return t.join(`
1734
+ `)}async function classifyPaths(e,t){let s=[],g=[];return await Promise.all(t.map(async t=>{try{let S=await stat$1(resolve(e,t));S.isDirectory()?g.push(t):S.isFile()&&s.push(t)}catch{/\.(md|mdx)$/i.test(t)&&s.push(t)}})),{files:s,dirs:g}}function errorCategoryResult(e,t){return textPlusStructured(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function withPreviewUrls(e,t){return e.map(e=>{let s=t(docNameFromPath(e.path));return{...e,previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}})}async function buildExecResult(e,t){let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return errorCategoryResult(`shell_construct_blocked`,`exec failed: ${s.error}`);let{cwd:g,config:S,url:w}=s,E=parseCommand(e.command);if(`error`in E)return errorCategoryResult(E.error.category,E.error.message);let D=augmentStagesWithExcludes(E.stages),O=serializeStages(D),k=await snapshotMtimes(g),j=createBashInstance(g),F=``,L=``;try{let e=await execBash(j,O);F=e.stdout,L=e.stderr}catch(e){return e instanceof StdoutOverflowError?errorCategoryResult(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`):errorCategoryResult(`shell_construct_blocked`,`exec failed: ${e instanceof Error?e.message:String(e)}`)}let B=await snapshotMtimes(g),H=diffMtimes(k.snapshot,B.snapshot);if(H.changed.length>0)return errorCategoryResult(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${H.changed.join(`, `)}. This indicates a parser bug; the command has been logged.`);let q=applySoftCap(F),J=extractReferencedPaths(F,D).filter(e=>resolveWithinRoot(g,e).ok),{files:Y,dirs:ee}=await classifyPaths(g,J),te=D.length===1&&D[0].command===`cat`&&Y.length===1,ne=await Promise.all(Y.map(e=>enrichPath(e,{projectDir:g,serverUrl:w},{includeRichFields:te}).catch(()=>({path:e,tags:[],frontmatter:{},backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null})))),ae=await Promise.all(ee.map(e=>enrichDirectoryRecursive(e,1,{projectDir:g}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!te&&w&&ne.length>0){let e=await fetchBacklinkCountsBatch(w,ne.map(e=>pathToDocName$1(e.path))).catch(()=>null);if(e)for(let t of ne){let s=e.get(pathToDocName$1(t.path));typeof s==`number`&&(t.backlinkCount=s)}}let oe=new Map(ne.map(e=>[e.path,e])),se=new Map(ae.map(e=>[e.path,e])),ce=[];for(let e of J){let t=oe.get(e);if(t){ce.push(t);continue}let s=se.get(e);s&&ce.push(s)}let ue=detectBinaryArgs(D),de=[];ue.length>0&&de.push(`File${ue.length>1?`s`:``} ${ue.join(`, `)} appear${ue.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let fe=detectHeadTailTruncation(D,F);fe&&de.push(fe.banner),L&&de.push(`stderr: ${L.trim()}`);let me=de.length>0?`${de.join(`
1735
+ `)}\n\n`:``,ge=buildStdoutProvenance(D,se,oe)+q.text,_e=`${me}${ge}${formatEnrichedBlock(ce)}`,{resolve:ve}=await buildListResolver({config:S,resolveCwd:async()=>g});return textPlusStructured(_e,{enrichedPaths:withPreviewUrls(ce,ve),stdout:ge,stdoutTruncated:q.truncated,cwd:g,...de.length>0?{warnings:de}:{}})}function register$11(e,t){e.registerTool(`exec`,{description:DESCRIPTION$11,inputSchema:{command:string().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:string().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},outputSchema:outputSchemaWithText({enrichedPaths:looseObjectArray.describe(`Per-referenced-file metadata: frontmatter, backlink/forward-link counts, recent shadow-repo activity, and a route-only previewUrl.`),stdout:string().optional().describe(`Raw command stdout (soft-cap truncated), without banners or enrichment.`),stdoutTruncated:boolean().optional().describe(`True when stdout was truncated by the soft cap.`),warnings:array(string()).optional().describe(`Tool-level warnings — head/tail truncation, binary detection, stderr.`),cwd:string().optional().describe(`Absolute directory the command ran in.`),error:object$1({category:string(),message:string()}).optional().describe(`Present on failure — the error category + message.`)})},async e=>{try{return await buildExecResult(e,t)}catch(e){return errorCategoryResult(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const DESCRIPTION$10=[`[Operates on disk; no running OK server required] Resolve the browser-reachable preview URL for an Open Knowledge project (optionally for a specific doc).`,``,"Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.",``,'Use this when YOUR host opens the URL itself: navigate your in-app browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Hosts with a preview pane (Claude Code Desktop) call `preview_start("open-knowledge-ui")` instead; the Claude Code CLI uses `ok open <doc>` to open in the OK Desktop app.',``,"Returns `{ url: null, baseUrl: null, running: false, autoOpen }` and a recovery hint when no UI is running for the project (start one with `ok ui`).",``,`**Parameters:**`,"- `document` (optional) — Extension-less doc path (e.g. `specs/foo/SPEC`). Omit for the UI root URL.","- `folder` (optional) — Folder path (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.","- `armPaneTarget` (optional) — When true with a `document`/`folder`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. This is the tool’s ONLY side effect; omit it and the call is read-only.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
1736
+ `),InputSchema$2={document:string().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),folder:string().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),armPaneTarget:boolean().optional().describe("When true with a `document` or `folder`, arm that target so a subsequent Claude-pane base-open (`preview_start`) lands there instead of the presence-driven default. TTL-bounded (~30s) so a stale arm cannot hijack a later open."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$4=outputSchemaWithText({url:string().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:string().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:boolean().describe(`Whether a UI is running for the project.`),autoOpen:boolean().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`.")}),NO_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code), or open the project in OK Electron.';function register$10(e,t){e.registerTool(`preview_url`,{description:DESCRIPTION$10,inputSchema:InputSchema$2,outputSchema:OutputSchema$4,annotations:{readOnlyHint:!1,idempotentHint:!0}},async e=>{if(e.document&&e.folder)return{isError:!0,content:[{type:`text`,text:`Error: document and folder are mutually exclusive — pass exactly one.`}]};let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=resolveLockDir(s.cwd),{baseUrl:S}=resolveUiInfo({lockDir:g}),w=s.config.appearance.preview.autoOpen,E=e.document?`#/${encodeDocName(e.document)}`:e.folder?`#/${encodeFolderRoute(e.folder)}`:null;if(e.armPaneTarget&&E)try{armPaneTarget(g,E)}catch{}let D=e.armPaneTarget&&!E?` (note: armPaneTarget was set but no document/folder was given, so nothing was armed)`:``;if(S===null)return textPlusStructured(`${NO_UI_MESSAGE}${D}`,{url:null,baseUrl:null,running:!1,autoOpen:w});let O=E?`${S}/${E}`:S;return textPlusStructured(`Preview URL: ${O}${D}`,{url:O,baseUrl:S,running:!0,autoOpen:w})})}const HistoryEntryOutputSchema=object$1({version:string().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:string().describe(`ISO timestamp of the entry.`),author:string().describe(`Author display name.`),authorEmail:string().describe(`Author email.`),kind:_enum([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:string().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:looseObjectArray.describe(`Per-contributor records parsed from the commit (writer id, name, docs, summaries).`),checkpoint:unknown().nullable().describe(`Checkpoint metadata when this entry is a checkpoint, else null.`)}),DESCRIPTION$9=[`[Requires: Hocuspocus server] List version history for a document, or the activity timeline for a folder.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.",``,"**Parameters (pass EXACTLY ONE of `document` / `folder`):**","- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",'- `folder` — Folder path for the FOLDER timeline: attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter) — who created / edited / renamed / moved / deleted them, when. `""` = project root.',"- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `kind` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
1737
+ `);function register$9(e,t){e.registerTool(`history`,{description:DESCRIPTION$9,inputSchema:{document:string().optional().describe("Document name to query history for. Mutually exclusive with `folder`."),folder:string().optional().describe('Folder path to query the FOLDER timeline for — attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter): created / edited / renamed / moved / deleted, by whom, when. Mutually exclusive with `document`. Use `""` for the project root.'),branch:string().optional().describe(`Branch name (default: current branch)`),limit:number().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:number().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),kind:_enum([`checkpoint`,`upstream`,`wip`]).optional().describe("Filter by entry type (`checkpoint` / `upstream` / `wip`)."),author:string().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:string().optional().describe(`Exclude entries by this author name or email`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({entries:array(HistoryEntryOutputSchema).describe("Timeline entries, newest first. Each carries a `version` for `restore_version`."),total:number().int().optional().describe(`Total entries available (pre-pagination).`),truncated:boolean().optional().describe(`Whether more entries exist beyond this returned page (the result was limit-capped).`),previewUrl:previewUrlOutputField,previewUrlSource:previewUrlSourceField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=e.folder!==void 0;if(w===(e.document!==void 0))return textResult("Error: pass EXACTLY ONE of `document` or `folder`.",!0);let E=new URLSearchParams,D=null;if(w)E.set(`folder`,e.folder??``);else{let t=normalizeDocName(e.document);if(!t.ok)return textResult(t.error,!0);E.set(`docName`,t.docName),D=t.docName}e.branch&&E.set(`branch`,e.branch),e.limit!=null&&E.set(`limit`,String(e.limit)),e.offset!=null&&E.set(`offset`,String(e.offset)),e.kind&&E.set(`type`,e.kind),e.author&&E.set(`author`,e.author),e.excludeAuthor&&E.set(`excludeAuthor`,e.excludeAuthor);let O=await httpGet(S,`/api/history?${E.toString()}`);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let{ok:k,...j}=O,F=(Array.isArray(j.entries)?j.entries:[]).map(e=>{let t=e;return{version:t.sha,timestamp:t.timestamp,author:t.author,authorEmail:t.authorEmail,kind:t.type,message:t.message,contributors:t.contributors,checkpoint:t.checkpoint??null}}),L=j.total,B=j.hasMore,H=D?await resolvePreviewUrlForTool(D,{config:t.config,resolveCwd:t.resolveCwd},g):null,q={entries:F,...typeof L==`number`?{total:L}:{},...typeof B==`boolean`?{truncated:B}:{}};return textPlusStructured(JSON.stringify(q,null,2),{...q,previewUrl:H?.url??null,...H?{previewUrlSource:H.source}:{}})})}const LINK_KINDS=[`backlinks`,`forward`,`dead`,`orphans`,`hubs`,`suggest`],DESCRIPTION$8=["[Requires: Hocuspocus server] Read the wiki-link graph. `kind` takes one value, or an array for a one-call audit — results merge into a single payload; any per-kind failure lands in an `errors` map.",``,'- `backlinks` / `forward` / `suggest` — operate on one page; require `document`. `suggest` finds prose mentions of the page not yet wrapped in link syntax. Each mention returns an `excerpt` (a normalized, `…`-trimmed snippet for context — NOT an edit-ready literal) plus an `offset`. To wrap one: re-read the doc (`exec("cat …")`), find the real mention text, and `edit` it into a `[[wiki-link]]`.',"- `dead` — missing internal link targets corpus-wide; optional `sourceDocuments` filter (OR semantics).","- `orphans` — disconnected pages; optional `mode`: `incoming` | `outgoing` | `both`.","- `hubs` — most-linked pages; optional `limit` (default 20)."].join(`
1738
+ `);function register$8(e,t){e.registerTool(`links`,{description:DESCRIPTION$8,inputSchema:{kind:union([_enum(LINK_KINDS),array(_enum(LINK_KINDS)).min(1)]).describe(`Link-graph view(s) to return — one kind, or an array to fetch several in one call (e.g. ["dead","orphans","hubs"] for a graph audit).`),document:string().optional().describe(`Target page (path, extension-less). Required for kind=backlinks|forward|suggest.`),sourceDocuments:array(string()).optional().describe(`Referring source docs to narrow the audit with OR semantics. Used by kind=dead.`),mode:_enum(ORPHAN_MODES).optional().describe(`Filter which type of graph disconnection to surface. Used by kind=orphans.`),limit:number().int().positive().max(100).optional().describe(`Maximum number of hubs to return (default 20, max 100). Used by kind=hubs.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({backlinks:looseObjectArray.optional().describe(`kind=backlinks: pages that link TO the target.`),forwardLinks:looseObjectArray.optional().describe(`kind=forward: links FROM the target (doc + external).`),deadLinks:looseObjectArray.optional().describe(`kind=dead: internal links whose target does not exist.`),orphans:looseObjectArray.optional().describe(`kind=orphans: disconnected pages.`),hubs:looseObjectArray.optional().describe(`kind=hubs: the most-linked pages.`),suggest:record(string(),unknown()).optional().describe("kind=suggest: `{ mentions: [{ source, excerpt, offset }], previewUrl }` — `excerpt` is a `…`-trimmed context snippet (re-read the doc for the real text before `edit`)."),errors:record(string(),string()).optional().describe("Per-kind failures on a multi-kind call: `{ kind: message }`."),cwd:string().describe(`Absolute directory the read ran against.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=Array.isArray(e.kind)?[...new Set(e.kind)]:[e.kind],{resolve:E}=await buildListResolver(t,g),D=await Promise.all(w.map(s=>runKind(s,e,S,g,t,E))),O={},k={};if(w.forEach((e,t)=>{let s=D[t];s.ok?Object.assign(O,s.data):k[e]=s.error}),Object.keys(O).length===0){let e=w.length===1?k[w[0]]:`All requested link kinds failed: ${JSON.stringify(k)}`;return textResult(e.startsWith(`Error`)?e:`Error: ${e}`,!0)}let j={...O,...Object.keys(k).length>0?{errors:k}:{},cwd:g};return textPlusStructured(JSON.stringify(j,null,2),j)})}function runKind(e,t,s,g,S,w){switch(e){case`backlinks`:return runBacklinks(t,s,w);case`forward`:return runForwardLinks(t,s,w);case`dead`:return runDeadLinks(t,s,w);case`orphans`:return runOrphans(t,s,w);case`hubs`:return runHubs(t,s,w);case`suggest`:return runSuggest(t,s,g,S)}}async function runBacklinks(e,t,s){if(!e.document)return{ok:!1,error:"kind=backlinks requires `document`."};let g=normalizeDocName(e.document);if(!g.ok)return{ok:!1,error:g.error};let S=await httpGet(t,`/api/backlinks?docName=${encodeURIComponent(g.docName)}`);if(!S.ok)return{ok:!1,error:String(S.error)};let{ok:w,...E}=S;return{ok:!0,data:{backlinks:(E.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runForwardLinks(e,t,s){if(!e.document)return{ok:!1,error:"kind=forward requires `document`."};let g=normalizeDocName(e.document);if(!g.ok)return{ok:!1,error:g.error};let S=await httpGet(t,`/api/forward-links?docName=${encodeURIComponent(g.docName)}`);if(!S.ok)return{ok:!1,error:String(S.error)};let{ok:w,...E}=S;return{ok:!0,data:{forwardLinks:(E.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runDeadLinks(e,t,s){let g=new URLSearchParams;for(let t of e.sourceDocuments??[]){let e=normalizeDocName(t);if(!e.ok)return{ok:!1,error:e.error};g.append(`sourceDocName`,e.docName)}let S=g.toString(),w=await httpGet(t,`/api/dead-links${S?`?${S}`:``}`);if(!w.ok)return{ok:!1,error:String(w.error)};let{ok:E,...D}=w;return{ok:!0,data:{deadLinks:(D.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,g=t?s(t):null,S=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}});return{...e,sources:S,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runOrphans(e,t,s){let g=await httpGet(t,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!g.ok)return{ok:!1,error:String(g.error)};let{ok:S,...w}=g;return{ok:!0,data:{orphans:(w.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runHubs(e,t,s){let g=await httpGet(t,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!g.ok)return{ok:!1,error:String(g.error)};let{ok:S,...w}=g;return{ok:!0,data:{hubs:(w.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runSuggest(e,t,s,g){if(!e.document)return{ok:!1,error:"kind=suggest requires `document`."};let S=normalizeDocName(e.document);if(!S.ok)return{ok:!1,error:S.error};let w=await httpGet(t,`/api/suggest-links?docName=${encodeURIComponent(S.docName)}`);if(!w.ok)return{ok:!1,error:String(w.error)};let{ok:E,...D}=w,O=await resolvePreviewUrlForTool(S.docName,{config:g.config,resolveCwd:g.resolveCwd},s);return{ok:!0,data:{suggest:{...D,previewUrl:O?.url??null,...O?{previewUrlSource:O.source}:{}}}}}const DESCRIPTION$7=["[Requires: Hocuspocus server] Move or rename a document, folder, or asset through the managed flow at `POST /api/rename-path`. Works for all three — the tool probes the content directory to decide. Inbound wiki-links plus supported inline Markdown links are rewritten across affected docs; renamed assets are reported.",``,`**Parameters:**`,"- `from` — Current path. Doc: docName (trailing `.md`/`.mdx` stripped). Folder: relative path, no leading/trailing slash. Asset: the file path incl. extension.","- `to` — New path. Same shape as `from`.",'- `template` — Move/rename a TEMPLATE instead of a doc/folder/asset: `{ from: "<folder>/<name>", to: "<folder>/<name>" }` (nested — a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc). Mutually exclusive with flat `from`/`to`. Inherited templates are not moved (move the local copy / the owning folder); templates carry no inbound links, so nothing is rewritten.','- `summary` — Optional one-line user-outcome (≤80 chars). If omitted, defaults to "Renamed X → Y". Avoid secrets or PII — persisted to git history.',``,"**Errors:** 400 — invalid path / excluded by `.gitignore`/`.okignore`; 404 — source does not exist; 409 — destination already exists (`colliding[]` returned)."].join(`
1739
+ `);function parseRenameMappings(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromDocName:t,toDocName:s}]:[]}):[]}function parseRewrittenDocs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:s}=e;return typeof t==`string`&&typeof s==`number`?[{docName:t,rewrites:s}]:[]}):[]}function parseRenamedAssets(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromPath:t,toPath:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromPath:t,toPath:s}]:[]}):[]}function isValidFolderPath(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`..`))}function pluralize(e,t,s=`${t}s`){return e===1?t:s}function resolveMoveKind(e,t){let s=resolveWithinRoot(e,t);if(!s.ok)return null;let g=s.abs;if(existsSync(g))try{let e=statSync(g);if(e.isDirectory())return`folder`;if(e.isFile())return g.endsWith(`.md`)||g.endsWith(`.mdx`)?`file`:`asset`}catch(e){let t=e.code;if(t===`EACCES`||t===`EPERM`)return`file`}for(let e of[`.md`,`.mdx`])if(existsSync(`${g}${e}`))return`file`;return null}function register$7(e,t){e.registerTool(`move`,{description:DESCRIPTION$7,inputSchema:{from:string().optional().describe(`Current path of a document, folder, or asset (auto-detected).`),to:string().optional().describe(`New path. All inbound wiki-links + inline links are rewritten automatically.`),template:object$1({from:string(),to:string()}).optional().describe('Move/rename a TEMPLATE instead: `{ from: "<folder>/<name>", to: "<folder>/<name>" }`. Nested because a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc. Mutually exclusive with flat `from`/`to`.'),summary:summaryArgSchema.describe(`Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({ok:boolean().describe(`Whether the move succeeded.`),kind:_enum([`file`,`folder`,`asset`,`template`]).optional().describe("What was moved (`file`/`folder`/`asset` auto-detected from `from`; `template` when the `template` target was used)."),committed:boolean().optional().describe("Template move only: `true` = tracked `git mv` (history preserved), `false` = plain disk rename (untracked / local-only `.ok/`)."),renamed:array(object$1({fromDocName:string(),toDocName:string()})).optional().describe(`docName remappings performed.`),rewrittenDocs:looseObjectArray.optional().describe(`Docs whose inbound links were rewritten.`),renamedAssets:looseObjectArray.optional().describe(`Referenced assets that were moved alongside.`),previewUrls:record(string(),string()).optional().describe(`Route-only preview URL per new docName.`),previewUrlSource:previewUrlSourceField,previousPreviewUrl:previousPreviewUrlField,summary:summaryOutputSchema.optional(),error:string().optional().describe("Present when `ok` is false."),colliding:looseObjectArray.optional().describe(`On a 409 collision: the conflicting from→to pairs.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.template!==void 0){if(e.from!==void 0||e.to!==void 0)return textResult("Error: pass EITHER flat `from`/`to` (document/folder/asset) OR `template: { from, to }` — not both.",!0);let s=resolveTemplatePath(e.template.from);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let g=resolveTemplatePath(e.template.to);if(!g.ok)return textResult(`Error: ${g.error}`,!0);let S=await httpPost(w,`/api/template`,{fromFolder:s.folder,fromName:s.name,toFolder:g.folder,toName:g.name,...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(t.identityRef?.current)});if(!S.ok){let e=typeof S.error==`string`?S.error:`Template move failed`;return textPlusStructured(`Error: ${e}`,{ok:!1,kind:`template`,error:e},!0)}let E=S.committed===!0,D=typeof S.from==`string`?S.from:e.template.from,O=typeof S.to==`string`?S.to:e.template.to;return textPlusStructured(`${E?`Renamed`:`Moved`} template ${D} → ${O}.${E?``:" (Untracked `.ok/` — moved on disk without git history.)"}`,{ok:!0,kind:`template`,committed:E})}if(e.from===void 0||e.to===void 0)return textResult("Error: provide both `from` and `to` (or use `template: { from, to }` to move a template).",!0);let E=join(g,S.content.dir),D=resolveMoveKind(E,e.from);if(D===null){let t=resolveTemplatePath(e.from);return t.ok&&existsSync(join(E,t.folder,`.ok`,`templates`,`${t.name}.md`))?textResult(`Error: \`${e.from}\` is a template, not a doc/folder/asset. Move it with \`move({ template: { from: "${e.from}", to: "<folder>/<newName>" } })\`.`,!0):textResult(`Error: \`${e.from}\` does not exist as a doc, folder, or asset under the content directory.`,!0)}let O=e.from,k=e.to;if(D===`file`){let t=normalizeDocName(e.from);if(!t.ok)return textResult(t.error,!0);let s=normalizeDocName(e.to);if(!s.ok)return textResult(s.error,!0);O=t.docName,k=s.docName}else if(D===`folder`&&(!isValidFolderPath(e.from)||!isValidFolderPath(e.to)))return textResult("Error: folder `from`/`to` must be relative paths with no leading/trailing slash.",!0);let j=await httpPost(w,`/api/rename-path`,{kind:D,fromPath:O,toPath:k,...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(t.identityRef?.current)});if(!j.ok){let e=j.error,t=parseRenameCollidingPairs(j.colliding),s={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return textPlusStructured(`Error: ${e}`,s,!0)}let F=parseRenameMappings(j.renamed),L=parseRewrittenDocs(j.rewrittenDocs),B=parseRenamedAssets(j.renamedAssets),H={config:t.config,resolveCwd:t.resolveCwd},q={},J,Y;if(D===`file`){let e=await resolvePreviewUrlForTool(k,H,g),t=await resolvePreviewUrlForTool(O,H,g);e&&(q[k]=e.url,J=e.source),t&&(Y=t.url)}else if(D===`folder`)for(let{toDocName:e}of F){let t=await resolvePreviewUrlForTool(e,H,g);t&&(q[e]=t.url,J??=t.source)}let ee=j.summary&&typeof j.summary==`object`?j.summary:void 0,te=typeof ee?.hint==`string`?ee.hint:void 0,ne=[];if(D===`asset`)ne.push(`Moved asset ${O} → ${k}.`);else if(D===`folder`)ne.push(F.length===0?`No managed docs under ${e.from}/ — nothing to rename. Empty folders are not tracked.`:`Renamed folder ${e.from}/ → ${e.to}/ (${F.length} doc${F.length===1?``:`s`}, ${L.length} rewrite${L.length===1?``:`s`}).`);else{let e=F.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${O} -> ${k}`,t=L.length===0?`No inbound links required updates.`:`Rewrote ${L.length} ${pluralize(L.length,`document`)}.`;ne.push(`Renamed ${e}. ${t}`)}return B.length>0&&ne.push(`Moved ${B.length} referenced ${pluralize(B.length,`asset`)}.`),te&&ne.push(te),textPlusStructured(ne.join(`
1740
+ `),{ok:!0,kind:D,renamed:F,rewrittenDocs:L,...B.length>0?{renamedAssets:B}:{},...Object.keys(q).length>0?{previewUrls:q}:{},...J?{previewUrlSource:J}:{},...Y?{previousPreviewUrl:Y}:{},...ee?{summary:ee}:{}})})}const DESCRIPTION$6=[`[Operates on registry data; no running OK server required] Return the OK authoring palette so a generated document reads as one coherent, themed artifact.`,``,`Three sections:`,"- `components` — the **markdown-native forms** OK auto-promotes into themed canonical components at parse time. Write `> [!NOTE]` (not `<Callout>`), `<details>` (not `<Accordion>`), ` ```mermaid `, `$x$`. Each entry carries a copy-ready `example` + `guidance`.","- `embedPatterns` — copy-ready ` ```html preview ` starters (chart, stat cards, custom SVG, interactive control) already wired to the theme tokens, so an embed tracks light/dark with no hand-picked colors.","- `tokens` — the CSS custom properties injected into every preview iframe; reference them as `var(--chart-1)`, `var(--foreground)`, … inside an `html preview` embed.",``,'Pass `components: [ids]` to ALSO get the full JSX-form prop schema for specific canonicals (e.g. `palette({ components: ["Callout", "Tabs"] })`) — merged from the former `get_components`.',``,`**Parameters:**`,"- `components` (optional) — Canonical ids to expand to full JSX-form detail (max 32). Case-sensitive (`Callout` not `callout`). Returns `componentDetails` + `notFound`.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
1741
+ `),InputSchema$1={components:array(string().min(1)).max(32).optional().describe("Canonical ids to expand to full JSX-form detail (max 32, case-sensitive). Returns `componentDetails` + `notFound`."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$3=outputSchemaWithText({version:literal(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:array(object$1({id:string(),displayName:string(),description:string(),authoring:_enum([`markdown`,`jsx`]).describe("`markdown` — write the markdown-native form OK auto-promotes; `jsx` — write the JSX tag directly (no markdown-native form exists)."),example:string().describe(`Copy-ready source for the authoring form.`),guidance:string().describe(`One line on when / how to use this construct.`)})).describe(`Canonical authoring constructs, keyed by the form an agent should write.`),embedPatterns:array(object$1({id:string(),title:string(),description:string(),snippet:string().describe("A complete, theme-wired ```html preview fenced block.")})).describe("Copy-ready themed `html preview` starters."),tokens:array(object$1({name:string().describe("CSS custom-property name, e.g. `--chart-1`."),light:string(),dark:string()})).describe("Theme tokens injected into every preview iframe — reference with `var(--name)`."),componentDetails:array(record(string(),unknown())).optional().describe("Full JSX-form prop schema for the requested `components` ids (when provided)."),notFound:array(string()).optional().describe("Requested `components` ids that did not match any canonical.")}),AUTHORING_FORMS=[{id:`Callout`,registryName:`Callout`,fallbackDisplayName:`Callout`,description:`Alert / admonition box in one of 15 themed type variants.`,authoring:`markdown`,example:`> [!NOTE]
1742
+ > Body text. Swap NOTE for TIP, IMPORTANT, WARNING, CAUTION, …`,guidance:"Write the GFM alert form — OK auto-promotes it to a themed Callout. 15 types; append `+` / `-` (e.g. `> [!NOTE]+`) to make it foldable."},{id:`Accordion`,registryName:`Accordion`,fallbackDisplayName:`Accordion`,description:`Collapsible section with a clickable summary.`,authoring:`markdown`,example:`<details>
1743
+ <summary>Section title</summary>
1744
+
1745
+ Hidden body content.
1746
+
1747
+ </details>`,guidance:"Write a plain `<details>` — OK auto-promotes it to a themed Accordion."},{id:`Mermaid`,fallbackDisplayName:`Mermaid diagram`,description:`Flowchart / sequence / class / state / ER / gantt / pie diagram.`,authoring:`markdown`,example:"```mermaid\ngraph LR\n A[Start] --> B[End]\n```",guidance:"Write a ` ```mermaid ` fenced block — it renders as a themed diagram."},{id:`Math`,registryName:`Math`,fallbackDisplayName:`Math`,description:`LaTeX math, rendered with KaTeX.`,authoring:`markdown`,example:`Inline: $E = mc^2$
1748
+
1749
+ Block:
1750
+
1751
+ $$
1752
+ \\int_0^1 x^2 \\, dx
1753
+ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-promotes it to Math."},{id:`wiki-embed`,fallbackDisplayName:`Wiki embed`,description:`Inline another document or an asset by name.`,authoring:`markdown`,example:`![[document-name]]
1754
+
1755
+ ![[diagram.png]]`,guidance:"Write a `![[file]]` wiki-embed to inline another doc or an uploaded asset."},{id:`Tabs`,registryName:`Tabs`,fallbackDisplayName:`Tabs`,description:`Tabbed panels — a pill strip with one panel visible at a time.`,authoring:`jsx`,example:`<Tabs>
1756
+ <Tab label="First">First panel content.</Tab>
1757
+ <Tab label="Second">Second panel content.</Tab>
1758
+ </Tabs>`,guidance:`Tabs is the one canonical with no markdown-native form — write the JSX directly.`}];function buildComponents(){let e=new Map(getAgentCanonicalDescriptors().map(e=>[e.name,e]));return AUTHORING_FORMS.map(t=>{let s=t.registryName?e.get(t.registryName):void 0;return{id:t.id,displayName:s?.displayName??s?.name??t.fallbackDisplayName,description:t.description,authoring:t.authoring,example:t.example,guidance:t.guidance}})}function register$6(e,t){e.registerTool(`palette`,{description:DESCRIPTION$6,inputSchema:InputSchema$1,outputSchema:OutputSchema$3,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{e.cwd;let t={version:1,components:buildComponents(),embedPatterns:PREVIEW_EMBED_STARTERS.map(e=>({id:e.id,title:e.title,description:e.description,snippet:previewEmbedFence(e)})),tokens:PREVIEW_THEME_TOKENS.map(e=>({name:e.name,light:e.light,dark:e.dark}))};if(e.components&&e.components.length>0){let s=new Map(getAgentCanonicalDescriptors().map(e=>[e.name,e])),g=[],S=[],w=new Set;for(let t of e.components){if(w.has(t))continue;w.add(t);let e=s.get(t);if(e===void 0){S.push(t);continue}g.push(projectFull(e))}t.componentDetails=g,t.notFound=S}return textPlusStructured(JSON.stringify(t,null,2),t)})}const DESCRIPTION$5=[`[Requires: Hocuspocus server] Resolve a tracked merge conflict by writing the chosen content to disk and committing.`,``,`Strategy:`,"- `mine` — runs `git checkout --ours -- <file>` then `git add` (your committed ours stage, stage 2). Fails on delete-modify (DU) conflicts where stage 2 is missing — use `delete` instead.","- `theirs` — runs `git checkout --theirs -- <file>` then `git add` (their committed stage 3). Fails on modify-delete (UD) conflicts where stage 3 is missing — use `delete` instead.",'- `content` — writes the provided `content` argument (e.g. a per-hunk merged result, or the live Y.Text bytes the user sees in the DiffView). The provided string must be non-empty — use `delete` to remove the file entirely (an agent constructing a per-hunk merge that happens to land on `""` gets a 400 at the Zod boundary rather than a misleading 500).','- `delete` — runs `git rm <file>` then commits the deletion. Honors deletion intent for delete-modify (DU: "keep deletion") and modify-delete (UD: "accept their deletion") shapes. Inspect the `shape` field on `conflicts({ kind: "content" })` to pick the right strategy for the conflict shape.',``,'Returns 200 on success; 500 indicates commit failure (re-call `conflicts({ kind: "list" })` to confirm post-state — the resolve API is best-effort, non-atomic, and the file may have been resolved by another session).',``,`**DESTRUCTIVE:** this modifies the working tree and creates a git commit.`,``,`**Parameters:**`,"- `file` — Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`).","- `strategy` — One of `mine` | `theirs` | `content` | `delete`.",'- `content` — Required (non-empty) when `strategy === "content"`; ignored otherwise.'].join(`
1759
+ `),OutputSchema$2=outputSchemaWithText({ok:boolean(),file:string()});function register$5(e,t){e.registerTool(`resolve_conflict`,{description:DESCRIPTION$5,inputSchema:{file:string().min(1).describe("Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`)."),strategy:_enum([`mine`,`theirs`,`content`,`delete`]).describe("Resolution strategy. `content` requires the `content` arg. `delete` runs `git rm` — use for delete-vs-modify (DU/UD) shapes where one stage is missing."),content:string().optional().describe('Exact bytes to write. Required when `strategy === "content"`; ignored otherwise.'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema$2,annotations:{readOnlyHint:!1,idempotentHint:!1,destructiveHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S={file:e.file,strategy:e.strategy};e.content!==void 0&&(S.content=e.content);let w=await httpPost(g,`/api/sync/resolve-conflict`,S);if(!w.ok){let t=w.error,s=typeof w.detail==`string`?w.detail:void 0;return textPlusStructured(`Error: ${s?`${t} — ${s}`:t}`,{ok:!1,file:e.file},!0)}return textPlusStructured(`Resolved conflict on ${e.file} (strategy: ${e.strategy}).`,{ok:!0,file:e.file})})}const DESCRIPTION$4=[`[Requires: Hocuspocus server] Restore a single document to a historical version via the CRDT layer — append-only (creates a new version with the old content; all connected editors see the change live).`,``,`**Parameters:**`,"- `document` — The document to restore (path, no extension; trailing `.md`/`.mdx` is stripped).","- `version` — The 40-character commit SHA to restore to. Copy it from the `history` tool (same field name there).",'- `summary` — Optional one-line summary (≤80 chars). Defaults to "Restored to <sha-short>". Avoid secrets or PII — persisted to git history.',``,'A response may include `structuredContent.contentDivergence` when the restored `Y.Text` does not byte-match the target-version bytes. The restore still landed; re-read the doc with `exec("cat <document>")` to see what converged.'].join(`
1760
+ `);function register$4(e,t){e.registerTool(`restore_version`,{description:DESCRIPTION$4,inputSchema:{document:string().describe(`Document to restore (path, no extension).`),version:versionInputSchema.describe("The 40-character commit SHA to restore to — copy it straight from a `history` entry's `version` field (same name there)."),summary:summaryArgSchema.describe(`Optional one-line summary (≤80 chars). Defaults to "Restored to <sha-short>". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:string().describe(`The document that was restored (echo of the input).`),version:string().describe(`The version the document was restored to (echo of the input).`),previewUrl:previewUrlOutputField,previewUrlSource:previewUrlSourceField,summary:summaryOutputSchema.optional(),contentDivergence:WriteWarningSchema.optional().describe(`Present only when the restored Y.Text did not byte-match the target version.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=normalizeDocName(e.document);if(!w.ok)return textResult(w.error,!0);let E=w.docName,D=await httpGet(S,`/api/history/${e.version}?docName=${encodeURIComponent(E)}`);if(!D.ok)return textResult(`Error: ${D.error??`Version not found`}`,!0);let O=t.identityRef?.current,k=await httpPost(S,`/api/rollback`,{docName:E,commitSha:e.version,...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(O)});if(!k.ok)return textResult(`Error: ${k.error}`,!0);let j=k.summary&&typeof k.summary==`object`?k.summary:void 0,F=typeof j?.hint==`string`?j.hint:void 0,L=parseContentDivergence(k.warning),B=typeof D.author==`string`?D.author:void 0,H=typeof D.timestamp==`string`?D.timestamp:void 0,q=B&&H?` (${B}, ${H})`:``,J=[`Restored "${E}" to version ${e.version.slice(0,8)}${q}. The change has been applied to all connected editors.`];F&&J.push(F),L&&J.push(formatContentDivergenceLine(L));let Y=await resolvePreviewUrlForTool(E,{config:t.config,resolveCwd:t.resolveCwd},g);return textPlusStructured(J.join(`
1761
+ `),{document:E,version:e.version,previewUrl:Y?.url??null,...Y?{previewUrlSource:Y.source}:{},...j?{summary:j}:{},...L?{contentDivergence:L}:{}})})}const DESCRIPTION$3=["[Requires: Hocuspocus server] Ranked page retrieval for a query (title boost + body BM25 + recency — the cmd-K engine). For literal search across every line, use `exec` (`grep`) instead.",``,"Returns scored page (and folder, with `omnibar` intent) hits, each with a body snippet. `exec`-grep covers every occurrence and needs no server.",``,`**Parameters:**`,"- `query` — Free-form; tokenized across title, name, path segments, and (with `full_text`) body.","- `intent` (optional) — `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.","- `scopes` (optional) — Result scope: `page` | `folder` | `content`. Defaults derive from `intent`.","- `limit` (optional) — Max rows; default 20, max 100.",``,'If the server is down, the tool returns a recovery hint — use `exec("grep ...")` as the server-free fallback.'].join(`
1762
+ `),InputSchema={query:string().describe(`Search query — title, path, or body terms.`),intent:_enum([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),scopes:array(_enum([`page`,`folder`,`content`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'content'. Defaults derive from intent.`),limit:number().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},SearchResultRowSchema=object$1({kind:_enum([`page`,`folder`]),path:string(),docName:string(),title:string().nullable(),score:number(),signals:object$1({lexical:number(),fullText:number(),recency:number()}),snippet:string().optional(),previewUrl:string().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),OutputSchema$1=outputSchemaWithText({cwd:string(),query:string(),intent:string(),resultCount:number().int(),results:array(SearchResultRowSchema),elapsedMs:number().nullable()});function isSearchKind(e){return e===`page`||e===`folder`}function normalizeSignals(e){return{lexical:typeof e?.lexical==`number`?e.lexical:0,fullText:typeof e?.fullText==`number`?e.fullText:0,recency:typeof e?.recency==`number`?e.recency:0}}function formatResultsBlock(e){if(e.length===0)return``;let t=[];for(let s of e){let e=s.title?.trim()||s.path;t.push(`### ${e} (${s.path})`),t.push(`Score ${s.score.toFixed(2)} — kind: ${s.kind}`),s.snippet&&t.push(s.snippet),t.push(``)}return t.join(`
1763
+ `)}function register$3(e,t){e.registerTool(`search`,{description:DESCRIPTION$3,inputSchema:InputSchema,outputSchema:OutputSchema$1,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(`${HOCUSPOCUS_NOT_RUNNING_ERROR}\nFor server-free literal-string search, use \`exec("grep ...")\` instead — it walks the filesystem and does not need Hocuspocus.`,!0);let E=e.intent??`full_text`,D=e.limit??20,O={query:e.query,intent:E,limit:D};e.scopes&&(O.scopes=e.scopes);let k=await httpPost(w,`/api/search`,O);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let{resolve:j}=await buildListResolver({config:S,resolveCwd:async()=>g},g),F=(k.results??[]).flatMap(e=>{if(!isSearchKind(e.kind)||typeof e.path!=`string`)return[];let t=docNameFromPath(e.path),s=j(t);return[{kind:e.kind,path:e.path,docName:t,title:e.title??null,score:typeof e.score==`number`?e.score:0,signals:normalizeSignals(e.signals),...e.snippet?{snippet:e.snippet}:{},previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}]}),L={cwd:g,query:e.query,intent:E,resultCount:F.length,results:F,elapsedMs:typeof k.elapsedMs==`number`?k.elapsedMs:null},B=`## Search results for "${e.query}" (${F.length} hit${F.length===1?``:`s`}, intent: ${E})`;return textPlusStructured(F.length===0?`No matches for "${e.query}".`:`${B}\n\n${formatResultsBlock(F)}`,L)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const DESCRIPTION$2=["[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",``,`Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own Open Knowledge install.`,``,"**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.",``,`**Parameters:**`,'- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.","- `cwd` (optional) — Project root (see `cwd` description below).",``,"**Preconditions:** project on a named branch (not detached HEAD); origin set to a `github.com` remote; the branch already pushed to origin."].join(`
1764
+ `);function messageForShareError(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is not a `github.com` remote. Share links are GitHub-only in v1.";case`invalid-path`:return"The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.";default:return`Unknown share-construct-url error: ${String(e)}`}}function isExistingDirectory(e){try{return statSync(e).isDirectory()}catch{return!1}}function resolveExistingDocPath(e,t){for(let s of[`.mdx`,`.md`]){let g=`${t}${s}`;if(existsSync(g)){let t=resolveWithinRoot(e,g);return t.ok?t.rel:null}}return null}function resolveShareTarget(e,t,s,g){if(s===``)return g===`folder`?{ok:!0,kind:`folder`,sharePath:``}:{ok:!1,code:`invalid-path`};let S=resolveWithinRoot(t,s);if(!S.ok)return{ok:!1,code:`target-not-found`};let w=resolveExistingDocPath(e,S.abs.replace(/\.(mdx|md)$/i,``)),E=isExistingDirectory(S.abs);if(g===`doc`)return w===null?E?{ok:!1,code:`kind-mismatch`}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:w};if(g===`folder`){if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return w===null?{ok:!1,code:`target-not-found`}:{ok:!1,code:`kind-mismatch`}}if(w!==null)return{ok:!0,kind:`doc`,sharePath:w};if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return{ok:!1,code:`target-not-found`}}const OutputSchema=outputSchemaWithText({ok:boolean().describe(`Success discriminator.`),shareUrl:string().optional().describe(`Marketing share URL (success only).`),sharedUrl:string().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:string().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:_enum([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),error:_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:string().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:string().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:string().optional().describe(`Internal: preview-URL provenance.`)});function register$2(e,t){e.registerTool(`share_link`,{description:DESCRIPTION$2,inputSchema:{path:string().describe('Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).'),kind:_enum([`doc`,`folder`]).optional().describe("Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveShareTarget(g,join(g,S.content.dir),e.path,e.kind);if(!E.ok){let t;if(E.code===`kind-mismatch`){let s=e.kind===`folder`?`folder`:`doc`;t=`\`${e.path}\` exists, but not as a ${s}. Pass \`kind: '${s===`doc`?`folder`:`doc`}'\` to share it as the other kind.`}else t=E.code===`invalid-path`?'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.':`Target \`${e.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;let s={ok:!1,error:E.code,message:t};return textPlusStructured(`Error: ${t}`,s,!0)}let D=E.kind===`doc`?{kind:`doc`,docPath:E.sharePath}:{kind:`folder`,folderPath:E.sharePath},O;try{O=await fetch(`${w}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(D),signal:AbortSignal.timeout(3e4)})}catch(e){let t=`Server unreachable: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let k;try{k=await O.json()}catch(e){let t=`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!O.ok){let e;if(k&&typeof k==`object`){let t=k,s=typeof t.title==`string`?t.title:void 0,g=typeof t.detail==`string`?t.detail:void 0;e=s&&g?`${s}: ${g}`:s||g||`HTTP ${O.status}`}else e=`HTTP ${O.status}`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let j=ShareConstructUrlResponseSchema.safeParse(k);if(!j.success){let e=`Server returned an unexpected share-construct-url response shape.`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let F=j.data;if(!F.ok){let e=messageForShareError(F.error,F.branch),t={ok:!1,error:F.error,message:e,...F.branch?{branch:F.branch}:{}};return textPlusStructured(`Error: ${e}`,t,!0)}let{shareUrl:L,sharedUrl:B,branch:H}=F,q={ok:!0,shareUrl:L,sharedUrl:B,branch:H,resolvedKind:E.kind},J={config:t.config,resolveCwd:t.resolveCwd},Y=await resolvePreviewUrlForTool(E.sharePath.replace(/\.(mdx|md)$/i,``),J,g);if(Y&&E.kind===`folder`){let e=E.sharePath.replace(/^\/+|\/+$/g,``),t=e===``?`/#/`:`/#/${encodeDocName(e)}/`;Y={...Y,url:t}}let ee=e.path===``?`(content root)`:e.path;return textPlusStructured(`Share link for ${E.kind} \`${ee}\` on branch \`${H}\`:\n${L}`,{...q,previewUrl:Y?.url??null,...Y?{previewUrlSource:Y.source}:{}})})}function buildConsolidateBody(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
1717
1765
 
1718
1766
  Topic: ${e}
1719
1767
 
@@ -1860,10 +1908,7 @@ superseded_by: <path-to-new-canonical-article>.md
1860
1908
  - **Don't delete research articles** — they are the trail; keep them with a \`superseded_by\` marker
1861
1909
  - **Don't rewrite research prose verbatim** — canonical articles have a different voice (direct, decided) than research (exploratory, provisional)
1862
1910
  - **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
1863
- `}const DESCRIPTION$22=[`Returns a step-by-step plan to promote stabilized research into a canonical article. Does NOT write you execute the plan after a STOP gate confirms a real decision was made.`,"Canonical, not provisional — the output becomes the source of truth, with a `supersedes` trail back to the research.",`Use when a team has decided after research and wants the outcome committed as authoritative knowledge.`].join(`
1864
- `);function register$22(e,t){e.registerTool(`consolidate`,{description:DESCRIPTION$22,inputSchema:{topic:string().describe(`The topic to consolidate into a canonical article`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},buildWorkflowHandler(`consolidate`,t,`topic`,buildBody$2))}const PREVIEW_URL_SOURCES=[`lock`];function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function encodeFolderRoute(e){let t=e.replace(/^\/+|\/+$/g,``);return t?`${encodeDocName(t)}/`:``}const START_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',ATTACH_PREVIEW_ONCE_MESSAGE=`No browser is attached to the preview. Open it with preview_start, or call get_preview_url for the URL.`;function buildPreviewAttachWarning(e,t){return e?{action:`attach-preview-once`,previewUrl:e.url,message:ATTACH_PREVIEW_ONCE_MESSAGE,autoOpen:t}:{action:`start-ui`,previewUrl:null,message:START_UI_MESSAGE,autoOpen:t}}const START_UI_TEXT_HINT=START_UI_MESSAGE;async function resolvePreviewUrlForTool(e,t,s){return resolvePreviewUrl(e,{lockDir:resolveLockDir(s??await t.resolveCwd())})}function resolveUiInfo(e){try{let t=readUiLock(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while resolving ui info: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null}}async function buildListResolver(e,t){let s={lockDir:resolveLockDir(t??await e.resolveCwd())};return{resolve:e=>resolvePreviewUrl(e,s)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let s=`/#/${encodeDocName(e)}`;try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:s,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const DESCRIPTION$21=["[Requires: Hocuspocus server] Delete a document through the managed delete flow at `POST /api/delete-path` (kind: file).",`Closes all open agent sessions for the doc, unloads it from Hocuspocus, and removes the file from disk.`,``,`**Parameters:**`,"- `docName` — A single document to delete, typically extension-less. A trailing `.md` or `.mdx` is stripped automatically.","- `docNames` — Batch form: an array of documents to delete in one call. Mutually exclusive with `docName`. Each is deleted independently; the response reports per-doc status.",``,`**Notes:**`,'- Inbound wiki-links to the deleted doc become dead links (redlinks) — they are NOT rewritten. Call `links({ kind: "backlinks", docName: "your-doc" })` BEFORE deleting to see which docs link here, then update or remove those references first.','- Deletion is irreversible from this tool. Use `version({ action: "save" })` beforehand if you may need to roll back.',"- The structured response includes `previousPreviewUrl` (when a preview source resolves) so agents can close any stale preview tab pointing at the deleted doc.",``,`**Errors:**`,"- 400 — `docName` is not a valid relative content path.",`- 404 — document does not exist.`].join(`
1865
- `);function parseDeletedDocNames(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}async function deleteOne(e,t,s,g){let S=normalizeDocName(e);if(!S.ok)return{docName:e,ok:!1,error:S.error};let w=g.identityRef?.current,E=await httpPost(t,`/api/delete-path`,{kind:`file`,path:S.docName,...w?{agentId:w.connectionId,agentName:w.displayName,clientName:w.clientInfo?.name,colorSeed:w.colorSeed}:{}});if(!E.ok)return{docName:S.docName,ok:!1,error:E.error};let D=parseDeletedDocNames(E.deletedDocNames),O=await resolvePreviewUrlForTool(S.docName,{config:g.config,resolveCwd:g.resolveCwd},s);return{docName:S.docName,ok:!0,deletedDocNames:D.length>0?D:[S.docName],...O?{previousPreviewUrl:O.url}:{}}}function register$21(e,t){e.registerTool(`delete_document`,{description:DESCRIPTION$21,inputSchema:{docName:string().optional().describe(`A single document to delete.`),docNames:array(string()).min(1).optional().describe("Batch: documents to delete in one call. Mutually exclusive with `docName`."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.docName===void 0&&e.docNames===void 0)return textResult("Error: provide `docName` (single) or `docNames` (batch).",!0);if(e.docName!==void 0&&e.docNames!==void 0)return textResult("Error: `docName` and `docNames` are mutually exclusive.",!0);if(e.docNames!==void 0){let s=await Promise.all(e.docNames.map(e=>deleteOne(e,S,g,t))),w=s.filter(e=>e.ok).length,E=w===s.length,D=s.map(e=>e.ok?`Deleted ${e.docName}.`:`Failed ${e.docName}: ${e.error}`);return textPlusStructured(`${w}/${s.length} deleted.\n${D.join(`
1866
- `)}`,{ok:E,documents:s},!E)}let w=await deleteOne(e.docName,S,g,t);if(!w.ok){let e={ok:!1,error:w.error??`unknown error`};return textPlusStructured(`Error: ${e.error}`,e,!0)}let E=w.deletedDocNames??[w.docName],D={ok:!0,deletedDocNames:E,...w.previousPreviewUrl?{previousPreviewUrl:w.previousPreviewUrl}:{}};return textPlusStructured(E.length===1?`Deleted ${E[0]}.`:`Deleted ${E.length} documents: ${E.join(`, `)}.`,D)})}function buildDiscoverBody(e){return`# Discover — Project Convention Extraction + Link Graph Activation
1911
+ `}function buildDiscoverBody(e){return`# DiscoverProject Convention Extraction + Link Graph Activation
1867
1912
 
1868
1913
  You're invoked because (a) the user explicitly asked to set up an existing repo, OR (b) an \`exec\` directory listing surfaced a hint because content exists with no folder frontmatter / templates configured. Your job: **extract conventions from existing siblings + activate the link graph, leaving the repo more structured and more navigable than you found it.**
1869
1914
 
@@ -1873,7 +1918,7 @@ Use OK primitives only — no new files outside \`<folder>/.ok/\`, no body rewri
1873
1918
 
1874
1919
  **You will work through 7 phases in order. STOP gates (⛔) require user confirmation before proceeding. Do not skip or batch ahead.**
1875
1920
 
1876
- **Server requirement.** Phases 1-4 run fs-direct — \`exec\` (scan + read) and \`folder_config\` (folder frontmatter + templates) need no running server. Phase 5 (link-graph activation) composes \`links\` and \`search\`, which **require the OK Hocuspocus server** — Phase 5 step 0 checks for it and exits cleanly with a \`run ok start\` instruction if it is down.
1921
+ **Server requirement.** Phases 1-4 run fs-direct — \`exec\` (scan + read) and the \`write\`/\`edit\` verbs (folder frontmatter + templates) need no running server. Phase 5 (link-graph activation) composes \`links\` and \`search\`, which **require the OK Hocuspocus server** — Phase 5 step 0 checks for it and exits cleanly with a \`run ok start\` instruction if it is down.
1877
1922
 
1878
1923
  ---
1879
1924
 
@@ -1974,43 +2019,42 @@ For **each** folder the user marked \`[KB]\`:
1974
2019
  - If this folder already has its own frontmatter → switch to "extend mode." Show existing keys to user; propose ADDITIONS only.
1975
2020
  - If \`templates_available\` includes a template → skip template extraction. Tell user: "existing template \`<name>\` found; preserving."
1976
2021
 
1977
- 5. **Propose folder frontmatter + template.** Both are \`folder_config\` writes — one call per action:
2022
+ 5. **Propose folder frontmatter + template.** One \`write\`/\`edit\` call per target:
1978
2023
 
1979
2024
  \`\`\`ts
1980
- folder_config({
1981
- action: 'set-rule',
1982
- rules: [{
1983
- match: '<folder>/**',
2025
+ edit({
2026
+ folder: {
2027
+ path: '<folder>',
1984
2028
  frontmatter: {
1985
2029
  title: '<inferred>', // e.g., "Specifications"
1986
2030
  description: '<inferred>', // 1-2 sentences describing the folder's purpose
1987
2031
  tags: ['<inferred>'], // e.g., ['spec']
1988
2032
  },
1989
- }],
2033
+ },
1990
2034
  })
1991
2035
 
1992
- folder_config({
1993
- action: 'write-template',
1994
- folder: '<folder>',
1995
- name: '<inferred-name>', // e.g., 'SPEC' for specs/, 'REPORT' for reports/
1996
- frontmatter: { title: '<placeholder>', description: '<placeholder>' },
1997
- body: '<heading skeleton from siblings; include a frontmatter region with recurring per-doc keys (status, owner, …) as starting values>',
2036
+ write({
2037
+ template: {
2038
+ path: '<folder>/<inferred-name>', // e.g., 'specs/SPEC', 'reports/REPORT'
2039
+ frontmatter: { title: '<placeholder>', description: '<placeholder>' },
2040
+ content: '<heading skeleton from siblings; include a frontmatter region with recurring per-doc keys (status, owner, …) as starting values>',
2041
+ },
1998
2042
  })
1999
2043
  \`\`\`
2000
2044
 
2001
2045
  6. **⛔ STOP gate 4 — Surface proposal to user.** Show: heading set + frontmatter shape + filename pattern + link patterns. Ask: "Apply this proposal? (yes / edit / skip this folder)"
2002
2046
 
2003
- 7. **Apply confirmed proposals** via the two \`folder_config\` calls above. Re-run \`exec("ls <folder>")\` to confirm \`templates_available\` + the folder's descriptive \`title\`/\`description\`/\`tags\` are populated.
2047
+ 7. **Apply confirmed proposals** via the \`edit({ folder })\` + \`write({ template })\` calls above. Re-run \`exec("ls <folder>")\` to confirm \`templates_available\` + the folder's descriptive \`title\`/\`description\`/\`tags\` are populated.
2004
2048
 
2005
2049
  Repeat for every \`[KB]\` folder.
2006
2050
 
2007
- **v1 scope note:** \`discover\` does NOT attempt nested-pattern detection (e.g., applying the same rule across \`specs/*/evidence/\` for every spec's evidence/ subfolder). \`folder_config\` rejects multi-folder globs with \`MULTI_FOLDER_GLOB\`. Users who want nested folder frontmatter set it up manually after \`discover\` finishes the top-level work.
2051
+ **v1 scope note:** \`discover\` does NOT attempt nested-pattern detection (e.g., applying the same folder frontmatter across \`specs/*/evidence/\` for every spec's evidence/ subfolder). Each folder is addressed by its own path — one \`edit({ folder })\` call per folder. Users who want nested folder frontmatter set it up manually after \`discover\` finishes the top-level work.
2008
2052
 
2009
2053
  ---
2010
2054
 
2011
2055
  ## Phase 5 — Link-graph activation
2012
2056
 
2013
- The largest phase. Uses the \`links\` tool (every link-graph view) plus \`search\` and \`edit_document\` to apply confirmed link insertions.
2057
+ The largest phase. Uses the \`links\` tool (every link-graph view) plus \`search\` and \`edit\` to apply confirmed link insertions.
2014
2058
 
2015
2059
  0. **Server check (required for this phase).** \`links\` and \`search\` need the OK Hocuspocus server. Probe via \`links({ kind: "hubs" })\`. If the response starts with \`"Error: Hocuspocus server is not running"\`, STOP — tell the user "the link-graph phase of discover needs the OK server. Start it with \`ok start\` from a terminal, then re-invoke \`discover\` (Phases 1-4 are already applied; it resumes here)." Exit cleanly.
2016
2060
 
@@ -2022,7 +2066,7 @@ Six sub-passes, each with its own STOP gate.
2022
2066
  2. For each orphan, run \`links({ kind: "suggest", docName: <orphan> })\`:
2023
2067
  - If \`mentions[]\` is non-empty → there are docs that mention this orphan without linking. Adoption candidates.
2024
2068
  - If \`mentions[]\` is empty → the orphan is **genuinely standalone** (no other doc references it at all). Surface as: "this looks intentionally standalone (e.g., a README). Skip / adopt anyway by linking from a hub / add to \`.okignore\`?"
2025
- 3. Confirm per orphan. For each "link" choice, \`edit_document\` on the source doc at the offset \`links({ kind: "suggest" })\` returned to wrap the existing mention in link syntax.
2069
+ 3. Confirm per orphan. For each "link" choice, \`edit({ document: { path, find, replace } })\` on the source doc find the existing mention text \`links({ kind: "suggest" })\` surfaced and replace it wrapped in link syntax.
2026
2070
 
2027
2071
  **Note on re-surfacing:** v1 does NOT persist "intentional standalone" markers. Each \`discover\` re-run surfaces the same intentional orphans (root \`README.md\`, \`CONTRIBUTING.md\`, etc.) and the user re-dismisses them. Acceptable minor friction.
2028
2072
 
@@ -2039,7 +2083,7 @@ Six sub-passes, each with its own STOP gate.
2039
2083
 
2040
2084
  1. Run \`links({ kind: "dead" })\` (no \`sourceDocNames\` → audits the whole corpus).
2041
2085
  2. For each dead link, propose: fix candidate (via \`search\` for the correct target), or delete (remove the link, or the prose around it). Leaving it as an "intentional redlink" is not an option — every dead link is fixed or removed.
2042
- 3. Confirm per dead-link. Apply confirmed fixes via \`edit_document\`.
2086
+ 3. Confirm per dead-link. Apply confirmed fixes via \`edit\`.
2043
2087
 
2044
2088
  ### 5d. Untextualized-reference detection (⛔ STOP gate 5d)
2045
2089
 
@@ -2056,7 +2100,7 @@ Six sub-passes, each with its own STOP gate.
2056
2100
  line 203: "...per AGENTS.md ecosystem convention" → matches root AGENTS.md — accept as link
2057
2101
  \`\`\`
2058
2102
 
2059
- 4. Confirm per source doc (batched). Apply confirmed link insertions via \`edit_document\` using the offsets the \`suggest\` view returned.
2103
+ 4. Confirm per source doc (batched). Apply confirmed link insertions via \`edit({ document: { path, find, replace } })\` find the mention text the \`suggest\` view surfaced and replace it wrapped in link syntax.
2060
2104
 
2061
2105
  **Truncation handling:** if the \`suggest\` view returns \`truncated: true\`, the scan hit its time budget. Iterate with smaller scope or accept partial coverage and tell the user.
2062
2106
 
@@ -2069,7 +2113,7 @@ Harder case: prose discusses a concept covered by another doc without naming it.
2069
2113
  3. For each candidate sibling:
2070
2114
  - Verify it is NOT already linked from this doc (\`links({ kind: "forward", docName: <doc> })\`).
2071
2115
  - Verify content is actually relevant (re-read summary; LLM judgment).
2072
- 4. Surface to user with brief justification per pair. Confirm. Apply via \`edit_document\` (insert link in a "Related" or "References" section).
2116
+ 4. Surface to user with brief justification per pair. Confirm. Apply via \`edit\` (insert link in a "Related" or "References" section).
2073
2117
 
2074
2118
  **Caveat:** vague-referential is LLM-judgment-heavy. False positives are expected; the user is the final arbiter. If the user rejects > 50% of proposals in a batch, recalibrate (tighten concept-extraction, raise relevance bar).
2075
2119
 
@@ -2079,7 +2123,7 @@ Harder case: prose discusses a concept covered by another doc without naming it.
2079
2123
  - Wiki-link syntax: \`[[Page Title]]\` (legacy)
2080
2124
  - Relative-markdown: \`[text](./path.md)\` or \`[text](path.md)\` (current OK recommended)
2081
2125
  2. Report ratio to user. If mixed, propose a one-time standardization: convert all \`[[Page]]\` to \`[Page](./path.md)\`. Ambiguous \`[[Page]]\` (multiple matching files) → surface for confirmation.
2082
- 3. Apply via \`edit_document\` on each affected doc, resolving page titles to file paths via \`exec("ls")\` / \`search\`.
2126
+ 3. Apply via \`edit\` on each affected doc, resolving page titles to file paths via \`exec("ls")\` / \`search\`.
2083
2127
 
2084
2128
  ---
2085
2129
 
@@ -2175,49 +2219,7 @@ Link-graph activation:
2175
2219
  - **Server down** (Phase 5 step 0): Phases 1-4 already applied fs-direct; surface "the link-graph phase needs \`ok start\` running" and exit cleanly — re-invoking resumes at Phase 5.
2176
2220
  - **User aborts at any STOP gate** → exit cleanly, leaving any already-applied proposals in place (apply is per-phase, not all-or-nothing).
2177
2221
  - **Validation failure** (Phase 6) → don't pretend to succeed; surface the failed step to the user.
2178
- `}const DESCRIPTION$20=[`Returns a step-by-step plan for setting up an existing repo: extract folder conventions, write folder frontmatter + templates, activate the link graph. Does NOT execute the plan you run it, with per-phase user confirmation.`,``,"Invoke on first arrival at a repo that has markdown content but no folder frontmatter / templates (an `exec` listing shows no folder `title`/`description`/`tags` and empty `templates_available`). Skip empty repos (use `ok seed`) and already-configured ones. One-shot per project; idempotent on re-run (extends, never re-proposes).",``,"Phases 1-4 run fs-direct; Phase 5 (link-graph activation) needs `ok start`. Composes existing tools only — `exec`, `links`, `search`, `folder_config`, `edit_document`."].join(`
2179
- `),InputSchema$5={cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$9=outputSchemaWithText({previewUrl:_null()});function register$20(e,t){e.registerTool(`discover`,{description:DESCRIPTION$20,inputSchema:InputSchema$5,outputSchema:OutputSchema$9,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!1}},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return s.ok?textPlusStructured(buildDiscoverBody(s.config.content.dir),{previewUrl:null}):textResult(`Error: ${s.error}`,!0)})}const DESCRIPTION$19=`${["[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer. The patch propagates to all connected editors in real-time. Use `offset` to target an exact occurrence; omit for first-match.",``,'**Body-only.** Frontmatter-intersecting find/replace is rejected with HTTP 400. For frontmatter: 1-2 keys → `edit_frontmatter`; full rewrite → `write_document({ position: "replace" })`.',``,`**Parameters:**`,"- `docName` — Document name, extension-less. Trailing `.md`/`.mdx` stripped.","- `find` — Text to find (exact match).","- `replace` — Replacement text.",'- `offset` — Optional JavaScript string offset of the exact occurrence to patch. Stale offsets return an error; re-fetch via `links({ kind: "suggest", docName })`.',"- `summary` — Optional one-line user-outcome (≤80 chars). Avoid secrets or PII — persisted to git history.",``,'Responses may include `structuredContent.contentDivergence` (`{kind: "content-divergence", intendedBytes, actualBytes, byteDelta, divergenceType, currentState, hint}`) when the converged Y.Text doesn\'t match the bytes your splice composed to. The patch still landed; you do NOT need to re-read — `currentState` carries the converged document inline (or a truncation marker over the soft cap).'].join(`
2180
- `)}\n${renderInventoryFooter()}`;function register$19(e,t){e.registerTool(`edit_document`,{description:DESCRIPTION$19,inputSchema:{docName:string().describe(`Document name to edit`),find:string().describe(`Text to find (exact match)`),replace:string().describe(`Replacement text`),offset:number().int().min(0).optional().describe(`Exact occurrence to patch, as a JavaScript string offset in the current markdown`),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=S.appearance.preview.autoOpen,D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=t.identityRef?.current,k=await httpPost(w,`/api/agent-patch`,{docName:D.docName,find:e.find,replace:e.replace,offset:e.offset,...e.summary===void 0?{}:{summary:e.summary},...O?{agentId:O.connectionId,agentName:O.displayName,clientName:O.clientInfo?.name,colorSeed:O.colorSeed}:{}});if(!k.ok){let e=typeof k.detail==`string`&&k.detail.length>0?k.detail:``;return textResult(e?`Error: ${k.error} (${e})`:`Error: ${k.error}`,!0)}let j=resolveLockDir(g),F=resolvePreviewUrl(D.docName,{lockDir:j}),L=typeof k.subscriberCount==`number`?k.subscriberCount:void 0,B=(typeof k.systemSubscriberCount==`number`?k.systemSubscriberCount:void 0)===0,H=L===0,q=k.summary&&typeof k.summary==`object`?k.summary:void 0,J=typeof q?.hint==`string`?q.hint:void 0,Y=WriteWarningSchema.safeParse(k.warning),ee=Y.success?Y.data:void 0,te=[`Edit applied successfully.`];B&&!F&&te.push(START_UI_TEXT_HINT),J&&te.push(J),ee&&te.push(ee.kind===`content-divergence`?`⚠ Content divergence: ${ee.actualBytes} actual bytes vs ${ee.intendedBytes} intended (byteDelta=${ee.byteDelta}). ${ee.hint??`currentState carries the converged content (re-read only if it is truncated).`}`:`⚠ ${ee.hint??`An out-of-band edit was reconciled into this document before your edit landed on top — re-read for the combined result.`}`);let ne=te.join(`
2181
- `);if(!F&&!B&&!H&&!q&&!ee)return textResult(ne);let ae={};return ee&&(ae.contentDivergence=ee),F&&(ae.previewUrl=F.url,ae.previewUrlSource=F.source),B&&(ae.warning=buildPreviewAttachWarning(F,E)),q&&(ae.summary=q),textPlusStructured(ne,ae)})}const DESCRIPTION$18=[`[Requires: Hocuspocus server] Set, create, or delete frontmatter properties via JSON Merge Patch (RFC 7396).`,``,`Field-level CRDT merge: concurrent patches to different keys (human form + this tool, or two agents) merge cleanly. Same-key concurrent writes resolve last-writer-wins per key.`,``,'**Use this tool — not `edit_document` — for any frontmatter change.** `edit_document` (agent-patch) targets body content; FM-intersecting `edit_document` calls return HTTP 400. For full-document rewrites (≥3-5 frontmatter keys changing), `write_document({ position: "replace" })` remains the canonical pathway.',``,`**Parameters:**`,"- `docName` — Document name. A trailing `.md` or `.mdx` is stripped automatically.","- `patch` — Object whose keys are property names. Each value is the new value (string, number, boolean, or array of strings) to **set or create** the key, or `null` to **delete** the key. Keys not present in `patch` are unchanged.","- `types` (optional) — **Currently ignored.** Shape-validated for forward-compat but not persisted server-side; type is inferred from value shape on read. Reserved for a future per-key widget-type override (`text | number | boolean | date | list`) once persistence ships.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Prefer outcome phrasing ("Marked spec as approved") over structural ("Set status field"). Avoid secrets / PII — summaries persist to git history.',``,`**Atomicity:** any value failing schema validation rejects the WHOLE patch (HTTP 400 with per-key error report). Either every change commits or none do.`].join(`
2182
- `),PatchValueSchema=union([FrontmatterValueSchema,_null()]).describe("Property value (string|number|boolean|string[]) — `null` deletes the key");function register$18(e,t){e.registerTool(`edit_frontmatter`,{description:DESCRIPTION$18,inputSchema:{docName:string().describe(`Document name`),patch:record(string(),PatchValueSchema).describe("JSON Merge Patch — `{key: value}` sets, `{key: null}` deletes"),types:record(string(),_enum(FRONTMATTER_TYPES)).optional().describe(`Currently ignored (shape-validated for forward-compat but not persisted). Type is inferred from value shape on read. Will become a real per-key widget-type override (text|number|boolean|date|list) once persistence lands.`),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=S.appearance.preview.autoOpen,D=normalizeDocName(e.docName);if(!D.ok)return textResult(D.error,!0);let O=t.identityRef?.current,k=await httpPost(w,`/api/frontmatter-patch`,{docName:D.docName,patch:e.patch,...e.types?{types:e.types}:{},...e.summary===void 0?{}:{summary:e.summary},...O?{agentId:O.connectionId,agentName:O.displayName,clientName:O.clientInfo?.name,colorSeed:O.colorSeed}:{}});if(!k.ok){let e=k.error,t=k.fieldErrors&&typeof k.fieldErrors==`object`?k.fieldErrors:void 0;return textResult(t?`Error: ${e}\n${Object.entries(t).map(([e,t])=>` ${e}: ${t}`).join(`
2183
- `)}`:`Error: ${e}`,!0)}let j=resolveLockDir(g),F=resolvePreviewUrl(D.docName,{lockDir:j}),L=typeof k.subscriberCount==`number`?k.subscriberCount:void 0,B=(typeof k.systemSubscriberCount==`number`?k.systemSubscriberCount:void 0)===0,H=L===0,q=k.summary&&typeof k.summary==`object`?k.summary:void 0,J=typeof q?.hint==`string`?q.hint:void 0,Y=[],ee=[];for(let[t,s]of Object.entries(e.patch))s===null?ee.push(t):Y.push(t);let te=[`Frontmatter patched (${[Y.length?`${Y.length} set`:``,ee.length?`${ee.length} deleted`:``].filter(Boolean).join(`, `)||`${Object.keys(e.patch).length} key(s)`}).`];B&&!F&&te.push(START_UI_TEXT_HINT),J&&te.push(J);let ne=WriteWarningSchema.safeParse(k.warning),ae=ne.success?ne.data:void 0;ae?.hint&&te.push(`⚠ ${ae.hint}`);let oe=te.join(`
2184
- `);if(!F&&!B&&!H&&!q&&!ae)return textResult(oe);let se={};return ae&&(se.contentDivergence=ae),F&&(se.previewUrl=F.url,se.previewUrlSource=F.source),B&&(se.warning=buildPreviewAttachWarning(F,E)),q&&(se.summary=q),textPlusStructured(oe,se)})}const PRODUCER_COMMANDS=new Set([`cat`,`ls`,`grep`,`find`]),PATH_FALLBACK_RE=/\b[\w./-]+\.(md|mdx)\b/g;function isWikiPath(e){return/\.(md|mdx)$/.test(e)}function normalize$1(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function argsOf(e){return e.args.slice(1)}function nonFlagArgs(e){return e.filter(e=>!e.startsWith(`-`))}function extractFromCat(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function extractFromLs(e,t){let s=nonFlagArgs(argsOf(t)),g=s.length>0?s[s.length-1]:``,S=g&&g!==`.`?normalize$1(g):``,w=[];S&&w.push(S);for(let t of e.split(`
2185
- `)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!isWikiPath(e))continue;let s=S?`${S}/${e}`:e;w.push(s)}return w}function extractFromGrep(e){let t=[];for(let s of e.split(`
2186
- `)){if(!s)continue;let e=s.indexOf(`:`);if(e<0)continue;let g=normalize$1(s.slice(0,e));isWikiPath(g)&&t.push(g)}return t}function extractFromFind(e){let t=[];for(let s of e.split(`
2187
- `)){let e=normalize$1(s);e&&isWikiPath(e)&&t.push(e)}return t}function extractFromHeadTail(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function headTailActsAsProducer(e){return nonFlagArgs(argsOf(e)).length>0}function fallback(e){let t=[],s=e.matchAll(PATH_FALLBACK_RE);for(let e of s)t.push(normalize$1(e[0]));return t}function extractReferencedPaths(e,t){let s=null;for(let e=t.length-1;e>=0;e--){let g=t[e];if(PRODUCER_COMMANDS.has(g.command)){s=g;break}if((g.command===`head`||g.command===`tail`)&&headTailActsAsProducer(g)){s=g;break}}let g;if(!s)g=fallback(e);else{switch(s.command){case`cat`:g=extractFromCat(s);break;case`ls`:g=extractFromLs(e,s);break;case`grep`:g=extractFromGrep(e);break;case`find`:g=extractFromFind(e);break;case`head`:case`tail`:g=extractFromHeadTail(s);break;default:g=fallback(e)}g.length===0&&(g=fallback(e))}let S=new Set,w=[];for(let e of g){let t=normalize$1(e);!t||S.has(t)||(S.add(t),w.push(t))}return w}function shellEscape(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const MAX_STDOUT_BYTES=16*1024*1024;var StdoutOverflowError=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,s){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=s}};function createBashInstance(e){if(!isAbsolute(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new xt({cwd:`/`,fs:new Ss({root:resolve(e),allowSymlinks:!1})})}async function execBash(e,t){let s=await e.exec(t);if(s.stdout.length>MAX_STDOUT_BYTES)throw new StdoutOverflowError(MAX_STDOUT_BYTES,s.stdout.length,{stdout:s.stdout.slice(0,MAX_STDOUT_BYTES),stderr:s.stderr,exitCode:s.exitCode});return{stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode}}const SCAN_CAP=1e3,SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function snapshotMtimes(e){let t=resolve(e),s=new Map,g=0,S=!1;async function w(e){if(S)return;let E;try{E=await readdir(e,{withFileTypes:!0})}catch{return}for(let D of E){if(S)return;if(D.isDirectory()&&SKIP_DIRS.has(D.name))continue;let E=resolve(e,D.name);if(D.isDirectory()){await w(E);continue}if(D.isFile()){if(g>=SCAN_CAP){S=!0;return}try{let e=await stat$1(E);s.set(relative(t,E),e.mtimeMs),g++}catch{}}}}return await w(t),{snapshot:s,truncated:S}}function diffMtimes(e,t){let s=[];for(let[g,S]of t){let t=e.get(g);(t===void 0||t!==S)&&s.push(g)}for(let[g]of e)t.has(g)||s.push(g);return{changed:s}}const WIKI_EXCLUDE_DIRS=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];function isRecursiveGrepFlag(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const STRATEGIES=[{command:`grep`,applies:e=>e.slice(1).some(isRecursiveGrepFlag),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let s of e)t.push(`-not`,`-path`,`*/${s}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function augmentStagesWithExcludes(e){return e.map(e=>{let t=STRATEGIES.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let s=t.buildExcludeArgs(WIKI_EXCLUDE_DIRS),g=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,g),...s,...e.args.slice(g)]}})}function serializeStages(e){return e.map(e=>e.args.map(shellEscape).join(` `)).join(` | `)}const ALLOWLIST=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),ALLOWLIST_HINT=`cat, ls, grep, find, head, tail, wc, sort, uniq, cut`,WRITE_OPS=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),SHELL_CONSTRUCT_OPS=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),UNIVERSAL_FLAG_DENY=new Set([`-o`,`--output-file`,`--output`]),UNIVERSAL_FLAG_PREFIX_DENY=[`-o=`,`--output-file=`,`--output=`],FIND_FLAG_DENY=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),SUSPICIOUS_STRING_RE=/[`]|\$\(|\$\{|\$'/;function isOpToken(e){return typeof e==`object`&&!!e&&`op`in e}function opTokenError(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return WRITE_OPS.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`}:SHELL_CONSTRUCT_OPS.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported. Only pipes (|) are allowed between allowlisted stages.`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function buildStageArgs(e){let t=[];for(let s of e){if(typeof s==`string`){if(SUSPICIOUS_STRING_RE.test(s))return{error:{category:`shell_construct_blocked`,message:`Argument '${s}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(s);continue}if(!isOpToken(s))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(s.op===`glob`&&typeof s.pattern==`string`){t.push(s.pattern);continue}return typeof s.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:opTokenError(s)}}return{args:t}}function checkStage(e){if(!ALLOWLIST.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: ${ALLOWLIST_HINT}.`};for(let t of e.args.slice(1)){if(UNIVERSAL_FLAG_DENY.has(t)||UNIVERSAL_FLAG_PREFIX_DENY.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use write_document or edit_document.`};if(e.command===`find`&&FIND_FLAG_DENY.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function parseCommand(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let s;try{s=import_shell_quote.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let g=[],S=[];for(let e of s){if(isOpToken(e)&&e.op===`|`){g.push(S),S=[];continue}S.push(e)}g.push(S);let w=[];for(let e of g){let t=buildStageArgs(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let s={command:t.args[0],args:t.args},g=checkStage(s);if(g)return{error:g};w.push(s)}return{stages:w}}const SOFT_CAP_LINES=500,SOFT_CAP_BYTES=50*1024,BINARY_EXT_RE=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,DESCRIPTION$17=["**STOP — when the project has `.ok/`, do NOT use native `Read`/`Grep`/`Glob` on in-scope `.md`/`.mdx`; use `exec` (this tool).** Native tools skip the frontmatter, backlinks, shadow-repo activity, and git history `exec` returns per wiki file. Reserve native tools for source code, non-markdown, and projects without `.ok/`. (Full rule + escape hatch: the `open-knowledge` skill / MCP `instructions`.)",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. Pipes (|) work between stages. Redirections, subshells, and writes are rejected.`,``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
2188
- `);function applySoftCap(e){let t=e.split(`
2189
- `),s=t[t.length-1]===``?t.length-1:t.length;if(s<=SOFT_CAP_LINES&&e.length<=SOFT_CAP_BYTES)return{text:e,truncated:!1,omittedLines:0};let g=Math.min(s,SOFT_CAP_LINES),S=0,w=0;for(let e=0;e<g;e++){let s=t[e];if(S+=s.length+1,S>SOFT_CAP_BYTES)break;w++}let E=t.slice(0,w).join(`
2190
- `),D=s-w;return{text:`${E}\n<truncated: ${D} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:D}}function detectBinaryArgs(e){let t=[];for(let s of e)if(s.command===`cat`)for(let e of s.args.slice(1))e.startsWith(`-`)||BINARY_EXT_RE.test(e)&&t.push(e);return t}function extractHeadTailLimit(e){for(let t=1;t<e.length;t++){let s=e[t],g=s.match(/^--lines=(\d+)$/);if(g)return Number(g[1]);if(s===`--lines`&&t+1<e.length){let s=Number(e[t+1]);if(Number.isFinite(s))return s}if(s===`-n`&&t+1<e.length){let s=Number(e[t+1]);if(Number.isFinite(s))return s}let S=s.match(/^-n(\d+)$/);if(S)return Number(S[1]);let w=s.match(/^-(\d+)$/);if(w)return Number(w[1])}return 10}function detectHeadTailTruncation(e,t){if(e.length<2)return null;let s=e[e.length-1];if(s.command!==`head`&&s.command!==`tail`)return null;let g=extractHeadTailLimit(s.args),S=t.split(`
2191
- `),w=S[S.length-1]===``?S.length-1:S.length;if(w<g)return null;let E=S.slice(0,w),D=new Set(E.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,O=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${s.command} -${g}\` cap (${w} lines, ${D} unique file${D===1?``:`s`}). The \`${O}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${s.command}\` or widen the cap.`}}function isDirectoryMeta(e){return e.type===`directory`}function formatDirectoryEntry(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`);let s=[];return s.push(`${e.recursiveMdCount} md file${e.recursiveMdCount===1?``:`s`}`),e.childDirCount>0&&s.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(s.join(`, `)),e.mostRecentMd&&t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path})`),e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function formatFileEntry(e){let t=[`**${e.title??e.path}** (${e.path})`];if(e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.backlinkCount!==null&&t.push(`backlinks: ${e.backlinkCount}`),e.forwardLinkCount!==null&&t.push(`forward links: ${e.forwardLinkCount}`),e.history&&e.history.length>0){let s=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${s.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let s=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${s.join(` · `)}`)}return`- ${t.join(` — `)}`}function buildStdoutProvenance(e,t,s){let g=null;for(let t=e.length-1;t>=0;t--){let s=e[t],S=s.command;if(S===`ls`||S===`cat`){g=s;break}if((S===`head`||S===`tail`)&&nonFlagArgs(argsOf(s)).length>0){g=s;break}}if(!g)return``;let S=nonFlagArgs(argsOf(g));if(g.command===`ls`){let e=S[S.length-1];if(!e||e===`.`)return``;let s=e.replace(/\/+/g,`/`);return s.startsWith(`./`)&&(s=s.slice(2)),s.endsWith(`/`)&&(s=s.slice(0,-1)),!s||!t.has(s)?``:`${s}/:\n`}let w=S.filter(e=>/\.(md|mdx)$/.test(e)&&s.has(e));return w.length===1?`==> ${w[0]} <==\n`:``}function formatEnrichedBlock(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let s of e)t.push(isDirectoryMeta(s)?formatDirectoryEntry(s):formatFileEntry(s));return t.join(`
2192
- `)}async function classifyPaths(e,t){let s=[],g=[];return await Promise.all(t.map(async t=>{try{let S=await stat$1(resolve(e,t));S.isDirectory()?g.push(t):S.isFile()&&s.push(t)}catch{/\.(md|mdx)$/i.test(t)&&s.push(t)}})),{files:s,dirs:g}}function errorCategoryResult(e,t){return textPlusStructured(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function withPreviewUrls(e,t){return e.map(e=>{let s=t(docNameFromPath(e.path));return{...e,previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}})}async function buildExecResult(e,t){let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return errorCategoryResult(`shell_construct_blocked`,`exec failed: ${s.error}`);let{cwd:g,config:S,url:w}=s,E=parseCommand(e.command);if(`error`in E)return errorCategoryResult(E.error.category,E.error.message);let D=augmentStagesWithExcludes(E.stages),O=serializeStages(D),k=await snapshotMtimes(g),j=createBashInstance(g),F=``,L=``;try{let e=await execBash(j,O);F=e.stdout,L=e.stderr}catch(e){return e instanceof StdoutOverflowError?errorCategoryResult(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`):errorCategoryResult(`shell_construct_blocked`,`exec failed: ${e instanceof Error?e.message:String(e)}`)}let B=await snapshotMtimes(g),H=diffMtimes(k.snapshot,B.snapshot);if(H.changed.length>0)return errorCategoryResult(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${H.changed.join(`, `)}. This indicates a parser bug; the command has been logged.`);let q=applySoftCap(F),J=extractReferencedPaths(F,D).filter(e=>resolveWithinRoot(g,e).ok),{files:Y,dirs:ee}=await classifyPaths(g,J),te=D.length===1&&D[0].command===`cat`&&Y.length===1,ne=await Promise.all(Y.map(e=>enrichPath(e,{projectDir:g,serverUrl:w},{includeRichFields:te}).catch(()=>({path:e,tags:[],frontmatter:{},backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null})))),ae=await Promise.all(ee.map(e=>enrichDirectoryRecursive(e,1,{projectDir:g}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!te&&w&&ne.length>0){let e=await fetchBacklinkCountsBatch(w,ne.map(e=>pathToDocName$1(e.path))).catch(()=>null);if(e)for(let t of ne){let s=e.get(pathToDocName$1(t.path));typeof s==`number`&&(t.backlinkCount=s)}}let oe=new Map(ne.map(e=>[e.path,e])),se=new Map(ae.map(e=>[e.path,e])),ce=[];for(let e of J){let t=oe.get(e);if(t){ce.push(t);continue}let s=se.get(e);s&&ce.push(s)}let ue=detectBinaryArgs(D),de=[];ue.length>0&&de.push(`File${ue.length>1?`s`:``} ${ue.join(`, `)} appear${ue.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let fe=detectHeadTailTruncation(D,F);fe&&de.push(fe.banner),L&&de.push(`stderr: ${L.trim()}`);let me=de.length>0?`${de.join(`
2193
- `)}\n\n`:``,ge=buildStdoutProvenance(D,se,oe)+q.text,_e=`${me}${ge}${formatEnrichedBlock(ce)}`,{resolve:ve}=await buildListResolver({config:S,resolveCwd:async()=>g});return textPlusStructured(_e,{enrichedPaths:withPreviewUrls(ce,ve),stdout:ge,stdoutTruncated:q.truncated,cwd:g,...de.length>0?{warnings:de}:{}})}function register$17(e,t){e.registerTool(`exec`,{description:DESCRIPTION$17,inputSchema:{command:string().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:string().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")}},async e=>{try{return await buildExecResult(e,t)}catch(e){return errorCategoryResult(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const DESCRIPTION$16=["[Operates on disk; no running OK server required] Folder-level configuration writes. Dispatches on `action`:",``,"- `action: \"set-rule\"` — Upsert a folder's own frontmatter (open-shape, exactly like a doc's frontmatter — any key). Writes nested `<folder>/.ok/frontmatter.yml`. SELF-ONLY: this metadata describes the folder and does NOT cascade values into child docs — for per-doc starting values, write a template instead. Always batch-shape: pass `rules: [{...}]` even for one. Empty `frontmatter: {}` removes the rule and auto-cleans `<folder>/.ok/` if empty. Use `new_match` to rename the rule's match glob. Multi-folder globs are rejected (split per folder).",'- `action: "write-template"` — Create or update `<folder>/.ok/templates/<name>.md`. Templates are markdown starter shapes (the single mechanism for "what new docs start with"); agents instantiate via `write_document({ template })`. `title` in frontmatter is REQUIRED (menu surface). Body MAY use `{{date}}` / `{{user}}` substitution tokens; any other `{{...}}` is rejected. Unknown keys are rejected.','- `action: "delete-template"` — Remove `<folder>/.ok/templates/<name>.md`. Idempotent (`existed: false` if missing). Auto-cleans empty `templates/` and `.ok/` dirs. Unknown keys are rejected.',``,"To apply several writes in one call (e.g. set a folder rule and write its template together), pass `operations: [{action, ...}, ...]` instead of a top-level `action`. Operations run in order; the response reports each.",``,`**Parameters:**`,"- `action` — `set-rule` | `write-template` | `delete-template`. Omit when using `operations`.","- `operations` — Array of `{action, ...}` objects. Mutually exclusive with a top-level `action`.","- `rules` — Required for `set-rule`. Array of `{match, frontmatter, new_match?}`. `match` is a folder glob (`specs/**`). `frontmatter` is the folder's own open-shape metadata (any key, like a doc); `null` / `''` / `[]` clears a key.","- `folder` — Required for `write-template`/`delete-template`. Project-root-relative folder. Empty / `.` means project root.","- `name` — Required for `write-template`/`delete-template`. Filename without `.md` (letters/digits/`_`/`-` only).","- `body` — Required for `write-template`. Markdown body. May use `{{date}}` / `{{user}}`.","- `frontmatter` — Required for `write-template`. `{title (required), description?, tags?: string[]}`.","- `cwd` (optional) — Project root."].join(`
2194
- `),ACTIONS$1=[`set-rule`,`write-template`,`delete-template`],FolderRuleUpsertInputSchema=object$1({match:string().min(1).describe(`Glob pattern (e.g. "specs/**", "meetings/prep-notes/**") that identifies the target folder.`),frontmatter:record(string(),unknown()).refine(e=>!(`title`in e&&e.title!==null&&typeof e.title!=`string`||`description`in e&&e.description!==null&&typeof e.description!=`string`||`tags`in e&&e.tags!==null&&!Array.isArray(e.tags)),{message:"Well-known keys must match expected types when present: `title` (string|null), `description` (string|null), `tags` (string[]|null)."}).describe("The folder's own open-shape frontmatter (any key, like a doc's). `title` / `description` / `tags` are conventional well-known keys the UI surfaces; other keys are allowed. Note one folder/doc asymmetry: only `title` / `description` / `tags` appear in `exec ls` output — other keys are stored and returned by `GET /api/folder-config` (and the folder-properties UI), but not surfaced on the directory listing. Self-only — does NOT cascade into child docs (use a template for per-doc starting values). `null` / `''` / `[]` clears a key; `{}` removes the rule."),new_match:string().min(1).optional().describe("If set, move the rule from `match` to this new folder.")}),TEMPLATE_NAME_REGEX=/^[A-Za-z0-9_-]+$/,TemplateFrontmatterSchema=object$1({title:string().min(1,"Template `title` is required — it is the menu surface agents pick from.").describe(`Required. The menu surface agents pick from.`),description:string().optional().describe(`Recommended. Disambiguates similarly-named templates.`),tags:array(string()).optional().describe(`Optional. Applied to docs created from this template.`)}),ACTION_FIELDS={rules:array(FolderRuleUpsertInputSchema).min(1).optional().describe("Required for `set-rule`. Array of folder rules to upsert."),folder:string().optional().describe("Required for `write-template`/`delete-template`. Project-root-relative folder. Empty / `.` means project root."),name:string().min(1).max(128).optional().describe("Required for `write-template`/`delete-template`. Template filename without `.md` extension (letters/digits/`_`/`-` only — enforced per-action)."),body:string().optional().describe("Required for `write-template`. Markdown body."),frontmatter:TemplateFrontmatterSchema.optional().describe("Required for `write-template`. Template menu metadata.")},OperationSchema=object$1({action:_enum(ACTIONS$1).describe(`Which folder-config write to perform.`),...ACTION_FIELDS}).strict();function checkActionFields(e,t,s){e.action===`set-rule`?e.rules||t.addIssue({code:`custom`,message:"action=set-rule requires `rules`.",path:[...s,`rules`]}):e.action===`write-template`?(e.folder===void 0&&t.addIssue({code:`custom`,message:"action=write-template requires `folder`.",path:[...s,`folder`]}),e.name?typeof e.name==`string`&&!TEMPLATE_NAME_REGEX.test(e.name)&&t.addIssue({code:`custom`,message:"Template name must use letters, digits, `_`, or `-` only (no slashes, dots, or spaces).",path:[...s,`name`]}):t.addIssue({code:`custom`,message:"action=write-template requires `name`.",path:[...s,`name`]}),e.body===void 0&&t.addIssue({code:`custom`,message:"action=write-template requires `body`.",path:[...s,`body`]}),e.frontmatter||t.addIssue({code:`custom`,message:"action=write-template requires `frontmatter`.",path:[...s,`frontmatter`]})):e.action===`delete-template`&&(e.folder===void 0&&t.addIssue({code:`custom`,message:"action=delete-template requires `folder`.",path:[...s,`folder`]}),e.name?typeof e.name==`string`&&!TEMPLATE_NAME_REGEX.test(e.name)&&t.addIssue({code:`custom`,message:"Template name must use letters, digits, `_`, or `-` only (no slashes, dots, or spaces).",path:[...s,`name`]}):t.addIssue({code:`custom`,message:"action=delete-template requires `name`.",path:[...s,`name`]}))}const FolderConfigInputSchema=object$1({action:_enum(ACTIONS$1).optional().describe("Which folder-config write to perform. Omit when `operations` is set."),...ACTION_FIELDS,operations:array(OperationSchema).min(1).optional().describe("Batch form: apply several folder-config writes in one call. Mutually exclusive with `action`."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}).strict().superRefine((e,t)=>{if(e.operations!==void 0){e.action!==void 0&&t.addIssue({code:`custom`,message:"`action` and `operations` are mutually exclusive.",path:[`action`]});for(let s of[`rules`,`folder`,`name`,`body`,`frontmatter`])e[s]!==void 0&&t.addIssue({code:`custom`,message:`\`${s}\` belongs inside an \`operations\` entry, not at the top level.`,path:[s]});e.operations.forEach((e,s)=>{checkActionFields(e,t,[`operations`,s])});return}if(e.action===void 0){t.addIssue({code:`custom`,message:"Provide either `action` or `operations`.",path:[`action`]});return}checkActionFields(e,t,[])}),AppliedEntrySchema=object$1({match:string(),path:string(),action:_enum([`written`,`deleted`])}),SingleResultSchema=union([object$1({ok:literal(!0),applied:array(AppliedEntrySchema)}),object$1({ok:literal(!1),error:object$1({code:_enum([`MULTI_FOLDER_GLOB`,`PATH_ESCAPE`,`BAD_PROJECT_DIR`,`WRITE_ERROR`]),message:string(),rule:string().optional()}),partiallyApplied:array(AppliedEntrySchema).optional()}),object$1({ok:literal(!0),path:string(),created:boolean(),warnings:array(string())}),object$1({ok:literal(!0),path:string(),existed:boolean(),cleanedEmpty:object$1({templatesDir:boolean(),okDir:boolean()})}),object$1({ok:literal(!1),error:object$1({code:string(),message:string()})})]),FolderConfigOutputSchema=outputSchemaWithText({result:union([SingleResultSchema,object$1({ok:boolean(),operations:array(object$1({action:_enum(ACTIONS$1),result:SingleResultSchema}))})])});function register$16(e,t){e.registerTool(`folder_config`,{description:DESCRIPTION$16,inputSchema:FolderConfigInputSchema,outputSchema:FolderConfigOutputSchema,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!0}},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let{cwd:g}=s;if(e.operations!==void 0)return handleBatch(e.operations,g);switch(e.action){case`set-rule`:return handleSetRule(e,g);case`write-template`:return handleWriteTemplate(e,g);case`delete-template`:return handleDeleteTemplate(e,g)}return{isError:!0,content:[{type:`text`,text:`Error: no action.`}]}})}function applyOperation(e,t){switch(e.action){case`set-rule`:return e.rules?applyNestedFolderRulesUpsert({projectDir:t,rules:e.rules.map(e=>({match:e.match,frontmatter:e.frontmatter??{},...e.new_match===void 0?{}:{new_match:e.new_match}}))}):{ok:!1,error:{code:`MISSING_FIELD`,message:"set-rule requires `rules`."}};case`write-template`:return e.folder===void 0||!e.name||e.body===void 0||!e.frontmatter?{ok:!1,error:{code:`MISSING_FIELD`,message:"write-template requires `folder`, `name`, `body`, and `frontmatter`."}}:applyTemplateWrite({projectDir:t,folder:e.folder,name:e.name,body:e.body,frontmatter:e.frontmatter});case`delete-template`:return e.folder===void 0||!e.name?{ok:!1,error:{code:`MISSING_FIELD`,message:"delete-template requires `folder` and `name`."}}:applyTemplateDelete({projectDir:t,folder:e.folder,name:e.name})}}function describeResult(e,t){return t.ok?`applied`in t?`${e}: ${t.applied.length} rule(s) applied`:`created`in t?`${e}: ${t.created?`created`:`updated`} ${t.path}`:`existed`in t?`${e}: ${t.existed?`deleted`:`no-op (missing)`} ${t.path}`:e:`${e}: ${t.error.code}: ${t.error.message}`}function handleBatch(e,t){let s=e.map(e=>({action:e.action,result:applyOperation(e,t)})),g=s.every(e=>e.result.ok),S={ok:g,operations:s},w=s.map(e=>describeResult(e.action,e.result)).join(`
2195
- `);return g?textPlusStructured(w,{result:S}):textPlusStructured(w,{result:S},!0)}function handleSetRule(e,t){let s=applyNestedFolderRulesUpsert({projectDir:t,rules:(e.rules??[]).map(e=>({match:e.match,frontmatter:e.frontmatter??{},...e.new_match===void 0?{}:{new_match:e.new_match}}))});return s.ok?textPlusStructured(JSON.stringify(s,null,2),{result:s}):textPlusStructured(`${s.error.code}: ${s.error.message}`,{result:s},!0)}function handleWriteTemplate(e,t){let s=applyTemplateWrite({projectDir:t,folder:e.folder??``,name:e.name??``,body:e.body??``,frontmatter:e.frontmatter??{title:``}});if(!s.ok)return textPlusStructured(`${s.error.code}: ${s.error.message}`,{result:s},!0);let g=[`${s.created?`Created`:`Updated`} template at ${s.path}`];if(s.warnings.length>0){g.push(``,`Warnings:`);for(let e of s.warnings)g.push(` - ${e}`)}return textPlusStructured(g.join(`
2196
- `),{result:s})}function handleDeleteTemplate(e,t){let s=applyTemplateDelete({projectDir:t,folder:e.folder??``,name:e.name??``});if(!s.ok)return textPlusStructured(`${s.error.code}: ${s.error.message}`,{result:s},!0);let g=[s.existed?`Deleted template at ${s.path}`:`Template at ${s.path} did not exist (no-op)`];return s.cleanedEmpty.templatesDir&&g.push(`Removed empty .ok/templates/ directory`),s.cleanedEmpty.okDir&&g.push(`Removed empty .ok/ directory`),textPlusStructured(g.join(`
2197
- `),{result:s})}const DESCRIPTION$15=[`[Operates on registry data; no running OK server required] Return the OK authoring palette so a generated document reads as one coherent, themed artifact.`,``,`Three sections:`,"- `components` — the **markdown-native forms** OK auto-promotes into themed canonical components at parse time. Write `> [!NOTE]` (not `<Callout>`), `<details>` (not `<Accordion>`), ` ```mermaid `, `$x$`. Each entry carries a copy-ready `example` + `guidance`.","- `embedPatterns` — copy-ready ` ```html preview ` starters (chart, stat cards, custom SVG, interactive control) already wired to the theme tokens, so an embed tracks light/dark with no hand-picked colors.","- `tokens` — the CSS custom properties injected into every preview iframe; reference them as `var(--chart-1)`, `var(--foreground)`, … inside an `html preview` embed.",``,"For the full JSX-form prop schema of a specific canonical, call `get_components({ ids })`.",``,`**Parameters:**`,"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
2198
- `),InputSchema$4={cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$8=outputSchemaWithText({version:literal(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:array(object$1({id:string(),displayName:string(),description:string(),authoring:_enum([`markdown`,`jsx`]).describe("`markdown` — write the markdown-native form OK auto-promotes; `jsx` — write the JSX tag directly (no markdown-native form exists)."),example:string().describe(`Copy-ready source for the authoring form.`),guidance:string().describe(`One line on when / how to use this construct.`)})).describe(`Canonical authoring constructs, keyed by the form an agent should write.`),embedPatterns:array(object$1({id:string(),title:string(),description:string(),snippet:string().describe("A complete, theme-wired ```html preview fenced block.")})).describe("Copy-ready themed `html preview` starters."),tokens:array(object$1({name:string().describe("CSS custom-property name, e.g. `--chart-1`."),light:string(),dark:string()})).describe("Theme tokens injected into every preview iframe — reference with `var(--name)`.")}),AUTHORING_FORMS=[{id:`Callout`,registryName:`Callout`,fallbackDisplayName:`Callout`,description:`Alert / admonition box in one of 15 themed type variants.`,authoring:`markdown`,example:`> [!NOTE]
2199
- > Body text. Swap NOTE for TIP, IMPORTANT, WARNING, CAUTION, …`,guidance:"Write the GFM alert form — OK auto-promotes it to a themed Callout. 15 types; append `+` / `-` (e.g. `> [!NOTE]+`) to make it foldable."},{id:`Accordion`,registryName:`Accordion`,fallbackDisplayName:`Accordion`,description:`Collapsible section with a clickable summary.`,authoring:`markdown`,example:`<details>
2200
- <summary>Section title</summary>
2201
-
2202
- Hidden body content.
2203
-
2204
- </details>`,guidance:"Write a plain `<details>` — OK auto-promotes it to a themed Accordion."},{id:`Mermaid`,fallbackDisplayName:`Mermaid diagram`,description:`Flowchart / sequence / class / state / ER / gantt / pie diagram.`,authoring:`markdown`,example:"```mermaid\ngraph LR\n A[Start] --> B[End]\n```",guidance:"Write a ` ```mermaid ` fenced block — it renders as a themed diagram."},{id:`Math`,registryName:`Math`,fallbackDisplayName:`Math`,description:`LaTeX math, rendered with KaTeX.`,authoring:`markdown`,example:`Inline: $E = mc^2$
2205
-
2206
- Block:
2207
-
2208
- $$
2209
- \\int_0^1 x^2 \\, dx
2210
- $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-promotes it to Math."},{id:`wiki-embed`,fallbackDisplayName:`Wiki embed`,description:`Inline another document or an asset by name.`,authoring:`markdown`,example:`![[document-name]]
2211
-
2212
- ![[diagram.png]]`,guidance:"Write a `![[file]]` wiki-embed to inline another doc or an uploaded asset."},{id:`Tabs`,registryName:`Tabs`,fallbackDisplayName:`Tabs`,description:`Tabbed panels — a pill strip with one panel visible at a time.`,authoring:`jsx`,example:`<Tabs>
2213
- <Tab label="First">First panel content.</Tab>
2214
- <Tab label="Second">Second panel content.</Tab>
2215
- </Tabs>`,guidance:`Tabs is the one canonical with no markdown-native form — write the JSX directly.`}];function buildComponents(){let e=new Map(getAgentCanonicalDescriptors().map(e=>[e.name,e]));return AUTHORING_FORMS.map(t=>{let s=t.registryName?e.get(t.registryName):void 0;return{id:t.id,displayName:s?.displayName??s?.name??t.fallbackDisplayName,description:t.description,authoring:t.authoring,example:t.example,guidance:t.guidance}})}function register$15(e,t){e.registerTool(`get_authoring_palette`,{description:DESCRIPTION$15,inputSchema:InputSchema$4,outputSchema:OutputSchema$8,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{e.cwd;let t={version:1,components:buildComponents(),embedPatterns:PREVIEW_EMBED_STARTERS.map(e=>({id:e.id,title:e.title,description:e.description,snippet:previewEmbedFence(e)})),tokens:PREVIEW_THEME_TOKENS.map(e=>({name:e.name,light:e.light,dark:e.dark}))};return textPlusStructured(JSON.stringify(t,null,2),t)})}const ID_CARDINALITY_CAP=32,DESCRIPTION$14=["[Operates on registry data; no running OK server required] Return full per-entry details for the canonical components an agent picked from the inventory rendered in the `write_document` / `edit_document` tool descriptions.",``,"Each entry carries: literal source-form `example` (copy-pasteable) + form-aware `params` (every prop, with `type` / `values?` / `required` / `defaultValue?` / `description`). Unmatched ids surface in `notFound` rather than failing the call.",``,`**Parameters:**`,`- \`ids\` — Array of canonical ids picked from the write-tool inventory (e.g. \`["Callout", "Tabs"]\`). Max ${ID_CARDINALITY_CAP} ids per call. Case-sensitive — must match the inventory exactly (\`Callout\` not \`callout\`; \`img\` not \`Image\`).`,"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
2216
- `),InputSchema$3={ids:array(string().min(1)).max(ID_CARDINALITY_CAP).describe(`Array of canonical ids to fetch. Max ${ID_CARDINALITY_CAP} ids per call. Empty array returns an empty components list.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},ParamSchema=object$1({name:string(),type:_enum([`string`,`boolean`,`number`,`enum`,`reactnode`]),values:array(string()).optional(),required:boolean(),defaultValue:union([string(),boolean(),number()]).optional(),description:string().optional(),omitOnDefault:literal(!0).optional(),advanced:literal(!0).optional(),language:_enum([`mermaid`,`latex`,`html`,`json`,`yaml`,`javascript`,`markdown`]).optional(),accept:array(string()).optional()}),ComponentEntrySchema=object$1({id:string(),displayName:string(),description:string(),kind:_enum([`jsx-block`,`jsx-void`]),example:string(),params:array(ParamSchema)}),OutputSchema$7=outputSchemaWithText({version:literal(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:array(ComponentEntrySchema).describe(`Full per-entry details for ids that matched.`),notFound:array(string()).describe(`Ids that did not match any canonical descriptor.`)});function register$14(e,t){e.registerTool(`get_components`,{description:DESCRIPTION$14,inputSchema:InputSchema$3,outputSchema:OutputSchema$7,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{e.cwd;let t=getAgentCanonicalDescriptors(),s=new Map(t.map(e=>[e.name,e])),g=[],S=[],w=new Set;for(let t of e.ids){if(w.has(t))continue;w.add(t);let e=s.get(t);if(e===void 0){S.push(t);continue}g.push(projectFull(e))}let E={version:1,components:g,notFound:S};return textPlusStructured(JSON.stringify(E,null,2),E)})}const DESCRIPTION$13=[`[Operates on disk; no running OK server required] Read the effective merged Open Knowledge config (defaults → user → project).`,``,`Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.`,``,"Read returns the FULL merged config or a sub-tree when `path` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, `github.*`, and `preview.*` config sub-trees were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or hardcoded behavior, in the case of `preview.*`). Reading those paths returns `exists: false`.",``,`**Parameters:**`,'- `path` (optional) — Dotted-segments array. `["content"]` returns the content sub-tree; `["appearance", "theme"]` returns just that leaf. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
2217
- `),InputSchema$2={path:array(string()).optional().describe(`Dotted path as array of segments (e.g. ["appearance","theme"]). Omit to return the full merged config.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$6=outputSchemaWithText({value:unknown().describe(`Resolved config value at the requested path (or full config).`),exists:boolean().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null"; absent on full-config reads.'),path:array(string()).optional().describe(`Echo of the requested dotted path (empty when reading the full config).`)});function readConfigPath(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s)return;s=s[e]}return s}function register$13(e,t){e.registerTool(`get_config`,{description:DESCRIPTION$13,inputSchema:InputSchema$2,outputSchema:OutputSchema$6,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=e.path??[],S=g.length>0?readConfigPath(s.config,g):s.config;return g.length>0&&S===void 0?textPlusStructured(`(no value at ${g.join(`.`)})`,{value:null,exists:!1,path:g}):textPlusStructured(JSON.stringify(S,null,2),{value:S,exists:!0,path:g})})}const DESCRIPTION$12=[`[Requires: Hocuspocus server] Fetch the three merge stages (base / ours / theirs) for a doc currently in a merge-conflict state, plus the doc's lifecycle status and the conflict shape discriminator.`,`Returns 404 if no conflict is tracked for the path.`,"The `ours` field is sourced from the live Y.Text (showing any pre-conflict unflushed user edits) when the doc is loaded server-side; falls back to `git show :2:<file>` otherwise.","The `kind` field discriminates conflict shape: `both-modified` (both sides edited the file), `delete-modify` (DU — you deleted, they edited; stage 2 absent, `ours` empty), or `modify-delete` (UD — you edited, they deleted; stage 3 absent, `theirs` empty). Use it to pick the right `resolve_conflict` strategy: both-modified accepts `mine`/`theirs`/`content`; delete-modify accepts `delete` (keep deletion) or `theirs` (restore); modify-delete accepts `mine` (keep your version) or `delete` (accept their deletion).",``,`**Parameters:**`,"- `file` — Relative-to-projectDir path WITH the `.md` extension (e.g. `notes/sso.md`). Mirrors the server-side wire contract."].join(`
2218
- `),OutputSchema$5=outputSchemaWithText({file:string(),base:string(),ours:string(),theirs:string(),kind:_enum([`both-modified`,`delete-modify`,`modify-delete`]),lifecycleStatus:string().nullable()});function register$12(e,t){e.registerTool(`get_conflict_content`,{description:DESCRIPTION$12,inputSchema:{file:string().min(1).describe("Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`). Server-side contract — do NOT strip the extension."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema$5,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=await httpGet(g,`/api/sync/conflict-content${`?file=${encodeURIComponent(e.file)}&source=ytext`}`);if(!S.ok){let e=S.error,t=typeof S.detail==`string`?S.detail:void 0;return textResult(`Error: ${t?`${e} — ${t}`:e}`,!0)}let w=S,E=typeof w.file==`string`?w.file:e.file,D=typeof w.base==`string`?w.base:``,O=typeof w.ours==`string`?w.ours:``,k=typeof w.theirs==`string`?w.theirs:``,j=w.kind===`delete-modify`||w.kind===`modify-delete`?w.kind:`both-modified`,F=typeof w.lifecycleStatus==`string`?w.lifecycleStatus:null,L={file:E,base:D,ours:O,theirs:k,kind:j,lifecycleStatus:F};return textPlusStructured(`Conflict stages for ${E} (kind: ${j})${F?` (lifecycle: ${F})`:``}:\n--- base ---\n${D}\n--- ours ---\n${O}\n--- theirs ---\n${k}`,L)})}const DESCRIPTION$11=[`[Requires: Hocuspocus server] List version history for a document.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,'Each entry includes a commit SHA that can be passed to `version({ action: "rollback" })`.',``,`**Parameters:**`,"- `docName` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `type` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
2219
- `);function register$11(e,t){e.registerTool(`get_history`,{description:DESCRIPTION$11,inputSchema:{docName:string().describe(`Document name to query history for`),branch:string().optional().describe(`Branch name (default: current branch)`),limit:number().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:number().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),type:_enum([`checkpoint`,`upstream`,`wip`]).optional().describe(`Filter by entry type`),author:string().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:string().optional().describe(`Exclude entries by this author name or email`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=normalizeDocName(e.docName);if(!w.ok)return textResult(w.error,!0);let E=new URLSearchParams;E.set(`docName`,w.docName),e.branch&&E.set(`branch`,e.branch),e.limit!=null&&E.set(`limit`,String(e.limit)),e.offset!=null&&E.set(`offset`,String(e.offset)),e.type&&E.set(`type`,e.type),e.author&&E.set(`author`,e.author),e.excludeAuthor&&E.set(`excludeAuthor`,e.excludeAuthor);let D=await httpGet(S,`/api/history?${E.toString()}`);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let{ok:O,...k}=D,j=await resolvePreviewUrlForTool(w.docName,{config:t.config,resolveCwd:t.resolveCwd},g);return textPlusStructured(JSON.stringify(k,null,2),{...k,previewUrl:j?.url??null,...j?{previewUrlSource:j.source}:{}})})}const DESCRIPTION$10=[`[Operates on disk; no running OK server required] Resolve the browser-reachable preview URL for an Open Knowledge project (optionally for a specific doc).`,``,"Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.",``,'Use this when YOUR host opens the URL itself: navigate your in-app browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Hosts with a preview pane (Claude Code Desktop) call `preview_start("open-knowledge-ui")` instead; the Claude Code CLI uses `ok open <doc>` to open in the OK Desktop app.',``,"Returns `{ url, baseUrl, running: false }` and a recovery hint when no UI is running for the project (start one with `ok ui`).",``,`**Parameters:**`,"- `docName` (optional) — Extension-less doc path (e.g. `specs/foo/SPEC`). Omit for the UI root URL.","- `folder` (optional) — Folder path (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `docName`.","- `armPaneTarget` (optional) — When true with a `docName`/`folder`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. This is the tool’s ONLY side effect; omit it and the call is read-only.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
2220
- `),InputSchema$1={docName:string().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),folder:string().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `docName`.'),armPaneTarget:boolean().optional().describe("When true with a `docName` or `folder`, arm that target so a subsequent Claude-pane base-open (`preview_start`) lands there instead of the presence-driven default. TTL-bounded (~30s) so a stale arm cannot hijack a later open."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$4=outputSchemaWithText({url:string().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `docName` is given, else the UI root. `null` when no UI is running."),baseUrl:string().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:boolean().describe(`Whether a UI is running for the project.`),autoOpen:boolean().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`.")}),NO_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code), or open the project in OK Electron.';function register$10(e,t){e.registerTool(`get_preview_url`,{description:DESCRIPTION$10,inputSchema:InputSchema$1,outputSchema:OutputSchema$4,annotations:{readOnlyHint:!1,idempotentHint:!0}},async e=>{if(e.docName&&e.folder)return{isError:!0,content:[{type:`text`,text:`Error: docName and folder are mutually exclusive — pass exactly one.`}]};let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=resolveLockDir(s.cwd),{baseUrl:S}=resolveUiInfo({lockDir:g}),w=s.config.appearance.preview.autoOpen,E=e.docName?`#/${encodeDocName(e.docName)}`:e.folder?`#/${encodeFolderRoute(e.folder)}`:null;if(e.armPaneTarget&&E)try{armPaneTarget(g,E)}catch{}let D=e.armPaneTarget&&!E?` (note: armPaneTarget was set but no docName/folder was given, so nothing was armed)`:``;if(S===null)return textPlusStructured(`${NO_UI_MESSAGE}${D}`,{url:null,baseUrl:null,running:!1,autoOpen:w});let O=E?`${S}/${E}`:S;return textPlusStructured(`Preview URL: ${O}${D}`,{url:O,baseUrl:S,running:!0,autoOpen:w})})}function buildBody$1(e,t){return`Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
2222
+ `}function buildIngestBody(e,t){return`Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim agent-initiated fetches are not exempt. **Raw preservation only** no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
2221
2223
 
2222
2224
  **Bias toward binary preservation.** When the source is a binary file (PDF, image, audio, video, Office doc, archive, dataset), preserve the raw bytes — do NOT settle for a text scrape. OK already ships a complete asset-embed surface (\`![[file.ext]]\` wiki-embed, file-watcher pickup, sha256 dedup, blocked-extension enforcement); this tool's job is to bridge \`ingest\` to it via your shell tool.
2223
2225
 
@@ -2359,7 +2361,7 @@ tags:
2359
2361
 
2360
2362
  The body is just the wiki-embed reference. For images, video, and audio, the embed renders inline. **For PDFs and other opaque file-attachment types (docx, xlsx, zip, etc.), the \`![[file.ext]]\` form renders as a Notion-style File row that click-dispatches to the appropriate viewer** — the pdfjs canvas viewer is opt-in via the explicit \`<Pdf src="./<slug>.pdf" />\` JSX form, NOT the wiki-embed default. If the user wants the inline canvas viewer for this specific PDF, they can post-edit the wrapper body to replace \`![[<slug>.pdf]]\` with \`<Pdf src="./<slug>.pdf" />\`.
2361
2363
 
2362
- Write via \`write_document\` (NOT native \`Write\` — the CRDT path is mandatory for in-scope markdown).
2364
+ Write via \`write\` (NOT native \`Write\` — the CRDT path is mandatory for in-scope markdown).
2363
2365
 
2364
2366
  ## Step 2b: Save the text wrapper (only after Step 1c — text path or shell-less fallback)
2365
2367
 
@@ -2442,7 +2444,7 @@ After preservation, briefly surface back to the user what the source actually co
2442
2444
 
2443
2445
  If the source is directly relevant to an existing article or research doc, update that doc to link the new raw source. A preserved source that no doc points at is an island. Limit this to 1–3 high-signal neighbors — don't touch everything tangentially related.
2444
2446
 
2445
- - Follow the \`write_document\` / \`edit_document\` contract from the skill (preview-before-edit).
2447
+ - Follow the \`write\` / \`edit\` contract from the skill (preview-before-edit).
2446
2448
  - For binary wrappers, prefer linking to the wrapper (the markdown doc), not the binary directly: \`[Source title](./external-sources/<slug>.md)\`. The wrapper is the closed-loop citation target; the binary is the embedded asset within it.
2447
2449
  - Do NOT mass-update every neighbor. Karpathy's pattern rewards focused cross-linking; noisy neighbor-pings degrade the signal.
2448
2450
 
@@ -2455,14 +2457,7 @@ If the source is directly relevant to an existing article or research doc, updat
2455
2457
  - **No OCR / transcription** — binary preservation only. \`research\` may apply analysis layers downstream.
2456
2458
  - **No streaming-video direct download** — \`yt-dlp\` is a separate workflow; \`ingest\` STOPs and routes to it (Step 1a STOP gate 1).
2457
2459
  - **No executable / scripted-document auto-fetch** — hard-blocked at Step 1b STOP gate 1 (write-path only). User runs \`curl\` manually outside the agent if they need to archive such a file.
2458
- `}const DESCRIPTION$9=[`Returns a step-by-step plan to capture an external source (URL or local file) into the knowledge base as raw, verbatim reference material — no analysis. Does NOT fetch or write — you execute the plan.`,"Biases toward preserving raw binary files (PDF, image, audio, video) via the shell + `![[file.ext]]` embed, falling back to text extraction on shell-less hosts. The KB is closed-loop: cite the captured local doc, never a bare URL.",`Use when a source needs preserving before analysis — including URLs you fetched yourself to ground a KB claim.`].join(`
2459
- `);function register$9(e,t){e.registerTool(`ingest`,{description:DESCRIPTION$9,inputSchema:{source:string().describe(`URL, file path, or identifier of the source to ingest`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},buildWorkflowHandler(`ingest`,t,`source`,buildBody$1))}const LINK_KINDS=[`backlinks`,`forward`,`dead`,`orphans`,`hubs`,`suggest`],DESCRIPTION$8=["[Requires: Hocuspocus server] Read the wiki-link graph. `kind` takes one value, or an array for a one-call audit — results merge into a single payload; any per-kind failure lands in an `errors` map.",``,"- `backlinks` / `forward` / `suggest` — operate on one page; require `docName`. `suggest` finds prose mentions of the page not yet wrapped in link syntax (each mention `offset` works with `edit_document`).","- `dead` — missing internal link targets corpus-wide; optional `sourceDocNames` filter (OR semantics).","- `orphans` — disconnected pages; optional `mode`: `incoming` | `outgoing` | `both`.","- `hubs` — most-linked pages; optional `limit` (default 20)."].join(`
2460
- `);function register$8(e,t){e.registerTool(`links`,{description:DESCRIPTION$8,inputSchema:{kind:union([_enum(LINK_KINDS),array(_enum(LINK_KINDS)).min(1)]).describe(`Link-graph view(s) to return — one kind, or an array to fetch several in one call (e.g. ["dead","orphans","hubs"] for a graph audit).`),docName:string().optional().describe(`Target page docName. Required for kind=backlinks|forward|suggest.`),sourceDocNames:array(string()).optional().describe(`Referring source docs to narrow the audit with OR semantics. Used by kind=dead.`),mode:_enum(ORPHAN_MODES).optional().describe(`Filter which type of graph disconnection to surface. Used by kind=orphans.`),limit:number().int().positive().optional().describe(`Maximum number of hubs to return. Used by kind=hubs.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=Array.isArray(e.kind)?[...new Set(e.kind)]:[e.kind],{resolve:E}=await buildListResolver(t,g),D=await Promise.all(w.map(s=>runKind(s,e,S,g,t,E))),O={},k={};if(w.forEach((e,t)=>{let s=D[t];s.ok?Object.assign(O,s.data):k[e]=s.error}),Object.keys(O).length===0){let e=w.length===1?k[w[0]]:`All requested link kinds failed: ${JSON.stringify(k)}`;return textResult(e.startsWith(`Error`)?e:`Error: ${e}`,!0)}let j={...O,...Object.keys(k).length>0?{errors:k}:{},cwd:g};return textPlusStructured(JSON.stringify(j,null,2),j)})}function runKind(e,t,s,g,S,w){switch(e){case`backlinks`:return runBacklinks(t,s,w);case`forward`:return runForwardLinks(t,s,w);case`dead`:return runDeadLinks(t,s,w);case`orphans`:return runOrphans(t,s,w);case`hubs`:return runHubs(t,s,w);case`suggest`:return runSuggest(t,s,g,S)}}async function runBacklinks(e,t,s){if(!e.docName)return{ok:!1,error:"kind=backlinks requires `docName`."};let g=normalizeDocName(e.docName);if(!g.ok)return{ok:!1,error:g.error};let S=await httpGet(t,`/api/backlinks?docName=${encodeURIComponent(g.docName)}`);if(!S.ok)return{ok:!1,error:String(S.error)};let{ok:w,...E}=S;return{ok:!0,data:{backlinks:(E.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runForwardLinks(e,t,s){if(!e.docName)return{ok:!1,error:"kind=forward requires `docName`."};let g=normalizeDocName(e.docName);if(!g.ok)return{ok:!1,error:g.error};let S=await httpGet(t,`/api/forward-links?docName=${encodeURIComponent(g.docName)}`);if(!S.ok)return{ok:!1,error:String(S.error)};let{ok:w,...E}=S;return{ok:!0,data:{forwardLinks:(E.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runDeadLinks(e,t,s){let g=new URLSearchParams;for(let t of e.sourceDocNames??[]){let e=normalizeDocName(t);if(!e.ok)return{ok:!1,error:e.error};g.append(`sourceDocName`,e.docName)}let S=g.toString(),w=await httpGet(t,`/api/dead-links${S?`?${S}`:``}`);if(!w.ok)return{ok:!1,error:String(w.error)};let{ok:E,...D}=w;return{ok:!0,data:{deadLinks:(D.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,g=t?s(t):null,S=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}});return{...e,sources:S,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runOrphans(e,t,s){let g=await httpGet(t,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!g.ok)return{ok:!1,error:String(g.error)};let{ok:S,...w}=g;return{ok:!0,data:{orphans:(w.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runHubs(e,t,s){let g=await httpGet(t,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!g.ok)return{ok:!1,error:String(g.error)};let{ok:S,...w}=g;return{ok:!0,data:{hubs:(w.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runSuggest(e,t,s,g){if(!e.docName)return{ok:!1,error:"kind=suggest requires `docName`."};let S=normalizeDocName(e.docName);if(!S.ok)return{ok:!1,error:S.error};let w=await httpGet(t,`/api/suggest-links?docName=${encodeURIComponent(S.docName)}`);if(!w.ok)return{ok:!1,error:String(w.error)};let{ok:E,...D}=w,O=await resolvePreviewUrlForTool(S.docName,{config:g.config,resolveCwd:g.resolveCwd},s);return{ok:!0,data:{suggest:{...D,previewUrl:O?.url??null,...O?{previewUrlSource:O.source}:{}}}}}const DESCRIPTION$7=[`[Requires: Hocuspocus server] Enumerate every document currently tracked as in a merge-conflict state.`,"Returns one entry per file (relative-path, detection timestamp, optional git SHAs). When no conflicts are tracked, returns `conflicts: []`.",``,"Use as the entry point to the conflict-resolution flow: `list_conflicts` to discover, `get_conflict_content` to inspect stages, `resolve_conflict` to write a chosen version."].join(`
2461
- `),OutputSchema$3=outputSchemaWithText({conflicts:array(ConflictEntrySchema)});function register$7(e,t){e.registerTool(`list_conflicts`,{description:DESCRIPTION$7,inputSchema:{cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema$3,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=await httpGet(g,`/api/sync/conflicts`);if(!S.ok){let e=S.error;return textPlusStructured(`Error: ${e}`,{conflicts:[]},!0)}let w=S.conflicts,E=Array.isArray(w)?w:[];return textPlusStructured(E.length===0?`No conflicts tracked.`:`Tracked conflicts (${E.length}):\n${E.map(e=>`- ${e&&typeof e==`object`&&`file`in e?String(e.file??``):``}`).join(`
2462
- `)}`,{conflicts:E})})}const DESCRIPTION$6=["[Requires: Hocuspocus server] Rename a doc or a folder through the managed rename flow at `POST /api/rename-path`. The tool probes the content directory to decide whether `from` is a doc or a folder, then sets `kind` (`file` vs `folder`) accordingly. Renaming rewrites inbound wiki-links plus supported internal inline Markdown links across affected docs.",``,`**Parameters:**`,"- `from` — Source path. For a doc, the docName (typically without extension; trailing `.md`/`.mdx` is stripped). For a folder, the folder path relative to the content directory with no leading/trailing slash (e.g. `notes/drafts`).","- `to` — Destination path. Same shape as `from`. For a folder rename, parent directories are auto-created.",'- `summary` — Optional one-line user-outcome description (≤80 chars). If omitted, defaults to "Renamed X → Y". Appears as a bullet in the timeline. Avoid secrets or PII — summaries persist to git history.',``,`**Output:**`,"- Doc rename — `{previewUrl, previousPreviewUrl?, renamed, rewrittenDocs, ...}`.","- Folder rename — `{previewUrls: Record<newDocName, url>, renamed, rewrittenDocs, ...}`.",``,`**Errors:**`,"- 400 — destination excluded by `.gitignore` / `.okignore`; invalid path shape.",`- 404 — source doc or folder does not exist.`,"- 409 — destination already exists; server returns a structured `colliding[]` list in this case."].join(`
2463
- `);function parseRenameMappings(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromDocName:t,toDocName:s}]:[]}):[]}function parseRewrittenDocs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:s}=e;return typeof t==`string`&&typeof s==`number`?[{docName:t,rewrites:s}]:[]}):[]}function isValidFolderPath(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`..`))}function pluralize(e,t,s=`${t}s`){return e===1?t:s}function resolveRenameKind(e,t){let s=resolveWithinRoot(e,t);if(!s.ok)return null;let g=s.abs;if(existsSync(g))try{let e=statSync(g);if(e.isDirectory())return`folder`;if(e.isFile()&&(g.endsWith(`.md`)||g.endsWith(`.mdx`)))return`file`}catch(e){let t=e.code;if(t===`EACCES`||t===`EPERM`)return`file`}for(let e of[`.md`,`.mdx`])if(existsSync(`${g}${e}`))return`file`;return null}function register$6(e,t){e.registerTool(`rename`,{description:DESCRIPTION$6,inputSchema:{from:string().describe(`Current path. Doc: docName (typically extensionless). Folder: relative path with no leading/trailing slash.`),to:string().describe(`New path. Doc: docName (typically extensionless). Folder: relative path with no leading/trailing slash.`),summary:summaryArgSchema.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Renamed X → Y" when omitted. Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveRenameKind(join(g,S.content.dir),e.from);return E===null?textResult(`Error: \`${e.from}\` does not exist as a doc or folder under the content directory.`,!0):E===`file`?handleFileRename(e,w,g,t):handleFolderRename(e,w,g,t)})}async function handleFileRename(e,t,s,g){let S=normalizeDocName(e.from);if(!S.ok)return textResult(S.error,!0);let w=normalizeDocName(e.to);if(!w.ok)return textResult(w.error,!0);let E=g.identityRef?.current,D=await httpPost(t,`/api/rename-path`,{kind:`file`,fromPath:S.docName,toPath:w.docName,...e.summary===void 0?{}:{summary:e.summary},...E?{agentId:E.connectionId,agentName:E.displayName,clientName:E.clientInfo?.name,colorSeed:E.colorSeed}:{}});if(!D.ok){let e=D.error,t=parseRenameCollidingPairs(D.colliding),s={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return textPlusStructured(`Error: ${e}`,s,!0)}let O=parseRenameMappings(D.renamed),k=parseRewrittenDocs(D.rewrittenDocs),j=O.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${S.docName} -> ${w.docName}`,F=k.length===0?`No inbound links required updates.`:`Rewrote ${k.length} ${pluralize(k.length,`document`)}.`,L={config:g.config,resolveCwd:g.resolveCwd},B=await resolvePreviewUrlForTool(w.docName,L,s),H=await resolvePreviewUrlForTool(S.docName,L,s),q=D.summary&&typeof D.summary==`object`?D.summary:void 0,J=typeof q?.hint==`string`?q.hint:void 0,Y={ok:!0,kind:`file`,renamed:O,rewrittenDocs:k,previewUrl:B?.url??null,...B?{previewUrlSource:B.source}:{},...H?{previousPreviewUrl:H.url}:{},...q?{summary:q}:{}},ee=[`Renamed ${j}. ${F}`];return J&&ee.push(J),textPlusStructured(ee.join(`
2464
- `),Y)}async function handleFolderRename(e,t,s,g){if(!isValidFolderPath(e.from))return textResult("Error: `from` must be a relative path with no leading/trailing slash.",!0);if(!isValidFolderPath(e.to))return textResult("Error: `to` must be a relative path with no leading/trailing slash.",!0);let S=g.identityRef?.current,w=await httpPost(t,`/api/rename-path`,{kind:`folder`,fromPath:e.from,toPath:e.to,...e.summary===void 0?{}:{summary:e.summary},...S?{agentId:S.connectionId,agentName:S.displayName,clientName:S.clientInfo?.name,colorSeed:S.colorSeed}:{}});if(!w.ok){let e=w.error,t=parseRenameCollidingPairs(w.colliding),s={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return textPlusStructured(`Error: ${e}`,s,!0)}let E=parseRenameMappings(w.renamed),D=parseRewrittenDocs(w.rewrittenDocs),O={config:g.config,resolveCwd:g.resolveCwd},k={},j;for(let{toDocName:e}of E){let t=await resolvePreviewUrlForTool(e,O,s);t&&(k[e]=t.url,j??=t.source)}let F=w.summary&&typeof w.summary==`object`?w.summary:void 0,L=typeof F?.hint==`string`?F.hint:void 0,B={ok:!0,kind:`folder`,renamed:E,rewrittenDocs:D,previewUrls:k,...j?{previewUrlSource:j}:{},...F?{summary:F}:{}},H=[];return E.length===0?H.push(`No managed docs under ${e.from}/ — nothing to rename. Empty folders are not tracked; create a doc inside the folder first.`):H.push(`Renamed folder ${e.from}/ → ${e.to}/ (${E.length} doc${E.length===1?``:`s`}, ${D.length} rewrite${D.length===1?``:`s`}).`),L&&H.push(L),textPlusStructured(H.join(`
2465
- `),B)}function buildBody(e,t){return`Conduct **evidence-driven research** on this topic and produce a provisional research article in the Open Knowledge content directory. This workflow mirrors the discipline of the \`eng:research\` skill, scoped to Open Knowledge's wiki-provisional layer.
2460
+ `}function buildResearchBody(e,t){return`Conduct **evidence-driven research** on this topic and produce a provisional research article in the Open Knowledge content directory. This workflow mirrors the discipline of the \`eng:research\` skill, scoped to Open Knowledge's wiki-provisional layer.
2466
2461
 
2467
2462
  Topic: ${e}
2468
2463
  Content directory: \`${t}\` (from \`.ok/config.yml\`)
@@ -2812,17 +2807,13 @@ In headless mode, write the recap into the research article's "Further reading"
2812
2807
  - **Don't skip the scoping gate in Supervised mode.** The user's rubric shapes everything downstream; you cannot recover a wrong-scope article cheaply.
2813
2808
  - **Don't mix 1P codebase analysis into the article unless asked.** Findings drift from factual synthesis to opinion when you do.
2814
2809
  - **Don't overwrite existing research silently.** If the topic was researched before, either iterate (Path C) or create a clearly-named successor (\`crdt-alternatives-2.md\`) and mark the old one as superseded.
2815
- `}const DESCRIPTION$5=["Returns a step-by-step plan to research a topic: scan existing coverage, scope a rubric, capture sources via `ingest`, then write a provisional research article. Does NOT fetch or write you execute the plan.","Provisional, not canonical — findings live here until decisions solidify (`consolidate` promotes them).",`Use when exploring a decision space, comparing alternatives, or synthesizing sources into structured analysis.`].join(`
2816
- `);function register$5(e,t){e.registerTool(`research`,{description:DESCRIPTION$5,inputSchema:{topic:string().describe(`The topic, question, or anchor URL to research`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},buildWorkflowHandler(`research`,t,`topic`,buildBody))}const DESCRIPTION$4=[`[Requires: Hocuspocus server] Resolve a tracked merge conflict by writing the chosen content to disk and committing.`,``,`Strategy:`,"- `mine` writes `git show :2:<file>` (your committed ours stage). Fails on delete-modify (DU) conflicts where stage 2 is missinguse `delete` instead.","- `theirs` writes `git show :3:<file>` (their committed stage). Fails on modify-delete (UD) conflicts where stage 3 is missing use `delete` instead.",'- `content` — writes the provided `content` argument (e.g. a per-hunk merged result, or the live Y.Text bytes the user sees in the DiffView). The provided string must be non-empty use `delete` to remove the file entirely (an agent constructing a per-hunk merge that happens to land on `""` gets a 400 at the Zod boundary rather than a misleading 500).','- `delete` runs `git rm <file>` then commits the deletion. Honors deletion intent for delete-modify (DU: "keep deletion") and modify-delete (UD: "accept their deletion") shapes. Inspect the `kind` field on `get_conflict_content` to pick the right strategy for the conflict shape.',``,"Returns 200 on success; 500 indicates commit failure (re-call `list_conflicts` to confirm post-state the resolve API is best-effort, non-atomic, and the file may have been resolved by another session).",``,`**DESTRUCTIVE:** this modifies the working tree and creates a git commit.`,``,`**Parameters:**`,"- `file` — Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`).","- `strategy` One of `mine` | `theirs` | `content` | `delete`.",'- `content` Required (non-empty) when `strategy === "content"`; ignored otherwise.'].join(`
2817
- `),OutputSchema$2=outputSchemaWithText({ok:boolean(),file:string()});function register$4(e,t){e.registerTool(`resolve_conflict`,{description:DESCRIPTION$4,inputSchema:{file:string().min(1).describe("Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`)."),strategy:_enum([`mine`,`theirs`,`content`,`delete`]).describe("Resolution strategy. `content` requires the `content` arg. `delete` runs `git rm` use for delete-vs-modify (DU/UD) shapes where one stage is missing."),content:string().optional().describe('Exact bytes to write. Required when `strategy === "content"`; ignored otherwise.'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema$2,annotations:{readOnlyHint:!1,idempotentHint:!1,destructiveHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S={file:e.file,strategy:e.strategy};e.content!==void 0&&(S.content=e.content);let w=await httpPost(g,`/api/sync/resolve-conflict`,S);if(!w.ok){let t=w.error,s=typeof w.detail==`string`?w.detail:void 0;return textPlusStructured(`Error: ${s?`${t} — ${s}`:t}`,{ok:!1,file:e.file},!0)}return textPlusStructured(`Resolved conflict on ${e.file} (strategy: ${e.strategy}).`,{ok:!0,file:e.file})})}const DESCRIPTION$3=["[Requires: Hocuspocus server] Ranked page retrieval for a query (title boost + body BM25 + recency — the cmd-K engine). For literal search across every line, use `exec` (`grep`) instead.",``,"Returns scored page (and folder, with `omnibar` intent) hits, each with a body snippet. `exec`-grep covers every occurrence and needs no server.",``,`**Parameters:**`,"- `query` Free-form; tokenized across title, name, path segments, and (with `full_text`) body.","- `intent` (optional) `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.","- `scopes` (optional) Result scope: `page` | `folder` | `content`. Defaults derive from `intent`.","- `limit` (optional) Max rows; default 20, max 100.",``,'If the server is down, the tool returns a recovery hint — use `exec("grep ...")` as the server-free fallback.'].join(`
2818
- `),InputSchema={query:string().describe(`Search query — title, path, or body terms.`),intent:_enum([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),scopes:array(_enum([`page`,`folder`,`content`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'content'. Defaults derive from intent.`),limit:number().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},SearchResultRowSchema=object$1({kind:_enum([`page`,`folder`]),path:string(),docName:string(),title:string().nullable(),score:number(),signals:object$1({lexical:number(),fullText:number(),recency:number()}),snippet:string().optional(),previewUrl:string().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),OutputSchema$1=outputSchemaWithText({cwd:string(),query:string(),intent:string(),resultCount:number().int(),results:array(SearchResultRowSchema),elapsedMs:number().nullable()});function isSearchKind(e){return e===`page`||e===`folder`}function normalizeSignals(e){return{lexical:typeof e?.lexical==`number`?e.lexical:0,fullText:typeof e?.fullText==`number`?e.fullText:0,recency:typeof e?.recency==`number`?e.recency:0}}function formatResultsBlock(e){if(e.length===0)return``;let t=[];for(let s of e){let e=s.title?.trim()||s.path;t.push(`### ${e} (${s.path})`),t.push(`Score ${s.score.toFixed(2)} kind: ${s.kind}`),s.snippet&&t.push(s.snippet),t.push(``)}return t.join(`
2819
- `)}function register$3(e,t){e.registerTool(`search`,{description:DESCRIPTION$3,inputSchema:InputSchema,outputSchema:OutputSchema$1,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(`${HOCUSPOCUS_NOT_RUNNING_ERROR}\nFor server-free literal-string search, use \`exec("grep ...")\` instead — it walks the filesystem and does not need Hocuspocus.`,!0);let E=e.intent??`full_text`,D=e.limit??20,O={query:e.query,intent:E,limit:D};e.scopes&&(O.scopes=e.scopes);let k=await httpPost(w,`/api/search`,O);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let{resolve:j}=await buildListResolver({config:S,resolveCwd:async()=>g},g),F=(k.results??[]).flatMap(e=>{if(!isSearchKind(e.kind)||typeof e.path!=`string`)return[];let t=docNameFromPath(e.path),s=j(t);return[{kind:e.kind,path:e.path,docName:t,title:e.title??null,score:typeof e.score==`number`?e.score:0,signals:normalizeSignals(e.signals),...e.snippet?{snippet:e.snippet}:{},previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}]}),L={cwd:g,query:e.query,intent:E,resultCount:F.length,results:F,elapsedMs:typeof k.elapsedMs==`number`?k.elapsedMs:null},B=`## Search results for "${e.query}" (${F.length} hit${F.length===1?``:`s`}, intent: ${E})`;return textPlusStructured(F.length===0?`No matches for "${e.query}".`:`${B}\n\n${formatResultsBlock(F)}`,L)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const DESCRIPTION$2=["[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",``,`Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own Open Knowledge install.`,``,"**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.",``,`**Parameters:**`,'- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.","- `cwd` (optional) — Project root (see `cwd` description below).",``,"**Preconditions:** project on a named branch (not detached HEAD); origin set to a `github.com` remote; the branch already pushed to origin."].join(`
2820
- `);function messageForShareError(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is not a `github.com` remote. Share links are GitHub-only in v1.";case`invalid-path`:return"The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.";default:return`Unknown share-construct-url error: ${String(e)}`}}function isExistingDirectory(e){try{return statSync(e).isDirectory()}catch{return!1}}function resolveExistingDocPath(e,t){for(let s of[`.mdx`,`.md`]){let g=`${t}${s}`;if(existsSync(g)){let t=resolveWithinRoot(e,g);return t.ok?t.rel:null}}return null}function resolveShareTarget(e,t,s,g){if(s===``)return g===`folder`?{ok:!0,kind:`folder`,sharePath:``}:{ok:!1,code:`invalid-path`};let S=resolveWithinRoot(t,s);if(!S.ok)return{ok:!1,code:`target-not-found`};let w=resolveExistingDocPath(e,S.abs.replace(/\.(mdx|md)$/i,``)),E=isExistingDirectory(S.abs);if(g===`doc`)return w===null?E?{ok:!1,code:`kind-mismatch`}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:w};if(g===`folder`){if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return w===null?{ok:!1,code:`target-not-found`}:{ok:!1,code:`kind-mismatch`}}if(w!==null)return{ok:!0,kind:`doc`,sharePath:w};if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return{ok:!1,code:`target-not-found`}}const OutputSchema=outputSchemaWithText({ok:boolean().describe(`Success discriminator.`),shareUrl:string().optional().describe(`Marketing share URL (success only).`),sharedUrl:string().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:string().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:_enum([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),error:_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:string().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:string().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:string().optional().describe(`Internal: preview-URL provenance.`)});function register$2(e,t){e.registerTool(`share_link`,{description:DESCRIPTION$2,inputSchema:{path:string().describe('Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).'),kind:_enum([`doc`,`folder`]).optional().describe("Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveShareTarget(g,join(g,S.content.dir),e.path,e.kind);if(!E.ok){let t;if(E.code===`kind-mismatch`){let s=e.kind===`folder`?`folder`:`doc`;t=`\`${e.path}\` exists, but not as a ${s}. Pass \`kind: '${s===`doc`?`folder`:`doc`}'\` to share it as the other kind.`}else t=E.code===`invalid-path`?'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.':`Target \`${e.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;let s={ok:!1,error:E.code,message:t};return textPlusStructured(`Error: ${t}`,s,!0)}let D=E.kind===`doc`?{kind:`doc`,docPath:E.sharePath}:{kind:`folder`,folderPath:E.sharePath},O;try{O=await fetch(`${w}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(D),signal:AbortSignal.timeout(3e4)})}catch(e){let t=`Server unreachable: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let k;try{k=await O.json()}catch(e){let t=`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!O.ok){let e;if(k&&typeof k==`object`){let t=k,s=typeof t.title==`string`?t.title:void 0,g=typeof t.detail==`string`?t.detail:void 0;e=s&&g?`${s}: ${g}`:s||g||`HTTP ${O.status}`}else e=`HTTP ${O.status}`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let j=ShareConstructUrlResponseSchema.safeParse(k);if(!j.success){let e=`Server returned an unexpected share-construct-url response shape.`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let F=j.data;if(!F.ok){let e=messageForShareError(F.error,F.branch),t={ok:!1,error:F.error,message:e,...F.branch?{branch:F.branch}:{}};return textPlusStructured(`Error: ${e}`,t,!0)}let{shareUrl:L,sharedUrl:B,branch:H}=F,q={ok:!0,shareUrl:L,sharedUrl:B,branch:H,resolvedKind:E.kind},J={config:t.config,resolveCwd:t.resolveCwd},Y=await resolvePreviewUrlForTool(E.sharePath.replace(/\.(mdx|md)$/i,``),J,g);if(Y&&E.kind===`folder`){let e=E.sharePath.replace(/^\/+|\/+$/g,``),t=e===``?`/#/`:`/#/${encodeDocName(e)}/`;Y={...Y,url:t}}let ee=e.path===``?`(content root)`:e.path;return textPlusStructured(`Share link for ${E.kind} \`${ee}\` on branch \`${H}\`:\n${L}`,{...q,previewUrl:Y?.url??null,...Y?{previewUrlSource:Y.source}:{}})})}const ACTIONS=[`save`,`rollback`],DESCRIPTION$1=["[Requires: Hocuspocus server] Project version management. Dispatches on `action`:",``,'- `action: "save"` — Project-wide checkpoint of every document. No `docName`. Returns `{checkpointRef, previewUrl: null}`. Find checkpoints later via `get_history`.','- `action: "rollback"` — Restore one document to a historical version via the CRDT layer (append-only — creates a new version with the old content; all connected editors see the change in real-time). Requires `docName` and `commitSha`. Find `commitSha` via `get_history`.',``,`**Parameters:**`,"- `action` — `save` | `rollback`.","- `docName` — Required for `rollback`. Document name, typically without extension; trailing `.md`/`.mdx` is stripped.","- `commitSha` — Required for `rollback`. 40-character SHA from the shadow-repo timeline.",'- `summary` — Optional rollback summary (≤80 chars). If omitted, defaults to "Restored to <sha-short>". Avoid secrets or PII — summaries persist to git history.',``,'A `rollback` response may include `structuredContent.contentDivergence` (`{kind: "content-divergence", intendedBytes, actualBytes, byteDelta, divergenceType, currentState, hint}`) when the restored `Y.Text` does not byte-match the target-version bytes. The rollback still landed; `currentState` carries the converged document inline (or a truncation marker over the soft cap), so you do NOT need to re-read.'].join(`
2821
- `);function register$1(e,t){e.registerTool(`version`,{description:DESCRIPTION$1,inputSchema:{action:_enum(ACTIONS).describe(`Which version action to perform.`),docName:string().optional().describe(`Document name. Required for action=rollback.`),commitSha:string().length(40).regex(/^[0-9a-f]+$/i).optional().describe(`40-character commit SHA from the shadow-repo timeline. Required for action=rollback. Find via get_history.`),summary:summaryArgSchema.describe(`Optional rollback summary (≤80 chars). Defaults to "Restored to <sha-short>". Appears as a bullet in the timeline.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);switch(e.action){case`save`:return handleSave(S,t);case`rollback`:return handleRollback(e,S,g,t);default:return textResult(`Error: unknown version action.`,!0)}})}async function handleSave(e,t){let s=t.identityRef?.current,g=await httpPost(e,`/api/save-version`,s?{writers:[{id:`agent-${s.connectionId}`,name:s.displayName,email:`agent-${s.connectionId}@openknowledge.local`}]}:{});return g.ok?textPlusStructured(`Checkpoint saved. Checkpoint ref: ${g.checkpointRef}`,{checkpointRef:g.checkpointRef,previewUrl:null}):textResult(`Error: ${g.error}`,!0)}async function handleRollback(e,t,s,g){if(!e.docName)return textResult("Error: action=rollback requires `docName`.",!0);if(!e.commitSha)return textResult("Error: action=rollback requires `commitSha`.",!0);let S=normalizeDocName(e.docName);if(!S.ok)return textResult(S.error,!0);let w=S.docName,E=await httpGet(t,`/api/history/${e.commitSha}?docName=${encodeURIComponent(w)}`);if(!E.ok)return textResult(`Error: ${E.error??`Version not found`}`,!0);let D=g.identityRef?.current,O=await httpPost(t,`/api/rollback`,{docName:w,commitSha:e.commitSha,...e.summary===void 0?{}:{summary:e.summary},...D?{agentId:D.connectionId,agentName:D.displayName,clientName:D.clientInfo?.name,colorSeed:D.colorSeed}:{}});if(!O.ok)return textResult(`Error: ${O.error}`,!0);let k=O.summary&&typeof O.summary==`object`?O.summary:void 0,j=typeof k?.hint==`string`?k.hint:void 0,F=WriteWarningSchema.safeParse(O.warning),L=F.success?F.data:void 0,B=typeof E.author==`string`?E.author:void 0,H=typeof E.timestamp==`string`?E.timestamp:void 0,q=B&&H?` (${B}, ${H})`:``,J=[`Restored "${w}" to version ${e.commitSha.slice(0,8)}${q}. The change has been applied to all connected editors.`];j&&J.push(j),L&&J.push(L.kind===`content-divergence`?`⚠ Content divergence: ${L.actualBytes} actual bytes vs ${L.intendedBytes} intended (byteDelta=${L.byteDelta}). ${L.hint??`currentState carries the converged content (re-read only if it is truncated).`}`:`⚠ ${L.hint??`An out-of-band edit was reconciled into this document before your change landed on top — re-read for the combined result.`}`);let Y=await resolvePreviewUrlForTool(w,{config:g.config,resolveCwd:g.resolveCwd},s);return textPlusStructured(J.join(`
2822
- `),{previewUrl:Y?.url??null,...Y?{previewUrlSource:Y.source}:{},...k?{summary:k}:{},...L?{contentDivergence:L}:{}})}const POSITIONS=[`append`,`prepend`,`replace`],DESCRIPTION=`${[`[Requires: Hocuspocus server] Write markdown to a document via the CRDT layer. Content propagates to all connected editors in real-time.`,``,'Frontmatter changes: 1-2 keys → prefer `edit_frontmatter` (field-level CRDT, atomic). Full rewrite (≥3-5 keys or body + frontmatter together) → this tool with `position: "replace"` and the full YAML block in the payload.',``,'Templates: `template: "<name>"` resolves against the parent folder\'s `templates_available` (see `exec("ls <folder>/")`) and becomes the new doc verbatim. `template` and `markdown` are mutually exclusive. With `template` set, `position` is forced to `"replace"`.',``,"To create several docs in one call (scaffolding a pack, seeding dossiers), pass `docs: [{docName, markdown|template, position?, summary?}, ...]` instead of the single-doc fields. Docs write in order; the response reports each.",``,`**Parameters:**`,"- `docName` — A single document (`notes/meeting`). On create, a trailing `.mdx` authors a `.mdx` file; `.md` or no extension authors `.md`. For an existing doc the on-disk extension is preserved regardless of the suffix passed (changing it in place is not available via the MCP today).","- `docs` — Batch form: array of `{docName, markdown?|template?, position?, summary?}`. Mutually exclusive with the single-doc fields.",'- `markdown` — Markdown payload. Required unless `template` is set. An empty string with `position: "replace"` clears the document body (frontmatter is preserved); empty `append`/`prepend` is a no-op. Empty content does NOT create a new document.',"- `template` — Template name. Mutually exclusive with `markdown`.","- `position` — `append` | `prepend` | `replace`. Optional for a new doc (defaults to `replace`); required for an existing doc. Forced to `replace` with `template`.","- `summary` — Optional one-line user-outcome (≤80 chars). Avoid secrets or PII — persisted to git history.",``,'Responses may include a content-divergence warning when the converged Y.Text doesn\'t match the bytes your payload composed to. The write still landed; you do NOT need to re-read — `currentState` carries the converged document inline (`{kind:"inline", content}`, or `{kind:"truncated", byteLength, hint}` over the soft cap). Single-doc shape: `structuredContent.contentDivergence = { kind: "content-divergence", intendedBytes, actualBytes, byteDelta, divergenceType, currentState, hint }`. Batch shape: per-doc `structuredContent.documents[].contentDivergence` with the same field set.'].join(`
2823
- `)}\n${renderInventoryFooter()}`;function frontmatterIgnoredNote(e,t){return e!==`prepend`&&e!==`append`||!t||stripFrontmatter(t).frontmatter.trim()===``?null:`Note: a \`---\` frontmatter block in this \`${e}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit_frontmatter\` (1-2 keys) or \`write_document({ position: "replace" })\` (full rewrite).`}function emptyAppendNoOpNote(e,t){return e!==`prepend`&&e!==`append`||t===void 0||stripFrontmatter(t).body!==``?null:`No content to ${e} — document unchanged. To clear a document, use \`position: "replace"\` with empty \`markdown\`.`}function docExtensionOnDisk(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=resolveWithinRoot(e,`${t}${s}`);if(g.ok&&existsSync(g.abs))return s}return null}function requestedDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}function extensionIgnoredNote(e,t,s){return e===null||t===null||e===t?null:`Note: "${s}" already exists as \`${s}${t}\`, so the requested \`${e}\` extension was not applied — the write went to \`${s}${t}\`. Changing a doc's on-disk extension in place isn't available via the MCP today.`}async function writeOneDoc(e,t,s,g,S){let w=normalizeDocName(e.docName);if(!w.ok)return{docName:e.docName,ok:!1,error:w.error};let E=w.docName,D=S.identityRef?.current;if(e.template===void 0&&e.markdown===void 0)return{docName:E,ok:!1,error:"either `markdown` or `template` must be provided — omitting both would write empty content."};if(e.template!==void 0&&e.markdown!==void 0)return{docName:E,ok:!1,error:"TEMPLATE_AND_MARKDOWN_BOTH_SET — `template` and `markdown` are mutually exclusive. Pass one; fill placeholders via subsequent `edit_document` calls."};let O=e.markdown??``,k=docExtensionOnDisk(s,E),j=k!==null,F=requestedDocExtension(e.docName),L;if(e.position!==void 0)L=e.position;else if(j)return{docName:E,ok:!1,error:`"${E}" already exists — pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit_document\` for a targeted change.`};else L=`replace`;if(e.template!==void 0){let s=parentFolderOf(E),g=resolveTemplatesAvailable(t,s,{depth:1}),S=g.find(t=>t.name===e.template);if(!S)return{docName:E,ok:!1,error:`template "${e.template}" not found for folder "${s||`.`}". Available: ${g.length===0?`(none)`:g.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`};let w;try{w=readFileSync(resolve(t,S.path),`utf-8`)}catch(e){return{docName:E,ok:!1,error:`failed to read template at ${S.path}: ${e.message}`}}let{body:k}=stripFrontmatter(w);O=applySubstitution(k,{date:todayIsoUtc(),user:D?.displayName??``}),L=`replace`}if(!j&&normalizeBridge(O)===``)return{docName:E,ok:!1,error:`"${E}" does not exist and the content is empty — provide non-empty content to create the document.`};let B=await httpPost(g,`/api/agent-write-md`,{docName:E,markdown:O,position:L,...F!==null&&!j?{extension:F}:{},...e.summary===void 0?{}:{summary:e.summary},...D?{agentId:D.connectionId,agentName:D.displayName,clientName:D.clientInfo?.name,colorSeed:D.colorSeed}:{}});if(!B.ok){let e=typeof B.detail==`string`&&B.detail.length>0?B.detail:``;return{docName:E,ok:!1,error:e?`${String(B.error)} (${e})`:String(B.error)}}let H=extensionIgnoredNote(F,k,E);return{docName:E,ok:!0,position:L,...e.template===void 0?{}:{fromTemplate:e.template},...H?{extensionNote:H}:{},raw:B}}function register(e,t){let s={docName:string().describe(`Document name to write to`),markdown:string().optional().describe("Markdown content to write. Optional when `template` is set."),template:string().min(1).optional().describe("Template name resolved against the parent folder's templates_available (leaf → root walk-up; closest-wins). Inspect the menu with an `exec` listing of the folder."),position:_enum(POSITIONS).optional().describe("Where to insert the content. Optional for a new doc (defaults to `replace`); required when the doc already exists."),summary:summaryArgSchema};e.registerTool(`write_document`,{description:DESCRIPTION,inputSchema:{docName:string().optional().describe(`A single document to write to.`),markdown:string().optional().describe("Markdown content. Optional when `template` is set."),template:string().min(1).optional().describe("Template name resolved against the parent folder's templates_available (leaf → root walk-up; closest-wins). Inspect the menu with an `exec` listing of the folder."),position:_enum(POSITIONS).optional().describe("Where to insert the content. Optional for a new doc (defaults to `replace`); required when the doc already exists."),summary:summaryArgSchema,docs:array(object$1(s)).min(1).optional().describe(`Batch: documents to write in one call. Mutually exclusive with the single-doc fields.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveLockDir(g),D=resolveContentDir(S,g),O=S.appearance.preview.autoOpen;if(e.docs!==void 0){if(e.docName!==void 0||e.markdown!==void 0||e.template!==void 0||e.position!==void 0||e.summary!==void 0)return textResult("Error: `docs` is the batch form — do not also pass top-level `docName` / `markdown` / `template` / `position` / `summary` (each `docs[]` entry carries its own).",!0);let s=[];for(let S of e.docs)s.push(await writeOneDoc(S,g,D,w,t));let S=s.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=resolvePreviewUrl(e.docName,{lockDir:E}),s=WriteWarningSchema.safeParse(e.raw.warning),g=s.success?s.data:void 0;return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...g?{contentDivergence:g}:{}}}),k=S.filter(e=>e.ok).length,j=k===S.length,F=e.docs.map((e,t)=>{let g=s[t];if(!g?.ok)return`Failed ${e.docName}: ${g?.error??`unknown error`}`;if(emptyAppendNoOpNote(g.position,e.markdown))return`No change to ${e.docName} — empty ${g.position}, document unchanged.`;let w=S[t],E=`Wrote ${e.docName} (${g.position}).`;return w?.ok&&w.contentDivergence?w.contentDivergence.kind===`content-divergence`?`${E} ⚠ Content divergence: ${w.contentDivergence.actualBytes} actual vs ${w.contentDivergence.intendedBytes} intended (byteDelta=${w.contentDivergence.byteDelta}).`:`${E} ⚠ An out-of-band disk edit was reconciled in before your write — re-read for the combined result.`:E}),L=e.docs.flatMap((e,t)=>{let g=s[t];if(!g?.ok)return[];let S=frontmatterIgnoredNote(g.position,e.markdown);return[...S?[S]:[],...g.extensionNote?[g.extensionNote]:[]].map(t=>`${e.docName} — ${t}`)}),B=[`${k}/${S.length} written.`,...F,...L].join(`
2824
- `),H={ok:j,documents:S},q=s.find(e=>e.ok);return q&&q.raw.systemSubscriberCount===0&&(H.warning=buildPreviewAttachWarning(resolvePreviewUrl(q.docName,{lockDir:E}),O)),textPlusStructured(B,H,!j)}if(e.docName===void 0)return textResult("Error: provide `docName` (single) or `docs` (batch).",!0);let k=await writeOneDoc({docName:e.docName,markdown:e.markdown,template:e.template,position:e.position,summary:e.summary},g,D,w,t);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let j=k.raw,F=resolvePreviewUrl(k.docName,{lockDir:E}),L=typeof j.subscriberCount==`number`?j.subscriberCount:void 0,B=(typeof j.systemSubscriberCount==`number`?j.systemSubscriberCount:void 0)===0,H=L===0,q=Array.isArray(j.hints)?j.hints:void 0,J=j.summary&&typeof j.summary==`object`?j.summary:void 0,Y=typeof J?.hint==`string`?J.hint:void 0,ee=WriteWarningSchema.safeParse(j.warning),te=ee.success?ee.data:void 0,ne=[emptyAppendNoOpNote(k.position,e.markdown)??(k.fromTemplate===void 0?`Written successfully (${k.position}).`:`Written successfully (instantiated from template "${k.fromTemplate}").`)],ae=frontmatterIgnoredNote(k.position,e.markdown);if(ae&&ne.push(ae),k.extensionNote&&ne.push(k.extensionNote),B&&!F&&ne.push(START_UI_TEXT_HINT),Y&&ne.push(Y),q)for(let e of q)e.message&&ne.push(e.message);te&&ne.push(te.kind===`content-divergence`?`⚠ Content divergence: ${te.actualBytes} actual bytes vs ${te.intendedBytes} intended (byteDelta=${te.byteDelta}). ${te.hint??`currentState carries the converged content (re-read only if it is truncated).`}`:`⚠ ${te.hint??`An out-of-band edit was reconciled into this document before your write landed on top — re-read for the combined result.`}`);let oe=ne.join(`
2825
- `);if(!F&&!B&&!H&&!q&&!J&&!te)return textResult(oe);let se={};return te&&(se.contentDivergence=te),F&&(se.previewUrl=F.url,se.previewUrlSource=F.source),B&&(se.warning=buildPreviewAttachWarning(F,O)),q&&(se.hints=q),J&&(se.summary=J),textPlusStructured(oe,se)})}function registerAllTools(e,t){let s=t.logger,g=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),S=e=>async g=>{try{let S=await t.resolveCwd(g);return(getCurrentMcpLogger()??s)?.debug(`tool cwd resolved`,{tool:e,cwd:S,...g?{explicit:g}:{}}),S}catch(t){throw(getCurrentMcpLogger()??s)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...g?{explicit:g}:{}}),t}};register$17(g,{resolveCwd:S(`exec`),serverUrl:t.serverUrl,config:t.config}),register$9(g,{config:t.config,resolveCwd:S(`ingest`)}),register$5(g,{config:t.config,resolveCwd:S(`research`)}),register$22(g,{config:t.config,resolveCwd:S(`consolidate`)}),register$20(g,{config:t.config,resolveCwd:S(`discover`)}),register$3(g,{resolveCwd:S(`search`),config:t.config,serverUrl:t.serverUrl}),register$8(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`links`)}),register(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`write_document`),identityRef:t.identityRef}),register$19(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit_document`),identityRef:t.identityRef}),register$21(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`delete_document`),identityRef:t.identityRef}),register$18(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit_frontmatter`),identityRef:t.identityRef}),register$6(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`rename`),identityRef:t.identityRef}),register$11(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`get_history`)}),register$1(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`version`),identityRef:t.identityRef}),register$14(g,{resolveCwd:S(`get_components`),config:t.config}),register$15(g,{resolveCwd:S(`get_authoring_palette`),config:t.config}),register$13(g,{config:t.config,resolveCwd:S(`get_config`)}),register$10(g,{config:t.config,resolveCwd:S(`get_preview_url`)}),register$16(g,{config:t.config,resolveCwd:S(`folder_config`)}),register$7(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`list_conflicts`)}),register$12(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`get_conflict_content`)}),register$4(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,s){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(s))}function createSessionServer(e,t,s){let g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{instructions:buildInstructions(g.content)});installPrettyZodErrors(S);let w=s??randomUUID(),E={current:{connectionId:w,displayName:w,colorSeed:w}};S.server.oninitialized=()=>{let e=S.server.getClientVersion(),t=sanitizeClientName(e?.name,w);E.current={connectionId:w,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let D=e.projectDir??e.contentDir;return registerAllTools(S,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return D;let t=resolveWithinRoot(D,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:g,identityRef:E}),{server:S,transport:t}}function createMcpHttpHandler(e){let t=new Map,s=e.sessionTtlMs??1800*1e3,g=e.maxSessions??100;async function S(s,g){let S=t.get(s);if(!S)return;t.delete(s),S.ttlTimer!==void 0&&clearTimeout(S.ttlTimer);let w=await Promise.allSettled([S.server.close(),S.transport.close()]);for(let t of w)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:s,reason:g},`MCP HTTP session close failed`);e.log?.info?.({sessionId:s,reason:g},`MCP HTTP session closed`)}function w(t,g){g.ttlTimer!==void 0&&clearTimeout(g.ttlTimer),g.ttlTimer=setTimeout(()=>{S(t,`ttl-expired`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},s),g.ttlTimer.unref?.()}return{async handle(s,E){let D=firstHeader(s.headers[`mcp-session-id`]);if(D){let e=t.get(D);if(!e){writePlain(E,404,`MCP session not found`);return}w(D,e),await e.transport.handleRequest(s,E);return}if(s.method!==`POST`){writePlain(E,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=g){e.log?.warn?.({activeSessions:t.size,maxSessions:g},`MCP HTTP session cap reached`),writePlain(E,503,`Too many active MCP sessions`);return}let O=firstHeader(s.headers[MCP_CONNECTION_ID_HEADER]),k=validateAgentId(O)??void 0;O!==void 0&&k===void 0&&e.log?.warn?.({headerLength:O.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let j=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async s=>{try{let g=createSessionServer(e,j,k);await g.server.connect(j),t.set(s,g),w(s,g),e.log?.info?.({sessionId:s},`MCP HTTP session initialized`)}catch(g){throw t.delete(s),e.log?.error?.({err:g,sessionId:s},`MCP HTTP session initialization failed`),g}}});j.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},j.onclose=()=>{let t=j.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}S(t,`transport-closed`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await j.handleRequest(s,E)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>S(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:s,mcpHttpHandler:g,log:S,sessionManager:w,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,contentAssetMiddleware:O,reactShellMiddleware:k}=e,j=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,F=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});F.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let L=new Map,B=new Set,H=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`));for(let[e,s]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,s);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(w?.startsWith(`/api/`)){s.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${w}`})}).catch(e=>{S.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},D=e=>E(O,`content-asset`,e),j=e=>E(k,`react-shell`,e),F=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(k!==void 0&&w?.startsWith(`/assets/`)){j(()=>D(F));return}if(O!==void 0||k!==void 0){D(()=>j(F));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),F.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=L.get(s);e!==void 0&&(clearTimeout(e),L.delete(s),S.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&D){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),g=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);D.setPresence(toBroadcasterKey(s),{displayName:t.displayName,icon:e,color:g,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){S.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let g=setInterval(()=>{try{t.ping()}catch{}},3e4);g.unref?.();let O=s?setInterval(()=>{D?.bumpPresenceTs(toBroadcasterKey(s))},3e3):null;O?.unref?.(),t.on(`close`,()=>{if(clearInterval(g),O!==null&&clearInterval(O),!s)return;let e=setTimeout(()=>{if(L.delete(s),H)return;let e=(async()=>{S.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await w?.closeAllForAgent(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{E?.clearFocus(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{D?.clearPresence(toBroadcasterKey(s))}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}})();B.add(e),e.finally(()=>B.delete(e))},j);e.unref?.(),L.set(s,e),S.info({connectionId:s,graceMs:j},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`Upgrade socket error`)}),F.handleUpgrade(e,t,g,t=>{let g=s.handleConnection(t,e),w=!1;t.on(`message`,e=>{if(w)return;let s=e.byteLength;if(s>MAX_COLLAB_MESSAGE_BYTES){w=!0,incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,bytes:s,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}g.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{g.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||S.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:F,shutdown:async()=>{if(!H){H=!0;for(let e of L.values())clearTimeout(e);L.clear(),B.size>0&&await Promise.allSettled(B)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),s=sanitizeIdentityField(t.searchParams.get(`displayName`)),g=sanitizeIdentityField(t.searchParams.get(`clientName`)),S=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return s===null||g===null||S===null?null:{displayName:s,clientName:g,colorSeed:S}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,s){super(MISSING_OK_CONFIG_MESSAGE,s),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-CblsKfnx.mjs`),S=dirname(e);try{tracedMkdirSync(S,{recursive:!0})}catch(e){e.code!==`EEXIST`&&s.warn({err:e,watchDir:S},`failed to create watch directory; watcher may be inert`)}let w=g(S,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==S&&t!==e});await new Promise(e=>{w.once(`ready`,e)});let E=null;try{E=readFileSync(e,`utf-8`)}catch{}let D=(g,S=!0)=>{if(g!==e)return;let w;try{w=readFileSync(g,`utf-8`)}catch(e){if(e.code===`ENOENT`){S&&s.debug({path:g},`config file disappeared between event and read; dropping`);return}s.warn({err:e,path:g},`config file read failed; dropping event`);return}if(w!==E){E=w;try{t(w)}catch(e){s.warn({err:e,path:g},`config file change handler threw`)}}},O=e=>D(e);w.on(`add`,O),w.on(`change`,O),w.on(`unlink`,t=>{t===e&&s.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),w.on(`error`,t=>{s.warn({err:t,watchDir:S,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let k=0,j=setInterval(()=>{k++,D(e,!1),k>=20&&clearInterval(j)},500);j.unref?.();let F=!1;return async()=>{F||(F=!0,clearInterval(j),await w.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-CblsKfnx.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&s.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&s.debug({path:e},`config file disappeared between event and read; dropping`);return}s.warn({err:t,path:e},`config file read failed; dropping event`);return}if(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=relative(g,join(s,e.file));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g}=e,S=relative(t,s),w=S.startsWith(`..`),E,D,O,k=0,j=0,F=0;function L(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],L=0,B=0;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=readFileSync(S,`utf-8`);L+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(S&&!w)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);L+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,S));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:L};B+=loadNestedIgnoreFiles(s,t,e,H),L=H.value;let q=loadGitExcludeSources(t,H);L=H.value,q.length>0&&(g.push(...q),e.add(q));let J=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return E=e,D=g,O=J,k=g.length,j=B,F=L,{patternCount:k,nestedFileCount:j,bytes:F}}L();let B=new Map;function H(e){if(w)return!1;let t=S?`${S}/${e}`:e;return E.ignores(t)}populateDirCount(s,``,H,B);function q(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function J(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return w?!1:H(e)}return{isExcluded(e,t){if(q(e)||pathHasAlwaysSkipSegment(e))return!0;if(t?.bypassFilters)return!1;if(J(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((B.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(w)return!1;let s=S?`${S}/${e}`:e;return E.ignores(s)||E.ignores(`${s}/`)},isPathIgnored(e,t){return q(e)||pathHasAlwaysSkipSegment(e)?!0:t?.bypassFilters?!1:J(e)},getWatcherIgnoreGlobs(){return O},incrementMdDir(e){let t=e===`.`?``:e;B.set(t,(B.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=B.get(t)??0;s<=1?B.delete(t):B.set(t,s-1)},rebuildDirCount(){let e=new Map(B);B.clear();try{populateDirCount(s,``,H,B)}catch(t){for(let[t,s]of e)B.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=E,S=D,w=O,q=k,J=j,Y=F,ee=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async te=>{try{let t=L();B.clear(),populateDirCount(s,``,H,B);let S=Date.now()-ee;if(te.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:S},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:S}}catch(g){E=t,D=S,O=w,k=q,j=J,F=Y,B.clear();try{populateDirCount(s,``,H,B)}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let L=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(L)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:L}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
2810
+ `}const DESCRIPTION$1=["Procedural guides for the three-layer wiki workflow + brownfield onboarding. Returns a numbered plan (instructional text, not data) you execute it. Dispatches on `kind`:",``,'- `kind: "ingest"` capture an external source (URL or local file) into the KB as raw, verbatim reference material (no analysis). Requires `source`.','- `kind: "research"` — gather sources and write provisional findings for a question. Requires `topic`.','- `kind: "consolidate"` fold provisional material into a canonical article. Requires `topic`.','- `kind: "discover"` extract conventions from an existing repo (folder frontmatter + templates + link graph). No payload.',``,`**Parameters:**`,"- `kind` — `ingest` | `research` | `consolidate` | `discover`.","- `source` Required for `ingest`: the URL / file path / identifier to capture.","- `topic` — Required for `research` / `consolidate`: the topic, question, or anchor URL.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
2811
+ `);function register$1(e,t){let s=buildWorkflowHandler(`ingest`,t,`source`,buildIngestBody),g=buildWorkflowHandler(`research`,t,`topic`,buildResearchBody),S=buildWorkflowHandler(`consolidate`,t,`topic`,buildConsolidateBody);e.registerTool(`workflow`,{description:DESCRIPTION$1,inputSchema:{kind:_enum([`ingest`,`research`,`consolidate`,`discover`]).describe(`Which workflow guide to return.`),source:string().optional().describe('Required for `kind: "ingest"` — the URL / file / identifier to capture.'),topic:string().optional().describe('Required for `kind: "research"` / `"consolidate"` — the topic / question / anchor URL.'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({previewUrl:previewUrlOutputField.describe(`Always null — a workflow guide is prose, not a previewable document.`)})},async e=>{switch(e.kind){case`ingest`:return e.source?s(e):textResult('Error: workflow({ kind: "ingest" }) requires `source` the URL / file / identifier to capture. e.g. workflow({ kind: "ingest", source: "https://example.com/spec" }).',!0);case`research`:return e.topic?g(e):textResult('Error: workflow({ kind: "research" }) requires `topic` the question or topic to investigate. e.g. workflow({ kind: "research", topic: "rate-limit strategies" }).',!0);case`consolidate`:return e.topic?S(e):textResult('Error: workflow({ kind: "consolidate" }) requires `topic`the topic to fold into a canonical article. e.g. workflow({ kind: "consolidate", topic: "rate-limit strategies" }).',!0);case`discover`:{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return s.ok?textPlusStructured(buildDiscoverBody(s.config.content.dir),{previewUrl:null}):textResult(`Error: ${s.error}`,!0)}default:return textResult(`Error: unknown workflow kind.`,!0)}})}const DESCRIPTION=`${["Create or replace one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, or `asset` (or `documents` for a batch of docs).",``,'- `document` — Create or overwrite a doc via the CRDT layer [Requires: Hocuspocus server]. `{ path, content }`, or `{ path, template }` to instantiate from a folder template (mutually exclusive with `content`). Optional `frontmatter` (its own YAML) and `position` (`replace` default for a new doc; required for an existing one) note supplying `frontmatter` alongside literal `content` forces `position: replace` (the only position that persists a YAML block), overriding an explicit `append`/`prepend`. Example: `{ document: { path: "meetings/standup", content: "# Standup\\n..." } }`.','- `folder` Create a NEW folder (optionally with its own properties) [Requires: Hocuspocus server]. `{ path, frontmatter? }`. To change an EXISTING folder use `edit`. Example: `{ folder: { path: "ideas" } }`.','- `template` Create a reusable starting shape for new docs in a folder. `{ path: "<folder>/<name>", content, frontmatter: { title, description?, tags? } }`.','- `asset` Upload a binary (image/file) via the media route [Requires: Hocuspocus server]. `{ path: "<folder>/<file.ext>", content(base64) | source(local path) }`.',"- `documents` Batch: `[{ path, content?|template?, frontmatter?, position?, summary? }, ...]` written in order; the response reports each.","- `summary` — Optional one-line user-outcome (≤80 chars) for the timeline, for a single `document`/`folder`/`template`/`asset` write. For a `documents` batch, give each entry its own `summary` instead (a top-level `summary` is ignored on the batch path). Avoid secrets or PII persisted to git history."].join(`
2812
+ `)}\n${renderInventoryFooter()}`;function frontmatterIgnoredNote(e,t){return e!==`prepend`&&e!==`append`||!t||stripFrontmatter(t).frontmatter.trim()===``?null:`Note: a \`---\` frontmatter block in this \`${e}\` payload was ignored — frontmatter is written only with \`position: "replace"\`. To change frontmatter, use \`edit({ document: { path, frontmatter } })\` (patch) or \`write({ document: { path, content, position: "replace" } })\` (full rewrite).`}function emptyAppendNoOpNote(e,t){return e!==`prepend`&&e!==`append`||t===void 0||stripFrontmatter(t).body!==``?null:`No content to ${e} document unchanged. To clear a document, use \`position: "replace"\` with empty \`content\`.`}function docExtensionOnDisk(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=resolveWithinRoot(e,`${t}${s}`);if(g.ok&&existsSync(g.abs))return s}return null}function requestedDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}function extensionIgnoredNote(e,t,s){return e===null||t===null||e===t?null:`Note: "${s}" already exists as \`${s}${t}\`, so the requested \`${e}\` extension was not applied — the write went to \`${s}${t}\`. Changing a doc's on-disk extension in place isn't available via the MCP today.`}function composeWithFrontmatter(e,t){let s=dropEmpties(e);return Object.keys(s).length===0?t:`---\n${(0,import_dist$1.stringify)(s)}---\n${t}`}async function writeOneDoc(e,t,s,g,S){let w=normalizeDocName(e.path);if(!w.ok)return{docName:e.path,ok:!1,error:w.error};let E=w.docName,D=S.identityRef?.current;if(e.template===void 0&&e.content===void 0)return{docName:E,ok:!1,error:"either `content` or `template` must be provided — omitting both would write empty content."};if(e.template!==void 0&&e.content!==void 0)return{docName:E,ok:!1,error:"TEMPLATE_AND_CONTENT_BOTH_SET — `template` and `content` are mutually exclusive. Pass one; fill placeholders via subsequent `edit` calls."};let O=e.content??``,k=e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0,j=docExtensionOnDisk(s,E),F=j!==null,L=requestedDocExtension(e.path),B;if(e.position!==void 0)B=e.position;else if(F)return{docName:E,ok:!1,error:`"${E}" already exists pass \`position\` (\`append\` | \`prepend\` | \`replace\`), or use \`edit\` for a targeted change.`};else B=`replace`;if(e.template!==void 0){let s=parentFolderOf(E),g=resolveTemplatesAvailable(t,s,{depth:1}),S=g.find(t=>t.name===e.template);if(!S)return{docName:E,ok:!1,error:`template "${e.template}" not found for folder "${s||`.`}". Available: ${g.length===0?`(none)`:g.map(e=>`${e.name} [${e.scope}]`).join(`, `)}. Templates are resolved by walk-up; check the parent folder's exec listing to see the menu.`};let w;try{w=readFileSync(resolve(t,S.path),`utf-8`)}catch(e){return{docName:E,ok:!1,error:`failed to read template at ${S.path}: ${e.message}`}}let{body:k}=stripFrontmatter(w);O=applySubstitution(k,{date:todayIsoUtc(),user:D?.displayName??``}),B=`replace`}else k&&(O=composeWithFrontmatter(e.frontmatter,O),B=`replace`);if(!F&&normalizeBridge(O)===``)return{docName:E,ok:!1,error:`"${E}" does not exist and the content is empty provide non-empty content to create the document.`};let H=await httpPost(g,`/api/agent-write-md`,{docName:E,markdown:O,position:B,...L!==null&&!F?{extension:L}:{},...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(D)});if(!H.ok){let e=typeof H.detail==`string`&&H.detail.length>0?H.detail:``;return{docName:E,ok:!1,error:e?`${String(H.error)} (${e})`:String(H.error)}}if(e.template!==void 0&&k){let t=await httpPost(g,`/api/frontmatter-patch`,{docName:E,patch:e.frontmatter,...agentIdentityFields(D)});if(!t.ok)return{docName:E,ok:!1,error:`document created from template but frontmatter failed: ${String(t.error)}`}}let q=extensionIgnoredNote(L,j,E);return{docName:E,ok:!0,position:B,...e.template===void 0?{}:{fromTemplate:e.template},...q?{extensionNote:q}:{},raw:H}}async function handleFolder(e,t,s,g){if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=g.identityRef?.current,w=await httpPost(s,`/api/create-folder`,{path:e.path,...t===void 0?{}:{summary:t},...agentIdentityFields(S)});if(!w.ok){let e=typeof w.detail==`string`&&w.detail.length>0?w.detail:``;return textResult(e?`Error: ${w.error} (${e})`:`Error: ${w.error}`,!0)}let E=[`Created folder ${e.path}.`];if(e.frontmatter!==void 0&&Object.keys(e.frontmatter).length>0){let g=await httpPut(s,`/api/folder-config`,{path:e.path,frontmatter:e.frontmatter,...t===void 0?{}:{summary:t},...agentIdentityFields(S)});if(!g.ok)return textPlusStructured(`Created folder ${e.path}, but writing its properties failed: ${g.error}. Use edit({ folder: { path: "${e.path}", frontmatter } }) to retry the properties.`,{folder:{ok:!0,path:e.path,frontmatterError:String(g.error)}});E.push(`Set folder properties (${e.path}/.ok/frontmatter.yml).`)}return textPlusStructured(E.join(`
2813
+ `),{folder:{ok:!0,path:e.path}})}async function handleTemplate(e,t,s,g){let S=resolveTemplatePath(e.path);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{folder:w,name:E}=S;if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=await httpPut(s,`/api/template`,{folder:w,name:E,body:e.content,frontmatter:{title:e.frontmatter.title,...typeof e.frontmatter.description==`string`?{description:e.frontmatter.description}:{},...Array.isArray(e.frontmatter.tags)?{tags:e.frontmatter.tags}:{}},...t===void 0?{}:{summary:t},...agentIdentityFields(g.identityRef?.current)});if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.created===!0,k=typeof D.path==`string`?D.path:void 0;return textPlusStructured(`${O?`Created`:`Updated`} template "${E}" in ${w||`(root)`}${k?` (${k})`:``}.`,{template:{ok:!0,path:k,created:O}})}async function handleAsset(e,t,s,g){if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.content===void 0==(e.source===void 0))return textResult("Error: provide exactly one of `content` (base64) or `source` (local file path) for an asset.",!0);let S;try{S=e.content===void 0?readFileSync(resolve(t,e.source)):Buffer.from(e.content,`base64`)}catch(e){return textResult(`Error: could not read asset bytes: ${e.message}`,!0)}if(S.byteLength===0)return textResult(`Error: asset is empty (0 bytes).`,!0);let{folder:w,name:E}=splitTargetPath(e.path),D=w?`${w}/${E}`:E,O=g.identityRef?.current,k=new URLSearchParams;O?.connectionId&&k.set(`agentId`,O.connectionId),O?.displayName&&k.set(`agentName`,O.displayName);let j=k.toString(),F=new FormData;F.append(`parentDocName`,D),F.append(`file`,new Blob([new Uint8Array(S)]),E);let L;try{let e=await fetch(`${s}/api/upload${j?`?${j}`:``}`,{method:`POST`,body:F}),t=await e.json().catch(()=>null);L=e.ok?{ok:!0,status:e.status,data:t??{}}:{ok:!1,status:e.status,error:t&&(typeof t.title==`string`?t.title:t.error)||`Upload failed (HTTP ${e.status}).`}}catch(e){return textResult(`Error: upload request failed: ${e.message}`,!0)}if(!L.ok)return textResult(`Error: ${L.error}`,!0);let B=typeof L.data?.src==`string`?L.data.src:void 0,H=typeof L.data?.path==`string`?L.data.path:void 0,q=L.data?.deduped===!0,J=B??H??E;return textPlusStructured([`Uploaded asset to ${D}${q?` (deduplicated — identical bytes already present)`:``}.`,`Reference it in a doc with: ![${E}](${J})`].join(`
2814
+ `),{asset:{ok:!0,...B?{src:B}:{},...H?{path:H}:{},...q?{deduped:q}:{}}})}async function handleBatch(e,t,s,g,S,w,E){let D=[];for(let w of e)D.push(await writeOneDoc(w,t,s,g,S));let O=D.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=resolvePreviewUrl(e.docName,{lockDir:w}),s=parseContentDivergence(e.raw.warning);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...s?{contentDivergence:s}:{}}}),k=O.filter(e=>e.ok).length,j=k===O.length,F=e.map((e,t)=>{let s=D[t];if(!s?.ok)return`Failed ${e.path}: ${s?.error??`unknown error`}`;if(emptyAppendNoOpNote(s.position,e.content))return`No change to ${e.path} — empty ${s.position}, document unchanged.`;let g=O[t],S=`Wrote ${e.path} (${s.position}).`;return g?.ok&&g.contentDivergence?`${S} ${formatContentDivergenceBrief(g.contentDivergence)}`:S}),L=e.flatMap((e,t)=>{let s=D[t];if(!s?.ok)return[];let g=frontmatterIgnoredNote(s.position,e.content);return[...g?[g]:[],...s.extensionNote?[s.extensionNote]:[]].map(t=>`${e.path}${t}`)}),B=[`${k}/${O.length} written.`,...F,...L].join(`
2815
+ `),H={documents:O},q=D.find(e=>e.ok);return q&&q.raw.systemSubscriberCount===0&&(H.warning=buildPreviewAttachWarning(resolvePreviewUrl(q.docName,{lockDir:w}),E)),textPlusStructured(B,H,!j)}async function handleSingleDoc(e,t,s,g,S,w,E){let D=await writeOneDoc(e,t,s,g,S);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.raw,k=resolvePreviewUrl(D.docName,{lockDir:w}),j=typeof O.subscriberCount==`number`?O.subscriberCount:void 0,F=(typeof O.systemSubscriberCount==`number`?O.systemSubscriberCount:void 0)===0,L=j===0,B=Array.isArray(O.hints)?O.hints:void 0,H=O.summary&&typeof O.summary==`object`?O.summary:void 0,q=typeof H?.hint==`string`?H.hint:void 0,J=parseContentDivergence(O.warning),Y=[emptyAppendNoOpNote(D.position,e.content)??(D.fromTemplate===void 0?`Written successfully (${D.position}).`:`Written successfully (instantiated from template "${D.fromTemplate}").`)],ee=frontmatterIgnoredNote(D.position,e.content);if(ee&&Y.push(ee),D.extensionNote&&Y.push(D.extensionNote),F&&!k&&Y.push(START_UI_TEXT_HINT),q&&Y.push(q),B)for(let e of B)e.message&&Y.push(e.message);J&&Y.push(formatContentDivergenceLine(J));let te=Y.join(`
2816
+ `);if(!k&&!F&&!L&&!B&&!H&&!J)return textResult(te);let ne={};return B&&(ne.hints=B),H&&(ne.summary=H),J&&(ne.contentDivergence=J),textPlusStructured(te,nestDocResult(k,F?buildPreviewAttachWarning(k,E):void 0,ne))}function register(e,t){let s={path:string().describe(`Document path, no extension. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup".`),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe(`Single-document write result (present when there is a doc-specific signal).`),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, contentDivergence?, error? }`."),previewUrl:previewUrlOutputField.optional(),previewUrlSource:previewUrlSourceField,warning:previewAttachWarningField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s,E=resolveLockDir(g),D=resolveContentDir(S,g),O=S.appearance.preview.autoOpen;if(e.documents!==void 0){let s=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`,`documents`]);return s?textResult(`Error: ${s}`,!0):w?handleBatch(e.documents,g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}let k=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`]);return k?textResult(`Error: ${k}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?handleAsset(e.asset,g,w,t):handleTemplate(e.template,e.summary,w,t):handleFolder(e.folder,e.summary,w,t):w?handleSingleDoc({...e.document,summary:e.summary},g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)})}function registerAllTools(e,t){let s=t.logger,g=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),S=e=>async g=>{try{let S=await t.resolveCwd(g);return(getCurrentMcpLogger()??s)?.debug(`tool cwd resolved`,{tool:e,cwd:S,...g?{explicit:g}:{}}),S}catch(t){throw(getCurrentMcpLogger()??s)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...g?{explicit:g}:{}}),t}};register$11(g,{resolveCwd:S(`exec`),serverUrl:t.serverUrl,config:t.config}),register$1(g,{config:t.config,resolveCwd:S(`workflow`)}),register$3(g,{resolveCwd:S(`search`),config:t.config,serverUrl:t.serverUrl}),register$8(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`links`)}),register(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`write`),identityRef:t.identityRef}),register$12(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit`),identityRef:t.identityRef}),register$13(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`delete`),identityRef:t.identityRef}),register$7(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`move`),identityRef:t.identityRef}),register$9(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`history`)}),register$16(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`checkpoint`),identityRef:t.identityRef}),register$4(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`restore_version`),identityRef:t.identityRef}),register$6(g,{resolveCwd:S(`palette`),config:t.config}),register$15(g,{config:t.config,resolveCwd:S(`config`)}),register$10(g,{config:t.config,resolveCwd:S(`preview_url`)}),register$14(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`conflicts`)}),register$5(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,s){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(s))}function createSessionServer(e,t,s){let g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{instructions:buildInstructions(g.content)});installPrettyZodErrors(S);let w=s??randomUUID(),E={current:{connectionId:w,displayName:w,colorSeed:w}};S.server.oninitialized=()=>{let e=S.server.getClientVersion(),t=sanitizeClientName(e?.name,w);E.current={connectionId:w,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let D=e.projectDir??e.contentDir;return registerAllTools(S,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return D;let t=resolveWithinRoot(D,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:g,identityRef:E}),{server:S,transport:t}}function createMcpHttpHandler(e){let t=new Map,s=e.sessionTtlMs??1800*1e3,g=e.maxSessions??100;async function S(s,g){let S=t.get(s);if(!S)return;t.delete(s),S.ttlTimer!==void 0&&clearTimeout(S.ttlTimer);let w=await Promise.allSettled([S.server.close(),S.transport.close()]);for(let t of w)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:s,reason:g},`MCP HTTP session close failed`);e.log?.info?.({sessionId:s,reason:g},`MCP HTTP session closed`)}function w(t,g){g.ttlTimer!==void 0&&clearTimeout(g.ttlTimer),g.ttlTimer=setTimeout(()=>{S(t,`ttl-expired`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},s),g.ttlTimer.unref?.()}return{async handle(s,E){let D=firstHeader(s.headers[`mcp-session-id`]);if(D){let e=t.get(D);if(!e){writePlain(E,404,`MCP session not found`);return}w(D,e),await e.transport.handleRequest(s,E);return}if(s.method!==`POST`){writePlain(E,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=g){e.log?.warn?.({activeSessions:t.size,maxSessions:g},`MCP HTTP session cap reached`),writePlain(E,503,`Too many active MCP sessions`);return}let O=firstHeader(s.headers[MCP_CONNECTION_ID_HEADER]),k=validateAgentId(O)??void 0;O!==void 0&&k===void 0&&e.log?.warn?.({headerLength:O.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let j=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async s=>{try{let g=createSessionServer(e,j,k);await g.server.connect(j),t.set(s,g),w(s,g),e.log?.info?.({sessionId:s},`MCP HTTP session initialized`)}catch(g){throw t.delete(s),e.log?.error?.({err:g,sessionId:s},`MCP HTTP session initialization failed`),g}}});j.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},j.onclose=()=>{let t=j.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}S(t,`transport-closed`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await j.handleRequest(s,E)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>S(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:s,mcpHttpHandler:g,log:S,sessionManager:w,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,contentAssetMiddleware:O,reactShellMiddleware:k}=e,j=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,F=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});F.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let L=new Map,B=new Set,H=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`));for(let[e,s]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,s);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(w?.startsWith(`/api/`)){s.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${w}`})}).catch(e=>{S.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},D=e=>E(O,`content-asset`,e),j=e=>E(k,`react-shell`,e),F=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(k!==void 0&&w?.startsWith(`/assets/`)){j(()=>D(F));return}if(O!==void 0||k!==void 0){D(()=>j(F));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),F.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=L.get(s);e!==void 0&&(clearTimeout(e),L.delete(s),S.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&D){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),g=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);D.setPresence(toBroadcasterKey(s),{displayName:t.displayName,icon:e,color:g,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){S.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let g=setInterval(()=>{try{t.ping()}catch{}},3e4);g.unref?.();let O=s?setInterval(()=>{D?.bumpPresenceTs(toBroadcasterKey(s))},3e3):null;O?.unref?.(),t.on(`close`,()=>{if(clearInterval(g),O!==null&&clearInterval(O),!s)return;let e=setTimeout(()=>{if(L.delete(s),H)return;let e=(async()=>{S.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await w?.closeAllForAgent(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{E?.clearFocus(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{D?.clearPresence(toBroadcasterKey(s))}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}})();B.add(e),e.finally(()=>B.delete(e))},j);e.unref?.(),L.set(s,e),S.info({connectionId:s,graceMs:j},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`Upgrade socket error`)}),F.handleUpgrade(e,t,g,t=>{let g=s.handleConnection(t,e),w=!1;t.on(`message`,e=>{if(w)return;let s=e.byteLength;if(s>MAX_COLLAB_MESSAGE_BYTES){w=!0,incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,bytes:s,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}g.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{g.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||S.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:F,shutdown:async()=>{if(!H){H=!0;for(let e of L.values())clearTimeout(e);L.clear(),B.size>0&&await Promise.allSettled(B)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),s=sanitizeIdentityField(t.searchParams.get(`displayName`)),g=sanitizeIdentityField(t.searchParams.get(`clientName`)),S=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return s===null||g===null||S===null?null:{displayName:s,clientName:g,colorSeed:S}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,s){super(MISSING_OK_CONFIG_MESSAGE,s),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-CblsKfnx.mjs`),S=dirname(e);try{tracedMkdirSync(S,{recursive:!0})}catch(e){e.code!==`EEXIST`&&s.warn({err:e,watchDir:S},`failed to create watch directory; watcher may be inert`)}let w=g(S,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==S&&t!==e});await new Promise(e=>{w.once(`ready`,e)});let E=null;try{E=readFileSync(e,`utf-8`)}catch{}let D=(g,S=!0)=>{if(g!==e)return;let w;try{w=readFileSync(g,`utf-8`)}catch(e){if(e.code===`ENOENT`){S&&s.debug({path:g},`config file disappeared between event and read; dropping`);return}s.warn({err:e,path:g},`config file read failed; dropping event`);return}if(w!==E){E=w;try{t(w)}catch(e){s.warn({err:e,path:g},`config file change handler threw`)}}},O=e=>D(e);w.on(`add`,O),w.on(`change`,O),w.on(`unlink`,t=>{t===e&&s.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),w.on(`error`,t=>{s.warn({err:t,watchDir:S,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let k=0,j=setInterval(()=>{k++,D(e,!1),k>=20&&clearInterval(j)},500);j.unref?.();let F=!1;return async()=>{F||(F=!0,clearInterval(j),await w.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-CblsKfnx.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&s.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&s.debug({path:e},`config file disappeared between event and read; dropping`);return}s.warn({err:t,path:e},`config file read failed; dropping event`);return}if(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=relative(g,join(s,e.file));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g}=e,S=relative(t,s),w=S.startsWith(`..`),E,D,O,k=0,j=0,F=0;function L(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],L=0,B=0;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=readFileSync(S,`utf-8`);L+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(S&&!w)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);L+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,S));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:L};B+=loadNestedIgnoreFiles(s,t,e,H),L=H.value;let q=loadGitExcludeSources(t,H);L=H.value,q.length>0&&(g.push(...q),e.add(q));let J=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return E=e,D=g,O=J,k=g.length,j=B,F=L,{patternCount:k,nestedFileCount:j,bytes:F}}L();let B=new Map;function H(e){if(w)return!1;let t=S?`${S}/${e}`:e;return E.ignores(t)}populateDirCount(s,``,H,B);function q(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function J(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return w?!1:H(e)}return{isExcluded(e,t){if(q(e)||pathHasAlwaysSkipSegment(e))return!0;if(t?.bypassFilters)return!1;if(J(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((B.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(w)return!1;let s=S?`${S}/${e}`:e;return E.ignores(s)||E.ignores(`${s}/`)},isPathIgnored(e,t){return q(e)||pathHasAlwaysSkipSegment(e)?!0:t?.bypassFilters?!1:J(e)},getWatcherIgnoreGlobs(){return O},incrementMdDir(e){let t=e===`.`?``:e;B.set(t,(B.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=B.get(t)??0;s<=1?B.delete(t):B.set(t,s-1)},rebuildDirCount(){let e=new Map(B);B.clear();try{populateDirCount(s,``,H,B)}catch(t){for(let[t,s]of e)B.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=E,S=D,w=O,q=k,J=j,Y=F,ee=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async te=>{try{let t=L();B.clear(),populateDirCount(s,``,H,B);let S=Date.now()-ee;if(te.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:S},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:S}}catch(g){E=t,D=S,O=w,k=q,j=J,F=Y,B.clear();try{populateDirCount(s,``,H,B)}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let L=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(L)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:L}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
2826
2817
  `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){return e.startsWith(`!`)?`!${t}/${e.slice(1)}`:`${t}/${e}`}function loadNestedIgnoreFiles(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let w=0;for(let E of S){if(!E.isDirectory()||BUILTIN_SKIP_DIRS.has(E.name))continue;let S=join(e,E.name),D=relative(t,S);if(!D.startsWith(`..`)&&!(s.ignores(D)||s.ignores(`${D}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(S,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);g.value+=e.length;let S=parseIgnorePatterns(e).map(e=>prefixPattern(e,D));s.add(S),w++}catch(s){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,s)}}w+=loadNestedIgnoreFiles(S,t,s,g)}}return w}async function initContentDirStateAsync(e,t,s,g,S,w,E){let D;try{D=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let O of D){let D=t?`${t}/${O.name}`:O.name;if(O.isDirectory()){if(BUILTIN_SKIP_DIRS.has(O.name))continue;let t=join(e,O.name);if(!w){let e=relative(s,t);if(e.startsWith(`..`)||g.ignores(e)||g.ignores(`${e}/`))continue;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${s} at ${S}:`,e)}}}await initContentDirStateAsync(t,D,s,g,S,w,E)}else if(O.isFile()&&isSupportedDocFile(O.name)){if(!w){let e=S?`${S}/${D}`:D;if(g.ignores(e))continue}E.set(t,(E.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:s,onAfterRebuild:g}=e,S=relative(t,s),w=S.startsWith(`..`),E=(0,import_ignore.default)(),D=[],O=new Map;function k(e){if(w)return!1;let t=S?`${S}/${e}`:e;return E.ignores(t)}function j(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function F(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return w?!1:k(e)}async function L(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[];for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(S&&!w)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=parseIgnorePatterns(await readFile$1(g,`utf-8`));e.add(t.map(e=>prefixPattern(e,S)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let k=await loadGitExcludeSourcesAsync(t,{value:0});k.length>0&&(g.push(...k),e.add(k));let j=new Map;await initContentDirStateAsync(s,``,t,e,S,w,j),E=e,D=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),O.clear();for(let[e,t]of j)O.set(e,t)}return await L(),{isExcluded(e,t){if(j(e)||pathHasAlwaysSkipSegment(e))return!0;if(t?.bypassFilters)return!1;if(F(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((O.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(w)return!1;let s=S?`${S}/${e}`:e;return E.ignores(s)||E.ignores(`${s}/`)},isPathIgnored(e,t){return j(e)||pathHasAlwaysSkipSegment(e)?!0:t?.bypassFilters?!1:F(e)},getWatcherIgnoreGlobs(){return D},incrementMdDir(e){let t=e===`.`?``:e;O.set(t,(O.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=O.get(t)??0;s<=1?O.delete(t):O.set(t,s-1)},rebuildDirCount(){let e=new Map(O);O.clear();try{populateDirCount(s,``,k,O)}catch(t){for(let[t,s]of e)O.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=E,s=D,S=new Map(O),w=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async k=>{try{await L();let t=Date.now()-w;if(k.setAttributes({"ok.ignore.pattern_count":D.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:D.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(g){E=t,D=s,O.clear();for(let[e,t]of S)O.set(e,t);let w=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(w)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:w}}}})}}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let s=resolve(e,t.slice(5));try{return readFileSync(s,`utf-8`).trim()}catch{try{let s=readFileSync(resolve(e,`packed-refs`),`utf-8`),g=t.slice(5),S=s.split(`
2827
2818
  `).find(e=>e.endsWith(` ${g}`));if(S)return S.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}async function startHeadWatcher(e,t,s){let g=resolveGitDir(e);if(!g)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let S=g,w=!1,E=null,D=null,O=null,k=null;async function j(e){if(L&&await L,!w)return;E&&=(clearTimeout(E),null),D&&=(clearTimeout(D),null);let t=readHeadSha(S),g=O!==t,j=readBranchFromHead(S),F;F=j?.startsWith(`detached-`)?`detached-head`:k===j?`within-branch`:`cross-branch`;let B=k;try{await s({headMoved:g,oldHead:O,newHead:t,timeout:e,batchKind:F,oldBranch:B,newBranch:j})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{w=!1,O=t,k=j}}function F(){E&&clearTimeout(E),E=setTimeout(()=>{E=null,j(!1)},QUIET_WINDOW_MS)}let L=null;async function B(e){if(!w){w=!0,O=readHeadSha(S);let s=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();L=s,await s,L=null,D=setTimeout(()=>{D=null,j(!0)},BATCH_TIMEOUT_MS)}F()}let H,q;try{q=await import(`@parcel/watcher`)}catch(e){throw Error(`@parcel/watcher unavailable for HEAD watching: ${e instanceof Error?e.message:e}`)}try{let e=await q.subscribe(S,(e,t)=>{if(e){console.error(`[head-watcher]`,e);return}for(let e of t){let t=e.path.split(`/`).pop()??``;if(WATCHED_FILES.has(t)){B(t);break}}});H=()=>e.unsubscribe()}catch(e){throw Error(`@parcel/watcher subscribe failed for HEAD watching: ${e instanceof Error?e.message:e}`)}return O=readHeadSha(S),k=readBranchFromHead(S),getLogger(`head-watcher`).info({gitDir:S},`watching for HEAD changes`),{unsubscribe:async()=>{w&&await j(!1),E&&clearTimeout(E),D&&clearTimeout(D),await H()},getLastKnownBranch:()=>k}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:s,signalChannel:g,debounceMs:S=100}=e,w=new Map;function E(e){let t=w.get(e);t&&(clearTimeout(t),w.delete(e))}function D(e,D){E(e),w.set(e,setTimeout(()=>{w.delete(e);try{let S=serializeLiveDocument(D);t.updateDocumentFromMarkdown(e,S),g?.(`backlinks`),g?.(`graph`),s&&(s.updateDocumentFromMarkdown(e,S),g?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},S))}return{async onChange({documentName:e,document:t,transactionOrigin:s}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(s)&&s.context?.origin===`file-watcher`||D(e,t)},async beforeUnloadDocument({documentName:e}){E(e)},async onDestroy(){for(let e of w.values())clearTimeout(e);w.clear()}}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function loadPrincipal(e){let t=getLocalDir(e),s=resolve(t,PRINCIPAL_FILE),{name:g,email:S}=await readGitConfig(e);if(existsSync(s)){let e;try{e=JSON.parse(readFileSync(s,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,w=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),E=t.slice(10,18),D={id:t,display_name:g?sanitizeGitIdentity(g):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:S?sanitizeGitIdentity(S):typeof e.display_email==`string`?e.display_email:`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:w};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}mkdirSync(t,{recursive:!0});let w=`principal-${randomUUID()}`,E=w.slice(10,18),D={id:w,display_name:g?sanitizeGitIdentity(g):`Local User`,display_email:S?sanitizeGitIdentity(S):`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}const DEFAULT_CAPACITY=1e4;var RecentlyRemovedDocs=class{map=new Map;capacity;onEviction;onSizeChange;now;constructor(e=DEFAULT_CAPACITY,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&this.onSizeChange?.(this.map.size)}get size(){return this.map.size}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size)}};function fileExistsForDocName(e,t){let s=e.resolveFilePath(t);return s!==null&&e.fileExists(s)}async function runRemovalRedirectGuard(e,t){try{if(isSystemDoc(e)||isConfigDoc(e))return;let s=t.recentlyRemovedDocs.get(e);if(s===void 0)return;if(s.kind===`deleted`){if(fileExistsForDocName(t,e)){t.recentlyRemovedDocs.delete(e);return}throw incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let g=new Set([e]),S=s.newDocName;for(;;){if(g.has(S)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:S}));return}g.add(S);let s=t.recentlyRemovedDocs.get(S);if(s===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S);if(s.kind===`deleted`)throw fileExistsForDocName(t,S)?(t.recentlyRemovedDocs.delete(S),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));S=s.newDocName}}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthRemovalGuardError(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}function createServerObserverExtension(e){let t=new Map,s=new Map;return{async afterLoadDocument({documentName:g,document:S}){if(isSystemDoc(g)||isConfigDoc(g)||t.has(g))return;let w=S,E=w.getXmlFragment(`default`),D=w.getText(`source`),O=()=>{try{let s=setupServerObservers({doc:w,xmlFragment:E,ytext:D,mdManager:e.mdManager,schema:e.schema,docName:g,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(g,s),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${g}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!O()){let e=setTimeout(()=>{s.delete(g),!t.has(g)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${g}'`),O())},5e3);s.set(g,e)}},async afterUnloadDocument({documentName:e}){let g=s.get(e);g&&(clearTimeout(g),s.delete(e));let S=t.get(e);S&&(S(),t.delete(e))},async onDestroy(){for(let e of s.values())clearTimeout(e);s.clear();for(let[e,s]of t.entries())try{s()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let s=t.createdBy;return!(typeof s.runtimeVersion!=`string`||s.protocolVersion!==void 0&&typeof s.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let s;try{s=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let g;try{g=JSON.parse(s)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(g))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:g}}function writeStateManifest(e,t){let s=manifestPath(e);mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),s=e.currentStateSchemaVersion??1,g=e.currentRuntimeVersion??RUNTIME_VERSION,S=e.currentProtocolVersion??1,w=(e.now??(()=>new Date))().toISOString(),E=manifestPath(e.lockDir),D=readStateManifest(e.lockDir);if(D.status===`present`){let O=D.manifest;if(!isCompatibleSchema(O.stateSchemaVersion,s))throw new StateManifestError({kind:`incompatible`,path:E,message:`State manifest at ${E} declares stateSchemaVersion=${O.stateSchemaVersion} but this binary supports ${s}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${O.createdBy.runtimeVersion}, protocol ${O.createdBy.protocolVersion}.)`});try{let t={...O,lastWriteBy:{runtimeVersion:g,protocolVersion:S,at:w}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),O}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let D={stateSchemaVersion:s,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S}};return writeStateManifest(e.lockDir,D),t.info({path:E,stateSchemaVersion:s},`[state-manifest] fresh project — wrote manifest`),D}let O={stateSchemaVersion:0,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S,adoptedAt:w}};return writeStateManifest(e.lockDir,O),t.warn({path:E,runtimeVersion:g},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),O}function deriveUserFacingCode(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_PATTERNS=[/\b(401|403)\b/,/authentication failed/i,/authorization failed/i,/invalid credentials/i,/credential helper/i,/bad credentials/i,/token.*expired/i,/expired.*token/i,/permission denied.*\(publickey\)/i,/host key verification failed/i,/fatal:.*repository.*not found/i],SCOPE_MISMATCH_PATTERNS=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],NON_FAST_FORWARD_PATTERNS=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],PROTECTED_BRANCH_PATTERNS=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],MERGE_CONFLICT_PATTERNS=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],LFS_PATTERNS=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],LARGE_FILE_PATTERNS=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PRE_RECEIVE_PATTERNS=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],SECRET_DETECTED_PATTERNS=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],INDEX_LOCK_PATTERNS=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],DIRTY_TREE_PATTERNS=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],DISK_FULL_PATTERNS=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],NETWORK_PATTERNS=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],HTTP_5XX_PATTERNS=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],HTTP_429_PATTERNS=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function classifyGitError(e){let t=classifyGitErrorBase(e);return{...t,userFacingCode:deriveUserFacingCode(t.class,t.subclass)}}function classifyGitErrorBase(e){let t=e instanceof Error?e:Error(String(e)),s=extractStderr(t),g=`${t.message}\n${s}`.toLowerCase();return matchesAny(g,INDEX_LOCK_PATTERNS)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:s}:matchesAny(g,DIRTY_TREE_PATTERNS)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:s}:matchesAny(g,DISK_FULL_PATTERNS)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:s}:matchesAny(g,SCOPE_MISMATCH_PATTERNS)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:s}:matchesAny(g,AUTH_PATTERNS)?/\b401\b/.test(g)||/token.*expired/i.test(g)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:s}:/\b403\b/.test(g)?matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:s}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:s}:matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:matchesAny(g,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:s}:matchesAny(g,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:s}:matchesAny(g,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:s}:matchesAny(g,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:s}:matchesAny(g,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:s}:matchesAny(g,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:s}:matchesAny(g,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:s}:matchesAny(g,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:s}:matchesAny(g,NETWORK_PATTERNS)?/timed? out/i.test(g)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:s}:/refused/i.test(g)||/econnrefused/i.test(g)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:s}:/resolve.*host/i.test(g)||/enotfound/i.test(g)||/getaddrinfo/i.test(g)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:s}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:s}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:s}}const log$2=getLogger(`github-permissions`),PROBE_TIMEOUT_MS=5e3;function githubApiBase(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function buildHeaders(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function readPushFlag(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let s=t.push;return typeof s==`boolean`?s:null}async function classify(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return log$2.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let s=readPushFlag(t);return s===null?(log$2.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):s?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return log$2.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function resolveProbeTokenWithSource(e,t,s){let g=t(e);if(g.available&&g.token)return{token:g.token,source:`gh`};if(s)try{let t=await s.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){log$2.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function runProbe(e){let{owner:t,repo:s,host:g=`github.com`,detectGh:S=()=>({available:!1}),tokenStore:w,_fetchFn:E=fetch,_timeoutMs:D=PROBE_TIMEOUT_MS}=e,{token:O,source:k}=await resolveProbeTokenWithSource(g,S,w),j=`${githubApiBase(g)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(s)}`;log$2.info({host:g,tokenSource:k,tokenLen:O===void 0?0:O.length},`[permissions] probe starting`);let F=new AbortController,L=setTimeout(()=>F.abort(),D);try{let e=await E(j,{signal:F.signal,headers:buildHeaders(O)}),t=await classify(e,O!==void 0);return log$2.info({host:g,tokenSource:k,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return F.signal.aborted?(log$2.warn({host:g,timeoutMs:D},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(log$2.warn({err:e,host:g},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(L)}}async function checkPushPermission(e){let t=performance.now(),s=await runProbe(e);return recordProbeTelemetry(s,performance.now()-t),s}function outcomeAttributes(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let _outcomeCounter=null;function outcomeCounter(){return _outcomeCounter||=getMeter().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.`}),_outcomeCounter}let _durationHist=null;function durationHist(){return _durationHist||=getMeter().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),_durationHist}function recordProbeTelemetry(e,t){let s=outcomeAttributes(e);outcomeCounter().add(1,s),durationHist().record(t,{outcome:s.outcome})}function computeRemainingMs(e,t,s=Date.now()){if(!e)return 0;let g=new Date(e).getTime();if(Number.isNaN(g))return 0;let S=g+t*1e3;return Math.max(0,S-s)}const log$1=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i;function pushPermissionStatusFrom(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function pushPermissionStatusEqual(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function jitteredMs(e){let t=e*1e3,s=t*.15*(2*Math.random()-1);return Math.round(t+s)}function isUnbornHead(e){try{let t=join(e,`.git`,`HEAD`);if(!existsSync(t))return!1;let s=readFileSync(t,`utf-8`).trim(),g=/^ref:\s+(refs\/.+)$/.exec(s);if(!g)return!1;let S=g[1];if(existsSync(join(e,`.git`,S)))return!1;let w=join(e,`.git`,`packed-refs`);if(existsSync(w)){let e=readFileSync(w,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${S}$`,`m`).test(e))return!1}return!0}catch{return!1}}function backoffMs(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var SyncEngine=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;setBatchInProgress;onAutoDisable;detectGh;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.detectGh=e.detectGh,this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??checkPushPermission,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){log$1.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log$1.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log$1.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null,g=s!==null&&existsSync(s);if(this.conflictCount>0&&!g)log$1.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&g)try{let e=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
2828
2819
  `).map(e=>e.trim()).filter(Boolean):[]),s=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<s&&log$1.info({cleared:s-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log$1.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(g&&this.conflictCount===0){log$1.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),log$1.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let S=computeRemainingMs(this.lastFetchUtc,this.pullIntervalSeconds),w=computeRemainingMs(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(S>0?S:void 0),this.schedulePush(w>0?w:void 0),log$1.info({branch:this.currentBranch,pullDelayMs:S,pushDelayMs:w},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=3e4,t=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-t>3e4){log$1.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await setTimeout$1(50)}this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log$1.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):log$1.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?readSyncRemoteInfo(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=readOriginGitHubRepo(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,pushPermissionStatusEqual(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,log$1.info({caller:e,host:`github.com`,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let s;try{s=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:`github.com`,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){log$1.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),s={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let g=pushPermissionStatusFrom(s),S=this.pushPermission;this.pushPermission=g;let w=!1;return g.checkStatus===`denied`&&this.syncEnabled===!0?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),w=!0,log$1.info({reason:g.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):g.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.syncEnabled===!0&&this.transitionTo(`idle`),w=!0,log$1.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!w&&!pushPermissionStatusEqual(S,g)&&this.cc1Broadcaster?.signal(`sync-status`),g}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log$1.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!existsSync(join(this.projectDir,`.git`)))return!1;try{return(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log$1.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null;if(!(s!==null&&existsSync(s)))log$1.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),s=new Set(t?t.split(`
@@ -2836,6 +2827,6 @@ In headless mode, write the recap into the research article's "Further reading"
2836
2827
  `,`
2837
2828
  `).split(`
2838
2829
  `),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:s}of e)try{let e=readFileSync(s,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let s;try{s=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1}=e,J=getLogger(`server`);function Y(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||J.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ee=randomUUID(),te=getLocalDir(s);if(acquireServerLock(te,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:te,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(te),e}let ne=createBasenameIndex(),ae=(e,t)=>ne.resolveEmbed(e,t),oe=(e,s)=>{let g=ne.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g),w=resolve(t);if(S!==w&&!S.startsWith(`${w}/`))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},se,ce,ue,de,fe,me,ge,_e=null,ve=null,ye=null,Ce=null,we=null,Te=new Set,De=!1,je,Me,Pe,Ie=new Promise((e,t)=>{Me=e,Pe=t});function Re(e){_e?.signal(e)}let ze=2e3,Be=null;function Ve(){Be!==null&&clearTimeout(Be),Be=setTimeout(()=>{Be=null,ce.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let Ue=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),We=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||Ue.setRenamed(e,t)},Ge=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(Ue.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ue.setDeleted(e)}},Ke=e=>{isSystemDoc(e)||isConfigDoc(e)||Ue.delete(e)};try{se=createContentFilter({projectDir:s,contentDir:t,onAfterRebuild:()=>{ce.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{ue.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let{prunedFiles:e,prunedFolders:t}=reconcileFileIndexAfterFilterRebuild(Lt),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`)}}}),ce=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:se}),ue=new TagIndex({contentDir:t,contentFilter:se});try{ue.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}de={current:F},fe=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:de,contentRoot:L,backlinkIndex:ce,configHomedirOverride:k,getCurrentBranch:()=>Rt?.getLastKnownBranch()??null,resolveEmbed:ae,resolveSize:oe,getPrincipal:()=>we,onAgentCommit:()=>_e?.signal(`session-activity`),onDiskFlush:(e,t,s,g)=>{_e?.emitDiskAck(e,t),!(isSystemDoc(e)||isConfigDoc(e))&&assetReferencesChanged(g,s)&&(Ce?.(),Re(`files`))},onConfigRejected:(e,t)=>_e?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),me=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[fe.extension]});let B=me.shouldUnloadDocument.bind(me);me.shouldUnloadDocument=e=>{if(Te.has(e)||De&&B(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},je=async e=>{Te.add(e);try{await me.unloadDocument(e)}finally{Te.delete(e)}},_e=new CC1Broadcaster(me),ve=new AgentFocusBroadcaster(me),ye=new AgentPresenceBroadcaster(me),ge=new AgentSessionManager(me);let q=createLiveDerivedIndexExtension({backlinkIndex:ce,tagIndex:ue,signalChannel:Re});me.configuration.extensions.push(q),me.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==ee)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ee}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(we&&s.principalId===we.id?E.principalId=we.id:we?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:we.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),me.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,s=t.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s))throw Error(`config-doc admission requires loopback peer (peer=${s}, doc=${e.documentName})`);let g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let J=resolve(t);function Y(e){if(!isSafeDocName(e))return null;let t=resolve(J,`${e}${getDocExtension(e)}`);return!t.startsWith(`${J}/`)&&t!==J?null:t}me.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Ue,resolveFilePath:Y,fileExists:existsSync})}}),me.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let te=createApiExtension({hocuspocus:me,sessionManager:ge,contentDir:t,contentFilter:se,serverInstanceId:ee,getFileIndex:()=>Lt?Lt.getFileIndex():new Map,getFolderIndex:()=>Lt?Lt.getFolderIndex():new Map,getAliasMap:()=>Lt?Lt.getAliasMap():new Map,rescanFiles:()=>Lt?.rescanFromDisk(),enableTestRoutes:j,shadowRef:de,flushGitCommit:()=>fe.flushPendingGitCommit(),flushContributors:()=>fe.flushContributors(),takeStoreFailure:e=>fe.takeStoreFailure(e),takeStoreDivergence:e=>fe.takeStoreDivergence(e),markAgentWriteStore:e=>fe.markAgentWriteStore(e),getCurrentBranch:()=>Rt?.getLastKnownBranch()??null,getDiskAckSVs:()=>_e?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:ce,tagIndex:ue,signalChannel:Re,agentFocusBroadcaster:ve,agentPresenceBroadcaster:ye,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>zt,localOpCliArgs:H,projectDir:s,resolveEmbed:ae,getPrincipal:()=>we,forceUnloadDocument:je,ready:Ie,recentlyRemovedDocs:Ue,serializeDoc:it,onReferencedAssetsCacheInvalidator:e=>{Ce=e}});me.configuration.extensions.push(te),me.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:de,contentRoot:L,getCurrentBranch:()=>Rt?.getLastKnownBranch()??null,resolveEmbed:ae,resolveSize:oe})),me.configuration.extensions.push(createSyncHandshakeSpanExtension()),me.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>zt,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(te),e}let Xe=null,$e=new Map,nt=[];function rt(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function it(e){let t=me.documents.get(e);if(!t)return null;let{frontmatter:s,body:g}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(s,g)}let at=(e,t)=>applyExternalChange(me,e,t,ae,oe);function st(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let vt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of me.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=me.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,ae,s)},FILE_WATCHER_ORIGIN)}catch(t){J.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},Tt=null,Et=e=>{e&&(Tt===null&&(Tt=new Set,setImmediate(()=>{let e=Tt;if(Tt=null,e)try{for(let t of e)vt(t)}catch(t){J.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Tt.add(e))};function Dt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function jt(e){try{switch(e.kind){case`create`:J.info({docName:e.docName},`[reconcile] create: ${e.docName}`),ce.updateDocumentFromMarkdown(e.docName,e.content),Ve(),ue.updateDocumentFromMarkdown(e.docName,e.content),Re(`files`),Re(`backlinks`),Re(`graph`),Re(`tags`),Ke(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=me.documents.get(t);if(!g){ce.updateDocumentFromMarkdown(t,s),Ve(),ue.updateDocumentFromMarkdown(t,s),Re(`backlinks`),Re(`graph`),Re(`tags`);return}let S=getReconciledBase(t)??``,w=it(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(J.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:st(g),ce.updateDocumentFromMarkdown(t,s),Ve(),ue.updateDocumentFromMarkdown(t,s),Re(`backlinks`),Re(`graph`),Re(`tags`);break;case`clean`:try{at(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),st(g),ce.updateDocumentFromMarkdown(t,s),Ve(),ue.updateDocumentFromMarkdown(t,s),Re(`backlinks`),Re(`graph`),Re(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),st(g)}break;case`merged`:try{at(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),st(g),ce.updateDocumentFromMarkdown(t,s),Ve(),ue.updateDocumentFromMarkdown(t,s),Re(`backlinks`),Re(`graph`),Re(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),st(g)}break;case`conflicts`:try{at(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),ce.updateDocumentFromMarkdown(t,s),Ve(),ue.updateDocumentFromMarkdown(t,s),Re(`backlinks`),Re(`graph`),Re(`tags`)}catch(e){J.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=me.documents.get(t);if(!s){ce.deleteDocument(t),Ve(),ue.deleteDocument(t),Re(`files`),Re(`backlinks`),Re(`graph`),Re(`tags`),Ge(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=it(t)??``,w=S!==g;if(w&&de.current){let e=de.current,s=Rt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{J.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),ce.deleteDocument(t),Ve(),ue.deleteDocument(t),J.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),me.closeConnections(t),await je(s),Re(`files`),Re(`backlinks`),Re(`graph`),Re(`tags`),Ge(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:s,content:g}=e,S=me.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),ce.renameDocument(t,s,g),Ve(),ue.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}J.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),Re(`files`),Re(`backlinks`),Re(`graph`),Re(`tags`),We(t,s),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:s,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,s=me.documents.get(t);if(!s)return;let g=it(t);g===null?J.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`),J.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ne.add(e.relativePath),Re(`files`),Et(basename(e.relativePath));break;case`asset-delete`:ne.remove(e.relativePath),Re(`files`),Et(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Re(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Dt(e);J.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Mt=[];async function Ft(e){if(isBatchInProgress()){Mt.push(e);return}await jt(e)}async function It(){let e=Mt.splice(0,Mt.length);for(let t of e)await jt(t)}let Lt=null,Rt=null,zt=null,Bt=null;async function Vt(e){if(me.documents.size===0)return;let t=!1,s=new Promise(e=>{me.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(me.documents.keys());me.closeConnections(),me.flushPendingStores();for(let e of me.documents.values())e.getConnectionsCount()===0&&me.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(me.documents.keys()),S=[],E=[];if(de.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=it(e);if(t===null){J.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=rt(de.current.gitDir,e);if(!s){J.warn({docName:e,gitDir:de.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),J.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),J.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else J.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function Ht(){return Bt||(Bt=(async()=>{let e=Date.now(),t=[];De=!0,Be!==null&&(clearTimeout(Be),Be=null);let g,S=await Promise.race([Ie.then(()=>`completed`,e=>(J.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&J.warn({},`[server] init did not complete within 5s during shutdown`);let w=me.documents.size;try{try{try{Rt&&=(await Rt.unsubscribe(),null),Lt&&=(await Lt.unsubscribe(),null);for(let{docName:e,cleanup:t}of nt)try{await t()}catch(t){J.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}nt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{_e?.destroy(),ye?.destroy(),Xe&&=(await Xe.disconnect(),null);for(let[e,t]of $e)try{await t.disconnect()}catch(t){J.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}$e.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ge.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Vt(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await fe.flushPendingGitCommit(),await fe.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{zt&&=(await zt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(de.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(de.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(de.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?J.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):J.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(te)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Bt)}let Ut=[];async function Wt(){try{we=await loadPrincipal(s),J.info({principalId:we.id},`[server] principal loaded`)}catch(e){J.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!de.current)try{de.current=await initShadowRepo(s),J.info({gitDir:de.current.gitDir},`[server] history repo initialized at ${de.current.gitDir}`)}catch(e){J.error({err:e},`[server] history repo init failed`),Ut.push(`shadow-repo`)}if(de.current){let e=null;try{e=loadRenameLogIndex(de.current.gitDir),sweepLazyPopOrphans(de.current.gitDir,e),setRenameLogIndex(de.current.gitDir,e),J.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){J.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(de.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){J.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(de.current)try{await shadowGit(de.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){J.warn({},`[server] history repo appears corrupted — reinitializing`);try{de.current=await initShadowRepo(s)}catch(e){J.error({err:e},`[server] history repo reinit failed`),de.current=void 0,Ut.includes(`shadow-repo`)||Ut.push(`shadow-repo`)}}else J.error({err:e},`[server] history repo check failed (transient?)`)}if(de.current)try{let e=resolve(de.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==t){let e=`main`;try{let t=(await esm_default({baseDir:s,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}J.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(de.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){J.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else J.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){J.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){J.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,s);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,s=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;J.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){J.error({err:e},`[server] managed rename recovery failed`),Ut.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&J.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){J.error({err:e},`[server] upload-tempfile sweep failed`),Ut.push(`upload-tempfile-sweep`)}try{Xe=await me.openDirectConnection(SYSTEM_DOC_NAME),_e?.emitServerInfo(ee,getActiveBranch())}catch(e){J.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Ut.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await me.openDirectConnection(e);$e.set(e,t)}catch(t){J.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Ut.push(`config-doc:${e}`)}let g=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 CONFIG_DOC_NAMES){let t=g.get(e);if(t)try{J.info({docName:e,path:t},`[config-file-watcher] starting`);let s=await startConfigFileWatcher(t,t=>{let s=me.documents.get(e);J.info({docName:e,hasDocument:s!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,e,t,fe.configPersistenceCtx);if(J.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=Y();zt?.setEnabled(e).catch(t=>{J.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});nt.push({docName:e,cleanup:s}),J.info({docName:e,path:t},`[config-file-watcher] started`)}catch(s){J.warn({err:s,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Ut.push(`config-file-watcher:${e}`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:s,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(s,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(S=t)}}catch{}let w=S?[e,g,S]:[e,g],E=J;E.info({okignorePath:e,gitignorePath:g,gitInfoExcludePath:S},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let D=await startMultiPathConfigFileWatcher(w,(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(me.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,fe.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 se.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`),_e?.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`),_e?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});nt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`)}catch(e){J.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Ut.push(`ignore-files-watcher`)}let S=resolveGitDir(s),w=S?readBranchFromHead(S)??`main`:`main`;switchReconciledBaseScope(w),ce.switchBranch(w);try{{let e=getActiveBranch();try{if(await ce.loadFromDisk(e)){let t=await ce.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&J.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await ce.rebuildFromDisk(e);ce.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){J.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Lt=await startWatcher(t,Ft,se),ue.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:se,basenameIndex:ne,onSkip:(t,s,g)=>{e++,J.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during seed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Ut.push(`basename-index-partial`))}catch(e){J.error({err:e},`[basename-index] startup seed failed`),Ut.push(`basename-index`)}}catch(e){J.error({err:e},`[server] disk bridge watcher failed to start`),Ut.push(`file-watcher`)}try{Rt=await startHeadWatcher(s,async({trigger:e})=>{if(J.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),me.flushPendingStores(),await fe.flushPendingGitCommit(),setBatchInProgress(!0),de.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of me.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=it(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(de.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),J.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){J.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Mt.length,g=e.newBranch??`main`;if(J.info({kind:e.batchKind,headMoved:e.headMoved,docs:s,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${s}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await It(),await fe.flushDeferredStores(`within-branch`),zt!==null)try{await zt.reconcileConflictsFromGit()}catch(e){J.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Mt.splice(0,Mt.length),switchReconciledBaseScope(g),Be!==null&&(clearTimeout(Be),Be=null),ce.switchBranch(g),se.rebuildDirCount();try{let e=0;ne.clear(),seedBasenameIndex({contentDir:t,contentFilter:se,basenameIndex:ne,onSkip:(t,s,S)=>{e++,J.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Ut.includes(`basename-index-partial`)||Ut.push(`basename-index-partial`))}catch(e){J.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of me.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=it(e)??``;if(S!==t&&de.current){let t=de.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{J.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),J.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);at(e,w),setReconciledBase(e,w),J.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){J.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}J.info({branch:g,docCount:me.documents.size},`[branch-switch] loaded branch ${g} (${me.documents.size} docs)`);try{if(await ce.loadFromDisk(g)){let e=await ce.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&J.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await ce.rebuildFromDisk(g);ce.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){J.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(ue.init(),de.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of me.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(de.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:at(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:at(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=me.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){J.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&J.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&de.current)try{let t=shadowGit(de.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
2839
- `))e&&await t.raw(`update-ref`,`-d`,e);J.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){J.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await fe.flushDeferredStores(`discard-stale`),_e?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&de.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(de.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),J.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){J.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){J.error({err:e},`[server] HEAD watcher failed to start`),Ut.push(`head-watcher`)}function E(e){for(let g of e)try{let e=relative(t,join(s,g));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=me.documents.get(S);if(!w)continue;let E=it(S);E===null?J.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`),J.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){J.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let D=buildSyncCredentialArgs(H);try{zt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:se,contentRoot:L,syncEnabled:Y(),credentialArgs:D,cc1Broadcaster:_e,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||fe.flushDeferredStores(`within-branch`).catch(e=>{J.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{J.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:E,onAutoDisable:async e=>{J.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||J.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await zt.start()}catch(e){J.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),zt=null}Re(`files`),Re(`backlinks`),Re(`graph`),Re(`tags`)}return Wt().then(Me,Pe),{hocuspocus:me,sessionManager:ge,cc1Broadcaster:_e,agentFocusBroadcaster:ve,agentPresenceBroadcaster:ye,contentFilter:se,basenameIndex:ne,serverInstanceId:ee,destroy:Ht,ready:Ie,degraded:Ut,lockDir:te,get syncEngine(){return zt}}}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 LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){let t=resolveLocalSinkConfig({projectDir:e.projectDir??e.contentDir,contentDir:e.contentDir});if(t){let e=t.telemetry.attributeDenylist,s=[];for(let t of e){s.push(t);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)s.push(`${`*.`.repeat(e)}${t}`)}loggerFactory.configure({pinoConfig:{fileSink:t.logs,redactPaths:s}})}initTelemetry({localSink:t?.telemetry}),installServerMemoryGauge();let{kind:s,gitdir:g}=computeWorktreeAttributes(e.projectDir??e.contentDir),S={"ok.worktree.kind":s};return g!==null&&(S[`ok.worktree.gitdir`]=normalizeFsPath(g)),withSpan(`ok.boot`,{attributes:S},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-CyhBidkz-3npi9JMD.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore}),{hocuspocus:q,destroy:J,ready:Y,degraded:ee,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe}=H,se=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ce=e.port??0,ue=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${se}:${ce}`,log:S}),de=D();de.headersTimeout=3e4,de.requestTimeout=6e4;let fe=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,me=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),me=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await J().catch(()=>{}),e}let ge=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,_e=mountMcpAndApi({httpServer:de,hocuspocus:q,mcpHttpHandler:ue,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:fe,reactShellMiddleware:ge}),ve=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ye=null;g!==null&&(ye=attachIdleShutdown({httpServer:de,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ve()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);de.once(`error`,g),de.listen(e.port,e.host,()=>{de.removeListener(`error`,g),t()})})}catch(e){if(me)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await J().catch(()=>{}),e}let Ce=de.address(),we=typeof Ce==`object`&&Ce?Ce.port:e.port??0;if(ce=we,O(te,we),me&&updateUiLockPort(te,we),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Te=!1,De=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};return ve=async()=>{if(Te)return;Te=!0;let e=[],t=async(t,s)=>{try{await De(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{ye?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>_e.shutdown()),await t(`mcpHttpHandler.close`,()=>ue.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{_e.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{de.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{de.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>J()),me&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:de,destroy:ve,lockDir:te,contentDir:e.contentDir,port:we,ready:Y,degraded:ee,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
2830
+ `))e&&await t.raw(`update-ref`,`-d`,e);J.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){J.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await fe.flushDeferredStores(`discard-stale`),_e?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&de.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(de.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),J.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){J.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){J.error({err:e},`[server] HEAD watcher failed to start`),Ut.push(`head-watcher`)}function E(e){for(let g of e)try{let e=relative(t,join(s,g));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=me.documents.get(S);if(!w)continue;let E=it(S);E===null?J.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`),J.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){J.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let D=buildSyncCredentialArgs(H);try{zt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:se,contentRoot:L,syncEnabled:Y(),credentialArgs:D,cc1Broadcaster:_e,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||fe.flushDeferredStores(`within-branch`).catch(e=>{J.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{J.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:E,onAutoDisable:async e=>{J.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||J.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await zt.start()}catch(e){J.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),zt=null}Re(`files`),Re(`backlinks`),Re(`graph`),Re(`tags`)}return Wt().then(Me,Pe),{hocuspocus:me,sessionManager:ge,cc1Broadcaster:_e,agentFocusBroadcaster:ve,agentPresenceBroadcaster:ye,contentFilter:se,basenameIndex:ne,serverInstanceId:ee,destroy:Ht,ready:Ie,degraded:Ut,lockDir:te,get syncEngine(){return zt}}}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 LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){let t=resolveLocalSinkConfig({projectDir:e.projectDir??e.contentDir});if(t){let e=t.telemetry.attributeDenylist,s=[];for(let t of e){s.push(t);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)s.push(`${`*.`.repeat(e)}${t}`)}loggerFactory.configure({pinoConfig:{fileSink:t.logs,redactPaths:s}})}initTelemetry({localSink:t?.telemetry}),installServerMemoryGauge();let{kind:s,gitdir:g}=computeWorktreeAttributes(e.projectDir??e.contentDir),S={"ok.worktree.kind":s};return g!==null&&(S[`ok.worktree.gitdir`]=normalizeFsPath(g)),withSpan(`ok.boot`,{attributes:S},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-CyhBidkz-DrsmjbY0.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore}),{hocuspocus:q,destroy:J,ready:Y,degraded:ee,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe}=H,se=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ce=e.port??0,ue=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${se}:${ce}`,log:S}),de=D();de.headersTimeout=3e4,de.requestTimeout=6e4;let fe=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,me=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),me=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await J().catch(()=>{}),e}let ge=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,_e=mountMcpAndApi({httpServer:de,hocuspocus:q,mcpHttpHandler:ue,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:fe,reactShellMiddleware:ge}),ve=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ye=null;g!==null&&(ye=attachIdleShutdown({httpServer:de,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ve()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);de.once(`error`,g),de.listen(e.port,e.host,()=>{de.removeListener(`error`,g),t()})})}catch(e){if(me)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await J().catch(()=>{}),e}let Ce=de.address(),we=typeof Ce==`object`&&Ce?Ce.port:e.port??0;if(ce=we,O(te,we),me&&updateUiLockPort(te,we),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Te=!1,De=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};return ve=async()=>{if(Te)return;Te=!0;let e=[],t=async(t,s)=>{try{await De(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{ye?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>_e.shutdown()),await t(`mcpHttpHandler.close`,()=>ue.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{_e.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{de.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{de.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>J()),me&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:de,destroy:ve,lockDir:te,contentDir:e.contentDir,port:we,ready:Y,degraded:ee,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
2840
2831
  `).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!1});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 getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let w=``;try{w=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,w);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}export{StateManifestError as $,pathToDocName as $n,toBroadcasterKey as $r,ensureProjectGit as $t,MCP_CONNECTION_ID_HEADER as A,resolveConfigPath as Ai,isConfigDoc as An,runAuthReposSubprocess as Ar,containsConflictMarkers as At,ProjectGitInitError as B,listRescueCheckpoints as Bn,saveVersion as Br,createMcpHttpHandler as Bt,HocuspocusAuthRejection as C,JSONRPCMessageSchema as Ci,initShadowRepo as Cn,resolvePack as Cr,clearArmedPaneTarget as Ct,LOG_MD_TEMPLATE as D,isJSONRPCResultResponse as Di,installUserSkill as Dn,restoreLifecycleFromConflictsJson as Dr,commitWip as Dt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as E,isJSONRPCRequest as Ei,installTestLoggers as En,restoreContributors as Er,commitUpstreamImport as Et,MissingOkConfigError as F,resolveGitDirDetailed as Fi,isPathWithinDir as Fn,safeContentPath as Fr,createContentFilter as Ft,STARTER_FOLDERS as G,logsPreviousPath as Gn,shutdownTelemetry as Gr,createStreamingErrorWriter as Gt,ROOT_GITIGNORE_TEMPLATE as H,loadPrincipal as Hn,serializeError as Hr,createPersistenceExtension as Ht,OBSERVER_SYNC_ORIGIN as I,resolveShadowDir as Ii,isProjectRoot as In,safeSubdir as Ir,createContentFilterAsync as It,STARTER_PACK_IDS as J,packageVersionMajorMinor as Jn,spawnDetached as Jr,detectGit as Jt,STARTER_FOLDER_FRONTMATTER_FILENAME as K,mountMcpAndApi as Kn,spansCurrentPath as Kr,createTestLogger as Kt,OK_OKIGNORE_TEMPLATE as L,isSelfWrite as Ln,safetyCheckpoint as Lr,createExternalChangeHandler as Lt,MIN_GIT_VERSION as M,writeConfigPatch as Mi,isKnownPackId as Mn,runCloneSubprocess as Mr,contributorCount as Mt,MISSING_OK_CONFIG_MESSAGE as N,GitDirAccessError as Ni,isLoopbackAddress as Nn,runDeviceFlowSubprocess as Nr,createApiExtension as Nt,MANAGED_RENAME_ORIGIN as O,atomicWriteFileSync as Oi,isAllowedApiOrigin as On,rewriteMarkdownLinksForDocumentRename as Or,commitWipFromTree as Ot,McpLogger as P,MalformedGitPointerError as Pi,isPairedWriteOrigin as Pn,runWithMcpLogger as Pr,createAssetServeMiddleware as Pt,SeedRootDirError as Q,parseKeepaliveConnectionId as Qn,swapContributors as Qr,encodeFolderRoute as Qt,PANE_TARGET_TTL_MS as R,isSystemDoc as Rn,sanitizeClientName as Rr,createFileLogger as Rt,HOCUSPOCUS_AUTH_REJECTION_REASONS as S,McpServer as Si,initContent as Sn,resolveLockDir as Sr,classifyFsPath as St,INSTALLED_AGENTS_SCHEMES as T,isInitializedNotification as Ti,installPrettyZodErrors as Tn,resolveUiInfo as Tr,coercePackId as Tt,SERVICE_WRITER as U,loggerFactory as Un,setActiveSpanAttributes as Ur,createServer$1 as Ut,ROLLBACK_ORIGIN as V,listStarterPacks as Vn,seedBasenameIndex as Vr,createOsProbe as Vt,SKILL_INSTALL_EVENTS_FILE_REL as W,logsCurrentPath as Wn,shadowGit as Wr,createServerObserverExtension as Wt,STATE_MANIFEST_FILENAME as X,parseGitVersion as Xn,startWatcher as Xr,emitPreflightFailureSpan as Xt,STARTER_TEMPLATES as Y,parseAuthRejectionWire as Yn,splitMarkdownBlocks as Yr,detectProjectShape as Yt,SeedPrerequisiteError as Z,parseHocuspocusAuthToken as Zn,streamingProblemEvent as Zr,encodeDocName as Zt,FILE_WATCHER_ORIGIN as _,withSpanSync as _i,getTracer as _n,resetMetrics as _r,buildInstructions as _t,AgentPresenceBroadcaster as a,tracedRenameSync as ai,findEnclosingProjectRoot as an,readSkillInstallStateSnapshot as ar,applyAgentMarkdownWrite as at,GitNotAvailableError as b,writeTargetVersion as bi,incrementCollabSocketFilteredError as bn,resolveCursorBinaryDefault as br,buildWipTree as bt,BacklinkIndex as c,tracedUnlinkSync as ci,formatContributorsFrom as cn,readTargetVersion as cr,armPaneTarget as ct,CONFLICT_MARKER_RE as d,updateLastKnownHash as di,getLocalDir as dn,recordContributor as dr,assertNeverDiskEvent as dt,tracedAppendFileSync as ei,errorResponse as en,planSeed as er,TagIndex as et,CURSOR_BUNDLE_PATHS_BY_PLATFORM as f,updateUiLockPort as fi,getLogFilePath as fn,recordSkillInstallEvent as fr,attachIdleShutdown as ft,FILE_SYSTEM_WRITER as g,withSpan as gi,getMetrics as gn,removeLastKnownHash as gr,buildExecResult as gt,DEFAULT_PACK_ID as h,validateSkillZip as hi,getMeter as hn,releaseUiLock as hr,buildConfigYmlContent as ht,AgentFocusBroadcaster as i,tracedRename as ii,findEnclosingGitRoot as in,readServerPackageVersion as ir,acquireUiLock as it,MCP_SERVER_NAME as j,withFileLockSync as ji,isHocuspocusAuthRejectionReason as jn,runAuthStatusSubprocess as jr,contentHash as jt,MAX_AGENT_SESSIONS as k,readConfigSafely as ki,isAllowedWorkspaceHostHeader as kn,rewriteWikiLinksForDocumentRename as kr,compareSemver as kt,CC1Broadcaster as l,tracedWriteFile as li,gcCheckpointRefs as ln,readUiLock as lr,assertCompatibleStateManifest as lt,DEFAULT_CHECKPOINT_RETENTION as m,validateCloneInputs as mi,getLogsDir as mn,registerWrite as mr,buildAndOpenSkill as mt,AGENT_ID_RE as n,tracedMkdir as ni,extractWikiLinksFromMarkdown as nn,readArmedPaneTarget as nr,__getShowAllWalkStatsForTesting as nt,AgentSessionCapacityError as o,tracedRmSync as oi,formatAuthRejectionWire as on,readStateManifest as or,applyExternalChange as ot,ConfigSchema as p,validateAgentId as pi,getLogger as pn,registerAllTools as pr,bootServer as pt,STARTER_PACKS as q,normalizeFsPath as qn,spansPreviousPath as qr,detectClaudeDesktopPresence as qt,AGENT_WRITE_ORIGIN as r,tracedMkdirSync as ri,fallbackPaths as rn,readBranchFromHead as rr,__resetShowAllWalkStatsForTesting as rt,AgentSessionManager as s,tracedRmdirSync as si,formatContributors as sn,readTargetRecordedAt as sr,applySeed as st,AGENT_ID_MAX_LEN as t,tracedLinkSync as ti,evictStaleTrackerEntries as tn,readAllTargets as tr,UiLockCollisionError as tt,CONFIG_FILENAME as u,tracedWriteFileSync as ui,getCurrentMcpLogger as un,reconcile as ur,assertGitAvailable as ut,GIT_PREFLIGHT_FAIL_SPAN_NAME as v,writeRootGitignoreForNewRepo as vi,handleCollabSocketError as vn,resolveBundledSkillDir as vr,buildSkillZip as vt,HocuspocusAuthTokenSchema as w,LATEST_PROTOCOL_VERSION as wi,initTelemetry as wn,resolvePackageVersion as wr,clearContributors as wt,GitTooOldError as x,writeTracker as xi,incrementServerObserverFire as xn,resolveCursorSpawnInvocation as xr,classifyEvents as xt,GIT_UPSTREAM_WRITER as y,writeStateManifest as yi,handleSpawnCursor as yn,resolveContentDir as yr,buildStarterFolderFrontmatterYaml as yt,PinoLogger as z,lastKnownHash as zn,saveInMemoryCheckpoint as zr,createLiveDerivedIndexExtension as zt};
2841
- //# sourceMappingURL=dist-DmAclKYw.mjs.map
2832
+ //# sourceMappingURL=dist-BQBP5cHC.mjs.map