@inkeep/open-knowledge 0.12.0-beta.1 → 0.12.0-beta.10

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 (54) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +4 -2
  3. package/dist/cli.mjs +52 -51
  4. package/dist/constants-9x9AXDZ2.mjs +2 -0
  5. package/dist/dist-D08oqwBZ.mjs +1 -0
  6. package/dist/{dist-CwxIEsQy.mjs → dist-DYMUIJ9w.mjs} +23 -28
  7. package/dist/{gh-detect-ZscWDX6j.mjs → gh-detect-DW_FsIun.mjs} +2 -2
  8. package/dist/index.mjs +1 -1
  9. package/dist/{init-cNgVcMgm.mjs → init-CcBUeoop.mjs} +8 -8
  10. package/dist/init-pEDEgd4i.mjs +1 -0
  11. package/dist/{loader-BbZRKaRe.mjs → loader-B5YrEGVT.mjs} +2 -2
  12. package/dist/loader-DFGNk6Y9.mjs +1 -0
  13. package/dist/{preview-Cch3dAg-.mjs → preview-CrPN0LRt.mjs} +2 -2
  14. package/dist/preview-Dgx_ot95.mjs +1 -0
  15. package/dist/public/assets/{ActivityModeContent-GZhv_7zY.js → ActivityModeContent-BIXjc03A.js} +1 -1
  16. package/dist/public/assets/DocumentContext-D6GST2uS.js +61 -0
  17. package/dist/public/assets/{GraphPanel-BxSz8ewJ.js → GraphPanel-D8NK8BUZ.js} +9 -9
  18. package/dist/public/assets/SettingsDialogBody-Ciq3C1io.js +7 -0
  19. package/dist/public/assets/SourceEditor-wygB4ExR.js +2 -0
  20. package/dist/public/assets/config-validation-events-mfAOR8V6.js +12 -0
  21. package/dist/public/assets/index-C-eV_aX_.css +1 -0
  22. package/dist/public/assets/index-DmXCsqro.js +1915 -0
  23. package/dist/public/assets/{keyboard-shortcuts-D-vGKVvE.js → keyboard-shortcuts-B_OdnEM8.js} +1 -1
  24. package/dist/public/assets/prop-types-B5unaqIG.js +516 -0
  25. package/dist/public/assets/{target-navigation-intent-DoJxCilM.js → target-navigation-intent-B9alFb27.js} +1 -1
  26. package/dist/public/assets/{typing-burst-detector-BqgdHaVB.js → typing-burst-detector-BOYqYZUw.js} +2 -2
  27. package/dist/public/index.html +8 -8
  28. package/dist/{repair-launch-json-gd6HASZf.mjs → repair-launch-json-BuV6MEHd.mjs} +2 -2
  29. package/dist/{repair-mcp-configs-BnssYjl_.mjs → repair-mcp-configs-K9a1ICoC.mjs} +2 -2
  30. package/dist/repair-skills-Bd5SRSCR.mjs +1 -0
  31. package/dist/{repair-skills-BOitDE4c.mjs → repair-skills-kqwWqRQI.mjs} +2 -2
  32. package/dist/{server-lock-BpjJj3OD-Bdq_xi-m.mjs → server-lock-BpjJj3OD-D_v2bsKE.mjs} +98 -98
  33. package/dist/server-lock-CyhBidkz-CEUtTbEY.mjs +1 -0
  34. package/dist/{src-MX5K9NuJ.mjs → src-CcCtFIRo.mjs} +3 -3
  35. package/dist/start-C2IUVLQt.mjs +1 -0
  36. package/dist/{start-DMP-pK8D.mjs → start-CtEX0mUw.mjs} +2 -2
  37. package/dist/{write-project-skill-DWgAMoqR.mjs → write-project-skill-Bxha8awD.mjs} +2 -2
  38. package/package.json +1 -1
  39. package/scripts/aggregate-tolerance-class-fires.ts +19 -10
  40. package/dist/constants-_h4MuxhZ.mjs +0 -2
  41. package/dist/dist-C6QrChIn.mjs +0 -1
  42. package/dist/init-CqqSsx_m.mjs +0 -1
  43. package/dist/loader-MeX-PJd9.mjs +0 -1
  44. package/dist/preview-C8fzH3DO.mjs +0 -1
  45. package/dist/public/assets/DocumentContext-DEqAINIM.js +0 -61
  46. package/dist/public/assets/SettingsDialogBody-De8CYbo0.js +0 -7
  47. package/dist/public/assets/SourceEditor-CgoTeaoc.js +0 -2
  48. package/dist/public/assets/config-validation-events-DGvggCbG.js +0 -12
  49. package/dist/public/assets/index-BGjGm9hb.css +0 -1
  50. package/dist/public/assets/index-BqnZCAQU.js +0 -1915
  51. package/dist/public/assets/prop-types-D83J1kgl.js +0 -516
  52. package/dist/repair-skills-CvYIs6o7.mjs +0 -1
  53. package/dist/server-lock-CyhBidkz-C-zDqt0G.mjs +0 -1
  54. package/dist/start-HDBWGE_W.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 preprocess,$n as TemplateMoveRequestSchema,$r as prependFrontmatter,$t as MetricsReconciliationSuccessSchema,A as ApiConfigSuccessSchema,Ai as detectRemovedKeys,An as ServerInfoSuccessSchema,Ar as detectFmRegion,At as FrontmatterValueSchema,B as CC1DiskAckPayloadSchema,Bi as _enum,Bn as StreamingProblemEventSchema,Br as getHeadingSlug,Bt as LinkGraphSuccessSchema,C as AgentPatchSuccessSchema,Ci as DEFAULT_SPANS_MAX_BYTES,Cn as SearchRequestSchema,Cr as createBasenameIndex,Ct as EmptyRequestSchema,D as AgentWriteMdSuccessSchema,Dn as SeedListPacksSuccessSchema,Dr as createWorkspaceSearchDocument,Dt as ForwardLinksSuccessSchema,E as AgentWriteMdRequestSchema,Ei as OK_PROJECT_MARKER,En as SeedApplySuccessSchema,Er as createWorkspaceSearchCorpus,Et as FolderConfigPutSuccessSchema,F as BridgeMergeContentLossError,Fi as validatePatchScopes,Fn as SharePublishRequestSchema,Fr as expandTagToHierarchy,Ft as InstallSkillRequestSchema,G as CC1_CHANNEL_DISK_ACK,Gi as custom,Gn as SyncResolveConflictSuccessSchema,Gr as isFrontmatterValueEmpty,Gt as LocalOpCloneRequestSchema,H as CC1_CHANNEL_BRANCH_SWITCHED,Hn as SyncConflictContentSuccessSchema,Hr as getWikiLinkText,Ht as LocalOpAuthHostRequestSchema,I as CC1BranchSwitchedPayloadSchema,Ii as withConfigSpan,In as SharePublishResponseSchema,Ir as extractFrontmatterTags,It as InstallSkillSuccessSchema,J as CLIENT_VERSION_HEADER,Ji as literal,Jn as SyncTriggerSuccessSchema,Jr as isValidBranchName,Jt as LocalOpOkInitRequestSchema,K as CC1_CHANNEL_SERVER_INFO,Ki as discriminatedUnion,Kn as SyncStatusSchema,Kr as isHiddenDocName,Kt as LocalOpEmbeddingsMutationSuccessSchema,L as CC1ConfigIgnoreNestedErrorPayloadSchema,Li as withConfigSpanSync,Ln as SkillInstallStateSuccessSchema,Lr as fnv1aDigest,Lt as InstalledAgentsSuccessSchema,M as BacklinksSuccessSchema,Mi as isKnownConfigError,Mn as ShareConstructUrlResponseSchema,Mr as emitToleranceFire,Mt as HistoryVersionSuccessSchema,N as BranchInfoResponseSchema,Ni as locateIssue,Nn as SharePublishNameCheckResponseSchema,Nr as emptySkillState,Nt as HubsSuccessSchema,O as AgentWriteRequestSchema,Oi as addConfigSpanEvent,On as SeedPlanSuccessSchema,Or as defaultScheduler,Ot as FrontmatterPatchRequestSchema,P as BridgeInvariantViolationError,Pi as toConfigIssue,Pn as SharePublishOwnersResponseSchema,Pr as encodeShareUrl,Pt as INLINE_RENDERABLE_EXTENSIONS,Q as CONFIG_DOC_NAME_PROJECT_LOCAL,Qi as optional,Qn as TemplateGetSuccessSchema,Qr as parseFrontmatterYaml,Qt as MetricsParseHealthSuccessSchema,R as CC1ConfigValidationRejectedPayloadSchema,Rn as SkillStateSchema,Rr as formatFileSize,Rt as LINEAGE_EPOCH_KEY,S as AgentPatchRequestSchema,Sa as require_dist$1,Si as DEFAULT_LOGS_MAX_BYTES,Sn as SaveVersionSuccessSchema,Sr as colorFromSeed,St as EmbedDetectSuccessSchema,T as AgentUndoSuccessSchema,Ti as LOCAL_DIR,Tn as SeedApplyRequestSchema,Tr as createTagInTextRegex,Tt as FolderConfigPutRequestSchema,U as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ui as array,Un as SyncConflictsSuccessSchema,Ur as iconFromClientName,Ut as LocalOpAuthSetIdentityRequestSchema,V as CC1ServerInfoPayloadSchema,Vi as _null,Vn as SuggestLinksSuccessSchema,Vr as getParseHealth,Vt as LocalOpAuthEmptySuccessSchema,W as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Wi as boolean,Wn as SyncResolveConflictRequestSchema,Wr as isBranchNotFoundGitError,Wt as LocalOpAuthStatusSuccessSchema,X as CONFIG_DOC_NAME_OKIGNORE,Xi as number,Xn as TagsListSuccessSchema,Xr as mergeThreeWay,Xt as MarkdownManager,Y as CONFIG_DOC_NAMES,Yi as looseObject,Yn as TagsForNameSuccessSchema,Yr as mediaKindForSidebarAssetExtension,Yt as LocalOpOkInitResponseSchema,Z as CONFIG_DOC_NAME_PROJECT,Zi as object$1,Zn as TemplateDeleteSuccessSchema,Zr as normalizeBridge,Zt as MetricsAgentPresenceSuccessSchema,_ as AGENT_ICON_COLORS,_a as clone,_i as Fragment,_n as SKILL_STATE_TARGETS,_r as applyPatchToFm,_t as DocumentReadSuccessSchema,a as acquireProcessLock,aa as datetime,ai as resolveInternalHref,an as PageHeadingsSuccessSchema,ar as TestRescanBacklinksSuccessSchema,at as CreateFolderSuccessSchema,b as AgentActivitySuccessSchema,ba as $constructor,bi as DEFAULT_EMBEDDINGS_BASE_URL,bn as SYSTEM_DOC_NAME,br as classifyWikiLinkTarget,c as isValidLockPid,ca as describe$1,ci as sharedExtensions,cn as ProblemDetailsSchema,cr as TrashCleanupRequestSchema,ct as DEFAULT_DEDUP_MODE,da as $ZodType,di as toBridgeInvariantLog,dn as RescueListSuccessSchema,dr as UploadAssetSuccessSchema,ea as record,ei as previewEmbedFence,en as ORPHAN_MODES,er as TemplateMoveSuccessSchema,et as CheckoutRequestSchema,f as readServerLock,fa as parse$1,fi as toWikiLinkSlug,fn as RollbackRequestSchema,fr as UploadRequestSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as prettifyError,gi as PluginKey,gn as SKILL_STATE_REL,gr as applyIncrementalDiff,gt as DocumentListSuccessSchema,h as updateProcessLockPort,ha as safeParseAsync$1,hi as getSchema,hn as SANDBOXED_HTML_EXTENSIONS,hr as applyFastDiff,ht as DeletePathSuccessSchema,ii as resolveAssetProjectPath,in as PROTOCOL_VERSION,ir as TestFlushGitSuccessSchema,it as CreateFolderRequestSchema,j as BacklinkCountsSuccessSchema,ji as humanFormat,jn as ShareConstructUrlRequestSchema,jr as displayNameFromClientName,jt as HistorySuccessSchema,k as AgentWriteSuccessSchema,ki as applyPatchToDocument,kn as SemanticIndexStatusSchema,kr as detectAppliedToleranceClasses,kt as FrontmatterPatchSuccessSchema,la as meta$1,li as stripFrontmatter,ln as RenamePathRequestSchema,lr as TrashCleanupSuccessSchema,m as releaseServerLock,ma as safeParse$1,mi as validateDocName,mn as SANDBOXED_HTML_CSP,mr as WriteWarningSchema,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as union,ni as readFmMap,nn as PREVIEW_EMBED_STARTERS,nr as TemplatePutSuccessSchema,nt as ClientLogsRequestSchema,o as acquireServerLock,oa as toJSONSchema,oi as searchWorkspaceCorpus,on as PagesSuccessSchema,or as TestRescanFilesSuccessSchema,ot as CreatePageRequestSchema,p as releaseProcessLock,pa as parseAsync,pi as unwrapFrontmatterFences,pn as RollbackSuccessSchema,pr as WorkspaceSuccessSchema,pt as DeadLinksSuccessSchema,q as CC1_CONTRACT_VERSION,qi as intersection,qn as SyncTriggerRequestSchema,qr as isOrphanMode,qt as LocalOpEmbeddingsSetKeyRequestSchema,ra as unknown,ri as renderInventoryFooter,rn as PREVIEW_THEME_TOKENS,rr as TemplatesListSuccessSchema,rt as ClientLogsSuccessSchema,s as isProcessAlive,si as setToleranceTelemetryHook,sn as PrincipalSuccessSchema,sr as TestResetSuccessSchema,st as CreatePageSuccessSchema,t as ProcessLockCollisionError,ta as string,ti as projectFull,tn as OrphansSuccessSchema,tr as TemplatePutRequestSchema,tt as CheckoutResponseSchema,u as readProcessLock,ua as $ZodObject,ui as tagsMatchingPrefix,un as RenamePathSuccessSchema,ur as UA_PATTERNS,va as defineLazy,vi as CONFIG_SCHEMA_MAJOR_PATH,vn as SKILL_STATE_VERSION_RE,vr as assertNeverProblemType,vt as DuplicatePathRequestSchema,w as AgentUndoRequestSchema,wi as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,wn as SearchSuccessSchema,wr as createCodeFenceTracker,wt as FolderConfigGetSuccessSchema,x as AgentBurstDiffSuccessSchema,xi as DEFAULT_EMBEDDINGS_MODEL,xn as SaveVersionRequestSchema,xt as EXECUTABLE_BLOCKLIST_EXTENSIONS,y as ASSET_EXTENSIONS,ya as normalizeParams,yi as ConfigSchema$1,yr as classifyMarkdownHref,yt as DuplicatePathSuccessSchema,z as CC1DerivedViewPayloadSchema,zi as ZodOptional$1,zn as SpawnCursorSuccessSchema,zr as getAgentCanonicalDescriptors,zt as LINKABLE_ASSET_EXTENSIONS}from"./server-lock-BpjJj3OD-Bdq_xi-m.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-k1YlZnpm.mjs";import{a as require_src$15,i as simpleGit,n as withParentLock,r as esm_default,t as createGitInstance}from"./git-handle--dq7Gq14-C8bnaqHA.mjs";import{t as createPatch}from"./libesm-D3nlnq5U.mjs";import{n as mimes,t as build_default}from"./build-CJEQ0nGy.mjs";import{t as require_yazl}from"./yazl-CB0sfSbo.mjs";import{t as b1}from"./chunk-YNYSPYQ5-iQGTFdx0.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-ePq2jelx.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-DmvuPNqm.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-BWGDFyz_.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-D1Ufj9fh.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BP3kiNgH.mjs";import"./chunk-DXB73IDG-C2RuFAAY.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-BfIuRNkK.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-C6ngIqYR.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-DWhg7YHU.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-C-Zyd2K_.mjs";import{n as n$1}from"./chunk-3THT3N7L-Ce6LrnIA.mjs";import{t as n$2}from"./chunk-44UOCSGV-uErOrz7G.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import*as U from"node:path";import{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import crypto$1 from"crypto";import crypto$1$1,{createHash,randomUUID,webcrypto}from"node:crypto";import*as zlib$1 from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
1
+ import{a as __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 preprocess,$n as TemplateMoveRequestSchema,$r as prependFrontmatter,$t as MetricsReconciliationSuccessSchema,A as ApiConfigSuccessSchema,Ai as detectRemovedKeys,An as ServerInfoSuccessSchema,Ar as detectFmRegion,At as FrontmatterValueSchema,B as CC1DiskAckPayloadSchema,Bi as _enum,Bn as StreamingProblemEventSchema,Br as getHeadingSlug,Bt as LinkGraphSuccessSchema,C as AgentPatchSuccessSchema,Ci as DEFAULT_SPANS_MAX_BYTES,Cn as SearchRequestSchema,Cr as createBasenameIndex,Ct as EmptyRequestSchema,D as AgentWriteMdSuccessSchema,Dn as SeedListPacksSuccessSchema,Dr as createWorkspaceSearchDocument,Dt as ForwardLinksSuccessSchema,E as AgentWriteMdRequestSchema,Ei as OK_PROJECT_MARKER,En as SeedApplySuccessSchema,Er as createWorkspaceSearchCorpus,Et as FolderConfigPutSuccessSchema,F as BridgeMergeContentLossError,Fi as validatePatchScopes,Fn as SharePublishRequestSchema,Fr as expandTagToHierarchy,Ft as InstallSkillRequestSchema,G as CC1_CHANNEL_DISK_ACK,Gi as custom,Gn as SyncResolveConflictSuccessSchema,Gr as isFrontmatterValueEmpty,Gt as LocalOpCloneRequestSchema,H as CC1_CHANNEL_BRANCH_SWITCHED,Hn as SyncConflictContentSuccessSchema,Hr as getWikiLinkText,Ht as LocalOpAuthHostRequestSchema,I as CC1BranchSwitchedPayloadSchema,Ii as withConfigSpan,In as SharePublishResponseSchema,Ir as extractFrontmatterTags,It as InstallSkillSuccessSchema,J as CLIENT_VERSION_HEADER,Ji as literal,Jn as SyncTriggerSuccessSchema,Jr as isValidBranchName,Jt as LocalOpOkInitRequestSchema,K as CC1_CHANNEL_SERVER_INFO,Ki as discriminatedUnion,Kn as SyncStatusSchema,Kr as isHiddenDocName,Kt as LocalOpEmbeddingsMutationSuccessSchema,L as CC1ConfigIgnoreNestedErrorPayloadSchema,Li as withConfigSpanSync,Ln as SkillInstallStateSuccessSchema,Lr as fnv1aDigest,Lt as InstalledAgentsSuccessSchema,M as BacklinksSuccessSchema,Mi as isKnownConfigError,Mn as ShareConstructUrlResponseSchema,Mr as emitToleranceFire,Mt as HistoryVersionSuccessSchema,N as BranchInfoResponseSchema,Ni as locateIssue,Nn as SharePublishNameCheckResponseSchema,Nr as emptySkillState,Nt as HubsSuccessSchema,O as AgentWriteRequestSchema,Oi as addConfigSpanEvent,On as SeedPlanSuccessSchema,Or as defaultScheduler,Ot as FrontmatterPatchRequestSchema,P as BridgeInvariantViolationError,Pi as toConfigIssue,Pn as SharePublishOwnersResponseSchema,Pr as encodeShareUrl,Pt as INLINE_RENDERABLE_EXTENSIONS,Q as CONFIG_DOC_NAME_PROJECT_LOCAL,Qi as optional,Qn as TemplateGetSuccessSchema,Qr as parseFrontmatterYaml,Qt as MetricsParseHealthSuccessSchema,R as CC1ConfigValidationRejectedPayloadSchema,Rn as SkillStateSchema,Rr as formatFileSize,Rt as LINEAGE_EPOCH_KEY,S as AgentPatchRequestSchema,Sa as require_dist$1,Si as DEFAULT_LOGS_MAX_BYTES,Sn as SaveVersionSuccessSchema,Sr as colorFromSeed,St as EmbedDetectSuccessSchema,T as AgentUndoSuccessSchema,Ti as LOCAL_DIR,Tn as SeedApplyRequestSchema,Tr as createTagInTextRegex,Tt as FolderConfigPutRequestSchema,U as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ui as array,Un as SyncConflictsSuccessSchema,Ur as iconFromClientName,Ut as LocalOpAuthSetIdentityRequestSchema,V as CC1ServerInfoPayloadSchema,Vi as _null,Vn as SuggestLinksSuccessSchema,Vr as getParseHealth,Vt as LocalOpAuthEmptySuccessSchema,W as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Wi as boolean,Wn as SyncResolveConflictRequestSchema,Wr as isBranchNotFoundGitError,Wt as LocalOpAuthStatusSuccessSchema,X as CONFIG_DOC_NAME_OKIGNORE,Xi as number,Xn as TagsListSuccessSchema,Xr as mergeThreeWay,Xt as MarkdownManager,Y as CONFIG_DOC_NAMES,Yi as looseObject,Yn as TagsForNameSuccessSchema,Yr as mediaKindForSidebarAssetExtension,Yt as LocalOpOkInitResponseSchema,Z as CONFIG_DOC_NAME_PROJECT,Zi as object$1,Zn as TemplateDeleteSuccessSchema,Zr as normalizeBridge,Zt as MetricsAgentPresenceSuccessSchema,_ as AGENT_ICON_COLORS,_a as clone,_i as Fragment,_n as SKILL_STATE_TARGETS,_r as applyPatchToFm,_t as DocumentReadSuccessSchema,a as acquireProcessLock,aa as datetime,ai as resolveInternalHref,an as PageHeadingsSuccessSchema,ar as TestRescanBacklinksSuccessSchema,at as CreateFolderSuccessSchema,b as AgentActivitySuccessSchema,ba as $constructor,bi as DEFAULT_EMBEDDINGS_BASE_URL,bn as SYSTEM_DOC_NAME,br as classifyWikiLinkTarget,c as isValidLockPid,ca as describe$1,ci as sharedExtensions,cn as ProblemDetailsSchema,cr as TrashCleanupRequestSchema,ct as DEFAULT_DEDUP_MODE,da as $ZodType,di as toBridgeInvariantLog,dn as RescueListSuccessSchema,dr as UploadAssetSuccessSchema,ea as record,ei as previewEmbedFence,en as ORPHAN_MODES,er as TemplateMoveSuccessSchema,et as CheckoutRequestSchema,f as readServerLock,fa as parse$1,fi as toWikiLinkSlug,fn as RollbackRequestSchema,fr as UploadRequestSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as prettifyError,gi as PluginKey,gn as SKILL_STATE_REL,gr as applyIncrementalDiff,gt as DocumentListSuccessSchema,h as updateProcessLockPort,ha as safeParseAsync$1,hi as getSchema,hn as SANDBOXED_HTML_EXTENSIONS,hr as applyFastDiff,ht as DeletePathSuccessSchema,ii as resolveAssetProjectPath,in as PROTOCOL_VERSION,ir as TestFlushGitSuccessSchema,it as CreateFolderRequestSchema,j as BacklinkCountsSuccessSchema,ji as humanFormat,jn as ShareConstructUrlRequestSchema,jr as displayNameFromClientName,jt as HistorySuccessSchema,k as AgentWriteSuccessSchema,ki as applyPatchToDocument,kn as SemanticIndexStatusSchema,kr as detectAppliedToleranceClasses,kt as FrontmatterPatchSuccessSchema,la as meta$1,li as stripFrontmatter,ln as RenamePathRequestSchema,lr as TrashCleanupSuccessSchema,m as releaseServerLock,ma as safeParse$1,mi as validateDocName,mn as SANDBOXED_HTML_CSP,mr as WriteWarningSchema,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as union,ni as readFmMap,nn as PREVIEW_EMBED_STARTERS,nr as TemplatePutSuccessSchema,nt as ClientLogsRequestSchema,o as acquireServerLock,oa as toJSONSchema,oi as searchWorkspaceCorpus,on as PagesSuccessSchema,or as TestRescanFilesSuccessSchema,ot as CreatePageRequestSchema,p as releaseProcessLock,pa as parseAsync,pi as unwrapFrontmatterFences,pn as RollbackSuccessSchema,pr as WorkspaceSuccessSchema,pt as DeadLinksSuccessSchema,q as CC1_CONTRACT_VERSION,qi as intersection,qn as SyncTriggerRequestSchema,qr as isOrphanMode,qt as LocalOpEmbeddingsSetKeyRequestSchema,ra as unknown,ri as renderInventoryFooter,rn as PREVIEW_THEME_TOKENS,rr as TemplatesListSuccessSchema,rt as ClientLogsSuccessSchema,s as isProcessAlive,si as setToleranceTelemetryHook,sn as PrincipalSuccessSchema,sr as TestResetSuccessSchema,st as CreatePageSuccessSchema,t as ProcessLockCollisionError,ta as string,ti as projectFull,tn as OrphansSuccessSchema,tr as TemplatePutRequestSchema,tt as CheckoutResponseSchema,u as readProcessLock,ua as $ZodObject,ui as tagsMatchingPrefix,un as RenamePathSuccessSchema,ur as UA_PATTERNS,va as defineLazy,vi as CONFIG_SCHEMA_MAJOR_PATH,vn as SKILL_STATE_VERSION_RE,vr as assertNeverProblemType,vt as DuplicatePathRequestSchema,w as AgentUndoRequestSchema,wi as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,wn as SearchSuccessSchema,wr as createCodeFenceTracker,wt as FolderConfigGetSuccessSchema,x as AgentBurstDiffSuccessSchema,xi as DEFAULT_EMBEDDINGS_MODEL,xn as SaveVersionRequestSchema,xt as EXECUTABLE_BLOCKLIST_EXTENSIONS,y as ASSET_EXTENSIONS,ya as normalizeParams,yi as ConfigSchema$1,yr as classifyMarkdownHref,yt as DuplicatePathSuccessSchema,z as CC1DerivedViewPayloadSchema,zi as ZodOptional$1,zn as SpawnCursorSuccessSchema,zr as getAgentCanonicalDescriptors,zt as LINKABLE_ASSET_EXTENSIONS}from"./server-lock-BpjJj3OD-D_v2bsKE.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-k1YlZnpm.mjs";import{a as require_src$15,i as simpleGit,n as withParentLock,r as esm_default,t as createGitInstance}from"./git-handle--dq7Gq14-C8bnaqHA.mjs";import{t as createPatch}from"./libesm-D3nlnq5U.mjs";import{n as mimes,t as build_default}from"./build-CJEQ0nGy.mjs";import{t as require_yazl}from"./yazl-CB0sfSbo.mjs";import{t as b1}from"./chunk-YNYSPYQ5-iQGTFdx0.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-ePq2jelx.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-DmvuPNqm.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-BWGDFyz_.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-D1Ufj9fh.mjs";import{r as o$1}from"./chunk-CWQS3NFK-BP3kiNgH.mjs";import"./chunk-DXB73IDG-C2RuFAAY.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-BfIuRNkK.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-C6ngIqYR.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-DWhg7YHU.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-C-Zyd2K_.mjs";import{n as n$1}from"./chunk-3THT3N7L-Ce6LrnIA.mjs";import{t as n$2}from"./chunk-44UOCSGV-uErOrz7G.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import*as U from"node:path";import{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import crypto$1 from"crypto";import crypto$1$1,{createHash,randomUUID,webcrypto}from"node:crypto";import*as zlib$1 from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
2
2
  `)){let e=s.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let s=JSON.parse(e.slice(17));if(typeof s==`object`&&s&&`id`in s&&typeof s.id==`string`&&`name`in s&&typeof s.name==`string`&&`docs`in s&&Array.isArray(s.docs)&&s.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in s)||typeof s.colorSeed==`string`)){let e=s;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(s)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let s;try{s=JSON.parse(e.slice(18))}catch{return null}if(typeof s!=`object`||!s)return null;let g=s,S=g.kind,w=g.metadata;if(typeof w!=`object`||!w)return null;let E=typeof g.docName==`string`?g.docName:null,D=typeof g.size==`number`&&Number.isFinite(g.size)?g.size:null;if(S===`bridge-merge-loss`){let e=w;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:E,size:D,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(S===`external-change-rescue`){let e=w;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:E,size:D,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}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 ee(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 ee(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=ee})),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 ee=require_merge$3();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return ee.merge}});var J=require_timeout$3();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$3();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return Y.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return Y.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 ee(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(ee,4,e>>>0)},j.prototype.sfixed32=j.prototype.fixed32,j.prototype.fixed64=function(e){var t=S.from(e);return this._push(ee,4,t.lo)._push(ee,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 J=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(J,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 ee(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 ee(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=ee})),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 ee=require_timeout$2();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return ee.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return ee.callWithTimeout}});var J=require_url$2();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return J.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return J.urlMatches}});var Y=require_callback$2();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return Y.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,7 +771,7 @@ 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:ee,singleLine:J,timestampKey:Y,translateTime:te}=e,ne=e.errorProps.split(`,`),ae=typeof e.useOnlyCustomProps==`boolean`?e.useOnlyCustomProps:e.useOnlyCustomProps===`true`,oe=S(e.customLevels),se=w(e.customLevels),ce=E(ae,oe,se),ue;if(e.customColors)if(typeof e.customColors==`string`)ue=e.customColors.split(`,`).reduce((t,g)=>{let[S,w]=g.split(`:`),E=(ae?e.customLevels:se[S]!==void 0)?se[S]:s[S],D=E===void 0?S:E;return t.push([D,w]),t},[]);else if(typeof e.customColors==`object`)ue=Object.keys(e.customColors).reduce((t,g)=>{let[S,w]=[g,e.customColors[g]],E=(ae?e.customLevels:se[S]!==void 0)?se[S]:s[S],D=E===void 0?S:E;return t.push([D,w]),t},[]);else throw Error(`options.customColors must be of type string or object.`);let de={customLevels:oe,customLevelNames:se};ae===!0&&!e.customLevels&&(de.customLevels=void 0,de.customLevelNames=void 0);let fe=e.include===void 0?void 0:new Set(e.include.split(`,`)),me=!fe&&e.ignore?new Set(e.ignore.split(`,`)):void 0,ge=g(e.colorize,ue,ae),_e=e.colorizeObjects?ge:g(!1,[],!1);return{EOL:t,IDENT:` `,colorizer:ge,customColors:ue,customLevelNames:se,customLevels:oe,customPrettifiers:O,customProperties:de,errorLikeObjectKeys:k,errorProps:ne,getLevelLabelData:ce,hideObject:j,ignoreKeys:me,includeKeys:fe,levelFirst:F,levelKey:L,levelLabel:B,messageFormat:H,messageKey:q,minimumLevel:ee,objectColorizer:_e,singleLine:J,timestampKey:Y,translateTime:te,useOnlyCustomProps:ae}}})),require_fast_safe_stringify=__commonJSMin(((e,t)=>{t.exports=D,D.default=D,D.stable=F,D.stableStringify=F;var s=`[...]`,g=`[Circular]`,S=[],w=[];function E(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function D(e,t,s,g){g===void 0&&(g=E()),k(e,``,0,[],void 0,0,g);var D;try{D=w.length===0?JSON.stringify(e,t,s):JSON.stringify(e,B(t),s)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;S.length!==0;){var O=S.pop();O.length===4?Object.defineProperty(O[0],O[1],O[3]):O[0][O[1]]=O[2]}}return D}function O(e,t,s,g){var E=Object.getOwnPropertyDescriptor(g,s);E.get===void 0?(g[s]=e,S.push([g,s,t])):E.configurable?(Object.defineProperty(g,s,{value:e}),S.push([g,s,t,E])):w.push([t,s,e])}function k(e,t,S,w,E,D,j){D+=1;var F;if(typeof e==`object`&&e){for(F=0;F<w.length;F++)if(w[F]===e){O(g,e,t,E);return}if(j.depthLimit!==void 0&&D>j.depthLimit){O(s,e,t,E);return}if(j.edgesLimit!==void 0&&S+1>j.edgesLimit){O(s,e,t,E);return}if(w.push(e),Array.isArray(e))for(F=0;F<e.length;F++)k(e[F],F,F,w,e,D,j);else{var L=Object.keys(e);for(F=0;F<L.length;F++){var B=L[F];k(e[B],B,F,w,e,D,j)}}w.pop()}}function j(e,t){return e<t?-1:e>t?1:0}function F(e,t,s,g){g===void 0&&(g=E());var D=L(e,``,0,[],void 0,0,g)||e,O;try{O=w.length===0?JSON.stringify(D,t,s):JSON.stringify(D,B(t),s)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;S.length!==0;){var k=S.pop();k.length===4?Object.defineProperty(k[0],k[1],k[3]):k[0][k[1]]=k[2]}}return O}function L(e,t,w,E,D,k,F){k+=1;var B;if(typeof e==`object`&&e){for(B=0;B<E.length;B++)if(E[B]===e){O(g,e,t,D);return}try{if(typeof e.toJSON==`function`)return}catch{return}if(F.depthLimit!==void 0&&k>F.depthLimit){O(s,e,t,D);return}if(F.edgesLimit!==void 0&&w+1>F.edgesLimit){O(s,e,t,D);return}if(E.push(e),Array.isArray(e))for(B=0;B<e.length;B++)L(e[B],B,B,E,e,k,F);else{var H={},q=Object.keys(e).sort(j);for(B=0;B<q.length;B++){var ee=q[B];L(e[ee],ee,B,E,e,k,F),H[ee]=e[ee]}if(D!==void 0)S.push([D,t,e]),D[t]=H;else return H}E.pop()}}function B(e){return e=e===void 0?function(e,t){return t}:e,function(t,s){if(w.length>0)for(var g=0;g<w.length;g++){var S=w[g];if(S[1]===t&&S[0]===s){s=S[2],w.splice(g,1);break}}return e.call(this,t,s)}}})),require_prettify_error=__commonJSMin(((e,t)=>{t.exports=g;let s=require_join_lines_with_indentation();function g({keyName:e,lines:t,eol:g,ident:S}){let w=``,E=`${S}${e}: ${s({input:t,ident:S,eol:g})}${g}`.split(g);for(let e=0;e<E.length;e+=1){e!==0&&(w+=g);let t=E[e];if(/^\s*"stack"/.test(t)){let e=/^(\s*"stack":)\s*(".*"),?$/.exec(t);if(e&&e.length===3){let s=/^\s*/.exec(t)[0].length+4,S=` `.repeat(s),E=e[2];w+=e[1]+g+S+JSON.parse(E).replace(/\n/g,g+S)}else w+=t}else w+=t}return w}})),require_prettify_object=__commonJSMin(((e,t)=>{t.exports=E;let{LOGGER_KEYS:s}=require_constants(),g=require_fast_safe_stringify(),S=require_join_lines_with_indentation(),w=require_prettify_error();function E({log:e,excludeLoggerKeys:t=!0,skipKeys:E=[],context:D}){let{EOL:O,IDENT:k,customPrettifiers:j,errorLikeObjectKeys:F,objectColorizer:L,singleLine:B,colorizer:H}=D,q=[].concat(E);t===!0&&Array.prototype.push.apply(q,s);let ee=``,{plain:J,errors:Y}=Object.entries(e).reduce(({plain:t,errors:s},[g,S])=>{if(q.includes(g)===!1){let w=typeof j[g]==`function`?j[g](S,g,e,{colors:H.colors}):S;F.includes(g)?s[g]=w:t[g]=w}return{plain:t,errors:s}},{plain:{},errors:{}});return B?(Object.keys(J).length>0&&(ee+=L.greyMessage(g(J))),ee+=O,ee=ee.replace(/\\\\/gi,`\\`)):Object.entries(J).forEach(([e,t])=>{let s=typeof j[e]==`function`?t:g(t,null,2);if(s===void 0)return;s=s.replace(/\\\\/gi,`\\`);let w=S({input:s,ident:k,eol:O});ee+=`${k}${L.property(e)}:${w.startsWith(O)?``:` `}${w}${O}`}),Object.entries(Y).forEach(([e,t])=>{let s=typeof j[e]==`function`?t:g(t,null,2);s!==void 0&&(ee+=w({keyName:e,lines:s,eol:O,ident:k}))}),ee}})),require_prettify_error_log=__commonJSMin(((e,t)=>{t.exports=E;let{LOGGER_KEYS:s}=require_constants(),g=require_is_object(),S=require_join_lines_with_indentation(),w=require_prettify_object();function E({log:e,context:t}){let{EOL:E,IDENT:D,errorProps:O,messageKey:k}=t,j=e.stack,F=`${D}${S({input:j,ident:D,eol:E})}${E}`;if(O.length>0){let S=s.concat(k,`type`,`stack`),j;j=O[0]===`*`?Object.keys(e).filter(e=>S.includes(e)===!1):O.filter(e=>S.includes(e)===!1);for(let s=0;s<j.length;s+=1){let S=j[s];if(S in e){if(g(e[S])){let s=w({log:e[S],excludeLoggerKeys:!1,context:{...t,IDENT:D+D}});F=`${F}${D}${S}: {${E}${s}${D}}${E}`;continue}F=`${F}${D}${S}: ${e[S]}${E}`}}}return F}})),require_prettify_level=__commonJSMin(((e,t)=>{t.exports=g;let s=require_get_property_value();function g({log:e,context:t}){let{colorizer:g,customLevels:S,customLevelNames:w,levelKey:E,getLevelLabelData:D}=t,O=t.customPrettifiers?.level,k=s(e,E);if(k===void 0)return;let j=g(k,{customLevels:S,customLevelNames:w});if(O){let[t]=D(k);return O(k,E,e,{label:t,labelColorized:j,colors:g.colors})}return j}})),require_prettify_message=__commonJSMin(((e,t)=>{t.exports=w;let{LEVELS:s}=require_constants(),g=require_get_property_value(),S=require_interpret_conditionals();function w({log:e,context:t}){let{colorizer:w,customLevels:E,levelKey:D,levelLabel:O,messageFormat:k,messageKey:j,useOnlyCustomProps:F}=t;if(k&&typeof k==`string`){let t=S(k,e),j=String(t).replace(/{([^{}]+)}/g,function(t,S){let w;if(S===O&&(w=g(e,D))!==void 0)return(F?E===void 0:E[w]===void 0)?s[w]:E[w];let k=g(e,S);return k===void 0?``:k});return w.message(j)}if(k&&typeof k==`function`){let t=k(e,j,O,{colors:w.colors});return w.message(t)}if(j in e&&!(typeof e[j]!=`string`&&typeof e[j]!=`number`&&typeof e[j]!=`boolean`))return w.message(e[j])}})),require_prettify_metadata=__commonJSMin(((e,t)=>{t.exports=s;function s({log:e,context:t}){let{customPrettifiers:s,colorizer:g}=t,S=``;if(e.name||e.pid||e.hostname){if(S+=`(`,e.name&&(S+=s.name?s.name(e.name,`name`,e,{colors:g.colors}):e.name),e.pid){let t=s.pid?s.pid(e.pid,`pid`,e,{colors:g.colors}):e.pid;e.name&&e.pid?S+=`/`+t:S+=t}if(e.hostname){let t=s.hostname?s.hostname(e.hostname,`hostname`,e,{colors:g.colors}):e.hostname;S+=`${S===`(`?`on`:` on`} ${t}`}S+=`)`}if(e.caller){let t=s.caller?s.caller(e.caller,`caller`,e,{colors:g.colors}):e.caller;S+=`${S===``?``:` `}<${t}>`}if(S!==``)return S}})),require_prettify_time=__commonJSMin(((e,t)=>{t.exports=g;let s=require_format_time();function g({log:e,context:t}){let{timestampKey:g,translateTime:S}=t,w=t.customPrettifiers?.time,E=null;if(g in e?E=e[g]:`timestamp`in e&&(E=e.timestamp),E===null)return;let D=S?s(E,S):E;return w?w(D):`[${D}]`}})),require_utils=__commonJSMin(((e,t)=>{t.exports={buildSafeSonicBoom:require_build_safe_sonic_boom(),createDate:require_create_date(),deleteLogProperty:require_delete_log_property(),filterLog:require_filter_log(),formatTime:require_format_time(),getPropertyValue:require_get_property_value(),handleCustomLevelsNamesOpts:require_handle_custom_levels_names_opts(),handleCustomLevelsOpts:require_handle_custom_levels_opts(),interpretConditionals:require_interpret_conditionals(),isObject:require_is_object(),isValidDate:require_is_valid_date(),joinLinesWithIndentation:require_join_lines_with_indentation(),noop:require_noop(),parseFactoryOptions:require_parse_factory_options(),prettifyErrorLog:require_prettify_error_log(),prettifyError:require_prettify_error(),prettifyLevel:require_prettify_level(),prettifyMessage:require_prettify_message(),prettifyMetadata:require_prettify_metadata(),prettifyObject:require_prettify_object(),prettifyTime:require_prettify_time(),splitPropertyKey:require_split_property_key(),getLevelLabelData:require_get_level_label_data()}})),require_secure_json_parse=__commonJSMin(((e,t)=>{let s=typeof Buffer<`u`,g=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,S=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function w(e,t,w){w==null&&typeof t==`object`&&t&&(w=t,t=void 0),s&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let D=JSON.parse(e,t);if(typeof D!=`object`||!D)return D;let O=w&&w.protoAction||`error`,k=w&&w.constructorAction||`error`;if(O===`ignore`&&k===`ignore`)return D;if(O!==`ignore`&&k!==`ignore`){if(g.test(e)===!1&&S.test(e)===!1)return D}else if(O!==`ignore`&&k===`ignore`){if(g.test(e)===!1)return D}else if(S.test(e)===!1)return D;return E(D,{protoAction:O,constructorAction:k,safe:w&&w.safe})}function E(e,{protoAction:t=`error`,constructorAction:s=`error`,safe:g}={}){let S=[e];for(;S.length;){let e=S;S=[];for(let w of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(w,`__proto__`)){if(g===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete w.__proto__}if(s!==`ignore`&&Object.prototype.hasOwnProperty.call(w,`constructor`)&&w.constructor!==null&&typeof w.constructor==`object`&&Object.prototype.hasOwnProperty.call(w.constructor,`prototype`)){if(g===!0)return null;if(s===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete w.constructor}for(let e in w){let t=w[e];t&&typeof t==`object`&&S.push(t)}}}return e}function D(e,t,s){let{stackTraceLimit:g}=Error;Error.stackTraceLimit=0;try{return w(e,t,s)}finally{Error.stackTraceLimit=g}}function O(e,t){let{stackTraceLimit:s}=Error;Error.stackTraceLimit=0;try{return w(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=s}}t.exports=D,t.exports.default=D,t.exports.parse=D,t.exports.safeParse=O,t.exports.scan=E})),require_pretty=__commonJSMin(((e,t)=>{t.exports=q;let s=require_secure_json_parse(),g=require_is_object(),S=require_prettify_error_log(),w=require_prettify_level(),E=require_prettify_message(),D=require_prettify_metadata(),O=require_prettify_object(),k=require_prettify_time(),j=require_filter_log(),{LEVELS:F,LEVEL_KEY:L,LEVEL_NAMES:B}=require_constants(),H=e=>{try{return{value:s.parse(e,{protoAction:`remove`})}}catch(e){return{err:e}}};function q(e){let t;if(g(e))t=e;else{let s=H(e);if(s.err||!g(s.value))return e+this.EOL;t=s.value}if(this.minimumLevel){let e;e=this.useOnlyCustomProps?this.customLevels:this.customLevelNames[this.minimumLevel]!==void 0;let s;if(s=e?this.customLevelNames[this.minimumLevel]:B[this.minimumLevel],s||=typeof this.minimumLevel==`string`?B[this.minimumLevel]:B[F[this.minimumLevel].toLowerCase()],t[this.levelKey===void 0?L:this.levelKey]<s)return}let s=E({log:t,context:this.context});(this.ignoreKeys||this.includeKeys)&&(t=j({log:t,context:this.context}));let q=w({log:t,context:{...this.context,...this.context.customProperties}}),ee=D({log:t,context:this.context}),J=k({log:t,context:this.context}),Y=``;if(this.levelFirst&&q&&(Y=`${q}`),J&&Y===``?Y=`${J}`:J&&(Y=`${Y} ${J}`),!this.levelFirst&&q&&(Y=Y.length>0?`${Y} ${q}`:q),ee&&(Y=Y.length>0?`${Y} ${ee}:`:ee),Y.endsWith(`:`)===!1&&Y!==``&&(Y+=`:`),s!==void 0&&(Y=Y.length>0?`${Y} ${s}`:s),Y.length>0&&!this.singleLine&&(Y+=this.EOL),t.type===`Error`&&typeof t.stack==`string`){let e=S({log:t,context:this.context});this.singleLine&&(Y+=this.EOL),Y+=e}else if(this.hideObject===!1){let e=[this.messageKey,this.levelKey,this.timestampKey].map(e=>e.replaceAll(/\\/g,``)).filter(e=>typeof t[e]==`string`||typeof t[e]==`number`||typeof t[e]==`boolean`),s=O({log:t,skipKeys:e,context:this.context});this.singleLine&&!/^\s$/.test(s)&&(Y+=` `),Y+=s}return Y}})),require_pino_pretty=__commonJSMin(((e,t)=>{let{isColorSupported:s}=require_colorette(),g=require_pump(),{Transform:S}=__require(`node:stream`),w=require_pino_abstract_transport(),E=require_colors(),{ERROR_LIKE_KEYS:D,LEVEL_KEY:O,LEVEL_LABEL:k,MESSAGE_KEY:j,TIMESTAMP_KEY:F}=require_constants(),{buildSafeSonicBoom:L,parseFactoryOptions:B}=require_utils(),H=require_pretty(),q={colorize:s,colorizeObjects:!0,crlf:!1,customColors:null,customLevels:null,customPrettifiers:{},errorLikeObjectKeys:D,errorProps:``,hideObject:!1,ignore:`hostname`,include:void 0,levelFirst:!1,levelKey:O,levelLabel:k,messageFormat:null,messageKey:j,minimumLevel:void 0,outputStream:process.stdout,singleLine:!1,timestampKey:F,translateTime:!0,useOnlyCustomProps:!0};function ee(e){let t=B(Object.assign({},q,e));return H.bind({...t,context:t})}function J(e={}){let t=ee(e),s;return w(function(w){w.on(`message`,function s(g){!g||g.code!==`PINO_CONFIG`||(Object.assign(e,{messageKey:g.config.messageKey,errorLikeObjectKeys:Array.from(new Set([...e.errorLikeObjectKeys||D,g.config.errorKey])),customLevels:g.config.levels.values}),t=ee(e),w.off(`message`,s))});let E=new S({objectMode:!0,autoDestroy:!0,transform(e,s,g){g(null,t(e))}});return s=typeof e.destination==`object`&&typeof e.destination.write==`function`?e.destination:L({dest:e.destination||1,append:e.append,mkdir:e.mkdir,sync:e.sync}),w.on(`unknown`,function(e){s.write(e+`
774
- `)}),g(w,E,s),E},{parse:`lines`,close(e,t){s.on(`close`,()=>{t(e)})}})}t.exports=J,t.exports.build=J,t.exports.PinoPretty=J,t.exports.prettyFactory=ee,t.exports.colorizerFactory=E,t.exports.isColorSupported=s,t.exports.default=J})),import_pino=__toESM(require_pino(),1),import_pino_pretty=__toESM(require_pino_pretty(),1),RotatingAppender=class{#e;#t;#n;#r=Promise.resolve();#i=!1;constructor(e){this.#e=e.currentPath,this.#t=e.previousPath,this.#n=e.maxBytes}append(e){let t=this.#r.catch(()=>void 0).then(()=>this.#a(e));return this.#r=t,t}async drain(){await this.#r.catch(()=>void 0)}async#a(e){this.#i||=(await mkdir(dirname(this.#e),{recursive:!0}),!0),await writeFile(this.#e,e,{flag:`a`});let t;try{t=statSync(this.#e).size}catch{this.#i=!1;return}t>this.#n&&await rename(this.#e,this.#t)}};const TELEMETRY_SUBDIR=[`.ok`,`local`,`telemetry`],CURRENT_FILENAME=`spans-current.jsonl`,PREVIOUS_FILENAME=`spans-prev.jsonl`;function spansCurrentPath(e){return join(e,...TELEMETRY_SUBDIR,CURRENT_FILENAME)}function spansPreviousPath(e){return join(e,...TELEMETRY_SUBDIR,PREVIOUS_FILENAME)}var FileSpanExporter=class{#e;#t=!1;constructor(e){this.#e=new RotatingAppender({currentPath:spansCurrentPath(e.projectDir),previousPath:spansPreviousPath(e.projectDir),maxBytes:e.maxBytes})}export(e,t){if(this.#t){t({code:import_src.ExportResultCode.FAILED,error:Error(`FileSpanExporter: export called after shutdown`)});return}if(e.length===0){t({code:import_src.ExportResultCode.SUCCESS});return}let s=import_src$1.JsonTraceSerializer.serializeRequest(e);if(!s||s.byteLength===0){t({code:import_src.ExportResultCode.SUCCESS});return}let g=new Uint8Array(s.byteLength+1);g.set(s),g[s.byteLength]=10,this.#e.append(g).then(()=>t({code:import_src.ExportResultCode.SUCCESS}),e=>t({code:import_src.ExportResultCode.FAILED,error:e instanceof Error?e:Error(String(e))}))}async shutdown(){this.#t=!0,await this.#e.drain()}async forceFlush(){await this.#e.drain()}};const REDACTED_SENTINEL=`[REDACTED]`,KEY_BOUNDARY_CHARS=new Set([`.`,`/`,`_`]);function keyMatchesDenylist(e,t){if(t.has(e))return!0;for(let s of t){if(s.length===0||e.length<=s.length||!e.endsWith(s))continue;let t=e.charAt(e.length-s.length-1);if(KEY_BOUNDARY_CHARS.has(t))return!0}return!1}function scrubAttributes(e,t,s){for(let g of Object.keys(e)){let S=e[g];if(S!==void 0){if(keyMatchesDenylist(g.toLowerCase(),t)){e[g]=REDACTED_SENTINEL;continue}if(typeof S==`string`){let t=Buffer.byteLength(S,`utf-8`);t>s&&(e[g]=`[TRUNCATED:${t}]`)}}}}var ScrubbingSpanProcessor=class{#e;#t;constructor(e){this.#e=new Set(e.attributeDenylist.map(e=>e.toLowerCase())),this.#t=e.maxValueBytes??4096}onStart(e,t){}onEnd(e){scrubAttributes(e.attributes,this.#e,this.#t);for(let t of e.events)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t);for(let t of e.links)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t)}async forceFlush(){}async shutdown(){}};const LOGS_SUBDIR=[`.ok`,`local`,`logs`],LOGS_CURRENT_FILENAME=`server-current.jsonl`,LOGS_PREVIOUS_FILENAME=`server-prev.jsonl`;function logsCurrentPath(e){return join(e,...LOGS_SUBDIR,LOGS_CURRENT_FILENAME)}function logsPreviousPath(e){return join(e,...LOGS_SUBDIR,LOGS_PREVIOUS_FILENAME)}var PinoFileSink=class extends Writable{#e;constructor(e){super({decodeStrings:!1}),this.#e=new RotatingAppender({currentPath:logsCurrentPath(e.projectDir),previousPath:logsPreviousPath(e.projectDir),maxBytes:e.maxBytes})}_write(e,t,s){this.#e.append(e).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}async drain(){await this.#e.drain()}};function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}const VALID_LOG_LEVELS=new Set([`fatal`,`error`,`warn`,`info`,`debug`,`trace`,`silent`]);function logLevelRank(e){return e===`silent`?1/0:import_pino.default.levels.values[e]??import_pino.default.levels.values.info}function mostVerboseLevel(e,t){return logLevelRank(e)<=logLevelRank(t)?e:t}var PinoLogger=class{name;transportConfigs=[];fileSinkOpts;redactPaths;activeFileSink;pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),t.fileSink&&(this.fileSinkOpts=t.fileSink),t.redactPaths&&t.redactPaths.length>0&&(this.redactPaths=t.redactPaths,this.options={...this.options,redact:{paths:[...t.redactPaths],censor:`[REDACTED]`}}),this.pinoInstance=this.buildInstance()}resolveStreamLevels(){let e=this.options.level??`info`,t=process.env.OK_CONSOLE_LEVEL?.toLowerCase(),s=t&&VALID_LOG_LEVELS.has(t)?t:e;return{fileLevel:e,consoleLevel:s,instanceLevel:mostVerboseLevel(e,s)}}buildInstance(){this.activeFileSink=void 0;let{fileLevel:e,consoleLevel:t,instanceLevel:s}=this.resolveStreamLevels();if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));let g;try{g=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`})}catch(g){if(console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,g),this.fileSinkOpts){let t=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=t,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:t,level:e}]))}return(0,import_pino.default)({...this.options,level:t})}if(this.fileSinkOpts){let S=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=S,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:g,level:t},{stream:S,level:e}]))}return(0,import_pino.default)({...this.options,level:t},g)}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}reconfigure(e){e.options&&(this.options={...this.options,...e.options}),e.transportConfigs&&(this.transportConfigs=e.transportConfigs),e.fileSink&&(this.fileSinkOpts=e.fileSink),e.redactPaths&&e.redactPaths.length>0&&(this.redactPaths=e.redactPaths,this.options={...this.options,redact:{paths:[...e.redactPaths],censor:`[REDACTED]`}}),this.recreateInstance()}getPinoInstance(){return this.pinoInstance}async flushFileSink(){this.activeFileSink&&await this.activeFileSink.drain()}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){if(this.config=e,e.pinoConfig&&!e.defaultLogger&&!e.loggerFactory){for(let t of this.loggers.values())t.reconfigure(e.pinoConfig);return}this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let s;return s=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,s),s}reset(){this.config={},this.loggers.clear()}async flushAllFileSinks(){let e=[];for(let t of this.loggers.values())e.push(t.flushFileSink());await Promise.all(e)}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(s=>({...s,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:s,...g}=t;return g})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let s=t.getLocalState()??{},g=e(s.agentFocus??{});t.setLocalState({...s,agentFocus:g})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,mapDrivenSpliceApplied:0,mapDrivenSpliceFallback:{},observerAResidualMergeRuns:0,bridgeSplitBrainRederives:0,bridgeSplitBrainRederivesSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0,authDocLineageMismatchCount:0,authDocLineageGuardErrors:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementMapDrivenSpliceApplied(){counters$1.mapDrivenSpliceApplied++}function incrementMapDrivenSpliceFallback(e){counters$1.mapDrivenSpliceFallback[e]=(counters$1.mapDrivenSpliceFallback[e]??0)+1}function incrementObserverAResidualMergeRuns(){counters$1.observerAResidualMergeRuns++}function incrementBridgeSplitBrainRederives(){counters$1.bridgeSplitBrainRederives++}function incrementBridgeSplitBrainRederivesSuppressed(){counters$1.bridgeSplitBrainRederivesSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementAuthDocLineageMismatch(){counters$1.authDocLineageMismatchCount++}function incrementAuthDocLineageGuardError(){counters$1.authDocLineageGuardErrors++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied},mapDrivenSpliceFallback:{...counters$1.mapDrivenSpliceFallback}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.mapDrivenSpliceApplied=0,counters$1.mapDrivenSpliceFallback={},counters$1.observerAResidualMergeRuns=0,counters$1.bridgeSplitBrainRederives=0,counters$1.bridgeSplitBrainRederivesSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0,counters$1.authDocLineageMismatchCount=0,counters$1.authDocLineageGuardErrors=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let s=0;this.mutateAgentPresence(g=>{let S=Date.now(),w={};for(let[t,E]of Object.entries(g)){if(S-E.ts>=2e4&&t!==e){s++;continue}w[t]=E}return w[e]=t,w})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),s>0&&this.log.info({evictedCount:s,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(s=>{if(!s[e])return s;t=!0;let{[e]:g,...S}=s;return S})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let s=[],g=!1,S=this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;g=!0;let E=Date.now();return s.push({currentDoc:w.currentDoc,ts:E}),{...S,[e]:{...w,mode:t,ts:E}}}),w=s[0];S&&w?this.log.debug({agentId:e,action:`touchMode`,currentDoc:w.currentDoc,ts:w.ts,mode:t},`[agent-presence] touchMode`):g||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(s=>{let g=s[e];if(!g)return s;let S=Date.now();return t=S,{...s,[e]:{...g,ts:S}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let s=t.getLocalState()??{},g=e(s.agentPresence??{});return t.setLocalState({...s,agentPresence:g}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null,fileSpanExporter=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(e={}){let t=e.localSink!==void 0,s=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!s||tracerProvider)return noopResult();try{let g=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),S=new import_src$2.AsyncLocalStorageContextManager;context.setGlobalContextManager(S);let w=[],E=e.localSink?.attributeDenylist??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;w.push(new ScrubbingSpanProcessor({attributeDenylist:E})),t&&e.localSink!==void 0&&(fileSpanExporter=new FileSpanExporter({projectDir:e.localSink.projectDir,maxBytes:e.localSink.spansMaxBytes}),w.push(new import_src$7.SimpleSpanProcessor(fileSpanExporter))),s&&w.push(new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter));let D=new import_src$7.BasicTracerProvider({resource:g,spanProcessors:w});trace.setGlobalTracerProvider(D),tracerProvider=D;try{propagation.setGlobalPropagator(new import_src.W3CTraceContextPropagator)}catch(e){getLogger(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let O=null;s&&(O=new import_src$6.MeterProvider({resource:g,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]}),metrics.setGlobalMeterProvider(O)),meterProvider=O,getLogger(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:s,otlp_endpoint:s?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:g.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized`)}catch(e){let t=getLogger(`telemetry`);tracerProvider===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),meterProvider=null,fileSpanExporter=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),meterProvider=null)}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3,shutdownHooks=new Set;function onTelemetryShutdown(e){shutdownHooks.add(e)}async function shutdownTelemetry(){let e=getLogger(`telemetry`);for(let t of shutdownHooks)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!tracerProvider&&!meterProvider)return;let t=(fileSpanExporter?fileSpanExporter.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),s;await Promise.race([t.then(()=>(s!==void 0&&clearTimeout(s),!1)),new Promise(e=>{s=setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS),s.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,fileSpanExporter=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,s){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await s(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,s){return getTracer().startActiveSpan(e,t??{},e=>{try{return s(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,s,g){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:s,"body.bytes":t.length,"doc.name":e.guid}},()=>{let s=e.getXmlFragment(`default`),S=e.getText(`source`),w=S.toString(),{body:E}=stripFrontmatter(t),D=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":E.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(E,buildParseOpts(g))),O=schema.nodeFromJSON(D);w!==t&&applyFastDiff(S,w,t),updateYFragment(e,s,O,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,s){withSpanSync(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let g=e.getXmlFragment(`default`),S=e.getText(`source`),{body:w}=stripFrontmatter(t),E=mdManager.parseWithFallback(w,buildParseOpts(s)),D=schema.nodeFromJSON(E),O=S.toString();O!==t&&(S.delete(0,O.length),S.insert(0,t)),updateYFragment(e,g,D,{mapping:new Map,isOMark:new Map})})}function deriveFragmentFromYtext(e,t){let s=e.getXmlFragment(`default`),{body:g}=stripFrontmatter(e.getText(`source`).toString()),S=mdManager.parseWithFallback(g,buildParseOpts(t));updateYFragment(e,s,schema.nodeFromJSON(S),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(e)??0)+1;this.seqs.set(e,s);let g=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:s});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(e,s),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let g=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});s.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,s);let g=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:s,branch:e});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,s)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,g);let S=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:g,docName:e,sv:Buffer.from(t).toString(`base64`)});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,s]of this.latestDiskAckSVs)e[t]=Buffer.from(s).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g);let S=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:g,docName:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g);let S=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:g,path:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let s=extname(e).slice(1).toLowerCase();return s.length>0&&t.has(s)}function stripDocExtension(e){let t=e.toLowerCase();for(let s of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(s))return e.slice(0,-s.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let s=canonicalize(t);if(!s)throw Error(`registerDocExtension: unsupported extension "${t}"`);let g=docExtensionByName.get(e);if(!g)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let S=canonicalize(g);return S?S===s?{effective:g,changed:!1,shadowed:null}:rank(s)<rank(S)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g}):{effective:g,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$13=()=>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$13().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$13().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$13()[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$13().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$13().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$13()[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$13().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$13().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$12=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$12.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$12.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$12.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$12.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$12.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,s=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));s.length>0&&await Promise.allSettled(s.map(e=>this.pendingSessions.get(e)));let g=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of g){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,s=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of s){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,s,g){let S=e.doc;if(!S)return;let w=++_effectCounter,E=S.getMap(`agent-effects`),D=k=>{e.unobserve(D),S.off(`destroy`,O);let j=`${t}:${w}`,F={sessionId:t,timestamp:Date.now(),delta:k.delta,agent_type:g??`agent`,color_seed:s??t};try{S.transact(()=>{if(E.set(j,F),E.size>RING_BUFFER_LIMIT){let e=[...E.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,E.size-RING_BUFFER_LIMIT))E.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let s=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:s})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},O=()=>{e.unobserve(D)};e.observe(D),S.once(`destroy`,O)}function collectItemsInDeleteSet(e,t,s){iterateDeletedStructs(e,t,e=>{e instanceof Item&&s.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let s=[],g=[],S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=``,O=``,k=0,j=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,S=t.length,F=w.has(e),L=E.has(e);e.deleted?L&&(g.push({position:k,content:t,length:S}),D+=t,k+=S):(O+=t,F?s.push({position:j,content:t,length:S}):(D+=t,k+=S),j+=S)}return{insertions:s,deletions:g,before:D,after:O}}function synthesizeStackItemDiffText(e,t,s){let{before:g,after:S}=synthesizeStackItemDiff(e,t);return g===S?``:createPatch(s,g,S,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let s=t.doc,g=new Set,S=new Set;s&&s.transact(t=>{collectItemsInDeleteSet(t,e.insertions,g),collectItemsInDeleteSet(t,e.deletions,S)});let w=0,E=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&g.has(e)&&(w+=t),S.has(e)&&(E+=t)}return{additions:w,deletions:E}}function listAgentActivity(e,t){let s=[],g=null,S=!1;for(let w of e.sessionsForConnection(t)){if(S=!0,!g){let e=w.origin.context,s=typeof e?.agent_type==`string`?e.agent_type:void 0,S=typeof e?.color_seed==`string`?e.color_seed:t,E=iconFromClientName(s),D=AGENT_ICON_COLORS[E]??colorFromSeed(S);g={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:D,icon:E,connectionId:t}}let e=w.docName,E=w.um,D=w.dc.document.getText(`source`),O=[];for(let e=0;e<E.undoStack.length;e++){let t=E.undoStack[e],s=getBurstTs(t),{additions:g,deletions:S}=countStackItemChanges(t,D);O.push({stackIndex:e,ts:s,additions:g,deletions:S})}if(O.length===0)continue;O.sort((e,t)=>t.stackIndex-e.stackIndex);let k=O.reduce((e,t)=>e+t.additions,0),j=O.reduce((e,t)=>e+t.deletions,0),F=Math.max(...O.map(e=>e.ts));s.push({docName:e,additionsTotal:k,deletionsTotal:j,lastTs:F,bursts:O})}return S?(s.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:g,files:s}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const HocuspocusAuthTokenSchema=object$1({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional(),expectedDocLineageEpoch:string().optional(),clientProtocolVersion:number().optional(),clientRuntimeVersion:string().optional(),clientKind:string().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),s=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(s))return{kind:null,payload:void 0};if(t===-1)return{kind:s,payload:void 0};let g=e.slice(t+1);return{kind:s,payload:g.length>0?g:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,s){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof s==`string`&&s.length>0?s:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let s=HocuspocusAuthTokenSchema.safeParse(t);return s.success?s.data:void 0}const counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let s=getCounters(e);s.lastUserTxGen=++globalCounter,s.lastUserTxAtMs=Date.now()},s=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,s),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,s)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let s=counters.get(e);return s?s.settledGen>s.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let s=counters.get(e);return!s||s.lastUserTxAtMs===null?null:Math.max(0,t-s.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map,lastSplitBrainEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,s=Date.now()){let g=rateKey(e,t),S=lastEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)s-t>=w&&lastEmitMs.delete(e);return lastEmitMs.set(g,s),!0}function shouldEmitBridgeToleranceApplied(e,t,s=Date.now()){let g=toleranceRateKey(e,t),S=lastToleranceEmitMs.get(g),w=readDebounceMs();return S!==void 0&&s-S<w?!1:(lastToleranceEmitMs.set(g,s),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let s=e??`__nodoc__`,g=lastPathBEmitMs.get(s),S=readDebounceMs();if(g!==void 0&&t-g<S)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,s]of lastPathBEmitMs)t-s>=S&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(s,t),!0}function emitObserverAPathBFired(e,t){let s=shouldEmitObserverAPathBFired(e,t);return s||incrementObserverAPathBFiresSuppressed(),s}function shouldEmitBridgeSplitBrainRederive(e,t,s=Date.now()){let g=`${e}::${t??`__nodoc__`}`,S=lastSplitBrainEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastSplitBrainEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastSplitBrainEmitMs)s-t>=w&&lastSplitBrainEmitMs.delete(e);return lastSplitBrainEmitMs.set(g,s),!0}function emitBridgeSplitBrainRederive(e,t,s){let g=shouldEmitBridgeSplitBrainRederive(e,t,s);return g||incrementBridgeSplitBrainRederivesSuppressed(),g}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,s){let g=normalizeBridge(e),S=normalizeBridge(t);if(g===S){if(e!==t){let g=detectAppliedToleranceClasses(e,t);emitToleranceFire(g,e,t,s.docName);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=J,t.exports.build=J,t.exports.PinoPretty=J,t.exports.prettyFactory=ee,t.exports.colorizerFactory=E,t.exports.isColorSupported=s,t.exports.default=J})),import_pino=__toESM(require_pino(),1),import_pino_pretty=__toESM(require_pino_pretty(),1),RotatingAppender=class{#e;#t;#n;#r=Promise.resolve();#i=!1;constructor(e){this.#e=e.currentPath,this.#t=e.previousPath,this.#n=e.maxBytes}append(e){let t=this.#r.catch(()=>void 0).then(()=>this.#a(e));return this.#r=t,t}async drain(){await this.#r.catch(()=>void 0)}async#a(e){this.#i||=(await mkdir(dirname(this.#e),{recursive:!0}),!0),await writeFile(this.#e,e,{flag:`a`});let t;try{t=statSync(this.#e).size}catch{this.#i=!1;return}t>this.#n&&await rename(this.#e,this.#t)}};const TELEMETRY_SUBDIR=[`.ok`,`local`,`telemetry`],CURRENT_FILENAME=`spans-current.jsonl`,PREVIOUS_FILENAME=`spans-prev.jsonl`;function spansCurrentPath(e){return join(e,...TELEMETRY_SUBDIR,CURRENT_FILENAME)}function spansPreviousPath(e){return join(e,...TELEMETRY_SUBDIR,PREVIOUS_FILENAME)}var FileSpanExporter=class{#e;#t=!1;constructor(e){this.#e=new RotatingAppender({currentPath:spansCurrentPath(e.projectDir),previousPath:spansPreviousPath(e.projectDir),maxBytes:e.maxBytes})}export(e,t){if(this.#t){t({code:import_src.ExportResultCode.FAILED,error:Error(`FileSpanExporter: export called after shutdown`)});return}if(e.length===0){t({code:import_src.ExportResultCode.SUCCESS});return}let s=import_src$1.JsonTraceSerializer.serializeRequest(e);if(!s||s.byteLength===0){t({code:import_src.ExportResultCode.SUCCESS});return}let g=new Uint8Array(s.byteLength+1);g.set(s),g[s.byteLength]=10,this.#e.append(g).then(()=>t({code:import_src.ExportResultCode.SUCCESS}),e=>t({code:import_src.ExportResultCode.FAILED,error:e instanceof Error?e:Error(String(e))}))}async shutdown(){this.#t=!0,await this.#e.drain()}async forceFlush(){await this.#e.drain()}};const REDACTED_SENTINEL=`[REDACTED]`,KEY_BOUNDARY_CHARS=new Set([`.`,`/`,`_`]);function keyMatchesDenylist(e,t){if(t.has(e))return!0;for(let s of t){if(s.length===0||e.length<=s.length||!e.endsWith(s))continue;let t=e.charAt(e.length-s.length-1);if(KEY_BOUNDARY_CHARS.has(t))return!0}return!1}function scrubAttributes(e,t,s){for(let g of Object.keys(e)){let S=e[g];if(S!==void 0){if(keyMatchesDenylist(g.toLowerCase(),t)){e[g]=REDACTED_SENTINEL;continue}if(typeof S==`string`){let t=Buffer.byteLength(S,`utf-8`);t>s&&(e[g]=`[TRUNCATED:${t}]`)}}}}var ScrubbingSpanProcessor=class{#e;#t;constructor(e){this.#e=new Set(e.attributeDenylist.map(e=>e.toLowerCase())),this.#t=e.maxValueBytes??4096}onStart(e,t){}onEnd(e){scrubAttributes(e.attributes,this.#e,this.#t);for(let t of e.events)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t);for(let t of e.links)t.attributes!==void 0&&scrubAttributes(t.attributes,this.#e,this.#t)}async forceFlush(){}async shutdown(){}};const LOGS_SUBDIR=[`.ok`,`local`,`logs`],LOGS_CURRENT_FILENAME=`server-current.jsonl`,LOGS_PREVIOUS_FILENAME=`server-prev.jsonl`;function logsCurrentPath(e){return join(e,...LOGS_SUBDIR,LOGS_CURRENT_FILENAME)}function logsPreviousPath(e){return join(e,...LOGS_SUBDIR,LOGS_PREVIOUS_FILENAME)}var PinoFileSink=class extends Writable{#e;constructor(e){super({decodeStrings:!1}),this.#e=new RotatingAppender({currentPath:logsCurrentPath(e.projectDir),previousPath:logsPreviousPath(e.projectDir),maxBytes:e.maxBytes})}_write(e,t,s){this.#e.append(e).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}async drain(){await this.#e.drain()}};function otelMixin(){let e=trace.getSpan(context.active());if(!e)return{};let t=e.spanContext();return{trace_id:t.traceId,span_id:t.spanId,trace_flags:t.traceFlags}}function shouldColorize(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}const VALID_LOG_LEVELS=new Set([`fatal`,`error`,`warn`,`info`,`debug`,`trace`,`silent`]);function logLevelRank(e){return e===`silent`?1/0:import_pino.default.levels.values[e]??import_pino.default.levels.values.info}function mostVerboseLevel(e,t){return logLevelRank(e)<=logLevelRank(t)?e:t}var PinoLogger=class{name;transportConfigs=[];fileSinkOpts;redactPaths;activeFileSink;pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),t.fileSink&&(this.fileSinkOpts=t.fileSink),t.redactPaths&&t.redactPaths.length>0&&(this.redactPaths=t.redactPaths,this.options={...this.options,redact:{paths:[...t.redactPaths],censor:`[REDACTED]`}}),this.pinoInstance=this.buildInstance()}resolveStreamLevels(){let e=this.options.level??`info`,t=process.env.OK_CONSOLE_LEVEL?.toLowerCase(),s=t&&VALID_LOG_LEVELS.has(t)?t:e;return{fileLevel:e,consoleLevel:s,instanceLevel:mostVerboseLevel(e,s)}}buildInstance(){this.activeFileSink=void 0;let{fileLevel:e,consoleLevel:t,instanceLevel:s}=this.resolveStreamLevels();if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));let g;try{g=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`})}catch(g){if(console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,g),this.fileSinkOpts){let t=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=t,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:t,level:e}]))}return(0,import_pino.default)({...this.options,level:t})}if(this.fileSinkOpts){let S=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=S,(0,import_pino.default)({...this.options,level:s},import_pino.default.multistream([{stream:g,level:t},{stream:S,level:e}]))}return(0,import_pino.default)({...this.options,level:t},g)}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}reconfigure(e){e.options&&(this.options={...this.options,...e.options}),e.transportConfigs&&(this.transportConfigs=e.transportConfigs),e.fileSink&&(this.fileSinkOpts=e.fileSink),e.redactPaths&&e.redactPaths.length>0&&(this.redactPaths=e.redactPaths,this.options={...this.options,redact:{paths:[...e.redactPaths],censor:`[REDACTED]`}}),this.recreateInstance()}getPinoInstance(){return this.pinoInstance}async flushFileSink(){this.activeFileSink&&await this.activeFileSink.drain()}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){if(this.config=e,e.pinoConfig&&!e.defaultLogger&&!e.loggerFactory){for(let t of this.loggers.values())t.reconfigure(e.pinoConfig);return}this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let s;return s=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,s),s}reset(){this.config={},this.loggers.clear()}async flushAllFileSinks(){let e=[];for(let t of this.loggers.values())e.push(t.flushFileSink());await Promise.all(e)}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(s=>({...s,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:s,...g}=t;return g})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let s=t.getLocalState()??{},g=e(s.agentFocus??{});t.setLocalState({...s,agentFocus:g})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,mapDrivenSpliceApplied:0,mapDrivenSpliceFallback:{},observerAResidualMergeRuns:0,bridgeSplitBrainRederives:0,bridgeSplitBrainRederivesSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0,authDocLineageMismatchCount:0,authDocLineageGuardErrors:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementMapDrivenSpliceApplied(){counters$1.mapDrivenSpliceApplied++}function incrementMapDrivenSpliceFallback(e){counters$1.mapDrivenSpliceFallback[e]=(counters$1.mapDrivenSpliceFallback[e]??0)+1}function incrementObserverAResidualMergeRuns(){counters$1.observerAResidualMergeRuns++}function incrementBridgeSplitBrainRederives(){counters$1.bridgeSplitBrainRederives++}function incrementBridgeSplitBrainRederivesSuppressed(){counters$1.bridgeSplitBrainRederivesSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementAuthDocLineageMismatch(){counters$1.authDocLineageMismatchCount++}function incrementAuthDocLineageGuardError(){counters$1.authDocLineageGuardErrors++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied},mapDrivenSpliceFallback:{...counters$1.mapDrivenSpliceFallback}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.mapDrivenSpliceApplied=0,counters$1.mapDrivenSpliceFallback={},counters$1.observerAResidualMergeRuns=0,counters$1.bridgeSplitBrainRederives=0,counters$1.bridgeSplitBrainRederivesSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0,counters$1.authDocLineageMismatchCount=0,counters$1.authDocLineageGuardErrors=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let s=0;this.mutateAgentPresence(g=>{let S=Date.now(),w={};for(let[t,E]of Object.entries(g)){if(S-E.ts>=2e4&&t!==e){s++;continue}w[t]=E}return w[e]=t,w})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),s>0&&this.log.info({evictedCount:s,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(s=>{if(!s[e])return s;t=!0;let{[e]:g,...S}=s;return S})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let s=[],g=!1,S=this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;g=!0;let E=Date.now();return s.push({currentDoc:w.currentDoc,ts:E}),{...S,[e]:{...w,mode:t,ts:E}}}),w=s[0];S&&w?this.log.debug({agentId:e,action:`touchMode`,currentDoc:w.currentDoc,ts:w.ts,mode:t},`[agent-presence] touchMode`):g||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(s=>{let g=s[e];if(!g)return s;let S=Date.now();return t=S,{...s,[e]:{...g,ts:S}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let s=t.getLocalState()??{},g=e(s.agentPresence??{});return t.setLocalState({...s,agentPresence:g}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null,fileSpanExporter=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(e={}){let t=e.localSink!==void 0,s=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!s||tracerProvider)return noopResult();try{let g=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),S=new import_src$2.AsyncLocalStorageContextManager;context.setGlobalContextManager(S);let w=[],E=e.localSink?.attributeDenylist??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;w.push(new ScrubbingSpanProcessor({attributeDenylist:E})),t&&e.localSink!==void 0&&(fileSpanExporter=new FileSpanExporter({projectDir:e.localSink.projectDir,maxBytes:e.localSink.spansMaxBytes}),w.push(new import_src$7.SimpleSpanProcessor(fileSpanExporter))),s&&w.push(new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter));let D=new import_src$7.BasicTracerProvider({resource:g,spanProcessors:w});trace.setGlobalTracerProvider(D),tracerProvider=D;try{propagation.setGlobalPropagator(new import_src.W3CTraceContextPropagator)}catch(e){getLogger(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let O=null;s&&(O=new import_src$6.MeterProvider({resource:g,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]}),metrics.setGlobalMeterProvider(O)),meterProvider=O,getLogger(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:s,otlp_endpoint:s?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:g.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized`)}catch(e){let t=getLogger(`telemetry`);tracerProvider===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),meterProvider=null,fileSpanExporter=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),meterProvider=null)}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3,shutdownHooks=new Set;function onTelemetryShutdown(e){shutdownHooks.add(e)}async function shutdownTelemetry(){let e=getLogger(`telemetry`);for(let t of shutdownHooks)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!tracerProvider&&!meterProvider)return;let t=(fileSpanExporter?fileSpanExporter.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),s;await Promise.race([t.then(()=>(s!==void 0&&clearTimeout(s),!1)),new Promise(e=>{s=setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS),s.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,fileSpanExporter=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,s){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await s(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,s){return getTracer().startActiveSpan(e,t??{},e=>{try{return s(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,s,g){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:s,"body.bytes":t.length,"doc.name":e.guid}},()=>{let s=e.getXmlFragment(`default`),S=e.getText(`source`),w=S.toString(),{body:E}=stripFrontmatter(t),D=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":E.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(E,buildParseOpts(g))),O=schema.nodeFromJSON(D);w!==t&&applyFastDiff(S,w,t),updateYFragment(e,s,O,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,s){withSpanSync(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let g=e.getXmlFragment(`default`),S=e.getText(`source`),{body:w}=stripFrontmatter(t),E=mdManager.parseWithFallback(w,buildParseOpts(s)),D=schema.nodeFromJSON(E),O=S.toString();O!==t&&(S.delete(0,O.length),S.insert(0,t)),updateYFragment(e,g,D,{mapping:new Map,isOMark:new Map})})}function deriveFragmentFromYtext(e,t){let s=e.getXmlFragment(`default`),{body:g}=stripFrontmatter(e.getText(`source`).toString()),S=mdManager.parseWithFallback(g,buildParseOpts(t));updateYFragment(e,s,schema.nodeFromJSON(S),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(e)??0)+1;this.seqs.set(e,s);let g=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:s});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(e,s),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let g=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});s.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,s);let g=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:s,branch:e});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,s)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,g);let S=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:g,docName:e,sv:Buffer.from(t).toString(`base64`)});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,s]of this.latestDiskAckSVs)e[t]=Buffer.from(s).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g);let S=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:g,docName:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g);let S=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:g,path:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let s=extname(e).slice(1).toLowerCase();return s.length>0&&t.has(s)}function stripDocExtension(e){let t=e.toLowerCase();for(let s of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(s))return e.slice(0,-s.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let s=canonicalize(t);if(!s)throw Error(`registerDocExtension: unsupported extension "${t}"`);let g=docExtensionByName.get(e);if(!g)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let S=canonicalize(g);return S?S===s?{effective:g,changed:!1,shadowed:null}:rank(s)<rank(S)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g}):{effective:g,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$13=()=>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$13().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$13().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$13()[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$13().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$13().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$13()[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$13().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$13().error({event:`api.streaming.error.write-failed`,type:g,status:s,handler:t,err:w.cause,writeErr:e},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const RESOLUTION_OPTIONS=[`mine`,`theirs`,`content`,`delete`];function isDocInConflict(e){return e.getMap(`lifecycle`).get(`status`)===`conflict`}var DocInConflictError=class extends Error{file;name=`DocInConflictError`;constructor(e){super(`Document is in conflict: ${e.file}`),this.file=e.file}};function respondDocInConflict(e,t,s){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:s,"doc.name":stripDocExtension(t.file)})),errorResponse(e,409,`urn:ok:error:doc-in-conflict`,`Document is in conflict.`,{handler:s,detail:`The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.`,extensions:{file:t.file,resolutionOptions:RESOLUTION_OPTIONS}})}const byteLength$1=e=>Buffer.byteLength(e,`utf8`);function capContent(e){let t=byteLength$1(e);return t<=51200?{kind:`inline`,content:e}:{kind:`truncated`,byteLength:t,hint:`Converged content exceeds the inline cap — re-read via exec("cat <doc>") for the full document.`}}function evaluateContentDivergence(e,t,s){if(e===t)return;let g=byteLength$1(t),S=byteLength$1(e);return{intendedBytes:g,actualBytes:S,byteDelta:S-g,divergenceType:`${s}-content-mismatch`,currentState:capContent(e)}}const DEFAULT_DIVERGENCE_HINT="The converged document differs from the bytes you composed. The write landed; `currentState` carries what is in the document now — re-read only if it is truncated.";function toContentDivergenceWarning(e,t=DEFAULT_DIVERGENCE_HINT){return{kind:`content-divergence`,intendedBytes:e.intendedBytes,actualBytes:e.actualBytes,byteDelta:e.byteDelta,divergenceType:e.divergenceType,currentState:e.currentState,hint:t}}const FIX_HINT='Frontmatter must be a top-level YAML mapping. Quote string values containing YAML-significant characters (`:`, `#`, leading `-`), e.g. `title: "Foo: bar"`.';var FrontmatterMalformedError=class extends Error{file;parseError;name=`FrontmatterMalformedError`;constructor(e){super(`Frontmatter YAML is malformed in ${e.file}: ${e.parseError}`),this.file=e.file,this.parseError=e.parseError}};function classifyParseError(e){return e===`top-level value is not a mapping`?`non-mapping-top-level`:e.startsWith(`value at "`)||e.startsWith(`schema validation failed:`)?`schema-rejection`:e.startsWith(`parse threw:`)||e.startsWith(`toJS threw:`)||e.length>0&&e!==`unknown YAML parse error`?`yaml-parse-error`:`unknown`}function respondFrontmatterMalformed(e,t,s){let g=classifyParseError(t.parseError);console.warn(JSON.stringify({event:`frontmatter-malformed-write-refused`,handler:s,class:g,"doc.name":stripDocExtension(t.file),parseError:t.parseError})),errorResponse(e,400,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,{handler:s,detail:`${t.parseError}. ${FIX_HINT}`,extensions:{file:t.file,parseError:t.parseError}})}let _editSurfaceCounter=null;function editSurfaceCounter(){return _editSurfaceCounter||=getMeter().createCounter(`ok.frontmatter.edit_surface_total`,{description:`Count of frontmatter edits by surface. Bounded label: source ∈ {source-mode, mcp-write, file-watcher}.`}),_editSurfaceCounter}function recordFrontmatterEditSurface(e){editSurfaceCounter().add(1,{source:e})}const log$12=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$12.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$12.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$12.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$12.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$12.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,s=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));s.length>0&&await Promise.allSettled(s.map(e=>this.pendingSessions.get(e)));let g=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of g){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,s=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of s){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,s,g){let S=e.doc;if(!S)return;let w=++_effectCounter,E=S.getMap(`agent-effects`),D=k=>{e.unobserve(D),S.off(`destroy`,O);let j=`${t}:${w}`,F={sessionId:t,timestamp:Date.now(),delta:k.delta,agent_type:g??`agent`,color_seed:s??t};try{S.transact(()=>{if(E.set(j,F),E.size>RING_BUFFER_LIMIT){let e=[...E.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,E.size-RING_BUFFER_LIMIT))E.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let s=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:s})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},O=()=>{e.unobserve(D)};e.observe(D),S.once(`destroy`,O)}function collectItemsInDeleteSet(e,t,s){iterateDeletedStructs(e,t,e=>{e instanceof Item&&s.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let s=[],g=[],S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=``,O=``,k=0,j=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,S=t.length,F=w.has(e),L=E.has(e);e.deleted?L&&(g.push({position:k,content:t,length:S}),D+=t,k+=S):(O+=t,F?s.push({position:j,content:t,length:S}):(D+=t,k+=S),j+=S)}return{insertions:s,deletions:g,before:D,after:O}}function synthesizeStackItemDiffText(e,t,s){let{before:g,after:S}=synthesizeStackItemDiff(e,t);return g===S?``:createPatch(s,g,S,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let s=t.doc,g=new Set,S=new Set;s&&s.transact(t=>{collectItemsInDeleteSet(t,e.insertions,g),collectItemsInDeleteSet(t,e.deletions,S)});let w=0,E=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&g.has(e)&&(w+=t),S.has(e)&&(E+=t)}return{additions:w,deletions:E}}function listAgentActivity(e,t){let s=[],g=null,S=!1;for(let w of e.sessionsForConnection(t)){if(S=!0,!g){let e=w.origin.context,s=typeof e?.agent_type==`string`?e.agent_type:void 0,S=typeof e?.color_seed==`string`?e.color_seed:t,E=iconFromClientName(s),D=AGENT_ICON_COLORS[E]??colorFromSeed(S);g={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:D,icon:E,connectionId:t}}let e=w.docName,E=w.um,D=w.dc.document.getText(`source`),O=[];for(let e=0;e<E.undoStack.length;e++){let t=E.undoStack[e],s=getBurstTs(t),{additions:g,deletions:S}=countStackItemChanges(t,D);O.push({stackIndex:e,ts:s,additions:g,deletions:S})}if(O.length===0)continue;O.sort((e,t)=>t.stackIndex-e.stackIndex);let k=O.reduce((e,t)=>e+t.additions,0),j=O.reduce((e,t)=>e+t.deletions,0),F=Math.max(...O.map(e=>e.ts));s.push({docName:e,additionsTotal:k,deletionsTotal:j,lastTs:F,bursts:O})}return S?(s.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:g,files:s}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const HocuspocusAuthTokenSchema=object$1({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional(),expectedDocLineageEpoch:string().optional(),clientProtocolVersion:number().optional(),clientRuntimeVersion:string().optional(),clientKind:string().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),s=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(s))return{kind:null,payload:void 0};if(t===-1)return{kind:s,payload:void 0};let g=e.slice(t+1);return{kind:s,payload:g.length>0?g:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,s){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof s==`string`&&s.length>0?s:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let s=HocuspocusAuthTokenSchema.safeParse(t);return s.success?s.data:void 0}const counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let s=getCounters(e);s.lastUserTxGen=++globalCounter,s.lastUserTxAtMs=Date.now()},s=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,s),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,s)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let s=counters.get(e);return s?s.settledGen>s.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let s=counters.get(e);return!s||s.lastUserTxAtMs===null?null:Math.max(0,t-s.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map,lastSplitBrainEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,s=Date.now()){let g=rateKey(e,t),S=lastEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)s-t>=w&&lastEmitMs.delete(e);return lastEmitMs.set(g,s),!0}function shouldEmitBridgeToleranceApplied(e,t,s=Date.now()){let g=toleranceRateKey(e,t),S=lastToleranceEmitMs.get(g),w=readDebounceMs();return S!==void 0&&s-S<w?!1:(lastToleranceEmitMs.set(g,s),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let s=e??`__nodoc__`,g=lastPathBEmitMs.get(s),S=readDebounceMs();if(g!==void 0&&t-g<S)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,s]of lastPathBEmitMs)t-s>=S&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(s,t),!0}function emitObserverAPathBFired(e,t){let s=shouldEmitObserverAPathBFired(e,t);return s||incrementObserverAPathBFiresSuppressed(),s}function shouldEmitBridgeSplitBrainRederive(e,t,s=Date.now()){let g=`${e}::${t??`__nodoc__`}`,S=lastSplitBrainEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastSplitBrainEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastSplitBrainEmitMs)s-t>=w&&lastSplitBrainEmitMs.delete(e);return lastSplitBrainEmitMs.set(g,s),!0}function emitBridgeSplitBrainRederive(e,t,s){let g=shouldEmitBridgeSplitBrainRederive(e,t,s);return g||incrementBridgeSplitBrainRederivesSuppressed(),g}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,s){let g=normalizeBridge(e),S=normalizeBridge(t);if(g===S){if(e!==t){let g=detectAppliedToleranceClasses(e,t),S=g.filter(e=>shouldEmitBridgeToleranceApplied(s.site,e,s.nowMs));g.length>0&&emitToleranceFire(g,e,t,s.docName);for(let e of S)incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:s.site,class:e}))}return!0}let w={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${g.slice(0,300)}\n frag: ${S.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(w);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let E=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(w,{verbose:E}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,s){let g={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return s&&Object.assign(g,s),g}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,s){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,s)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,s){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,s)})}function tracedAppendFileSync(e,t,s){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,s)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,s){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,s)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
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(g.ephemeral&&t===`__config__/okignore`||s===CONFIG_VALIDATION_REVERT_ORIGIN)return`no-op`;let S=e.getText(`source`),w=S.toString(),E=g.lkgCache.get(t);if(w.length===0&&(t!==`__config__/okignore`||E===void 0||E===``)||E!==void 0&&w===E)return`no-op`;let D=configScopeAttr(t),O=withConfigSpanSync(`config.validate`,{"config.scope":D,"config.validation.layer":`L3`},e=>{let s=validateConfigContent(t,w);return e.setAttribute(`config.outcome`,s.ok?`success`:`rejected`),s.ok||emitSchemaInvalidIssueEvents(s.error),s});if(!O.ok)return await withConfigSpan(`config.revert`,{"config.scope":D,"config.outcome":`reverted`},async()=>{let s=E??defaultLkgFor(t);e.transact(()=>{S.length>0&&S.delete(0,S.length),S.insert(0,s)},CONFIG_VALIDATION_REVERT_ORIGIN),E===void 0&&g.lkgCache.set(t,s),t===`__config__/okignore`&&isKnownConfigError(O.error)&&okignoreRejectionCounter().add(1,{"error.code":O.error.code}),g.onConfigRejected?.(t,O.error)}),`reverted`;let k=configDocAbsPath(t,g);try{await tracedMkdir(dirname(k),{recursive:!0})}catch(e){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] could not create parent dir for ${k}: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not create parent directory for ${k}: ${s}`}),`write-failed`}try{return await withFileLock(`${k}.lock`,async()=>{let s=null;try{s=readFileSync(k,`utf-8`)}catch(e){if(e.code!==`ENOENT`){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] could not read config for reconciliation: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not read config for reconciliation at ${k}: ${s}`}),`write-failed`}}if(s!==null&&E!==void 0&&s!==E){if(validateConfigContent(t,s).ok)return e.transact(()=>{S.length>0&&S.delete(0,S.length),S.insert(0,s)},CONFIG_FILE_WATCHER_ORIGIN),g.lkgCache.set(t,s),getLogger(`config-persistence`).info({docName:t,path:k},`[config-persistence] reconciled: external writer landed; imported disk into Y.Text`),`reconciled`;getLogger(`config-persistence`).warn({docName:t,path:k},`[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write`)}try{await atomicWriteConfig(k,w)}catch(e){let s=e instanceof Error?e.message:String(e);return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] write-failed at ${k}: ${s}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Failed to persist config at ${k}: ${s}`}),`write-failed`}return g.lkgCache.set(t,w),`persisted`},{onWarn:(e,t)=>{getLogger(`config-persistence`).warn(t,`[config-persistence] ${e}`)}})}catch(e){if(e instanceof FileLockTimeoutError)return getLogger(`config-persistence`).warn({docName:t,path:k,err:e},`[config-persistence] lock timeout at ${k}: ${e.message}`),g.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:e.message}),`write-failed`;throw e}}function applyExternalConfigChange(e,t,s,g){if(!e)return`no-op`;let S=g.lkgCache.get(t);if(S!==void 0&&S===s)return`no-op`;let w=configScopeAttr(t),E=withConfigSpanSync(`config.validate`,{"config.scope":w,"config.validation.layer":`L3`},e=>{let g=validateConfigContent(t,s);return e.setAttribute(`config.outcome`,g.ok?`success`:`rejected`),g.ok||emitSchemaInvalidIssueEvents(g.error),g});if(!E.ok)return t===`__config__/okignore`&&isKnownConfigError(E.error)&&okignoreRejectionCounter().add(1,{"error.code":E.error.code}),g.onConfigRejected?.(t,E.error),`rejected`;let D=e.getText(`source`);return e.transact(()=>{D.length>0&&D.delete(0,D.length),D.insert(0,s)},CONFIG_FILE_WATCHER_ORIGIN),g.lkgCache.set(t,s),`applied`}let pendingContributors=new Map;function recordContributor(e,t,s,g,S,w,E,D){let O=pendingContributors.get(t);if(O||(O={writerId:t,displayName:s,colorSeed:g??s,docs:new Set,subjectOverride:S,actor:w,summaries:[],previousPaths:[]},pendingContributors.set(t,O)),O.docs.add(e),S!==void 0&&(O.subjectOverride=S),w!==void 0){let e=O.actor??{};w.principalId!==void 0&&(e.principalId=w.principalId),w.agentType!==void 0&&(e.agentType=w.agentType),w.clientName!==void 0&&(e.clientName=w.clientName),w.clientVersion!==void 0&&(e.clientVersion=w.clientVersion),w.label!==void 0&&(e.label=w.label),O.actor=e}if(typeof E==`string`&&E.length>0&&O.summaries.push(E),D&&D.length>0)for(let e of D)O.previousPaths.push(e)}function swapContributors(){let e=pendingContributors;return pendingContributors=new Map,e}function restoreContributors(e){for(let[t,s]of e){let e=pendingContributors.get(t);e||(e={writerId:t,displayName:s.displayName,colorSeed:s.colorSeed,docs:new Set,actor:s.actor,summaries:[],previousPaths:[]},pendingContributors.set(t,e));for(let t of s.docs)e.docs.add(t);s.summaries.length>0&&(e.summaries=[...s.summaries,...e.summaries]),s.previousPaths.length>0&&(e.previousPaths=[...s.previousPaths,...e.previousPaths])}}function formatContributorsFrom(e){if(e.size===0)return``;let t=[``];for(let s of e.values()){let e={v:1,id:s.writerId,name:s.displayName,colorSeed:s.colorSeed,docs:[...s.docs]};s.summaries.length>0&&(e.summaries=[...s.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
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(`
@@ -795,9 +795,9 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
795
795
  `);try{S.stdin.end(`${j}\n`)}catch(e){clearTimeout(k),console.warn(`[rename-log] WARN: batchCheckExistence stdin write failed: ${e.message}`),O(E())}})}function rewriteJsonlAtomically(e,t){let s=renameLogPath(e),g=serializeIndexToString(t);if(g.length===0){if(existsSync(s))try{tracedWriteFileSync(s,``)}catch(e){console.warn(`[rename-log] WARN: failed to truncate empty jsonl:`,e)}return}let S=`${s}.tmp`;try{tracedWriteFileSync(S,g),tracedRenameSync(S,s)}catch(e){console.warn(`[rename-log] WARN: atomic rewrite failed; index ahead of disk:`,e);try{existsSync(S)&&tracedUnlinkSync(S)}catch{}}}function backfillRenameLogCommitSha(e,t,s,g){if(!/^[0-9a-f]{40}$/.test(s))return console.warn(`[rename-log] WARN: backfill rejected invalid commitSha: ${JSON.stringify(s)}`),{updated:0};let S=0;for(let e of g.byTo.values())e.commitSha===``&&e.actor.writerId===t&&(e.commitSha=s,S+=1);return S>0&&rewriteJsonlAtomically(e,g),{updated:S}}function sweepLazyPopOrphans(e,t){let s=[];for(let e of t.byTo.values())e.commitSha===``&&s.push(e);if(s.length===0)return{dropped:0};for(let e of s)indexRemove(t,e);return rewriteJsonlAtomically(e,t),liveEntriesGauge().add(-s.length),console.warn(`[rename-log] gc swept ${s.length} orphan entries (lazy-pop residue from mid-rename crash)`),{dropped:s.length}}async function gcRenameLog(e,t,s){let g={scanned:0,dropped:0,retained:0,rebuilt:0};if(gcPending.has(e.gitDir))return g;gcPending.add(e.gitDir);try{return await gcRenameLogInner(e,t,s,g)}finally{gcPending.delete(e.gitDir)}}async function gcRenameLogInner(e,t,s,g){let S=shadowGit(e),w=[];for(let e of t.byTo.values())e.commitSha!==``&&w.push({entry:e,observedSha:e.commitSha});let E;try{E=(await S.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`,`refs/checkpoints/`)).split(`
796
796
  `).map(e=>e.trim()).filter(Boolean)}catch(e){return console.warn(`[rename-log] WARN: gcRenameLog aborted — failed to enumerate refs:`,e),g}let D=new Set;if(E.length>0){let t;try{t=await revListReachable(e,E)}catch(e){return console.warn(`[rename-log] WARN: gcRenameLog aborted — rev-list failed:`,e),g}for(let e of t.split(`
797
797
  `)){let t=e.trim();t.length===40&&D.add(t)}}g.scanned=t.byTo.size;let O=[];for(let{entry:e,observedSha:s}of w)D.has(s)||t.byTo.get(e.to)===e&&e.commitSha===s&&O.push(e);for(let e of O)t.byTo.get(e.to)===e&&indexRemove(t,e);if(g.dropped=O.length,g.retained=t.byTo.size,s?.rebuild){let s;try{s=await S.raw(`log`,`--all`,`--grep=^rename: `,`--format=%H%x00%cI%x00%B%x1e`)}catch(e){console.warn(`[rename-log] WARN: gcRenameLog rebuild: git log --grep failed; skipping reconstruction:`,e),s=``}let w=await buildBranchReachabilityMap(e,E);for(let e of s.split(``)){let s=e.trimStart();if(!s)continue;let S=s.split(`\0`),E=(S[0]??``).trim(),O=(S[1]??``).trim(),k=S[2]??``;if(E.length!==40||!D.has(E))continue;let j=parseOkActors(k),F=0;for(let e of j)F+=e.previous_paths?.length??0;if(F===0)continue;let L=F>1?`folder`:`file`,B=lookupBranchInMap(w,E),H=deriveGroupId(E,``,``);for(let e of j)if(!(!e.previous_paths||e.previous_paths.length===0))for(let s of e.previous_paths)t.byTo.has(s.to)||(indexInsert(t,{v:1,from:s.from,to:s.to,at:O||new Date(0).toISOString(),commitSha:E,branch:B,groupId:H,kind:L,actor:{writerId:e.writer_id,displayName:e.display_name}}),g.rebuilt+=1,g.retained+=1)}}return(g.dropped>0||g.rebuilt>0)&&rewriteJsonlAtomically(e.gitDir,t),g.dropped>0&&(console.warn(`[rename-log] gc swept ${g.dropped} dead entries (${g.retained} live remain)`),gcDroppedCounter().add(g.dropped),liveEntriesGauge().add(-g.dropped)),g.rebuilt>0&&liveEntriesGauge().add(g.rebuilt),g}function deriveGroupId(e,t,s){let g=createHash(`sha256`);g.update(`${e}\0${t}\0${s}`);let S=g.digest(`hex`);return`${S.slice(0,8)}-${S.slice(8,12)}-${S.slice(12,16)}-${S.slice(16,20)}-${S.slice(20,32)}`}async function buildBranchReachabilityMap(e,t){let s=new Map;for(let e of[...t].sort()){let t=/^refs\/(?:wip|checkpoints)\/([^/]+)\//.exec(e);if(!t?.[1])continue;let g=s.get(t[1])??[];g.push(e),s.set(t[1],g)}let g=new Map;for(let[t,S]of s){let s;try{s=await revListReachable(e,S)}catch(e){console.warn(`[rename-log] WARN: gcRenameLog rebuild: rev-list failed for branch ${t}; reconstructed entries on this branch will fall back to 'main':`,e);continue}let w=new Set;for(let e of s.split(`
798
- `)){let t=e.trim();t.length===40&&w.add(t)}g.set(t,w)}return g}function lookupBranchInMap(e,t){for(let[s,g]of e)if(g.has(t))return s;return`main`}async function resolveDocPathAtCommit(e,t,s,g,S,w,E,D){let{chain:O}=expandPredecessors(t,g,S),k=await Promise.all(O.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,g,D);return s.length===0?new Set:buildAncestorShaSet(e,s,g,E)})),j=[];for(let e=O.length-1;e>=0;e--){let t=O[e],g=k[e];g!==null&&!g.has(s)||j.push({sha:s,path:w(t.path)})}if(j.length===0)return null;let F=await batchCheckExistence(e,j);for(let e=0;e<j.length;e++)if(F[e])return j[e].path;return null}function computeMapDrivenBodySplice(e,t,s,g){let S,w,E;try{S=s.parseToMdast(e).children,w=s.serialize(t),E=s.parseToMdast(w).children}catch{return g?.(`parse-error`),null}if(!allBlocksCarryPositions(S)||!allBlocksCarryPositions(E))return g?.(`missing-position`),null;let D=0;for(;D<S.length&&D<E.length&&structurallyEqual(S[D],E[D]);)D++;let O=0;for(;O<S.length-D&&O<E.length-D&&structurallyEqual(S[S.length-1-O],E[E.length-1-O]);)O++;let k=D>0?blockEndOffset(S[D-1]):S.length>0?blockStartOffset(S[0]):0,j=O>0?blockStartOffset(S[S.length-O]):e.length,F=D>0?blockEndOffset(E[D-1]):E.length>0?blockStartOffset(E[0]):0,L=O>0?blockStartOffset(E[E.length-O]):w.length;return{spliceStart:k,spliceEnd:j,newSlice:w.slice(F,L)}}function allBlocksCarryPositions(e){for(let t of e){let e=t.position?.start?.offset,s=t.position?.end?.offset;if(typeof e!=`number`||typeof s!=`number`)return!1}return!0}function blockStartOffset(e){let t=e.position?.start?.offset;if(typeof t!=`number`)throw Error(`mdast node missing position.start.offset`);return t}function blockEndOffset(e){let t=e.position?.end?.offset;if(typeof t!=`number`)throw Error(`mdast node missing position.end.offset`);return t}function structurallyEqual(e,t){return stringifyIgnorePosition(e)===stringifyIgnorePosition(t)}function stringifyIgnorePosition(e){return JSON.stringify(e,(e,t)=>e===`position`?void 0:t)}const OBSERVER_SYNC_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},isPairedWriteOrigin=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0;function shouldRethrowBridgeMergeLoss(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}function tryComputeMapDrivenSplice(e){let{currentText:t,lastSyncedXmlMd:s,json:g,mdManager:S,docName:w}=e;if(t!==s)return incrementMapDrivenSpliceFallback(`text-mismatch`),null;if(w!==void 0&&(isSystemDoc(w)||isConfigDoc(w)))return incrementMapDrivenSpliceFallback(`synthetic-doc`),null;let{body:E}=stripFrontmatter(t),D=t.length-E.length,O=computeMapDrivenBodySplice(E,g,S,incrementMapDrivenSpliceFallback);return O?{spliceStart:D+O.spliceStart,spliceEnd:D+O.spliceEnd,newSlice:O.newSlice}:null}function applyMapDrivenSplice(e,t){let s=t.spliceEnd-t.spliceStart;s>0&&e.delete(t.spliceStart,s),t.newSlice.length>0&&e.insert(t.spliceStart,t.newSlice)}function settlesSplitBrain(e,t){return e!==t&&normalizeBridge(e)!==normalizeBridge(t)}function setupServerObservers(e){let{doc:t,xmlFragment:s,ytext:g,mdManager:S,schema:w}=e,E=(t,s)=>{let g=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:g}),docName:e.docName??null,timestamp:new Date().toISOString()})),incrementBridgeMergeContentLoss();let S=e.shadow?.();if(!S||!e.docName)return;let w=e.getBranch?.()??`main`,E=e.contentRoot??``;queueMicrotask(()=>{saveInMemoryCheckpoint(S,E,{kind:`bridge-merge-loss`,docName:e.docName,contents:s,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:w,metadata:{lostSubstrings:t.info.lostSubstrings}}).then(t=>{incrementBridgeMergeCheckpointCreated(),console.warn(JSON.stringify({event:`bridge-merge-checkpoint-created`,docName:e.docName,sha:t,kind:`bridge-merge-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{let t=e instanceof Error?e:Error(String(e));console.warn(`[Server Observer A] Silent checkpoint write failed:`,{name:t.name,message:t.message,stack:t.stack?.split(`
798
+ `)){let t=e.trim();t.length===40&&w.add(t)}g.set(t,w)}return g}function lookupBranchInMap(e,t){for(let[s,g]of e)if(g.has(t))return s;return`main`}async function resolveDocPathAtCommit(e,t,s,g,S,w,E,D){let{chain:O}=expandPredecessors(t,g,S),k=await Promise.all(O.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,g,D);return s.length===0?new Set:buildAncestorShaSet(e,s,g,E)})),j=[];for(let e=O.length-1;e>=0;e--){let t=O[e],g=k[e];g!==null&&!g.has(s)||j.push({sha:s,path:w(t.path)})}if(j.length===0)return null;let F=await batchCheckExistence(e,j);for(let e=0;e<j.length;e++)if(F[e])return j[e].path;return null}function computeMapDrivenBodySplice(e,t,s,g){let S,w,E;try{S=s.parseToMdast(e).children,w=s.serialize(t),E=s.parseToMdast(w).children}catch(e){return g?.(`parse-error`,e),null}if(!allBlocksCarryPositions(S)||!allBlocksCarryPositions(E))return g?.(`missing-position`),null;let D=0;for(;D<S.length&&D<E.length&&structurallyEqual(S[D],E[D]);)D++;let O=0;for(;O<S.length-D&&O<E.length-D&&structurallyEqual(S[S.length-1-O],E[E.length-1-O]);)O++;let k=D>0?blockEndOffset(S[D-1]):S.length>0?blockStartOffset(S[0]):0,j=O>0?blockStartOffset(S[S.length-O]):e.length,F=D>0?blockEndOffset(E[D-1]):E.length>0?blockStartOffset(E[0]):0,L=O>0?blockStartOffset(E[E.length-O]):w.length;return{spliceStart:k,spliceEnd:j,newSlice:w.slice(F,L)}}function allBlocksCarryPositions(e){for(let t of e){let e=t.position?.start?.offset,s=t.position?.end?.offset;if(typeof e!=`number`||typeof s!=`number`)return!1}return!0}function blockStartOffset(e){let t=e.position?.start?.offset;if(typeof t!=`number`)throw Error(`mdast node missing position.start.offset`);return t}function blockEndOffset(e){let t=e.position?.end?.offset;if(typeof t!=`number`)throw Error(`mdast node missing position.end.offset`);return t}function structurallyEqual(e,t){return stringifyIgnorePosition(e)===stringifyIgnorePosition(t)}function stringifyIgnorePosition(e){return JSON.stringify(e,(e,t)=>e===`position`?void 0:t)}const OBSERVER_SYNC_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},isPairedWriteOrigin=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0;function shouldRethrowBridgeMergeLoss(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}let mapDrivenParseErrorWarned=!1;function warnOnceMapDrivenParseError(e,t){mapDrivenParseErrorWarned||(mapDrivenParseErrorWarned=!0,console.warn(`[Server Observer A] Map-driven splice parse/serialize threw (doc: ${e??`unknown`}); drains fall back to the incremental diff (warned once; further failures count in mapDrivenSpliceFallback only):`,t instanceof Error?t.message:String(t)))}function tryComputeMapDrivenSplice(e){let{currentText:t,lastSyncedXmlMd:s,json:g,mdManager:S,docName:w}=e;if(t!==s)return incrementMapDrivenSpliceFallback(`text-mismatch`),null;if(w!==void 0&&(isSystemDoc(w)||isConfigDoc(w)))return incrementMapDrivenSpliceFallback(`synthetic-doc`),null;let{body:E}=stripFrontmatter(t),D=t.length-E.length,O=computeMapDrivenBodySplice(E,g,S,(e,t)=>{incrementMapDrivenSpliceFallback(e),e===`parse-error`&&warnOnceMapDrivenParseError(w,t)});return O?{spliceStart:D+O.spliceStart,spliceEnd:D+O.spliceEnd,newSlice:O.newSlice}:null}function applyMapDrivenSplice(e,t){let s=t.spliceEnd-t.spliceStart;s>0&&e.delete(t.spliceStart,s),t.newSlice.length>0&&e.insert(t.spliceStart,t.newSlice)}function settlesSplitBrain(e,t,s){return e!==t&&normalizeBridge(e)!==(s??normalizeBridge(t))}function setupServerObservers(e){let{doc:t,xmlFragment:s,ytext:g,mdManager:S,schema:w}=e,E=(t,s)=>{let g=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:g}),docName:e.docName??null,timestamp:new Date().toISOString()})),incrementBridgeMergeContentLoss();let S=e.shadow?.();if(!S||!e.docName)return;let w=e.getBranch?.()??`main`,E=e.contentRoot??``;queueMicrotask(()=>{saveInMemoryCheckpoint(S,E,{kind:`bridge-merge-loss`,docName:e.docName,contents:s,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:w,metadata:{lostSubstrings:t.info.lostSubstrings}}).then(t=>{incrementBridgeMergeCheckpointCreated(),console.warn(JSON.stringify({event:`bridge-merge-checkpoint-created`,docName:e.docName,sha:t,kind:`bridge-merge-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{let t=e instanceof Error?e:Error(String(e));console.warn(`[Server Observer A] Silent checkpoint write failed:`,{name:t.name,message:t.message,stack:t.stack?.split(`
799
799
  `).slice(0,4).join(`
800
- `)})})})},D=t=>{try{emitBridgeSplitBrainRederive(t,e.docName)&&(incrementBridgeSplitBrainRederives(),console.warn(JSON.stringify({event:`bridge-split-brain-rederive`,"doc.name":e.docName??null,site:t})))}catch(e){console.warn(`[Server Observer A] Split-brain telemetry failed:`,e)}},O=``,k=``,j=!1,F=!1,L=!1,B=()=>{k=g.toString(),j=!1},H=e=>{O=e,B(),j=e!==``},q=e=>{O=e,k=e,j=!1},ee=e=>{O=e,j=!1},J=e=>{O=e,k=g.toString(),j=!0},Y=()=>stripFrontmatter(g.toString()).frontmatter;try{let t=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(t),D=prependFrontmatter(Y(),E),O=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,k=S.serialize(S.parseWithFallback(stripFrontmatter(g.toString()).body,O)),j=e=>e.replace(/^\n+/,``).replace(/\n+$/,``);j(k)===j(E)?H(D):q(D)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),H(``)}let te=()=>{try{let F=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),B=S.serialize(F),ee=prependFrontmatter(Y(),B);if(j&&O===ee){settlesSplitBrain(g.toString(),ee)?(q(ee),L=!0,D(`identity-gate`),setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged-rederive`})):setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged`});return}let J=g.toString();if(normalizeBridge(J)===normalizeBridge(ee)){setActiveSpanAttributes({"observer.a.path":`gated-in-sync`}),H(ee);return}let te=k,ne=J===k,ae=k===O||normalizeBridge(k)===normalizeBridge(O),oe=j&&!ae;setActiveSpanAttributes({"observer.a.path":ne?oe?`residual-merge`:`path-a`:`path-b`});let se={mergedText:null},ce=ne&&oe?null:tryComputeMapDrivenSplice({currentText:J,lastSyncedXmlMd:k,json:F,mdManager:S,docName:e.docName});ce&&setActiveSpanAttributes({"observer.a.path":`map-driven-splice`}),t.transact(()=>{if(ce)applyMapDrivenSplice(g,ce);else if(ne&&!oe)applyIncrementalDiff(g,J,ee);else{let e=ne?O:te;try{let t=mergeThreeWay(e,ee,J);applyFastDiff(g,J,t),se.mergedText=t}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(E(e,te),shouldRethrowBridgeMergeLoss()))throw e;applyFastDiff(g,J,e.info.result),se.mergedText=e.info.result}}},OBSERVER_SYNC_ORIGIN),ce&&incrementMapDrivenSpliceApplied(),se.mergedText!==null&&!ne&&emitObserverAPathBFired(e.docName)&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!ne,mergeBytesChanged:Math.abs(se.mergedText.length-J.length)}))),se.mergedText!==null&&ne&&incrementObserverAResidualMergeRuns(),incrementServerObserverFire(`a`),H(ee),settlesSplitBrain(g.toString(),ee)&&(L=!0,D(`post-merge`))}catch(t){if(t instanceof BridgeMergeContentLossError)throw t;incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,t);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e),E=prependFrontmatter(Y(),t);settlesSplitBrain(g.toString(),E)?(J(E),L=!0,D(`error-recovery`)):H(E)}catch(s){console.warn(`[Server Observer A] Baseline recovery also failed`,JSON.stringify({"doc.name":e.docName??null,originalError:t instanceof Error?t.message:String(t),recoveryError:s instanceof Error?s.message:String(s)})),O=``,k=``,j=!1}}},ne=()=>{withSpanSync(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},te)},ae=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=Y();B(),oe=e}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),F=!0}return}F=!0}};if(s.length>0&&g.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(e),D=prependFrontmatter(Y(),E);t.transact(()=>{g.insert(0,D)},OBSERVER_SYNC_ORIGIN),H(D)}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),H(``)}let oe=Y(),se=()=>{try{let w=g.toString(),{frontmatter:E,body:D}=stripFrontmatter(w);if(normalizeBridge(k)===normalizeBridge(w)){oe!==E&&(recordFrontmatterEditSurface(`source-mode`),oe=E);return}let O=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,j=S.parseWithFallback(D,O),F=e.schema.nodeFromJSON(j);t.transact(()=>{updateYFragment(t,s,F,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),oe!==E&&(recordFrontmatterEditSurface(`source-mode`),oe=E),incrementServerObserverFire(`b`);try{let t=prependFrontmatter(E,S.serialize(j));assertBridgeInvariant(g.toString(),t,{site:`observer-b`,docName:e.docName}),H(t)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),H(prependFrontmatter(E,D))}}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e);ee(prependFrontmatter(Y(),t))}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},ce=()=>{withSpanSync(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},se)},ue=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=Y();B(),oe=e}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),L=!0}return}L=!0}},de=(t,s)=>{withSpanSync(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!F&&!L){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(s.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){F=!1,L=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}let g=F;F&&(F=!1,e.onDispatch?.(`a`),ne());let S=L;L&&(L=!1,e.onDispatch?.(`b`),ce()),t.setAttribute(`observer.dispatch`,g&&S?`a-then-b`:g?`a`:S?`b`:`none`)})};s.observeDeep(ae),g.observe(ue),t.on(`afterAllTransactions`,de);let fe=attachQuiescenceTracker(t);return()=>{fe(),t.off(`afterAllTransactions`,de),s.unobserveDeep(ae),g.unobserve(ue)}}const log$11=getLogger(`persistence`);var DocumentOpenSizeLimitError=class extends Error{docName;size;limit;constructor(e,t,s=DOCUMENT_OPEN_BYTE_LIMIT){super(`Document "${e}" is ${formatFileSize(t)}; Open Knowledge opens documents up to ${formatFileSize(s)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=s}};function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let s=e;if(s.source===`local`){let e=s.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(s.source===`connection`){let e=s.connection?.context;if(typeof e?.principalId==`string`){let s=e.principalId,g=t?.();return g&&g.id===s&&g.display_name&&g.display_email?{id:g.id,name:g.display_name,email:g.display_email}:{id:s,name:`Local User`,email:`${s}@openknowledge.local`}}return SERVICE_WRITER}return null}const ERRNO_FS_CODES=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function classifyDeferredStoreError(e){if(typeof e!=`object`||!e)return`unknown`;let t=e,s=typeof t.message==`string`?t.message:``;return s.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&ERRNO_FS_CODES.has(t.code)?s.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof BridgeInvariantViolationError?`serialize`:`unknown`}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let s=resolve(t,`${e}${getDocExtension(e)}`);if(!s.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return s}function isWithinContentDir(e,t){return e===t||e.startsWith(t+sep)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function toStoreFailure(e){let t;try{let s=e?.code;typeof s==`string`&&(t=s)}catch{}let s=`unknown store error`;try{s=e instanceof Error?e.message:String(e)}catch{}return{code:t,message:s}}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),s;try{s=realpathSync(t)}catch{s=t}let g=e?.projectDir??process.cwd(),S=e?.shadowRef,w=e?.contentRoot??(relative(g,s)||`.`),E=e?.backlinkIndex,D=e?.getPrincipal,O=e?.onAgentCommit,k=e?.onDiskFlush,j=e?.mdManager??mdManager,F=e?.ephemeral??!1,L={projectDir:g,contentDir:s,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected,ephemeral:F},B=new Set,H=e?.applyDiskContentToDoc??applyDiskContentToDoc,q=null,ee=8,J=new Map,Y=new Map,te=new Set,ne=new Set,ae=e?.gitEnabled??!0,oe=e?.commitDebounceMs??15e3,se=e?.wipRef??`refs/wip/main`,ce=e?.getCurrentBranch,ue=null,de=0,fe=null,me=!1,ge=null,_e=new Map;async function ve(){Re();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await ye()).finally(()=>{Ie?.record((Date.now()-e)/1e3)})}async function ye(){let e=S?.current;if(e){let t=swapContributors(),s=ce?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},g=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,w,g,s);de=0,log$11.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`);try{backfillRenameLogCommitSha(e.gitDir,SERVICE_WRITER.id,t,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$11.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){de++,incrementGitAutoSaveFailure(),log$11.error({err:e,attempt:de},`[persistence] Shadow commit failed (attempt ${de})`),de>=3&&log$11.error({attempt:de},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let g;try{g=await buildWipTree(e,w)}catch(e){restoreContributors(t),de++,incrementGitAutoSaveFailure(),log$11.error({err:e,attempt:de},`[persistence] Shadow WIP tree build failed (attempt ${de})`);return}let S=!1;for(let[w,E]of t){let t={id:w,name:E.displayName,email:`${w}@openknowledge.local`},D=[...E.docs],k=E.actor,j=[...E.summaries],F=[...E.previousPaths],L={v:1,writer_id:w,principal:k?.principalId??null,agent_session:w.startsWith(`agent-`)?w.slice(6):null,agent_type:k?.agentType??null,client_name:k?.clientName??null,client_version:k?.clientVersion??null,label:k?.label??null,display_name:E.displayName,color_seed:E.colorSeed,docs:D,...j.length>0?{summaries:j}:{},...F.length>0?{previous_paths:F}:{}},B=`${composeCommitSubject(E.subjectOverride??formatWipSubject(D),j)}\n\n${formatOkActor(L)}`;try{let E=await commitWipFromTree(e,t,g,B,s);S=!0,log$11.info({sha:E.slice(0,8),writer:w,tree:g.slice(0,8)},`[persistence] Shadow WIP commit: ${E.slice(0,8)} on refs/wip/${w}`);try{backfillRenameLogCommitSha(e.gitDir,w,E,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$11.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}w.startsWith(`agent-`)&&O?.()}catch(e){restoreContributorEntry(w,E),incrementGitWriterCommitFailure(),log$11.error({err:e,writer:w},`[persistence] Per-writer shadow commit failed for ${w}`)}}S?de=0:(de++,incrementGitAutoSaveFailure(),de>=3&&log$11.error({attempt:de},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(g,`.git`),workTree:g}),s=resolve(g,`.git/index-wip`),E={GIT_INDEX_FILE:s};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(E).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$11.info({},`[persistence] Empty repo — starting with empty index`):log$11.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(E).raw(`add`,w);let e=(await t.env(E).raw(`write-tree`)).trim(),s=null;try{s=(await t.raw(`rev-parse`,se)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let g=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];s&&g.push(`-p`,s);let S=(await t.raw(...g)).trim();await t.raw(`update-ref`,se,S),de=0,log$11.info({sha:S.slice(0,8),wipRef:se},`[persistence] Git commit: ${S.slice(0,8)} on ${se}`)}catch(e){de++,incrementGitAutoSaveFailure(),log$11.error({err:e,attempt:de},`[persistence] Git commit failed (attempt ${de})`),de>=3&&log$11.error({attempt:de},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(s)}catch{}}}function Ce(e){if(e<=0)return oe;let t=2**Math.min(e,5),s=Math.random()*.25*oe;return oe*t+s}function we(){ae&&(isBatchInProgress()||(ue&&clearTimeout(ue),ue=setTimeout(()=>{if(ue=null,fe){me=!0;return}fe=ve().finally(()=>{fe=null,me&&(me=!1,we())})},Ce(de))))}async function Te(){ue&&(clearTimeout(ue),ue=null,fe||=ve().finally(()=>{fe=null,me&&(me=!1,we())})),fe&&await fe}function De(t,s){try{let{frontmatter:g,body:S}=stripFrontmatter(t),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:s}:void 0,E=j.parseWithFallback(S,w);return normalizeBridge(prependFrontmatter(g,j.serialize(E)))}catch(e){return log$11.debug({err:e,documentName:s},`[g8] ephemeral canonical baseline failed; falling through to write`),null}}function je(t,s,g){try{let S=t.getXmlFragment(`default`),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:g}:void 0,E=mdManager.parseWithFallback(s,w),D=schema.nodeFromJSON(E);t.transact(()=>{updateYFragment(t,S,D,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN)}catch(e){incrementPersistenceReconciliationFailures(),log$11.warn({err:e,documentName:g},`[persistence] reconcileFragmentNow failed for ${g}`)}}let Me=null,Pe=null,Ie=null;function Re(){if(Me)return;let e=getMeter();Me=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),Pe=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),Ie=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function ze({document:e,documentName:t,lastTransactionOrigin:g}){Re();let S=Date.now();return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":t}},async()=>{let S=ne.delete(t),w=e.getMap(`lifecycle`).get(`status`);if(w===`deleted-upstream`||w===`renamed`||w===`conflict`){log$11.info({documentName:t,lifecycleStatus:w},`[persistence] Skipped store for ${t}: lifecycle=${w}`),J.delete(t),B.delete(t);return}if(!isDocQuiescent(e)){let s=J.get(t)??0;if(s<8){let g=getMsSinceLastUserTx(e);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":t,wallClockMsSinceLastTransaction:g??null,deferCount:s})),incrementPersistenceSkipNonQuiescent(),J.set(t,s+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":t,wallClockMsSinceLastTransaction:getMsSinceLastUserTx(e)??null,deferCount:s})),incrementPersistenceForceFlushDuringBurst()}let{sv:O,json:L}=captureDocSnapshotForPersistence(e),{frontmatter:q,body:ee}=stripFrontmatter(e.getText(`source`).toString()),ae=prependFrontmatter(q,ee),oe;try{oe=assertBridgeInvariant(ae,prependFrontmatter(q,j.serialize(L)),{site:`persistence`,docName:t,suppressDevThrow:!0})}catch(e){incrementPersistenceSanityCheckSerializeFailures(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":t,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),log$11.warn({err:e,documentName:t},`[persistence] Sanity-check serialize failed for ${t}; proceeding with ytext bytes`),oe=!1}oe||je(e,ee,t);let se=getReconciledBase(t),ce=normalizeBridge(ae),ue=se!==void 0&&ce===normalizeBridge(se);if(!ue&&F&&se!==void 0){let e=De(se,t);e!==null&&ce===e&&(ue=!0)}if(ue){contributorCount()>0&&we(),J.delete(t);return}if(se===void 0&&normalizeBridge(ae)===``){log$11.warn({documentName:t},`[persistence] Skipped phantom write for ${t}: empty Y.Doc with no reconciled base`),J.delete(t);return}let de=resolveWriterFromOrigin(g,D);if(de&&de.id!==SERVICE_WRITER.id&&(hasContributor(de.id)||recordContributor(t,de.id,de.name,de.id)),se!==void 0){let g=classifyDuplication(ae,se);if(g.kind===`block`){if(B.has(t)){log$11.warn({documentName:t},`[persistence] Tripwire breaker active — skipping duplicate store for ${t}`);return}let S=e.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":t,candidateBytes:ae.length,baseBytes:se.length,fragmentChildren:S,copies:g.copies,reason:g.reason}));try{let g=safeContentPath(t,s),S;if(existsSync(g)){let e=null;try{e=realpathSync(g)}catch(e){log$11.warn({err:e,documentName:t},`[persistence] Tripwire reset realpath failed for ${t}; using currentBase`)}if(e&&isWithinContentDir(e,s))try{S=readFileSync(e,`utf-8`)}catch(s){log$11.warn({err:s,documentName:t,canonical:e},`[persistence] Tripwire reset readFileSync failed for ${t}; using currentBase`),S=se}else e&&console.warn(`[persistence] symlink-escape on tripwire reset: ${g} → ${e}, using currentBase`,{docName:t,originalPath:g,canonical:e,contentDir:s}),S=se}else S=se;e.transact(()=>{H(e,S)},FILE_WATCHER_ORIGIN),B.delete(t)}catch(e){B.add(t),log$11.error({err:e,documentName:t},`[persistence] Tripwire reset failed for ${t}`)}J.delete(t);return}}let fe=safeContentPath(t,s);await tracedMkdir(dirname(fe),{recursive:!0});let me;try{me=await realpath(fe)}catch(e){let s=e.code;if(s===`ENOENT`){let e=!1;try{e=lstatSync(fe).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$11.warn({err:e,path:fe},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),me=fe}else if(s===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${fe}`),Error(`Symlink cycle detected at ${fe}`);else throw e}if(!isWithinContentDir(me,s)){let e=`symlink-escape: ${fe} resolves to ${me} outside ${s}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:fe,canonical:me,contentDir:s}),Error(e)}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_DIVERGENCE===t&&await tracedWriteFile(me,`# NATIVE
800
+ `)})})})},D=t=>{try{emitBridgeSplitBrainRederive(t,e.docName)&&(incrementBridgeSplitBrainRederives(),console.warn(JSON.stringify({event:`bridge-split-brain-rederive`,"doc.name":e.docName??null,site:t})))}catch(e){console.warn(`[Server Observer A] Split-brain telemetry failed:`,e)}},O=``,k=``,j=!1,F=!1,L=!1,B=()=>{k=g.toString(),j=!1},H=e=>{O=e,B(),j=e!==``},q=e=>{O=e,k=e,j=!1},ee=e=>{O=e,j=!1},J=e=>{O=e,k=g.toString(),j=!0},Y=()=>stripFrontmatter(g.toString()).frontmatter;try{let t=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(t),D=prependFrontmatter(Y(),E),O=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,k=S.serialize(S.parseWithFallback(stripFrontmatter(g.toString()).body,O)),j=e=>e.replace(/^\n+/,``).replace(/\n+$/,``);j(k)===j(E)?H(D):q(D)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),H(``)}let te=()=>{try{let F=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),B=S.serialize(F),ee=prependFrontmatter(Y(),B);if(j&&O===ee){settlesSplitBrain(g.toString(),ee)?(q(ee),L=!0,D(`identity-gate`),setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged-rederive`})):setActiveSpanAttributes({"observer.a.path":`gated-fragment-unchanged`});return}let J=g.toString(),te=normalizeBridge(J),ne=normalizeBridge(ee);if(te===ne){setActiveSpanAttributes({"observer.a.path":`gated-in-sync`}),H(ee);return}let ae=k,oe=J===k,se=oe&&j&&k!==O&&te!==normalizeBridge(O);setActiveSpanAttributes({"observer.a.path":oe?se?`residual-merge`:`path-a`:`path-b`});let ce={mergedText:null},ue=performance.now(),de=oe&&se?null:tryComputeMapDrivenSplice({currentText:J,lastSyncedXmlMd:k,json:F,mdManager:S,docName:e.docName});de&&setActiveSpanAttributes({"observer.a.path":`map-driven-splice`,"observer.a.splice.compute_ms":Math.round(performance.now()-ue)}),t.transact(()=>{if(de)applyMapDrivenSplice(g,de);else if(oe&&!se)applyIncrementalDiff(g,J,ee);else{let e=oe?O:ae;try{let t=mergeThreeWay(e,ee,J);applyFastDiff(g,J,t),ce.mergedText=t}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(E(e,ae),shouldRethrowBridgeMergeLoss()))throw e;applyFastDiff(g,J,e.info.result),ce.mergedText=e.info.result}}},OBSERVER_SYNC_ORIGIN),de&&incrementMapDrivenSpliceApplied(),ce.mergedText!==null&&!oe&&emitObserverAPathBFired(e.docName)&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!oe,mergeBytesChanged:Math.abs(ce.mergedText.length-J.length)}))),ce.mergedText!==null&&oe&&incrementObserverAResidualMergeRuns(),incrementServerObserverFire(`a`),H(ee),settlesSplitBrain(g.toString(),ee,ne)&&(L=!0,D(`post-merge`))}catch(t){if(t instanceof BridgeMergeContentLossError)throw t;incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,t);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e),E=prependFrontmatter(Y(),t);settlesSplitBrain(g.toString(),E)?(J(E),L=!0,D(`error-recovery`)):H(E)}catch(s){console.warn(`[Server Observer A] Baseline recovery also failed`,JSON.stringify({"doc.name":e.docName??null,originalError:t instanceof Error?t.message:String(t),recoveryError:s instanceof Error?s.message:String(s)})),O=``,k=``,j=!1}}},ne=()=>{withSpanSync(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},te)},ae=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=Y();B(),oe=e}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),F=!0}return}F=!0}};if(s.length>0&&g.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(e),D=prependFrontmatter(Y(),E);t.transact(()=>{g.insert(0,D)},OBSERVER_SYNC_ORIGIN),H(D)}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),H(``)}let oe=Y(),se=()=>{try{let w=g.toString(),{frontmatter:E,body:D}=stripFrontmatter(w);if(normalizeBridge(k)===normalizeBridge(w)){oe!==E&&(recordFrontmatterEditSurface(`source-mode`),oe=E);return}let O=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,j=S.parseWithFallback(D,O),F=e.schema.nodeFromJSON(j);t.transact(()=>{updateYFragment(t,s,F,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),oe!==E&&(recordFrontmatterEditSurface(`source-mode`),oe=E),incrementServerObserverFire(`b`);try{let t=prependFrontmatter(E,S.serialize(j));assertBridgeInvariant(g.toString(),t,{site:`observer-b`,docName:e.docName}),H(t)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),H(prependFrontmatter(E,D))}}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e);ee(prependFrontmatter(Y(),t))}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},ce=()=>{withSpanSync(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},se)},ue=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=Y();B(),oe=e}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),L=!0}return}L=!0}},de=(t,s)=>{withSpanSync(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!F&&!L){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(s.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){F=!1,L=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}let g=F;F&&(F=!1,e.onDispatch?.(`a`),ne());let S=L;L&&(L=!1,e.onDispatch?.(`b`),ce()),t.setAttribute(`observer.dispatch`,g&&S?`a-then-b`:g?`a`:S?`b`:`none`)})};s.observeDeep(ae),g.observe(ue),t.on(`afterAllTransactions`,de);let fe=attachQuiescenceTracker(t);return()=>{fe(),t.off(`afterAllTransactions`,de),s.unobserveDeep(ae),g.unobserve(ue)}}const log$11=getLogger(`persistence`);var DocumentOpenSizeLimitError=class extends Error{docName;size;limit;constructor(e,t,s=DOCUMENT_OPEN_BYTE_LIMIT){super(`Document "${e}" is ${formatFileSize(t)}; Open Knowledge opens documents up to ${formatFileSize(s)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=s}};function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let s=e;if(s.source===`local`){let e=s.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(s.source===`connection`){let e=s.connection?.context;if(typeof e?.principalId==`string`){let s=e.principalId,g=t?.();return g&&g.id===s&&g.display_name&&g.display_email?{id:g.id,name:g.display_name,email:g.display_email}:{id:s,name:`Local User`,email:`${s}@openknowledge.local`}}return SERVICE_WRITER}return null}const ERRNO_FS_CODES=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function classifyDeferredStoreError(e){if(typeof e!=`object`||!e)return`unknown`;let t=e,s=typeof t.message==`string`?t.message:``;return s.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&ERRNO_FS_CODES.has(t.code)?s.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof BridgeInvariantViolationError?`serialize`:`unknown`}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let s=resolve(t,`${e}${getDocExtension(e)}`);if(!s.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return s}function isWithinContentDir(e,t){return e===t||e.startsWith(t+sep)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function toStoreFailure(e){let t;try{let s=e?.code;typeof s==`string`&&(t=s)}catch{}let s=`unknown store error`;try{s=e instanceof Error?e.message:String(e)}catch{}return{code:t,message:s}}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),s;try{s=realpathSync(t)}catch{s=t}let g=e?.projectDir??process.cwd(),S=e?.shadowRef,w=e?.contentRoot??(relative(g,s)||`.`),E=e?.backlinkIndex,D=e?.getPrincipal,O=e?.onAgentCommit,k=e?.onDiskFlush,j=e?.mdManager??mdManager,F=e?.ephemeral??!1,L={projectDir:g,contentDir:s,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected,ephemeral:F},B=new Set,H=e?.applyDiskContentToDoc??applyDiskContentToDoc,q=null,ee=8,J=new Map,Y=new Map,te=new Set,ne=new Set,ae=e?.gitEnabled??!0,oe=e?.commitDebounceMs??15e3,se=e?.wipRef??`refs/wip/main`,ce=e?.getCurrentBranch,ue=null,de=0,fe=null,me=!1,ge=null,_e=new Map;async function ve(){Re();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await ye()).finally(()=>{Ie?.record((Date.now()-e)/1e3)})}async function ye(){let e=S?.current;if(e){let t=swapContributors(),s=ce?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},g=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,w,g,s);de=0,log$11.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`);try{backfillRenameLogCommitSha(e.gitDir,SERVICE_WRITER.id,t,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$11.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){de++,incrementGitAutoSaveFailure(),log$11.error({err:e,attempt:de},`[persistence] Shadow commit failed (attempt ${de})`),de>=3&&log$11.error({attempt:de},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let g;try{g=await buildWipTree(e,w)}catch(e){restoreContributors(t),de++,incrementGitAutoSaveFailure(),log$11.error({err:e,attempt:de},`[persistence] Shadow WIP tree build failed (attempt ${de})`);return}let S=!1;for(let[w,E]of t){let t={id:w,name:E.displayName,email:`${w}@openknowledge.local`},D=[...E.docs],k=E.actor,j=[...E.summaries],F=[...E.previousPaths],L={v:1,writer_id:w,principal:k?.principalId??null,agent_session:w.startsWith(`agent-`)?w.slice(6):null,agent_type:k?.agentType??null,client_name:k?.clientName??null,client_version:k?.clientVersion??null,label:k?.label??null,display_name:E.displayName,color_seed:E.colorSeed,docs:D,...j.length>0?{summaries:j}:{},...F.length>0?{previous_paths:F}:{}},B=`${composeCommitSubject(E.subjectOverride??formatWipSubject(D),j)}\n\n${formatOkActor(L)}`;try{let E=await commitWipFromTree(e,t,g,B,s);S=!0,log$11.info({sha:E.slice(0,8),writer:w,tree:g.slice(0,8)},`[persistence] Shadow WIP commit: ${E.slice(0,8)} on refs/wip/${w}`);try{backfillRenameLogCommitSha(e.gitDir,w,E,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$11.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}w.startsWith(`agent-`)&&O?.()}catch(e){restoreContributorEntry(w,E),incrementGitWriterCommitFailure(),log$11.error({err:e,writer:w},`[persistence] Per-writer shadow commit failed for ${w}`)}}S?de=0:(de++,incrementGitAutoSaveFailure(),de>=3&&log$11.error({attempt:de},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(g,`.git`),workTree:g}),s=resolve(g,`.git/index-wip`),E={GIT_INDEX_FILE:s};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(E).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$11.info({},`[persistence] Empty repo — starting with empty index`):log$11.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(E).raw(`add`,w);let e=(await t.env(E).raw(`write-tree`)).trim(),s=null;try{s=(await t.raw(`rev-parse`,se)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let g=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];s&&g.push(`-p`,s);let S=(await t.raw(...g)).trim();await t.raw(`update-ref`,se,S),de=0,log$11.info({sha:S.slice(0,8),wipRef:se},`[persistence] Git commit: ${S.slice(0,8)} on ${se}`)}catch(e){de++,incrementGitAutoSaveFailure(),log$11.error({err:e,attempt:de},`[persistence] Git commit failed (attempt ${de})`),de>=3&&log$11.error({attempt:de},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(s)}catch{}}}function Ce(e){if(e<=0)return oe;let t=2**Math.min(e,5),s=Math.random()*.25*oe;return oe*t+s}function we(){ae&&(isBatchInProgress()||(ue&&clearTimeout(ue),ue=setTimeout(()=>{if(ue=null,fe){me=!0;return}fe=ve().finally(()=>{fe=null,me&&(me=!1,we())})},Ce(de))))}async function Te(){ue&&(clearTimeout(ue),ue=null,fe||=ve().finally(()=>{fe=null,me&&(me=!1,we())})),fe&&await fe}function De(t,s){try{let{frontmatter:g,body:S}=stripFrontmatter(t),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:s}:void 0,E=j.parseWithFallback(S,w);return normalizeBridge(prependFrontmatter(g,j.serialize(E)))}catch(e){return log$11.debug({err:e,documentName:s},`[g8] ephemeral canonical baseline failed; falling through to write`),null}}function je(t,s,g){try{let S=t.getXmlFragment(`default`),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:g}:void 0,E=mdManager.parseWithFallback(s,w),D=schema.nodeFromJSON(E);t.transact(()=>{updateYFragment(t,S,D,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN)}catch(e){incrementPersistenceReconciliationFailures(),log$11.warn({err:e,documentName:g},`[persistence] reconcileFragmentNow failed for ${g}`)}}let Me=null,Pe=null,Ie=null;function Re(){if(Me)return;let e=getMeter();Me=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),Pe=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),Ie=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function ze({document:e,documentName:t,lastTransactionOrigin:g}){Re();let S=Date.now();return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":t}},async()=>{let S=ne.delete(t),w=e.getMap(`lifecycle`).get(`status`);if(w===`deleted-upstream`||w===`renamed`||w===`conflict`){log$11.info({documentName:t,lifecycleStatus:w},`[persistence] Skipped store for ${t}: lifecycle=${w}`),J.delete(t),B.delete(t);return}if(!isDocQuiescent(e)){let s=J.get(t)??0;if(s<8){let g=getMsSinceLastUserTx(e);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":t,wallClockMsSinceLastTransaction:g??null,deferCount:s})),incrementPersistenceSkipNonQuiescent(),J.set(t,s+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":t,wallClockMsSinceLastTransaction:getMsSinceLastUserTx(e)??null,deferCount:s})),incrementPersistenceForceFlushDuringBurst()}let{sv:O,json:L}=captureDocSnapshotForPersistence(e),{frontmatter:q,body:ee}=stripFrontmatter(e.getText(`source`).toString()),ae=prependFrontmatter(q,ee),oe;try{oe=assertBridgeInvariant(ae,prependFrontmatter(q,j.serialize(L)),{site:`persistence`,docName:t,suppressDevThrow:!0})}catch(e){incrementPersistenceSanityCheckSerializeFailures(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":t,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),log$11.warn({err:e,documentName:t},`[persistence] Sanity-check serialize failed for ${t}; proceeding with ytext bytes`),oe=!1}oe||je(e,ee,t);let se=getReconciledBase(t),ce=normalizeBridge(ae),ue=se!==void 0&&ce===normalizeBridge(se);if(!ue&&F&&se!==void 0){let e=De(se,t);e!==null&&ce===e&&(ue=!0)}if(ue){contributorCount()>0&&we(),J.delete(t);return}if(se===void 0&&normalizeBridge(ae)===``){log$11.warn({documentName:t},`[persistence] Skipped phantom write for ${t}: empty Y.Doc with no reconciled base`),J.delete(t);return}let de=resolveWriterFromOrigin(g,D);if(de&&de.id!==SERVICE_WRITER.id&&(hasContributor(de.id)||recordContributor(t,de.id,de.name,de.id)),se!==void 0){let g=classifyDuplication(ae,se);if(g.kind===`block`){if(B.has(t)){log$11.warn({documentName:t},`[persistence] Tripwire breaker active — skipping duplicate store for ${t}`);return}let S=e.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":t,candidateBytes:ae.length,baseBytes:se.length,fragmentChildren:S,copies:g.copies,reason:g.reason}));try{let g=safeContentPath(t,s),S;if(existsSync(g)){let e=null;try{e=realpathSync(g)}catch(e){log$11.warn({err:e,documentName:t},`[persistence] Tripwire reset realpath failed for ${t}; using currentBase`)}if(e&&isWithinContentDir(e,s))try{S=readFileSync(e,`utf-8`)}catch(s){log$11.warn({err:s,documentName:t,canonical:e},`[persistence] Tripwire reset readFileSync failed for ${t}; using currentBase`),S=se}else e&&console.warn(`[persistence] symlink-escape on tripwire reset: ${g} → ${e}, using currentBase`,{docName:t,originalPath:g,canonical:e,contentDir:s}),S=se}else S=se;e.transact(()=>{H(e,S)},FILE_WATCHER_ORIGIN),B.delete(t)}catch(e){B.add(t),log$11.error({err:e,documentName:t},`[persistence] Tripwire reset failed for ${t}`)}J.delete(t);return}}let fe=safeContentPath(t,s);await tracedMkdir(dirname(fe),{recursive:!0});let me;try{me=await realpath(fe)}catch(e){let s=e.code;if(s===`ENOENT`){let e=!1;try{e=lstatSync(fe).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$11.warn({err:e,path:fe},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),me=fe}else if(s===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${fe}`),Error(`Symlink cycle detected at ${fe}`);else throw e}if(!isWithinContentDir(me,s)){let e=`symlink-escape: ${fe} resolves to ${me} outside ${s}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:fe,canonical:me,contentDir:s}),Error(e)}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_DIVERGENCE===t&&await tracedWriteFile(me,`# NATIVE
801
801
 
802
802
  native-divergence-injected
803
803
  `,`utf-8`),S&&se!==void 0){let s=null;try{existsSync(me)&&(s=readFileSync(me,`utf-8`))}catch(e){s=null,log$11.warn({err:e,documentName:t},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(s!==null&&normalizeBridge(s)!==normalizeBridge(se)){let g=s;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":t,outcome:`reverted`,diskBytes:g.length,baseBytes:se.length,candidateBytes:ae.length}));try{e.transact(()=>{H(e,g)},FILE_WATCHER_ORIGIN)}catch(e){throw Y.set(t,toStoreFailure(e)),J.delete(t),e}setReconciledBase(t,g),te.add(t),J.delete(t);return}}let ge=`${me}.tmp.${crypto.randomUUID()}`;try{if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_FAULT===t){let e=Error(`OK_TEST_STORE_FAULT: simulated disk failure for ${t}`);throw e.code=`ENOSPC`,e}await tracedWriteFile(ge,ae,`utf-8`),await tracedRename(ge,me),registerWrite(me,contentHash(ae)),Y.delete(t),incrementPersistenceDiskWrite();try{k?.(t,O,ae,se??null)}catch(e){log$11.warn({err:e,documentName:t},`[persistence] onDiskFlush callback failed for ${t}`)}}catch(e){try{tracedUnlinkSync(ge)}catch{}throw J.delete(t),Y.set(t,toStoreFailure(e)),log$11.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}log$11.info({filePath:me,bytes:ae.length},`[persistence] Wrote ${me} (${ae.length} bytes)`),setReconciledBase(t,ae),B.delete(t),J.delete(t),E&&(E.updateDocumentFromMarkdown(t,ae),E.saveToDisk().catch(e=>{log$11.warn({err:e,documentName:t},`[backlinks] Failed to persist cache for ${t}`)})),setActiveSpanAttributes({"persistence.bytes":ae.length}),we()}).finally(()=>{Pe?.record((Date.now()-S)/1e3)})}function Be({document:e,documentName:t,lastTransactionOrigin:s}){_e.set(t,{branch:getActiveBranch(),document:e,lastTransactionOrigin:s})}async function Ve(e=`within-branch`){return ge?(q=q===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,ge):(ge=(async()=>{let t=e;for(;;){let e=[..._e.entries()];if(_e.clear(),t!==`discard-stale`){for(let[t,s]of e)if(s.branch===getActiveBranch())try{await ze({document:s.document,documentName:t,lastTransactionOrigin:s.lastTransactionOrigin})}catch(e){let s=process.env.OK_TELEMETRY_VERBOSE===`1`,g=``;try{g=String(e?.message??``)}catch{g=``}let S=fnv1aDigest(g),w;try{w=classifyDeferredStoreError(e)}catch(e){let g=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":t,classifyErrorHash:fnv1aDigest(g),errorMessageHash:S,...s?{classifyErrorMessage:g}:{},timestamp:new Date().toISOString()})),w=`unknown`}incrementDeferredStoreFailures(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":t,errorClass:w,errorMessageHash:S,...s?{errorMessage:g}:{},timestamp:new Date().toISOString()})),log$11.error({err:e,documentName:t},`[persistence] Deferred store failed for ${t}`)}}let s=q;if(q=null,_e.size===0&&s===null)break;t=s??`within-branch`}})().finally(()=>{ge=null}),ge)}let Ue={async onLoadDocument({document:t,documentName:g,context:S}){if(isSystemDoc(g))return;if(isConfigDoc(g)){loadConfigDoc(t,g,L);return}Re();let w=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":g}},async()=>{log$11.info({documentName:g,connections:t.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${g} (connections: ${t.getConnectionsCount?.()??`?`})`);let S=safeContentPath(g,s);if(!existsSync(S))return;let w=S;try{let e=realpathSync(S);if(!isWithinContentDir(e,s)){console.warn(`[persistence] symlink-escape on load: ${S} → ${e}, refusing`);return}w=e}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${S}, refusing`);return}}let E=statSync(w).size;if(E>524288)throw log$11.warn({documentName:g,fileSize:E,limit:DOCUMENT_OPEN_BYTE_LIMIT},`[persistence] Document exceeds open byte limit; refusing to load`),new DocumentOpenSizeLimitError(g,E);let D=readFileSync(S,`utf-8`),O=t.getXmlFragment(`default`);log$11.info({documentName:g,fragmentLength:O.length},`[persistence] onLoadDocument ${g}: fragment.length=${O.length} before update`),O.length===0?(t.transact(()=>{applyDiskContentToDoc(t,D,e?.resolveEmbed,g,e?.resolveSize),t.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},FILE_WATCHER_ORIGIN),log$11.info({filePath:S,children:O.length},`[persistence] Loaded ${S} into Y.Doc (${O.length} children)`),O.observeDeep(()=>{log$11.info({documentName:g,fragmentLength:O.length},`[persistence] MUTATION on ${g}: fragment.length=${O.length}`)})):log$11.info({documentName:g,children:O.length},`[persistence] Skipped load for ${g} — fragment already has ${O.length} children`),setReconciledBase(g,D)}).finally(()=>{Me?.record((Date.now()-w)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:s,lastContext:g}){if(!isSystemDoc(t)){if(isConfigDoc(t)){await storeConfigDoc(e,t,s,L);return}if(isBatchInProgress()){Be({document:e,documentName:t,lastTransactionOrigin:s});return}return ze({document:e,documentName:t,lastTransactionOrigin:s})}}};async function We(){fe&&await fe}async function Ge(){if(fe){await fe;return}contributorCount()!==0&&(fe=ve().finally(()=>{fe=null,me&&(me=!1,we())}),await fe)}function Ke(e){let t=Y.get(e);return t&&Y.delete(e),t??null}function Xe(e){return te.has(e)?(te.delete(e),!0):!1}function $e(e){ne.add(e)}return{extension:Ue,flushDeferredStores:Ve,flushPendingGitCommit:Te,flushContributors:Ge,waitForPendingCommits:We,takeStoreFailure:Ke,takeStoreDivergence:Xe,markAgentWriteStore:$e,configPersistenceCtx:L}}const MARKDOWN_LINK_OR_IMAGE_RE=/!?\[[^\]\n]*(?:\][^[\]\n]*)?\]\((?:<([^>\n]+)>|([^)\s]+))(?:\s+['"][^'"]*['"])?\)/g,WIKI_LINK_OR_EMBED_RE=/!?\[\[([^[\]|#]+?)(?:#[^\]|]+?)?(?:\|[^\]]+?)?\]\]/g,HTML_LINK_ATTR_RE=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function isRemoteOrOpaqueHref(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function stripHrefDecorations(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),s=t.indexOf(`#`),g=s>=0?t.slice(0,s):t,S=g.indexOf(`?`);return S>=0?g.slice(0,S):g}function isLocalAssetReferenceHref(e){let t=stripHrefDecorations(e);return!t||isRemoteOrOpaqueHref(t)?!1:LINKABLE_ASSET_EXTENSIONS.has(extname(t).slice(1).toLowerCase())}function assetReferenceSignature(e){return e?[...new Set(extractLocalAssetHrefs(e).filter(isLocalAssetReferenceHref))].sort().join(`\0`):``}function assetReferencesChanged(e,t){return assetReferenceSignature(e)!==assetReferenceSignature(t)}function decodeHrefPath(e){let t=stripHrefDecorations(e);try{return decodeURI(t)}catch{return t}}function mediaKindForAssetPath(e){return mediaKindForSidebarAssetExtension(extname(e).slice(1).toLowerCase())}function errnoCode$1(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function collectHrefsFromLine(e,t){for(let s of e.matchAll(MARKDOWN_LINK_OR_IMAGE_RE)){let e=s[1]??s[2];e&&t.add(e)}for(let s of e.matchAll(WIKI_LINK_OR_EMBED_RE)){let e=s[1];e&&t.add(e)}for(let s of e.matchAll(HTML_LINK_ATTR_RE)){let e=s[1]??s[2]??s[3]??s[4];e&&t.add(e)}}function stripHtmlComments(e,t){let s=e,g=``;for(;s.length>0;){if(t.inComment){let e=s.indexOf(`-->`);if(e===-1)return g;s=s.slice(e+3),t.inComment=!1;continue}let e=s.indexOf(`<!--`);if(e===-1)return g+s;g+=s.slice(0,e),s=s.slice(e+4),t.inComment=!0}return g}function extractLocalAssetHrefs(e){let t=new Set,s=createCodeFenceTracker(),g={inComment:!1};for(let S of e.replaceAll(`\r
@@ -821,13 +821,11 @@ 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: "${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(`
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)}}let S=s===void 0?g:resolve(s);try{let e=await resolveConfig(t,g);return{ok:!0,cwd:g,executionCwd:S,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function resolveProjectServerContext(e,t,s,g){let S=await resolveProjectConfigContext(e,t,g);if(!S.ok)return S;let{cwd:w,executionCwd:E,config:D}=S;try{return{ok:!0,cwd:w,executionCwd:E,config:D,url:await resolveServerUrl(s,w)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function 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 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$10=getLogger(`embeddings`);let _tokens=null,_errors=null,_requestDuration=null,_queryTotal=null,_queryEmbedDuration=null;function tokensCounter(){return _tokens||=getMeter().createCounter(`ok.embeddings.tokens_total`,{description:`Embeddings tokens billed, by role. Bounded label: role ∈ {query, document}. Makes spend legible; never includes content.`}),_tokens}function errorsCounter(){return _errors||=getMeter().createCounter(`ok.embeddings.provider_errors_total`,{description:`Embeddings provider failures, by reason. Bounded label: reason ∈ {rate_limit, timeout, http_error, network, dims_mismatch, malformed_response}.`}),_errors}function requestDurationHist(){return _requestDuration||=getMeter().createHistogram(`ok.embeddings.request_duration_ms`,{description:`Wall-clock duration of one embeddings API request. Bounded label: role.`,unit:`ms`}),_requestDuration}function queryTotalCounter(){return _queryTotal||=getMeter().createCounter(`ok.search.semantic_query_total`,{description:`Semantic-requested searches, by outcome and caller surface. Bounded labels: outcome ∈ {applied, no_match, warming, incapable, provider_error}, source ∈ {omnibar, mcp, http}. The omnibar/mcp split separates interactive cost from agent cost.`}),_queryTotal}function queryEmbedDurationHist(){return _queryEmbedDuration||=getMeter().createHistogram(`ok.search.semantic_query_embed_ms`,{description:`Wall-clock latency of the per-query embed on the semantic search path.`,unit:`ms`}),_queryEmbedDuration}function recordEmbeddingTokens(e,t){t>0&&tokensCounter().add(t,{role:e})}function recordEmbeddingProviderError(e){errorsCounter().add(1,{reason:e})}function recordEmbeddingRequestDuration(e,t){requestDurationHist().record(Math.max(0,t),{role:e})}function recordSemanticQuery(e){queryTotalCounter().add(1,{outcome:e.outcome,source:e.source}),e.queryEmbedMs!==null&&queryEmbedDurationHist().record(Math.max(0,e.queryEmbedMs)),log$10.debug({outcome:e.outcome,source:e.source,capable:e.capable,embedded:e.embedded,total:e.total,coverage:e.total>0?e.embedded/e.total:0,queryEmbedMs:e.queryEmbedMs,vectorContributors:e.vectorContributors},`[search] semantic query`)}const DEFAULT_EMBEDDINGS_DIMENSIONS=1536,EMBEDDINGS_API_KEY_ENV=`OK_EMBEDDINGS_API_KEY`;var EmbeddingDimsMismatchError=class extends Error{name=`EmbeddingDimsMismatchError`;constructor(e,t){super(`embeddings provider returned ${t}-dim vectors, expected ${e}. Set search.semantic.dimensions to ${t} (or point at the right model).`),this.expected=e,this.got=t}},MalformedEmbeddingResponseError=class extends Error{name=`MalformedEmbeddingResponseError`;constructor(e,t){super(`embeddings response had ${t} vectors, expected ${e}`)}};function cosineSimilarity(e,t){let s=0,g=Math.min(e.length,t.length);for(let S=0;S<g;S++)s+=e[S]*t[S];return s}function normalizeInPlace(e){let t=0;for(let s=0;s<e.length;s++)t+=e[s]*e[s];if(t=Math.sqrt(t),t>0)for(let s=0;s<e.length;s++)e[s]/=t;return e}const DEFAULTS={maxBatchSize:96,maxBatchChars:96e3,docTimeoutMs:3e4,queryTimeoutMs:8e3,maxRetries:4,backoffBaseMs:500};function normalizeProviderId(e){try{let t=new URL(e),s=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${s}`}catch{return e.trim().replace(/\/+$/,``)}}function assertSafeEmbeddingsBaseUrl(e){let t;try{t=new URL(e)}catch{throw Error(`embeddings baseUrl is not a valid URL: ${e}`)}if(t.protocol===`https:`)return;let s=t.hostname.toLowerCase(),g=s===`localhost`||s===`127.0.0.1`||s===`::1`||s===`[::1]`;if(!(t.protocol===`http:`&&g))throw Error(`refusing to send the embeddings API key to a non-HTTPS endpoint (${t.protocol}//${t.host}); use https:// (http:// is allowed only for localhost)`)}const RETRYABLE_STATUS=new Set([408,409,429,500,502,503,504]);function defaultSleep$1(e){return new Promise(t=>setTimeout(t,e))}function createOpenAiEmbedder(e,t={}){let s=t.fetchImpl??fetch,g=t.sleep??defaultSleep$1,S=t.maxBatchSize??DEFAULTS.maxBatchSize,w=t.maxBatchChars??DEFAULTS.maxBatchChars,E=t.maxRetries??DEFAULTS.maxRetries,D=t.backoffBaseMs??DEFAULTS.backoffBaseMs,O=t.docTimeoutMs??DEFAULTS.docTimeoutMs,k=t.queryTimeoutMs??DEFAULTS.queryTimeoutMs;assertSafeEmbeddingsBaseUrl(e.baseUrl);let j=e.dimensions??1536,F=`${e.baseUrl.replace(/\/+$/,``)}/embeddings`;function L(e){let t=[],s=[],g=0;for(let E of e)s.length>0&&(s.length>=S||g+E.length>w)&&(t.push(s),s=[],g=0),s.push(E),g+=E.length;return s.length>0&&t.push(s),t}async function B(t,g,S,w){let E=new AbortController,D=setTimeout(()=>E.abort(),w),O=performance.now();try{let w=await s(F,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.apiKey}`},body:t,signal:E.signal});if(recordEmbeddingRequestDuration(S,performance.now()-O),!w.ok){await w.text().catch(()=>``);let e=w.status===429?`rate_limit`:`http_error`,t=Error(`embeddings request failed: HTTP ${w.status}`);return RETRYABLE_STATUS.has(w.status)?{kind:`retry`,reason:e,error:t}:{kind:`fatal`,reason:e,error:t}}let D=await w.json(),k=q(D,g,j);return recordEmbeddingTokens(S,D.usage?.total_tokens??0),{kind:`ok`,vectors:k}}catch(e){if(e instanceof EmbeddingDimsMismatchError)return{kind:`fatal`,reason:`dims_mismatch`,error:e};if(e instanceof MalformedEmbeddingResponseError)return{kind:`fatal`,reason:`malformed_response`,error:e};let t=e instanceof Error&&e.name===`AbortError`,s=e instanceof Error?e:Error(String(e));return{kind:`retry`,reason:t?`timeout`:`network`,error:s}}finally{clearTimeout(D)}}async function H(t,s){let S=s===`query`?k:O,w=s===`query`?`query`:`document`,j=JSON.stringify({model:e.model,input:t,encoding_format:`float`,...e.dimensions===void 0?{}:{dimensions:e.dimensions}}),F=0;for(;;){let e=await B(j,t.length,w,S);if(e.kind===`ok`)return e.vectors;if(recordEmbeddingProviderError(e.reason),e.kind===`fatal`||F>=E)throw e.error;F+=1;let s=D*2**(F-1);await g(Math.round(s/2+s/2*Math.random()))}}function q(e,t,s){let g=e.data;if(!Array.isArray(g)||g.length!==t)throw new MalformedEmbeddingResponseError(t,g?.length??0);let S=[...g].sort((e,t)=>(e.index??0)-(t.index??0)),w=[];for(let e of S){let g=e.embedding;if(!Array.isArray(g))throw new MalformedEmbeddingResponseError(t,0);if(g.length!==s)throw new EmbeddingDimsMismatchError(s,g.length);w.push(normalizeInPlace(Float32Array.from(g)))}return w}return{providerId:normalizeProviderId(e.baseUrl),modelId:e.model,dims:j,async embed(e,{role:t}){if(e.length===0)return[];let s=[];for(let g of L(e))s.push(...await H(g,t));return s}}}async function loadOpenAiEmbedder(e){let t=(e.keyStore?await e.keyStore.get().catch(()=>null):null)??process.env.OK_EMBEDDINGS_API_KEY??null;return t?createOpenAiEmbedder({...e.config,apiKey:t},e.options):null}const SECRETS_KEY_FIELD=`OPENAI_API_KEY`,LEGACY_KEY_FIELD=`embeddings`;function secretsFilePath(e){return join(e??homedir(),`.ok`,`secrets.yml`)}var FileEmbeddingsBackend=class{backend=`file`;secretsFile;constructor(e){this.secretsFile=e??secretsFilePath()}tightenPermsIfLoose(){let e;try{e=statSync(this.secretsFile).mode&511}catch{return}if(e&63)try{chmodSync(this.secretsFile,384),process.stderr.write(`[embeddings] ${this.secretsFile} was readable beyond your user account (mode ${e.toString(8)}); tightened to 600. It stores an API key.\n`)}catch(t){let s=t instanceof Error?t.message:`unknown error`;process.stderr.write(`[embeddings] ${this.secretsFile} is readable beyond your user account (mode ${e.toString(8)}) and could not be tightened (${s}); your API key remains exposed — run: chmod 600 ${this.secretsFile}\n`)}}read(){if(!existsSync(this.secretsFile))return{};this.tightenPermsIfLoose();try{return(0,import_dist$1.parse)(readFileSync(this.secretsFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[embeddings] Failed to parse ${this.secretsFile}: ${t}. Starting with empty secrets.\n`),{}}}write(e){let t=dirname(this.secretsFile);existsSync(t)||tracedMkdirSync(t,{recursive:!0,mode:448}),tracedWriteFileSync(this.secretsFile,(0,import_dist$1.stringify)(e),{mode:384}),chmodSync(this.secretsFile,384)}get(){let e=this.read(),t=e[SECRETS_KEY_FIELD]??e[LEGACY_KEY_FIELD];return Promise.resolve(typeof t==`string`&&t!==``?t:null)}set(e){let t=this.read();return delete t[LEGACY_KEY_FIELD],t[SECRETS_KEY_FIELD]=e,this.write(t),Promise.resolve()}clear(){let e=this.read();if(SECRETS_KEY_FIELD in e||LEGACY_KEY_FIELD in e)if(delete e[SECRETS_KEY_FIELD],delete e[LEGACY_KEY_FIELD],Object.keys(e).length===0)try{tracedUnlinkSync(this.secretsFile)}catch{}else this.write(e);return Promise.resolve()}};function createEmbeddingsSecretStore(e){return new FileEmbeddingsBackend(e)}function makeLazyEmbeddingsKeyStore(e){return new FileEmbeddingsBackend(e)}async function describeStoredEmbeddingsKey(e){return{file:await new FileEmbeddingsBackend(e).get()!=null}}async function clearEmbeddingsKeyFromAllBackends(e){let t=[],s=new FileEmbeddingsBackend(e);return await s.get()!=null&&(await s.clear(),t.push(`file`)),{touched:t}}function readProjectLocalSemanticConfig(e,t){let s=readConfigSafely({absPath:resolveConfigPath(`project-local`,e,t?.configHomedirOverride),sideline:!1,warn:t?.onWarn??(()=>{})}).value.search?.semantic;return{enabled:s?.enabled===!0,baseUrl:s?.baseUrl??`https://api.openai.com/v1`,model:s?.model??`text-embedding-3-small`,dimensions:s?.dimensions??void 0,similarityFloor:s?.similarityFloor??void 0}}const CHUNK_CONFIG_ID=`c8000-o400-m80`;function chunkDocument(e,t={}){let s=Math.max(1,t.targetChars??8e3),g=Math.max(0,Math.min(t.overlapChars??400,s-1)),S=t.maxChunks??80;if(e.trim().length===0)return[];if(e.length<=s)return[e.trim()];let w=[],E=0;for(;E<e.length&&w.length<S;){let t=Math.min(e.length,E+s);if(t<e.length){let g=Math.max(e.lastIndexOf(` `,t),e.lastIndexOf(`
827
- `,t));g>E+Math.floor(s/2)&&(t=g)}let S=e.slice(E,t).trim();if(S&&w.push(S),t>=e.length)break;let D=t-g;E=D>E?D:t}return w}const log$9=getLogger(`embeddings`),MANIFEST_SCHEMA_VERSION=1,VEC_SUBDIR=`vec`,MANIFEST_NAME=`manifest.json`;function hashContent(e){return createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function serializeVectors(e){let t=0;for(let s of e)t+=s.length;let s=new Float32Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function deserializeVectors(e,t){let s=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),g=new Float32Array(s);if(g.length%t!==0)throw Error(`vector blob length ${g.length} is not a multiple of dims ${t}`);let S=[];for(let e=0;e<g.length;e+=t)S.push(g.slice(e,e+t));return S}var VectorCache=class{cacheDir;vecDir;manifestPath;providerId;modelId;dims;chunkConfigId;entries=new Map;vectorsByHash=new Map;persistedHashes=new Set;dirty=!1;constructor(e){this.cacheDir=e.cacheDir,this.vecDir=e.cacheDir?join(e.cacheDir,VEC_SUBDIR):null,this.manifestPath=e.cacheDir?join(e.cacheDir,MANIFEST_NAME):null,this.providerId=e.providerId,this.modelId=e.modelId,this.dims=e.dims,this.chunkConfigId=e.chunkConfigId}async init(){if(!this.cacheDir||!this.manifestPath||!this.vecDir)return;let e=null;try{existsSync(this.manifestPath)&&(e=JSON.parse(await readFile$1(this.manifestPath,`utf-8`)))}catch(t){log$9.warn({err:t instanceof Error?t.message:String(t)},`[embeddings] unreadable cache manifest — rebuilding`),e=null}if(!(e!==null&&e.schemaVersion===MANIFEST_SCHEMA_VERSION&&e.providerId===this.providerId&&e.modelId===this.modelId&&e.dims===this.dims&&e.chunkConfigId===this.chunkConfigId)){e!==null&&log$9.info({hadModel:e.modelId,wantModel:this.modelId},`[embeddings] cache identity changed (provider/model/dims/chunking) — invalidating`),this.wipeDisk();return}if(e){for(let[t,s]of Object.entries(e.entries))if(s?.contentHash&&(this.entries.set(t,{contentHash:s.contentHash,mtimeMs:s.mtimeMs??0}),!this.vectorsByHash.has(s.contentHash)))try{let e=join(this.vecDir,`${s.contentHash}.bin`);if(existsSync(e)){let t=await readFile$1(e);this.vectorsByHash.set(s.contentHash,deserializeVectors(t,this.dims)),this.persistedHashes.add(s.contentHash)}}catch(e){log$9.warn({hash:s.contentHash,err:e instanceof Error?e.message:String(e)},`[embeddings] corrupt vector blob — will re-embed`)}}}isFresh(e,t){let s=this.entries.get(e);return s!==void 0&&s.mtimeMs===t&&this.vectorsByHash.has(s.contentHash)}link(e,t,s){if(!this.vectorsByHash.has(t))return!1;let g=this.entries.get(e);return(!g||g.contentHash!==t||g.mtimeMs!==s)&&(this.dirty=!0),this.entries.set(e,{contentHash:t,mtimeMs:s}),!0}store(e,t,s,g){this.vectorsByHash.set(t,g),this.entries.set(e,{contentHash:t,mtimeMs:s}),this.dirty=!0}getVectors(e){let t=this.entries.get(e);if(t)return this.vectorsByHash.get(t.contentHash)}get embeddedCount(){let e=0;for(let t of this.entries.values()){let s=this.vectorsByHash.get(t.contentHash);s&&s.length>0&&(e+=1)}return e}retain(e){for(let t of this.entries.keys())e.has(t)||(this.entries.delete(t),this.dirty=!0);let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of this.vectorsByHash.keys())t.has(e)||this.vectorsByHash.delete(e)}clearMemory(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.dirty=!1}async persist(){if(!(!this.cacheDir||!this.manifestPath||!this.vecDir)&&this.dirty)try{await tracedMkdir(this.vecDir,{recursive:!0});let e=new Set;for(let t of this.entries.values())e.add(t.contentHash);for(let t of e){if(this.persistedHashes.has(t))continue;let e=this.vectorsByHash.get(t);e&&(await tracedWriteFile(join(this.vecDir,`${t}.bin`),serializeVectors(e)),this.persistedHashes.add(t))}let t={schemaVersion:MANIFEST_SCHEMA_VERSION,providerId:this.providerId,modelId:this.modelId,dims:this.dims,chunkConfigId:this.chunkConfigId,entries:Object.fromEntries(this.entries)},s=`${this.manifestPath}.tmp`;await tracedWriteFile(s,JSON.stringify(t)),await tracedRename(s,this.manifestPath);for(let t of readdirSync(this.vecDir)){if(!t.endsWith(`.bin`))continue;let s=t.slice(0,-4);e.has(s)||(tracedUnlinkSync(join(this.vecDir,t)),this.persistedHashes.delete(s))}this.dirty=!1}catch(e){log$9.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to persist vector cache`)}}wipeDisk(){if(this.cacheDir)try{tracedRmSync(this.cacheDir,{recursive:!0,force:!0})}catch(e){log$9.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to wipe stale cache`)}}};const log$8=getLogger(`embeddings`);function errMsg(e){return e instanceof Error?e.message:String(e)}const EMBED_BATCH_CHUNK_LIMIT=96,MAX_CONSECUTIVE_EMBED_FAILURES=5;var SemanticSearchService=class{loadEmbedder;cacheDir;enabled;providerFingerprint;capable=!1;ready=!1;embedder=null;cache=null;warmPromise=null;embedChain=Promise.resolve();queuedDocs=null;constructor(e){this.loadEmbedder=e.loadEmbedder,this.cacheDir=e.cacheDir,this.enabled=e.enabled??!1,this.providerFingerprint=e.providerFingerprint??``}isEnabled(){return this.enabled}getStatus(){return{enabled:this.enabled,capable:this.capable,ready:this.ready,embeddedCount:this.cache?.embeddedCount??0}}applyConfig(e){e.providerFingerprint!==this.providerFingerprint&&(this.providerFingerprint=e.providerFingerprint,this.resetWarm()),e.enabled!==this.enabled&&(this.enabled=e.enabled,e.enabled||(this.cache?.clearMemory(),this.resetWarm()))}resetWarm(){this.warmPromise=null,this.ready=!1,this.capable=!1,this.embedder=null,this.cache=null}ensureWarm(){return!this.enabled||this.ready?Promise.resolve():(this.warmPromise||=this.warm(),this.warmPromise)}async warm(){try{let e=await this.loadEmbedder();if(!e){this.capable=!1,this.ready=!0,log$8.info({},`[embeddings] no embeddings key configured — semantic search degrades to lexical`);return}this.embedder=e,this.cache=new VectorCache({cacheDir:this.cacheDir,providerId:e.providerId,modelId:e.modelId,dims:e.dims,chunkConfigId:CHUNK_CONFIG_ID}),await this.cache.init(),this.capable=!0,this.ready=!0}catch(e){this.capable=!1,this.ready=!0,log$8.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] warm failed`)}}embedCorpus(e){return this.enabled?(this.queuedDocs=e,this.embedChain=this.embedChain.then(async()=>{let e=this.queuedDocs;if(e){this.queuedDocs=null;try{await this.runEmbedPass(e)}catch(e){log$8.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] embed pass failed`)}}}),this.embedChain):Promise.resolve()}async runEmbedPass(e){if(await this.ensureWarm(),!this.enabled||!this.embedder||!this.cache)return;let t=this.cache,s=this.embedder,g=e.filter(e=>e.kind===`page`),S=new Set(g.map(e=>e.id)),w=[];for(let e of g){if(!this.enabled)return;let s=e.modifiedTs;if(t.isFresh(e.id,s))continue;let g=hashContent(e.content);t.link(e.id,g,s)||w.push({doc:e,contentHash:g,chunks:chunkDocument(e.content)})}let E=0,D=(e,s)=>{t.store(e.doc.id,e.contentHash,e.doc.modifiedTs,s)},O=async e=>{let t=e.flatMap(e=>e.chunks);try{let g=t.length?await s.embed(t,{role:`document`}):[],S=0;for(let t of e)D(t,g.slice(S,S+t.chunks.length)),S+=t.chunks.length;return E=0,!0}catch(t){if(e.length===1)return log$8.warn({docId:e[0].doc.id,err:errMsg(t)},`[embeddings] failed to embed document`),E+=1,E<MAX_CONSECUTIVE_EMBED_FAILURES;for(let t of e){if(!this.enabled)return!1;try{D(t,t.chunks.length?await s.embed(t.chunks,{role:`document`}):[]),E=0}catch(e){if(log$8.warn({docId:t.doc.id,err:errMsg(e)},`[embeddings] failed to embed document`),E+=1,E>=MAX_CONSECUTIVE_EMBED_FAILURES)return!1}}return!0}},k=[],j=0;for(let e of w){if(!this.enabled)break;if(k.push(e),j+=Math.max(1,e.chunks.length),j>=EMBED_BATCH_CHUNK_LIMIT){let e=await O(k);if(k=[],j=0,!e)break}}k.length>0&&this.enabled&&await O(k),!(!this.enabled||this.cache!==t)&&(t.retain(S),await t.persist())}async queryScores(e,t){if(!this.enabled||!this.capable||!this.ready||!this.embedder||!this.cache||this.cache.embeddedCount===0)return null;let s=e.trim();if(!s)return null;let g;try{[g]=await this.embedder.embed([s],{role:`query`})}catch(e){return log$8.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] query embed failed — degrading to lexical`),null}if(!g)return null;let S=new Map;for(let e of t){let t=this.cache.getVectors(e.id);if(!t||t.length===0)continue;let s=-1/0;for(let e of t){let t=cosineSimilarity(g,e);t>s&&(s=t)}s>-1/0&&S.set(e.id,s)}return S}};const log$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(`
828
- `).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(`
829
- ---`,4);if(!e.startsWith(`---
830
- `)||t<0)return;let s=e.slice(4,t),g=s.search(/^metadata:/m);if(g<0)return;let S=s.slice(g).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{frontmatter:t}=stripFrontmatter(e.replace(/^/,``));return t===``?null:unwrapFrontmatterFences(t)}function parseFrontmatterRaw(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return null;try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i;function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${s}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.backlinks??s.results??s.links;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e,s=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;s&&S.push({source:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let s=[...new Set(t)],g=[];for(let e=0;e<s.length;e+=BACKLINK_COUNT_CHUNK)g.push(s.slice(e,e+BACKLINK_COUNT_CHUNK));let S=await Promise.all(g.map(async t=>{let s=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return s.ok?s.counts??{}:null})),w=new Map,E=!1;for(let e of S)if(e){E=!0;for(let[t,s]of Object.entries(e))typeof s==`number`&&Number.isFinite(s)&&w.set(t,s)}return E?w:null}async function fetchForwardLinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.forwardLinks??s.links??s.results;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){S.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let s=typeof t.docName==`string`?t.docName:void 0;s&&S.push({kind:`doc`,docName:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}function liftOwnFrontmatter(e){let t=e??{};return{title:typeof t.title==`string`?t.title:void 0,description:typeof t.description==`string`?t.description:void 0,tags:Array.isArray(t.tags)?t.tags.filter(e=>typeof e==`string`):[],frontmatter:t}}async function enrichPath(e,t,s={}){let g=resolveWithinRoot(t.projectDir,e);if(!g.ok)throw Error(`enrichPath: ${g.reason}`);let S=g.rel,w=g.abs,E=t.historyDepth??5,D=s.includeRichFields===!0,O=readFrontmatter(w);if(!D){let e=liftOwnFrontmatter(await O);return{path:S,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[k,j,F,L,B]=await Promise.all([O,fetchBacklinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),readShadowLog(t.projectDir,S,E).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,S,E).catch(()=>({commits:[],source:`git`}))]),H=liftOwnFrontmatter(k);return{path:S,title:H.title,description:H.description,tags:H.tags,frontmatter:H.frontmatter,backlinkCount:j?.length??null,backlinks:j,forwardLinkCount:F?.length??null,forwardLinks:F,history:L.commits,historySource:L.source,projectHistory:B.commits,projectHistorySource:B.source}}async function scanDirectory(e,t){let s={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},g=0,S=[{path:e,depth:0}];for(;S.length>0;){let e=S.shift();if(!e)break;if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}let w;try{w=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let E of w){if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}g++;let w=E.name;if(E.isDirectory()){if(DIR_SKIP.has(w)||w.startsWith(`.`))continue;e.depth===0&&s.childDirCount++,S.push({path:`${e.path}/${w}`,depth:e.depth+1})}else if(E.isFile()&&WIKI_EXT_RE.test(w)){s.recursiveMdCount++,e.depth===0&&s.directMdCount++;let g=`${e.path}/${w}`;try{let e=await stat$1(g);(!s.mostRecent||e.mtimeMs>s.mostRecent.mtimeMs)&&(s.mostRecent={absPath:g,relPath:relative(t,g).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return s}async function enrichDirectory(e,t){let s=resolveWithinRoot(t.projectDir,e);if(!s.ok)throw Error(`enrichDirectory: ${s.reason}`);let g=s.rel,S=s.abs,w=await scanDirectory(S,t.projectDir),E;if(w.mostRecent){let e=await readFrontmatter(w.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;E={path:w.mostRecent.relPath,title:t??basename(w.mostRecent.relPath),updatedAt:new Date(w.mostRecent.mtimeMs).toISOString()}}let D={path:g,type:`directory`,directMdCount:w.directMdCount,recursiveMdCount:w.recursiveMdCount,childDirCount:w.childDirCount,mostRecentMd:E,truncated:w.truncated},O=readFolderFrontmatter(t.projectDir,g);O.title!==void 0&&(D.title=O.title),O.description!==void 0&&(D.description=O.description),(O.tags?.length??0)>0&&(D.tags=O.tags);let k=resolveTemplatesAvailable(t.projectDir,g);return k.length>0&&(D.templates_available=k),D}async function enrichDirectoryRecursive(e,t,s){let g=await enrichDirectory(e,s);if(t<=1)return g;let S=g.path,w=resolve(s.projectDir,S),E;try{E=await readdir(w,{withFileTypes:!0})}catch{return g}let D=[];for(let e of E){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let g=await enrichDirectoryRecursive(S?`${S}/${e.name}`:e.name,t-1,s);D.push(g)}return D.length>0&&(g.subfolders=D),g}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function mergePatch(e,t){let s={...e};for(let[e,g]of Object.entries(t))if(g!==void 0){if(isEmpty$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$10=getLogger(`embeddings`);let _tokens=null,_errors=null,_requestDuration=null,_queryTotal=null,_queryEmbedDuration=null;function tokensCounter(){return _tokens||=getMeter().createCounter(`ok.embeddings.tokens_total`,{description:`Embeddings tokens billed, by role. Bounded label: role ∈ {query, document}. Makes spend legible; never includes content.`}),_tokens}function errorsCounter(){return _errors||=getMeter().createCounter(`ok.embeddings.provider_errors_total`,{description:`Embeddings provider failures, by reason. Bounded label: reason ∈ {rate_limit, timeout, http_error, network, dims_mismatch, malformed_response}.`}),_errors}function requestDurationHist(){return _requestDuration||=getMeter().createHistogram(`ok.embeddings.request_duration_ms`,{description:`Wall-clock duration of one embeddings API request. Bounded label: role.`,unit:`ms`}),_requestDuration}function queryTotalCounter(){return _queryTotal||=getMeter().createCounter(`ok.search.semantic_query_total`,{description:`Semantic-requested searches, by outcome and caller surface. Bounded labels: outcome ∈ {applied, no_match, warming, incapable, provider_error}, source ∈ {omnibar, mcp, http}. The omnibar/mcp split separates interactive cost from agent cost.`}),_queryTotal}function queryEmbedDurationHist(){return _queryEmbedDuration||=getMeter().createHistogram(`ok.search.semantic_query_embed_ms`,{description:`Wall-clock latency of the per-query embed on the semantic search path.`,unit:`ms`}),_queryEmbedDuration}function recordEmbeddingTokens(e,t){t>0&&tokensCounter().add(t,{role:e})}function recordEmbeddingProviderError(e){errorsCounter().add(1,{reason:e})}function recordEmbeddingRequestDuration(e,t){requestDurationHist().record(Math.max(0,t),{role:e})}function recordSemanticQuery(e){queryTotalCounter().add(1,{outcome:e.outcome,source:e.source}),e.queryEmbedMs!==null&&queryEmbedDurationHist().record(Math.max(0,e.queryEmbedMs)),log$10.debug({outcome:e.outcome,source:e.source,capable:e.capable,embedded:e.embedded,total:e.total,coverage:e.total>0?e.embedded/e.total:0,queryEmbedMs:e.queryEmbedMs,vectorContributors:e.vectorContributors},`[search] semantic query`)}const DEFAULT_EMBEDDINGS_DIMENSIONS=1536,EMBEDDINGS_API_KEY_ENV=`OK_EMBEDDINGS_API_KEY`;var EmbeddingDimsMismatchError=class extends Error{name=`EmbeddingDimsMismatchError`;constructor(e,t){super(`embeddings provider returned ${t}-dim vectors, expected ${e}. Set search.semantic.dimensions to ${t} (or point at the right model).`),this.expected=e,this.got=t}},MalformedEmbeddingResponseError=class extends Error{name=`MalformedEmbeddingResponseError`;constructor(e,t){super(`embeddings response had ${t} vectors, expected ${e}`)}};function cosineSimilarity(e,t){let s=0,g=Math.min(e.length,t.length);for(let S=0;S<g;S++)s+=e[S]*t[S];return s}function normalizeInPlace(e){let t=0;for(let s=0;s<e.length;s++)t+=e[s]*e[s];if(t=Math.sqrt(t),t>0)for(let s=0;s<e.length;s++)e[s]/=t;return e}const DEFAULTS={maxBatchSize:96,maxBatchChars:96e3,docTimeoutMs:3e4,queryTimeoutMs:8e3,maxRetries:4,backoffBaseMs:500};function normalizeProviderId(e){try{let t=new URL(e),s=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${s}`}catch{return e.trim().replace(/\/+$/,``)}}function assertSafeEmbeddingsBaseUrl(e){let t;try{t=new URL(e)}catch{throw Error(`embeddings baseUrl is not a valid URL: ${e}`)}if(t.protocol===`https:`)return;let s=t.hostname.toLowerCase(),g=s===`localhost`||s===`127.0.0.1`||s===`::1`||s===`[::1]`;if(!(t.protocol===`http:`&&g))throw Error(`refusing to send the embeddings API key to a non-HTTPS endpoint (${t.protocol}//${t.host}); use https:// (http:// is allowed only for localhost)`)}const RETRYABLE_STATUS=new Set([408,409,429,500,502,503,504]);function defaultSleep$1(e){return new Promise(t=>setTimeout(t,e))}function createOpenAiEmbedder(e,t={}){let s=t.fetchImpl??fetch,g=t.sleep??defaultSleep$1,S=t.maxBatchSize??DEFAULTS.maxBatchSize,w=t.maxBatchChars??DEFAULTS.maxBatchChars,E=t.maxRetries??DEFAULTS.maxRetries,D=t.backoffBaseMs??DEFAULTS.backoffBaseMs,O=t.docTimeoutMs??DEFAULTS.docTimeoutMs,k=t.queryTimeoutMs??DEFAULTS.queryTimeoutMs;assertSafeEmbeddingsBaseUrl(e.baseUrl);let j=e.dimensions??1536,F=`${e.baseUrl.replace(/\/+$/,``)}/embeddings`;function L(e){let t=[],s=[],g=0;for(let E of e)s.length>0&&(s.length>=S||g+E.length>w)&&(t.push(s),s=[],g=0),s.push(E),g+=E.length;return s.length>0&&t.push(s),t}async function B(t,g,S,w){let E=new AbortController,D=setTimeout(()=>E.abort(),w),O=performance.now();try{let w=await s(F,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.apiKey}`},body:t,signal:E.signal});if(recordEmbeddingRequestDuration(S,performance.now()-O),!w.ok){await w.text().catch(()=>``);let e=w.status===429?`rate_limit`:`http_error`,t=Error(`embeddings request failed: HTTP ${w.status}`);return RETRYABLE_STATUS.has(w.status)?{kind:`retry`,reason:e,error:t}:{kind:`fatal`,reason:e,error:t}}let D=await w.json(),k=q(D,g,j);return recordEmbeddingTokens(S,D.usage?.total_tokens??0),{kind:`ok`,vectors:k}}catch(e){if(e instanceof EmbeddingDimsMismatchError)return{kind:`fatal`,reason:`dims_mismatch`,error:e};if(e instanceof MalformedEmbeddingResponseError)return{kind:`fatal`,reason:`malformed_response`,error:e};let t=e instanceof Error&&e.name===`AbortError`,s=e instanceof Error?e:Error(String(e));return{kind:`retry`,reason:t?`timeout`:`network`,error:s}}finally{clearTimeout(D)}}async function H(t,s){let S=s===`query`?k:O,w=s===`query`?`query`:`document`,j=JSON.stringify({model:e.model,input:t,encoding_format:`float`,...e.dimensions===void 0?{}:{dimensions:e.dimensions}}),F=0;for(;;){let e=await B(j,t.length,w,S);if(e.kind===`ok`)return e.vectors;if(recordEmbeddingProviderError(e.reason),e.kind===`fatal`||F>=E)throw e.error;F+=1;let s=D*2**(F-1);await g(Math.round(s/2+s/2*Math.random()))}}function q(e,t,s){let g=e.data;if(!Array.isArray(g)||g.length!==t)throw new MalformedEmbeddingResponseError(t,g?.length??0);let S=[...g].sort((e,t)=>(e.index??0)-(t.index??0)),w=[];for(let e of S){let g=e.embedding;if(!Array.isArray(g))throw new MalformedEmbeddingResponseError(t,0);if(g.length!==s)throw new EmbeddingDimsMismatchError(s,g.length);w.push(normalizeInPlace(Float32Array.from(g)))}return w}return{providerId:normalizeProviderId(e.baseUrl),modelId:e.model,dims:j,async embed(e,{role:t}){if(e.length===0)return[];let s=[];for(let g of L(e))s.push(...await H(g,t));return s}}}async function loadOpenAiEmbedder(e){let t=(e.keyStore?await e.keyStore.get().catch(()=>null):null)??process.env.OK_EMBEDDINGS_API_KEY??null;return t?createOpenAiEmbedder({...e.config,apiKey:t},e.options):null}const SECRETS_KEY_FIELD=`OPENAI_API_KEY`,LEGACY_KEY_FIELD=`embeddings`;function secretsFilePath(e){return join(e??homedir(),`.ok`,`secrets.yml`)}var FileEmbeddingsBackend=class{backend=`file`;secretsFile;constructor(e){this.secretsFile=e??secretsFilePath()}tightenPermsIfLoose(){let e;try{e=statSync(this.secretsFile).mode&511}catch{return}if(e&63)try{chmodSync(this.secretsFile,384),process.stderr.write(`[embeddings] ${this.secretsFile} was readable beyond your user account (mode ${e.toString(8)}); tightened to 600. It stores an API key.\n`)}catch(t){let s=t instanceof Error?t.message:`unknown error`;process.stderr.write(`[embeddings] ${this.secretsFile} is readable beyond your user account (mode ${e.toString(8)}) and could not be tightened (${s}); your API key remains exposed — run: chmod 600 ${this.secretsFile}\n`)}}read(){if(!existsSync(this.secretsFile))return{};this.tightenPermsIfLoose();try{return(0,import_dist$1.parse)(readFileSync(this.secretsFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[embeddings] Failed to parse ${this.secretsFile}: ${t}. Starting with empty secrets.\n`),{}}}write(e){let t=dirname(this.secretsFile);existsSync(t)||tracedMkdirSync(t,{recursive:!0,mode:448}),tracedWriteFileSync(this.secretsFile,(0,import_dist$1.stringify)(e),{mode:384}),chmodSync(this.secretsFile,384)}get(){let e=this.read(),t=e[SECRETS_KEY_FIELD]??e[LEGACY_KEY_FIELD];return Promise.resolve(typeof t==`string`&&t!==``?t:null)}set(e){let t=this.read();return delete t[LEGACY_KEY_FIELD],t[SECRETS_KEY_FIELD]=e,this.write(t),Promise.resolve()}clear(){let e=this.read();if(SECRETS_KEY_FIELD in e||LEGACY_KEY_FIELD in e)if(delete e[SECRETS_KEY_FIELD],delete e[LEGACY_KEY_FIELD],Object.keys(e).length===0)try{tracedUnlinkSync(this.secretsFile)}catch{}else this.write(e);return Promise.resolve()}};function createEmbeddingsSecretStore(e){return new FileEmbeddingsBackend(e)}function makeLazyEmbeddingsKeyStore(e){return new FileEmbeddingsBackend(e)}async function describeStoredEmbeddingsKey(e){return{file:await new FileEmbeddingsBackend(e).get()!=null}}async function clearEmbeddingsKeyFromAllBackends(e){let t=[],s=new FileEmbeddingsBackend(e);return await s.get()!=null&&(await s.clear(),t.push(`file`)),{touched:t}}function readProjectLocalSemanticConfig(e,t){let s=readConfigSafely({absPath:resolveConfigPath(`project-local`,e,t?.configHomedirOverride),sideline:!1,warn:t?.onWarn??(()=>{})}).value.search?.semantic;return{enabled:s?.enabled===!0,baseUrl:s?.baseUrl??`https://api.openai.com/v1`,model:s?.model??`text-embedding-3-small`,dimensions:s?.dimensions??void 0,similarityFloor:s?.similarityFloor??void 0}}const CHUNK_CONFIG_ID=`c8000-o400-m80`;function chunkDocument(e,t={}){let s=Math.max(1,t.targetChars??8e3),g=Math.max(0,Math.min(t.overlapChars??400,s-1)),S=t.maxChunks??80;if(e.trim().length===0)return[];if(e.length<=s)return[e.trim()];let w=[],E=0;for(;E<e.length&&w.length<S;){let t=Math.min(e.length,E+s);if(t<e.length){let g=Math.max(e.lastIndexOf(` `,t),e.lastIndexOf(`
827
+ `,t));g>E+Math.floor(s/2)&&(t=g)}let S=e.slice(E,t).trim();if(S&&w.push(S),t>=e.length)break;let D=t-g;E=D>E?D:t}return w}const log$9=getLogger(`embeddings`),MANIFEST_SCHEMA_VERSION=1,VEC_SUBDIR=`vec`,MANIFEST_NAME=`manifest.json`;function hashContent(e){return createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function serializeVectors(e){let t=0;for(let s of e)t+=s.length;let s=new Float32Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function deserializeVectors(e,t){let s=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),g=new Float32Array(s);if(g.length%t!==0)throw Error(`vector blob length ${g.length} is not a multiple of dims ${t}`);let S=[];for(let e=0;e<g.length;e+=t)S.push(g.slice(e,e+t));return S}var VectorCache=class{cacheDir;vecDir;manifestPath;providerId;modelId;dims;chunkConfigId;entries=new Map;vectorsByHash=new Map;persistedHashes=new Set;dirty=!1;constructor(e){this.cacheDir=e.cacheDir,this.vecDir=e.cacheDir?join(e.cacheDir,VEC_SUBDIR):null,this.manifestPath=e.cacheDir?join(e.cacheDir,MANIFEST_NAME):null,this.providerId=e.providerId,this.modelId=e.modelId,this.dims=e.dims,this.chunkConfigId=e.chunkConfigId}async init(){if(!this.cacheDir||!this.manifestPath||!this.vecDir)return;let e=null;try{existsSync(this.manifestPath)&&(e=JSON.parse(await readFile$1(this.manifestPath,`utf-8`)))}catch(t){log$9.warn({err:t instanceof Error?t.message:String(t)},`[embeddings] unreadable cache manifest — rebuilding`),e=null}if(!(e!==null&&e.schemaVersion===MANIFEST_SCHEMA_VERSION&&e.providerId===this.providerId&&e.modelId===this.modelId&&e.dims===this.dims&&e.chunkConfigId===this.chunkConfigId)){e!==null&&log$9.info({hadModel:e.modelId,wantModel:this.modelId},`[embeddings] cache identity changed (provider/model/dims/chunking) — invalidating`),this.wipeDisk();return}if(e){for(let[t,s]of Object.entries(e.entries))if(s?.contentHash&&(this.entries.set(t,{contentHash:s.contentHash,mtimeMs:s.mtimeMs??0}),!this.vectorsByHash.has(s.contentHash)))try{let e=join(this.vecDir,`${s.contentHash}.bin`);if(existsSync(e)){let t=await readFile$1(e);this.vectorsByHash.set(s.contentHash,deserializeVectors(t,this.dims)),this.persistedHashes.add(s.contentHash)}}catch(e){log$9.warn({hash:s.contentHash,err:e instanceof Error?e.message:String(e)},`[embeddings] corrupt vector blob — will re-embed`)}}}isFresh(e,t){let s=this.entries.get(e);return s!==void 0&&s.mtimeMs===t&&this.vectorsByHash.has(s.contentHash)}link(e,t,s){if(!this.vectorsByHash.has(t))return!1;let g=this.entries.get(e);return(!g||g.contentHash!==t||g.mtimeMs!==s)&&(this.dirty=!0),this.entries.set(e,{contentHash:t,mtimeMs:s}),!0}store(e,t,s,g){this.vectorsByHash.set(t,g),this.entries.set(e,{contentHash:t,mtimeMs:s}),this.dirty=!0}getVectors(e){let t=this.entries.get(e);if(t)return this.vectorsByHash.get(t.contentHash)}get embeddedCount(){let e=0;for(let t of this.entries.values()){let s=this.vectorsByHash.get(t.contentHash);s&&s.length>0&&(e+=1)}return e}retain(e){for(let t of this.entries.keys())e.has(t)||(this.entries.delete(t),this.dirty=!0);let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of this.vectorsByHash.keys())t.has(e)||this.vectorsByHash.delete(e)}clearMemory(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.dirty=!1}async persist(){if(!(!this.cacheDir||!this.manifestPath||!this.vecDir)&&this.dirty)try{await tracedMkdir(this.vecDir,{recursive:!0});let e=new Set;for(let t of this.entries.values())e.add(t.contentHash);for(let t of e){if(this.persistedHashes.has(t))continue;let e=this.vectorsByHash.get(t);e&&(await tracedWriteFile(join(this.vecDir,`${t}.bin`),serializeVectors(e)),this.persistedHashes.add(t))}let t={schemaVersion:MANIFEST_SCHEMA_VERSION,providerId:this.providerId,modelId:this.modelId,dims:this.dims,chunkConfigId:this.chunkConfigId,entries:Object.fromEntries(this.entries)},s=`${this.manifestPath}.tmp`;await tracedWriteFile(s,JSON.stringify(t)),await tracedRename(s,this.manifestPath);for(let t of readdirSync(this.vecDir)){if(!t.endsWith(`.bin`))continue;let s=t.slice(0,-4);e.has(s)||(tracedUnlinkSync(join(this.vecDir,t)),this.persistedHashes.delete(s))}this.dirty=!1}catch(e){log$9.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to persist vector cache`)}}wipeDisk(){if(this.cacheDir)try{tracedRmSync(this.cacheDir,{recursive:!0,force:!0})}catch(e){log$9.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to wipe stale cache`)}}};const log$8=getLogger(`embeddings`);function errMsg(e){return e instanceof Error?e.message:String(e)}const EMBED_BATCH_CHUNK_LIMIT=96,MAX_CONSECUTIVE_EMBED_FAILURES=5;var SemanticSearchService=class{loadEmbedder;cacheDir;enabled;providerFingerprint;capable=!1;ready=!1;embedder=null;cache=null;warmPromise=null;embedChain=Promise.resolve();queuedDocs=null;constructor(e){this.loadEmbedder=e.loadEmbedder,this.cacheDir=e.cacheDir,this.enabled=e.enabled??!1,this.providerFingerprint=e.providerFingerprint??``}isEnabled(){return this.enabled}getStatus(){return{enabled:this.enabled,capable:this.capable,ready:this.ready,embeddedCount:this.cache?.embeddedCount??0}}applyConfig(e){e.providerFingerprint!==this.providerFingerprint&&(this.providerFingerprint=e.providerFingerprint,this.resetWarm()),e.enabled!==this.enabled&&(this.enabled=e.enabled,e.enabled||(this.cache?.clearMemory(),this.resetWarm()))}resetWarm(){this.warmPromise=null,this.ready=!1,this.capable=!1,this.embedder=null,this.cache=null}ensureWarm(){return!this.enabled||this.ready?Promise.resolve():(this.warmPromise||=this.warm(),this.warmPromise)}async warm(){try{let e=await this.loadEmbedder();if(!e){this.capable=!1,this.ready=!0,log$8.info({},`[embeddings] no embeddings key configured — semantic search degrades to lexical`);return}this.embedder=e,this.cache=new VectorCache({cacheDir:this.cacheDir,providerId:e.providerId,modelId:e.modelId,dims:e.dims,chunkConfigId:CHUNK_CONFIG_ID}),await this.cache.init(),this.capable=!0,this.ready=!0}catch(e){this.capable=!1,this.ready=!0,log$8.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] warm failed`)}}embedCorpus(e){return this.enabled?(this.queuedDocs=e,this.embedChain=this.embedChain.then(async()=>{let e=this.queuedDocs;if(e){this.queuedDocs=null;try{await this.runEmbedPass(e)}catch(e){log$8.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] embed pass failed`)}}}),this.embedChain):Promise.resolve()}async runEmbedPass(e){if(await this.ensureWarm(),!this.enabled||!this.embedder||!this.cache)return;let t=this.cache,s=this.embedder,g=e.filter(e=>e.kind===`page`),S=new Set(g.map(e=>e.id)),w=[];for(let e of g){if(!this.enabled)return;let s=e.modifiedTs;if(t.isFresh(e.id,s))continue;let g=hashContent(e.content);t.link(e.id,g,s)||w.push({doc:e,contentHash:g,chunks:chunkDocument(e.content)})}let E=0,D=(e,s)=>{t.store(e.doc.id,e.contentHash,e.doc.modifiedTs,s)},O=async e=>{let t=e.flatMap(e=>e.chunks);try{let g=t.length?await s.embed(t,{role:`document`}):[],S=0;for(let t of e)D(t,g.slice(S,S+t.chunks.length)),S+=t.chunks.length;return E=0,!0}catch(t){if(e.length===1)return log$8.warn({docId:e[0].doc.id,err:errMsg(t)},`[embeddings] failed to embed document`),E+=1,E<MAX_CONSECUTIVE_EMBED_FAILURES;for(let t of e){if(!this.enabled)return!1;try{D(t,t.chunks.length?await s.embed(t.chunks,{role:`document`}):[]),E=0}catch(e){if(log$8.warn({docId:t.doc.id,err:errMsg(e)},`[embeddings] failed to embed document`),E+=1,E>=MAX_CONSECUTIVE_EMBED_FAILURES)return!1}}return!0}},k=[],j=0;for(let e of w){if(!this.enabled)break;if(k.push(e),j+=Math.max(1,e.chunks.length),j>=EMBED_BATCH_CHUNK_LIMIT){let e=await O(k);if(k=[],j=0,!e)break}}k.length>0&&this.enabled&&await O(k),!(!this.enabled||this.cache!==t)&&(t.retain(S),await t.persist())}async queryScores(e,t){if(!this.enabled||!this.capable||!this.ready||!this.embedder||!this.cache||this.cache.embeddedCount===0)return null;let s=e.trim();if(!s)return null;let g;try{[g]=await this.embedder.embed([s],{role:`query`})}catch(e){return log$8.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] query embed failed — degrading to lexical`),null}if(!g)return null;let S=new Map;for(let e of t){let t=this.cache.getVectors(e.id);if(!t||t.length===0)continue;let s=-1/0;for(let e of t){let t=cosineSimilarity(g,e);t>s&&(s=t)}s>-1/0&&S.set(e.id,s)}return S}};const log$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?unwrapFrontmatterFences(e).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let s=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(s))return normalizeFrontmatterScalar(t.slice(s.length))||null;return null}function parseInlineAliases(e){let t=[],s=``,g=null;for(let S of e){if(g){s+=S,S===g&&(g=null);continue}if(S===`"`||S===`'`){g=S,s+=S;continue}if(S===`,`){let e=normalizeFrontmatterScalar(s);e&&t.push(e),s=``;continue}s+=S}let S=normalizeFrontmatterScalar(s);return S&&t.push(S),t}function dedupeExact(e){let t=[],s=new Set;for(let g of e)!g||s.has(g)||(s.add(g),t.push(g));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let s=splitFrontmatterLines(t);for(let e=0;e<s.length;e+=1){let t=s[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let g=t[1]?.trim()??``;if(g){if(g.startsWith(`[`)&&g.endsWith(`]`))return dedupeExact(parseInlineAliases(g.slice(1,-1)));let e=normalizeFrontmatterScalar(g);return e?[e]:[]}let S=[];for(let t=e+1;t<s.length;t+=1){let e=s[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&S.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(S)}return[]}function extractPageTitle(e,t){let{frontmatter:s,body:g}=stripFrontmatter(e),S=extractFrontmatterScalar(s,`title`);if(S)return S;let w=g.match(/^# (.+)$/m);return w?w[1].trim():t}const ICON_VALUE_LENGTH_CAP=2048;function extractPageIcon(e){let{frontmatter:t}=stripFrontmatter(e),s=extractFrontmatterScalar(t,`icon`);if(!(!s||s.length>ICON_VALUE_LENGTH_CAP))return s}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let s=`${t}:`,g=splitFrontmatterLines(e);for(let e=0;e<g.length;e+=1){let t=g[e];if(!t?.startsWith(s))continue;let S=t.slice(s.length).trim();if(S){if(S.startsWith(`[`)&&S.endsWith(`]`)){let e=parseInlineAliases(S.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(S);return e?[e]:void 0}let w=[];for(let t=e+1;t<g.length;t+=1){let e=g[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&w.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return w.length>0?w:void 0}}function extractPageIdentity(e,t){let s=extractPageTitle(e,t),g=extractPageAliases(e),S=dedupeExact([s,...g]),w=[],E=new Set;for(let e of S){let t=toWikiLinkSlug(e);!t||E.has(t)||(E.add(t),w.push(t))}return{docName:t,title:s,aliases:g,matchLabels:S,normalizedMatchLabels:w}}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(`
828
+ `).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{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let s=unwrapFrontmatterFences(t),g=s.search(/^metadata:/m);if(g<0)return;let S=s.slice(g).split(`
831
829
  `).slice(1);for(let e of S){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,s={}){let g=s.bundle??`project`,S=statSync(e).size;if(S>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${S} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let w=await sha256OfFile(e),E=await readFile$1(join(s.sourceDir??resolveBundledSkillDir(g,{checkDesktop:!1}),`SKILL.md`),`utf-8`),D=BUNDLE_SKILL_NAME[g];if(!RegExp(`^name:\\s+${D}$`,`m`).test(E.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${D}'. Check packages/server/assets/skills/${g}/SKILL.md frontmatter.`);let O=extractMetadataVersion(E);if(t!==void 0){if(!O)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${g}/SKILL.md.`);if(O!==t)throw Error(`SKILL.md metadata.version (${O}) does not match expected version (${t}).`)}return{size:S,sha256:w,skillVersion:O}}async function buildSkillZip(e={}){let t=e.bundle??`project`,s=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),g=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(s,g,BUNDLE_SKILL_NAME[t]);let{size:S,sha256:w,skillVersion:E}=await validateSkillZip(g,e.expectedSkillVersion,{bundle:t,sourceDir:s});return{outputPath:g,size:S,sha256:w,skillVersion:E}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let s=t?.homedir??(()=>process.env.HOME??``),g=t?.warn??((e,t)=>{console.warn(t,e)}),S=s();if(!S){g({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let w=join(S,...SKILL_INSTALL_EVENTS_FILE_REL),E=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(w),{recursive:!0})}catch(e){g({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(w,E,{flag:`a`,encoding:`utf-8`})}catch(e){g({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)},TRACED_FS_ADAPTER={writeFile:(e,t,s)=>tracedWriteFile(e,t,s),rename:(e,t)=>tracedRename(e,t)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let s=skillStateYamlPath(e),g;try{g=await readFileAsync(s,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let S=(0,import_dist$1.parseDocument)(g);if(S.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:s,errors:S.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let w=SkillStateSchema.safeParse(S.toJSON());if(!w.success){let e=w.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:s,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:s,issues:w.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return w.data}async function writeSkillStateFile(e,t){let s=SkillStateSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid skill-state: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=skillStateYamlPath(e);await tracedMkdir(dirname(g),{recursive:!0});let S=(0,import_dist$1.parseDocument)(``);S.contents=S.createNode(s.data),await atomicWriteFile(g,S.toString(),{fs:TRACED_FS_ADAPTER})}async function readTargetVersion(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.version??null}async function readTargetRecordedAt(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,s,g,S){if(!SKILL_STATE_VERSION_RE.test(s))throw Error(`Refusing to write invalid version string: ${s}`);let w=await readSkillStateFile(e,S)??emptySkillState(),E=new Date().toISOString(),D=w.targets[t],O=g===void 0?D?.surface??void 0:g,k=O===void 0?{version:s,recordedAt:E}:{version:s,recordedAt:E,surface:O};await writeSkillStateFile(e,{...w,targets:{...w.targets,[t]:k}})}async function readServerPackageVersion(){let e=await readFileAsync(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function readSkillInstallStateSnapshot(e,t){let[s,g]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:s,targets:g}}async function readAllTargets(e,t=DEFAULT_LOGGER){let s=null;try{s=await readSkillStateFile(e,t)}catch(g){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(g)},`non-ENOENT error reading skill-state.yml; treating as absent`),s=null}let g=SKILL_STATE_TARGETS.map(e=>{let t=s?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(g)}const CENTRAL_SKILL_DIR_REL=[`.agents`,`skills`,`open-knowledge-discovery`],LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$3=6e4;function centralSkillDir(e){return join(e,...CENTRAL_SKILL_DIR_REL)}async function centralSkillExists(e){try{return(await stat$1(centralSkillDir(e))).isDirectory()}catch{return!1}}function runSpawn(e,t,s,g,S){return new Promise(w=>{let E;try{E=e(t,s,{env:g,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){w({kind:`spawn-error`,stderr:``,error:e});return}let D=``,O=!1,k=e=>{O||(O=!0,clearTimeout(j),w(e))};E.stderr?.on(`data`,e=>{D+=typeof e==`string`?e:e.toString(`utf-8`)}),E.on(`error`,e=>{k({kind:`spawn-error`,stderr:D,error:e})}),E.on(`exit`,e=>{k(e===0?{kind:`ok`,exitCode:e,stderr:D}:{kind:`nonzero`,exitCode:e,stderr:D})});let j=setTimeout(()=>{try{E.kill(`SIGTERM`)}catch{}k({kind:`timeout`,stderr:D})},S)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,s,g,S){if(!await anyLegacyUserSkillExists(e))return;let w=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],s,g);w.kind!==`ok`&&S.warn({event:`skill-install.legacy-remove-failed`,reason:w.kind,exitCode:w.exitCode,stderr:w.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}async function installUserSkill(e={}){let t=e.home??homedir(),s=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},g=e.spawn??spawn,S=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,w=e.surface??`cli-npx-skills-add`,E=async(e,g,S)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:w,target:`cli-hosts`,bundle:`discovery`,outcome:e,...g===void 0?{}:{version:g},...S===void 0?{}:{reason:S}},{homedir:()=>t,warn:s.warn})},D;try{D=await readServerPackageVersion()}catch(e){return s.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await E(`failed`,void 0,`version-read-failed`),`failed`}let O=await readTargetVersion(t,`cli-hosts`,s).catch(e=>(s.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(O!==null&&O===D){if(await centralSkillExists(t))return s.info?.({event:`skill-install.skip-current`,version:D},`Open Knowledge skill already installed at current version; skipping.`),await E(`skip-current`,D),`skip-current`;s.info?.({event:`skill-install.reinstall-missing`,version:D,path:centralSkillDir(t)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let k;try{k=resolveBundledSkillDir(`discovery`,{checkDesktop:!1})}catch(e){return s.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled discovery SKILL.md asset not found.`),await E(`failed`,D,`bundled-asset-missing`),`failed`}let j={...process.env,HOME:t};await removeLegacyUserSkill(t,g,j,S,s);let F=await runSpawn(g,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,k,`--agent`,`*`,`-g`,`-y`,`--copy`],j,S);if(F.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,D,w,s)}catch(e){return s.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await E(`failed`,D,`sidecar-write-failed`),`failed`}return s.info?.({event:`skill-install.installed`,version:D},`Open Knowledge skill installed to detected agent hosts.`),await E(`installed`,D),`installed`}return F.kind===`timeout`?(s.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:S,stderr:F.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${k} --agent '*' -g -y --copy`),await E(`failed`,D,`timeout`),`failed`):F.kind===`spawn-error`?(s.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(F.error),stderr:F.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${k} --agent '*' -g -y --copy`),await E(`failed`,D,`spawn-error`),`failed`):(s.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:F.exitCode,stderr:F.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${k} --agent '*' -g -y --copy`),await E(`failed`,D,`nonzero-exit:${F.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,s){let g={detached:!0,stdio:`ignore`};try{return t===`darwin`?(s(`open`,[e],g).unref(),{ok:!0}):t===`win32`?(s(`cmd`,[`/c`,`start`,`""`,e],g).unref(),{ok:!0}):t===`linux`?(s(`xdg-open`,[e],g).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),s=resolve(e.out??defaultDownloadsPath(t)),g=e.platformName??platform(),S=e.spawnFn??spawn,w=e.logger,E=async(e,s,g)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...s===void 0?{}:{version:s},...g===void 0?{}:{reason:g}},{homedir:()=>t,warn:w?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){w?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let s=null,g=null;try{[s,g]=await Promise.all([readTargetVersion(t,`claude-cowork`,w),readTargetRecordedAt(t,`claude-cowork`,w)])}catch(e){w?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(s!==null&&s===e)return w?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`Open Knowledge skill already delivered at current version; skipping rebuild.`),await E(`skip-current`,e),{status:`skip-current`,skillVersion:e,...g===null?{}:{recordedAt:g}}}}try{await tracedMkdir(dirname(s),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let D;try{D=await buildSkillZip({outputPath:s,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let O={status:`built`,outputPath:D.outputPath,size:D.size,sha256:D.sha256,skillVersion:D.skillVersion};if(D.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,D.skillVersion,`server-build-and-open`,w)}catch(e){w?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:D.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await E(`built`,D.skillVersion),O;let k=invokeFileAssociation(D.outputPath,g,S);return k.ok?(await E(`installed`,D.skillVersion),{...O,status:`installed`}):(await E(`built`,D.skillVersion,`handoff-${k.reason}`),{...O,handoffError:{reason:k.reason,message:k.message}})}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function uploadStatusFor(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return assertNeverProblemType(e)}}function classifyUploadErrno(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function uploadTitleFor(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return assertNeverProblemType(e)}}const log$6=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,s){this.hash.update(e),this.bytes+=e.length,s(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(getLocalDir(e),`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,s){let g=extname(s),S=s.slice(0,s.length-g.length),w=[s,...Array.from({length:99},(e,t)=>`${S}-${t+1}${g}`)];for(let s of w){let g=resolve(t,s);try{tracedLinkSync(e,g);try{tracedUnlinkSync(e)}catch{}return s}catch(t){let s=t.code;if(s===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw s===`ENOSPC`||s===`EDQUOT`?new UploadWriteError(`urn:ok:error:storage-full`,t):s===`EROFS`||s===`EACCES`||s===`EPERM`?new UploadWriteError(`urn:ok:error:storage-readonly`,t):new UploadWriteError(`urn:ok:error:storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`urn:ok:error:collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let s=tmpUploadDir(e),g={scanned:0,deleted:0,errors:0};if(!existsSync(s))return g;let S;try{S=readdirSync(s)}catch(e){return log$6.warn({err:e,dir:s},`[upload-tempfile-sweep] readdir failed`),g.errors++,g}let w=Date.now()-t;for(let e of S){if(!e.startsWith(`upload-`))continue;g.scanned++;let t=resolve(s,e);try{if(statSync(t).mtimeMs>=w)continue;tracedUnlinkSync(t),g.deleted++}catch(e){log$6.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),g.errors++}}return(g.deleted>0||g.errors>0)&&log$6.info({dir:s,scanned:g.scanned,deleted:g.deleted,errors:g.errors},`[upload-tempfile-sweep] swept ${g.deleted}/${g.scanned} (errors: ${g.errors})`),g}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,length:s.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let s=0;for(;e[t+s]==="`";)s++;if(s===0)return null;let g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S++;continue}let t=0;for(;e[S+t]==="`";)t++;if(t===s)return{nextIndex:S+s};S+=t}return{nextIndex:g}}function readWikiLink$2(e,t){let s=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!s)return null;let g=s[1]?.trim(),S=s[2]?.trim()||null,w=s[3]?.trim()||null;return g?{target:g,alias:w,anchor:S,nextIndex:t+s[0].length}:null}function readWikiLinkOrEmbed(e,t){if(e[t]===`!`&&e[t+1]===`[`&&e[t+2]===`[`){let s=readWikiLink$2(e,t+1);return s?{...s,embed:!0}:null}if(e[t]===`[`&&e[t+1]===`[`){let s=readWikiLink$2(e,t);return s?{...s,embed:!1}:null}return null}function readMarkdownLink$2(e,t){let s=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!s)return null;let g=s[2]??``;return{text:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,titleSuffix:s[3]??``,nextIndex:t+s[0].length}}function readImageRef(e,t){let s=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!s)return null;let g=s[2]??``;return{alt:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,titleSuffix:s[3]??``,nextIndex:t+s[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),s=[];for(let e=0;e<t.length;e+=2)s.push({line:t[e]??``,ending:t[e+1]??``});return s}function rewriteWikiLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$2(e,w);if(E){E.target===t?(g+=`[[${s}${E.anchor?`#${E.anchor}`:``}${E.alias?`|${E.alias}`:``}]]`,S++):g+=e.slice(w,E.nextIndex),w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function recomputeRelativeImageHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w;if(O.startsWith(`/`)||O.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(O))return null;let k=posix.dirname(t),j=posix.dirname(s);if(k===j)return null;let F=k===`.`?`/`:`/${k}/`,L=posix.resolve(F,O).slice(1),B=posix.relative(j===`.`?``:j,L);return B||=posix.basename(L),O.startsWith(`./`)&&!B.startsWith(`./`)&&!B.startsWith(`../`)&&(B=`./${B}`),`${B}${D}${S}`}function decodeHrefForAssetResolution(e){try{return decodeURI(e)}catch{return e}}function splitHrefPathAndSuffix(e){let t=e.indexOf(`#`),s=t>=0?e.slice(t):``,g=t>=0?e.slice(0,t):e,S=g.indexOf(`?`),w=S>=0?g.slice(S):``;return{pathPart:S>=0?g.slice(0,S):g,suffix:`${w}${s}`}}function buildAssetHrefFromSource(e,t,s,g={}){let S=g.encodePath??!0,w=e=>S?encodeURI(e):e,{pathPart:E,suffix:D}=splitHrefPathAndSuffix(e);if(E.startsWith(`/`))return`/${w(s)}${D}`;let O=posix.dirname(t),k=posix.relative(O===`.`?``:O,s);return k||=posix.basename(s),E.startsWith(`./`)&&!k.startsWith(`./`)&&!k.startsWith(`../`)&&(k=`./${k}`),`${w(k)}${D}`}function rewriteAssetHrefForRename(e,t,s,g,S={}){return resolveAssetProjectPath(decodeHrefForAssetResolution(e),t)===s?buildAssetHrefFromSource(e,t,g,S):null}function recomputeRelativeMarkdownHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w,k=O.startsWith(`/`),j=posix.dirname(t),F=k?`/${s}`:posix.relative(j===`.`?``:j,s);return F||=posix.basename(s),O.endsWith(`.mdx`)?F+=`.mdx`:O.endsWith(`.md`)&&(F+=`.md`),!k&&O.startsWith(`./`)&&!F.startsWith(`./`)&&!F.startsWith(`../`)&&(F=`./${F}`),`${F}${D}${S}`}function rewriteMarkdownLinksInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=t===s&&s!==g?recomputeRelativeImageHref(D.href,s,g):null;if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`![${D.alt}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){if(resolveInternalHref(D.href,t)?.docName===s){let e=recomputeRelativeMarkdownHref(D.href,t,g),s=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${e}>`:e;S+=`[${D.text}](${s}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}function renderWikiLinkOrEmbed(e,t){return`${e.embed?`!`:``}[[${t}${e.anchor?`#${e.anchor}`:``}${e.alias?`|${e.alias}`:``}]]`}const HTML_ASSET_ATTR_RE=/(\s(?:href|src)\s*=\s*)(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function rewriteHtmlAssetAttrsInTag(e,t,s,g){let S=0;return{markdown:e.replace(HTML_ASSET_ATTR_RE,(e,w,E,D,O,k)=>{let j=E??D??O??k;if(typeof j!=`string`)return e;let F=rewriteAssetHrefForRename(j,t,s,g);return F===null?e:(S++,E===void 0?D===void 0?O===void 0?`${w}${F}`:`${w}“${F}”`:`${w}'${F}'`:`${w}"${F}"`)}),rewrites:S}}function rewriteAssetReferencesInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}let D=readWikiLinkOrEmbed(e,E);if(D){let O=rewriteAssetHrefForRename(D.target,t,s,g,{encodePath:!1});O===null?S+=e.slice(E,D.nextIndex):(S+=renderWikiLinkOrEmbed(D,O),w++),E=D.nextIndex;continue}if(e.startsWith(`<!--`,E)){let t=e.indexOf(`-->`,E+4);if(t===-1){S+=e.slice(E);break}S+=e.slice(E,t+3),E=t+3;continue}if(e[E]===`<`){let D=e.indexOf(`>`,E+1);if(D!==-1){let O=rewriteHtmlAssetAttrsInTag(e.slice(E,D+1),t,s,g);if(O.rewrites>0){S+=O.markdown,w+=O.rewrites,E=D+1;continue}}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`![${D.alt}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`[${D.text}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,s){let g=``,S=0,w=0;for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`<`){let E=new RegExp(MIRROR_TAG_RE.source),D=e.slice(w),O=E.exec(D);if(O&&O.index===0){let[e,E]=O,D=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),k=E.replace(D,(e,g,w,E)=>E===t?(S++,`${g}${w}${s}${w}`):e);g+=`<Mirror${k}/>`,w+=e.length;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteMirrorSrcForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteMirrorSrcInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteWikiLinksForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteWikiLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteMarkdownLinksForDocumentRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteMarkdownLinksInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteAssetReferencesForRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteAssetReferencesInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteOutboundMarkdownLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let t=readWikiLink$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`!`&&e[w+1]===`[`){let t=readImageRef(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`){let E=readMarkdownLink$2(e,w);if(E){let D=resolveInternalHref(E.href,t);if(D!==null){let t=recomputeRelativeMarkdownHref(E.href,s,D.docName);if(t!==E.href){let e=E.hrefRaw.startsWith(`<`)&&E.hrefRaw.endsWith(`>`)?`<${t}>`:t;g+=`[${E.text}](${e}${E.titleSuffix})`,S++}else g+=e.slice(w,E.nextIndex)}else g+=e.slice(w,E.nextIndex);w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,s){if(posix.dirname(t)===posix.dirname(s))return{markdown:e,rewrites:0};let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteOutboundMarkdownLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e,t=`${e} does not exist`){super(t),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e,t=`Source path is not a ${e}`){super(t),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},ManagedRenameInvalidRequestError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameInvalidRequestError`}},ManagedRenameReservedPathError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameReservedPathError`}},SymlinkEscapeError=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},BacklinkIndexRequiredError=class extends Error{constructor(){super(`Managed rename requires backlink index support`),this.name=`BacklinkIndexRequiredError`}},ManagedRenameSnapshotMissingError=class extends Error{docName;constructor(e){super(`Cannot snapshot missing document: ${e}`),this.name=`ManagedRenameSnapshotMissingError`,this.docName=e}},ManagedRenameMissingDocumentError=class extends Error{docName;constructor(e){super(`Cannot rename missing document: ${e}`),this.name=`ManagedRenameMissingDocumentError`,this.docName=e}};function buildRenameMap(e){let t=new Map,s=[];for(let{from:g,to:S}of e){for(let[e,w]of t)e!==g&&w===S&&s.push({existing:e,incoming:g,to:S});t.set(g,S)}if(s.length>0)throw new ManagedRenameCollisionError(s);return t}function rewriteSupportedLinksForRename(e,t,s,g){let{frontmatter:S,body:w}=stripFrontmatter(e),E=rewriteWikiLinksForDocumentRename(w,s,g),D=rewriteMarkdownLinksForDocumentRename(E.markdown,t,s,g),O=rewriteMirrorSrcForDocumentRename(D.markdown,s,g);return{markdown:prependFrontmatter(S,O.markdown),rewrites:E.rewrites+D.rewrites+O.rewrites}}function applyRenameMap(e,t,s){let g=e,S=0,w,E=[];for(let[e,g]of s)e!==g&&(e===t?w=g:E.push([e,g]));if(w!==void 0){let e=rewriteSupportedLinksForRename(g,t,t,w);g=e.markdown,S+=e.rewrites;let{frontmatter:s,body:E}=stripFrontmatter(g),D=rewriteOutboundMarkdownLinksForSourceMove(E,t,w);g=prependFrontmatter(s,D.markdown),S+=D.rewrites}let D=w??t,O=new Map;for(let[e,t]of E){let s=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,w=rewriteSupportedLinksForRename(g,D,e,s);w.rewrites>0&&(g=w.markdown,S+=w.rewrites,O.set(s,t))}for(let[e,t]of O)g=rewriteSupportedLinksForRename(g,D,e,t).markdown;return{markdown:g,rewrites:S}}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState$1(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,s){if(!normalizeSnippet$1(e))return null;let g=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
832
830
  `,t-1)),S=[e.indexOf(`.`,s),e.indexOf(`?`,s),e.indexOf(`!`,s),e.indexOf(`
833
831
  `,s)].filter(e=>e>=0),w=g>=0?g+1:Math.max(0,t-60),E=S.length>0?Math.min(...S)+1:Math.min(e.length,s+60),D=w>0?`…`:``,O=E<e.length?`…`:``,k=normalizeSnippet$1(e.slice(w,E));return k?`${D}${k}${O}`:null}function matchFence$1(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,length:s.length}}function isFenceClose$1(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$1(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$1(e,t){let s=0;for(;e[t+s]==="`";)s++;if(s===0)return null;let g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S++;continue}let t=0;for(;e[S+t]==="`";)t++;if(t===s)return{text:e.slice(g,S),nextIndex:S+s};S+=t}return{text:e.slice(t,g),nextIndex:g}}function readWikiLink$1(e,t){WIKI_LINK_RE$1.lastIndex=t;let s=WIKI_LINK_RE$1.exec(e);if(!s)return null;let g=s[1]?.trim(),S=s[2]?.trim()||null,w=s[3]?.trim()||null;return g?{target:g,alias:w,anchor:S,nextIndex:t+s[0].length}:null}function extractWikiLinksFromLine(e){let t=``,s=[],g=leadingMarkdownPrefixLength$1(e);for(;g<e.length;){if(e[g]===`\\`&&g+1<e.length){t+=e[g+1],g+=2;continue}if(e[g]==="`"){let s=readInlineCode$1(e,g);if(s){t+=s.text,g=s.nextIndex;continue}}if(e[g]===`[`&&e[g+1]===`[`){let S=readWikiLink$1(e,g);if(S){let e=getWikiLinkText(S),w=t.length;t+=e;let E=classifyWikiLinkTarget(S.target,S.anchor);E?.kind===`doc`&&s.push({target:E.docName,anchor:E.anchor,start:w,end:w+e.length}),g=S.nextIndex;continue}}t+=e[g],g++}return{text:t,occurrences:s}}function extractExternalWikiLinksFromLine(e){let t=``,s=[],g=leadingMarkdownPrefixLength$1(e);for(;g<e.length;){if(e[g]===`\\`&&g+1<e.length){t+=e[g+1],g+=2;continue}if(e[g]==="`"){let s=readInlineCode$1(e,g);if(s){t+=s.text,g=s.nextIndex;continue}}if(e[g]===`[`&&e[g+1]===`[`){let S=readWikiLink$1(e,g);if(S){let e=getWikiLinkText(S),w=t.length;t+=e;let E=classifyWikiLinkTarget(S.target,S.anchor);E?.kind===`external`&&s.push({url:E.url,label:e,start:w,end:w+e.length}),g=S.nextIndex;continue}}t+=e[g],g++}return{text:t,occurrences:s}}function normalizeMarkdownHref$1(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function readMarkdownLink$1(e,t){MD_LINK_RE$1.lastIndex=t;let s=MD_LINK_RE$1.exec(e);return s?{text:s[1]??``,href:normalizeMarkdownHref$1(s[2]??``),nextIndex:t+s[0].length}:null}function extractMarkdownLinksFromLine(e,t){let s=``,g=[],S=leadingMarkdownPrefixLength$1(e);for(;S<e.length;){if(e[S]===`\\`&&S+1<e.length){s+=e[S+1],S+=2;continue}if(e[S]==="`"){let t=readInlineCode$1(e,S);if(t){s+=t.text,S=t.nextIndex;continue}}if(e[S]===`[`&&e[S+1]===`[`){let t=readWikiLink$1(e,S);if(t){s+=getWikiLinkText(t),S=t.nextIndex;continue}}if(e[S]===`[`&&e[S-1]!==`!`){let w=readMarkdownLink$1(e,S);if(w){let e=classifyMarkdownHref(w.href,t);if(e?.kind===`doc`){let t=s.length;s+=w.text,g.push({target:e.docName,anchor:e.anchor,start:t,end:t+w.text.length})}else s+=w.text;S=w.nextIndex;continue}}s+=e[S],S++}return{text:s,occurrences:g}}function extractExternalMarkdownLinksFromLine(e,t){let s=``,g=[],S=leadingMarkdownPrefixLength$1(e);for(;S<e.length;){if(e[S]===`\\`&&S+1<e.length){s+=e[S+1],S+=2;continue}if(e[S]==="`"){let t=readInlineCode$1(e,S);if(t){s+=t.text,S=t.nextIndex;continue}}if(e[S]===`[`&&e[S+1]===`[`){let t=readWikiLink$1(e,S);if(t){s+=getWikiLinkText(t),S=t.nextIndex;continue}}if(e[S]===`[`&&e[S-1]!==`!`){let w=readMarkdownLink$1(e,S);if(w){let e=classifyMarkdownHref(w.href,t);if(s+=w.text,e?.kind===`external`){let t=s.length-w.text.length;g.push({url:e.url,label:w.text||null,start:t,end:t+w.text.length})}S=w.nextIndex;continue}}s+=e[S],S++}return{text:s,occurrences:g}}function extractMarkdownLinksFromMarkdown(e,t){let s=e.replaceAll(`\r
@@ -1699,39 +1697,36 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
1699
1697
  `).filter(e=>e.length===40)}catch{}try{let e=(await J.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/${S}/`)).trim().split(`
1700
1698
  `).filter(Boolean);te.push(...e)}catch{}if(ne&&te.length===0)try{let e=(await J.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/main/`)).trim().split(`
1701
1699
  `).filter(Boolean);te.push(...e)}catch{}if(te.length===0&&Y.length===0&&ae.length===0)return EMPTY;let oe=[...Y,...ae],se=[];if(oe.length>0){let t=parseGitLogOutput(await J.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,ee,q)),ne&&Y.length>0&&ae.length>0){let e=new Set(Y),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 J.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,ee)})))),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(`
1702
- `).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})}function resumeSyncOnAuthEvent(e,t){e.type===`complete`&&t?.()?.notifyCredentialsChanged().catch(()=>{})}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$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 ee of L){if(E?.aborted){j=!0;return}if(O>=w){k=!0;return}let L=t?`${t}/${ee.name}`:ee.name;if(ee.isDirectory()){if(s.isDirExcluded(L,{bypassFilters:!0}))continue;let t=`${e}/${ee.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(!ee.isFile()||s.isExcluded(L,{bypassFilters:!0})||!F(L))continue;let J=null;try{J=await stat$1(`${e}/${ee.name}`)}catch(t){console.warn(`[document-list][showAll] stat failed for ${e}/${ee.name}:`,t);continue}if(isSupportedDocFile(ee.name)){let e=L.replace(/\.(md|mdx)$/i,``),t=S(e);O+=1,yield{kind:`document`,docName:e,docExt:t,size:J.size,modified:J.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let Y=synthesizeShowAllAssetExt(ee.name),te=mediaKindForSidebarAssetExtension(Y);O+=1,yield{kind:`asset`,docName:L,docExt:Y,path:L,assetExt:Y,mediaKind:te,referencedBy:[],size:J.size,modified:J.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(`---
1703
- `)||e.startsWith(`---\r
1704
- `)){let s=e.indexOf(`
1705
- ---`,3);s!==-1&&(t=e.slice(s+4))}let s=[],g=new Map,S=createCodeFenceTracker();for(let e of t.split(`
1700
+ `).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})}function resumeSyncOnAuthEvent(e,t){e.type===`complete`&&t?.()?.notifyCredentialsChanged().catch(()=>{})}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$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 ee of L){if(E?.aborted){j=!0;return}if(O>=w){k=!0;return}let L=t?`${t}/${ee.name}`:ee.name;if(ee.isDirectory()){if(s.isDirExcluded(L,{bypassFilters:!0}))continue;let t=`${e}/${ee.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(!ee.isFile()||s.isExcluded(L,{bypassFilters:!0})||!F(L))continue;let J=null;try{J=await stat$1(`${e}/${ee.name}`)}catch(t){console.warn(`[document-list][showAll] stat failed for ${e}/${ee.name}:`,t);continue}if(isSupportedDocFile(ee.name)){let e=L.replace(/\.(md|mdx)$/i,``),t=S(e);O+=1,yield{kind:`document`,docName:e,docExt:t,size:J.size,modified:J.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let Y=synthesizeShowAllAssetExt(ee.name),te=mediaKindForSidebarAssetExtension(Y);O+=1,yield{kind:`asset`,docName:L,docExt:Y,path:L,assetExt:Y,mediaKind:te,referencedBy:[],size:J.size,modified:J.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{body:t}=stripFrontmatter(e),s=[],g=new Map,S=createCodeFenceTracker();for(let e of t.split(`
1706
1701
  `)){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:ee,getCurrentBranch:J,getDiskAckSVs:Y,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,semanticSearch:De,getSemanticSimilarityFloor:je,embeddingsSecretsFile:Me,ephemeral:Pe=!1}=e,Ie=createConcurrencyGuard(),Re=new Map,ze=null;function Be(){let e=E?.();return e instanceof Map?e:null}function Ve(e){let t=Be();if(t)try{upsertFolderIndexEntry(t,g,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function Ue(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)Ve(resolve(g,t.slice(0,e).join(`/`)))}function We(e){let t=Be();t&&removeFolderIndexEntries(t,e)}function Ge(e,t){let s=Be();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)&&Ve(e);return}for(let[e,t]of S)s.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(g,e)})}function Ke(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
1707
- `)}function Xe(){ze=null}D?.(Xe);let $e=createInstalledAgentsProbe({probe:ve??createOsProbe(process.platform)});function nt(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 rt(e){let t=nt(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function it(e,t){return t.has(e)?rt(e):e}let at={cluster:void 0,category:void 0,tags:void 0};function st(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=nt(e);if(!t||!existsSync(t))return at;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):at}catch{return at}}function vt(e,t){return t.has(e)?st(e):at}function Tt(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 Et(e){return O?.().get(e)??e}function Dt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function jt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Mt(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 Ft(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ee?.(e),await t.debouncer.executeNow(s));let g=H?.(e)??null;return g?{kind:`failure`,failure:g}:q?.(e)?{kind:`divergence`}:null}function It(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 Lt(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 Rt(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 zt(){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 Bt(){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 Vt=Bt(),Ht=e=>e.endsWith(`.`)?e:`${e}.`;function Ut(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Ht(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Ht(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Ht(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Ht(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Ht(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Ht(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Ht(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 Wt(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 Kt(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 $t(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 en(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 jr(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 Mr(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=Ir(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 Fr(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 Ir(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=Fr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Lr(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=Fr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function zr(e){let t=[];if(e.length===0)return t;let s=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let g of s){let s=en(g);if(typeof s!=`string`)continue;let S=Fr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Br(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 Vr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Lr(S.docName,s):S;e.rewrites!==0&&(jr(S.docName,e.markdown),ne?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Hr(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),s=t===-1?``:e.slice(0,t),S=t===-1?e:e.slice(t+1),w=s?resolveContentEntryPath(g,`folder`,s):g,E;try{E=readdirSync(w,{withFileTypes:!0})}catch(t){let s=t.code;if(s===`ENOENT`||s===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let D=E.filter(e=>e.isFile()&&e.name.startsWith(`${S}.`)).map(e=>s?`${s}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function Ur(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 Wr(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 Gr(e,t){return Vt(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,LINKABLE_ASSET_EXTENSIONS)||!isSupportedAssetFile(S,LINKABLE_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=zr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Br(O.map(e=>e.docName)),await renameTrackedPathInGit(me,w,E)||renamePathOnDisk(w,E);let k=Vr(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 Kr(e,s,S,E){return Vt(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`?Wr(O,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[stripDocExtension(e)]:Ur(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=zr(L);Br(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(me,O,k)||renamePathOnDisk(O,k),Ge(e,s),oe?.(`files`)),g.push(...Vr(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})),ee=new Set;for(let{from:e}of B)for(let t of ne.getBacklinks(e))H.has(t.source)||ee.add(t.source);let Y=[...ee].sort((e,t)=>e.localeCompare(t)),te=new Map,ae=new Set,se=new Set,ce=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){ce.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=en(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)??en(t);typeof e==`string`&&Ir(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))}}Br(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:$t([...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)?Mr(e,H,L):Ir(te.get(e)??``,e,e,H,L);s.rewrites>0&&(jr(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`&&Ge(e,s);let k=await Wt([...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=J?.()??`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=Ir(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Kt([{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 qr(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 Jr(e){return{principalId:ge?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Yr(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 Xr(e){return{value:e.value}}function Zr(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Qr(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=Yr(S),E=g||!w.response?w.response:Xr(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(),Zr(S,!g);for(let{docName:e}of s)Mt(e,`rename-path`);return E}case`principal`:{let t=Yr(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)}Zr(e.summary,!1);for(let{docName:e}of s)Mt(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 ji(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 Hi(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=Yr(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Ui(e){if(B)try{await B()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let Gi=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=Et(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=qr(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write`});return}let H=normalizeSummary(E.summary),q=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),J=new Date().toISOString(),Y=typeof E.content==`string`?E.content:`Hello from the agent! ${J}`,{response:te,stored:ne}=Yr(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,`${Y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),q.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${Y.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,Jr({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),Zr(H)}finally{ce?.touchMode(O,`idle`)}let ae=await Ft(D);if(ae?.kind===`failure`){It(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Lt(w,`agent-write`);return}Mt(D,`agent-write`),ue?.();let oe=Rt(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...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`}),Ki=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=Et(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=qr(E);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`agent-write-md`});return}E.extension!==void 0&&!docNameExistsWithAnySupportedExtension(g,O)&&registerDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=Yr(q),Y=await s.getSession(O,k,{displayName:j,colorSeed:F,clientName:L}),te=reconcileDiskBeforeAgentWrite(t,O,g,e.resolveEmbed),ne=new Date().toISOString(),ae;try{let t=iconFromClientName(L),s=AGENT_ICON_COLORS[t]??colorFromSeed(F??k);ce?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),k,F,L),Y.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(Y.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),Y.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),ae!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:S,intendedBytes:ae.intendedBytes,actualBytes:ae.actualBytes,byteDelta:ae.byteDelta,"agent.id":k,"agent.client_name":L})),recordContentDivergenceGate(`agent-write-md`,ae),recordContributor(O,k,j,F,void 0,Jr({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),Zr(q)}finally{ce?.touchMode(k,`idle`)}let oe=await Ft(O);if(oe?.kind===`failure`){It(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Lt(w,`agent-write-md`);return}Mt(O,`agent-write-md`),se?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),ue?.();let de=Tt(O),fe=Dt(O),me=jt();me===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let ge=Rt(te);successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:fe,systemSubscriberCount:me,...de?{hints:de}:{},...ee?{summary:ee}:{},...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`}),Yi=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=Et(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=qr(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let H=E.patch??{},q=Object.keys(H),ee=normalizeSummary(E.summary),{response:J,stored:Y}=Yr(ee),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,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(`
1702
+ `)}function Xe(){ze=null}D?.(Xe);let $e=createInstalledAgentsProbe({probe:ve??createOsProbe(process.platform)});function nt(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 rt(e){let t=nt(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function it(e,t){return t.has(e)?rt(e):e}let at={cluster:void 0,category:void 0,tags:void 0};function st(e){try{let s=t.documents.get(e);if(s){let e=readFmMap(s.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,s=typeof e.category==`string`?e.category:void 0,g;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);g=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(g=[e.tags]);return{cluster:t,category:s,tags:g}}}}catch{}try{let t=nt(e);if(!t||!existsSync(t))return at;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):at}catch{return at}}function vt(e,t){return t.has(e)?st(e):at}function Tt(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 Et(e){return O?.().get(e)??e}function Dt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function jt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Mt(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 Ft(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ee?.(e),await t.debouncer.executeNow(s));let g=H?.(e)??null;return g?{kind:`failure`,failure:g}:q?.(e)?{kind:`divergence`}:null}function It(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 Lt(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 Rt(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 zt(){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 Bt(){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 Vt=Bt(),Ht=e=>e.endsWith(`.`)?e:`${e}.`;function Ut(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Ht(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Ht(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Ht(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Ht(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Ht(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Ht(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Ht(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 Wt(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 Kt(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 $t(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 en(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 jr(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 Mr(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=Ir(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 Fr(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 Ir(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=Fr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Lr(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=Fr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function zr(e){let t=[];if(e.length===0)return t;let s=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let g of s){let s=en(g);if(typeof s!=`string`)continue;let S=Fr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Br(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 Vr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Lr(S.docName,s):S;e.rewrites!==0&&(jr(S.docName,e.markdown),ne?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Hr(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),s=t===-1?``:e.slice(0,t),S=t===-1?e:e.slice(t+1),w=s?resolveContentEntryPath(g,`folder`,s):g,E;try{E=readdirSync(w,{withFileTypes:!0})}catch(t){let s=t.code;if(s===`ENOENT`||s===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let D=E.filter(e=>e.isFile()&&e.name.startsWith(`${S}.`)).map(e=>s?`${s}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function Ur(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 Wr(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 Gr(e,t){return Vt(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,LINKABLE_ASSET_EXTENSIONS)||!isSupportedAssetFile(S,LINKABLE_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=zr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Br(O.map(e=>e.docName)),await renameTrackedPathInGit(me,w,E)||renamePathOnDisk(w,E);let k=Vr(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 Kr(e,s,S,E){return Vt(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`?Wr(O,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[stripDocExtension(e)]:Ur(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=zr(L);Br(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(me,O,k)||renamePathOnDisk(O,k),Ge(e,s),oe?.(`files`)),g.push(...Vr(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})),ee=new Set;for(let{from:e}of B)for(let t of ne.getBacklinks(e))H.has(t.source)||ee.add(t.source);let Y=[...ee].sort((e,t)=>e.localeCompare(t)),te=new Map,ae=new Set,se=new Set,ce=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){ce.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=en(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)??en(t);typeof e==`string`&&Ir(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))}}Br(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:$t([...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)?Mr(e,H,L):Ir(te.get(e)??``,e,e,H,L);s.rewrites>0&&(jr(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`&&Ge(e,s);let k=await Wt([...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=J?.()??`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=Ir(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Kt([{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 qr(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 Jr(e){return{principalId:ge?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Yr(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 Xr(e){return{value:e.value}}function Zr(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Qr(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=Yr(S),E=g||!w.response?w.response:Xr(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(),Zr(S,!g);for(let{docName:e}of s)Mt(e,`rename-path`);return E}case`principal`:{let t=Yr(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)}Zr(e.summary,!1);for(let{docName:e}of s)Mt(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 ji(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 Hi(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=Yr(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Ui(e){if(B)try{await B()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let Gi=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=Et(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=qr(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write`});return}let H=normalizeSummary(E.summary),q=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),J=new Date().toISOString(),Y=typeof E.content==`string`?E.content:`Hello from the agent! ${J}`,{response:te,stored:ne}=Yr(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,`${Y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),q.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${Y.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,Jr({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),Zr(H)}finally{ce?.touchMode(O,`idle`)}let ae=await Ft(D);if(ae?.kind===`failure`){It(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Lt(w,`agent-write`);return}Mt(D,`agent-write`),ue?.();let oe=Rt(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...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`}),Ki=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=Et(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=qr(E);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`agent-write-md`});return}E.extension!==void 0&&!docNameExistsWithAnySupportedExtension(g,O)&&registerDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=Yr(q),Y=await s.getSession(O,k,{displayName:j,colorSeed:F,clientName:L}),te=reconcileDiskBeforeAgentWrite(t,O,g,e.resolveEmbed),ne=new Date().toISOString(),ae;try{let t=iconFromClientName(L),s=AGENT_ICON_COLORS[t]??colorFromSeed(F??k);ce?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),k,F,L),Y.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(Y.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),Y.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),ae!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:S,intendedBytes:ae.intendedBytes,actualBytes:ae.actualBytes,byteDelta:ae.byteDelta,"agent.id":k,"agent.client_name":L})),recordContentDivergenceGate(`agent-write-md`,ae),recordContributor(O,k,j,F,void 0,Jr({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),Zr(q)}finally{ce?.touchMode(k,`idle`)}let oe=await Ft(O);if(oe?.kind===`failure`){It(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Lt(w,`agent-write-md`);return}Mt(O,`agent-write-md`),se?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),ue?.();let de=Tt(O),fe=Dt(O),me=jt();me===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let ge=Rt(te);successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:fe,systemSubscriberCount:me,...de?{hints:de}:{},...ee?{summary:ee}:{},...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`}),Yi=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=Et(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=qr(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let H=E.patch??{},q=Object.keys(H),ee=normalizeSummary(E.summary),{response:J,stored:Y}=Yr(ee),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,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(`
1708
1703
  `),S=s.nextFenced+(g?`
1709
- `:``)+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,Jr({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),Zr(ee),fe){let e=await Ft(D);if(e?.kind===`failure`){It(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Lt(w,`frontmatter-patch`);return}}Mt(D,`frontmatter-patch`)}se?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),ue?.();let ge=Dt(D),_e=jt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Rt(ne);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:ge,systemSubscriberCount:_e,appliedKeys:me,...J?{summary:J}:{},...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 Xi(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 Zi=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=Et(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:Xi(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:Xi(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}),ka=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=Re.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;Re.set(e,E),w.finally(()=>{Re.get(e)===E&&Re.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(),Re.get(e)===w&&Re.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=Ke(k);ze?.signature!==e&&(ze={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=ze?.assets??[]}catch(e){ze=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}),_s=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:rt(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}),xs=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}),Cs=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=zt();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ne.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:it(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),Ts=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=zt();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=vt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:it(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),Ds=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:rt(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}),Os=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=zt();successResponse(t,200,HubsSuccessSchema,{hubs:ne.getHubs(S).map(e=>({docName:e.docName,title:it(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),ks=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=>Et(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ne.getDeadLinks(zt(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:rt(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}),As=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=Et(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=qr(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,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(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){de=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));fe=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),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}=Yr(J);recordContributor(j,F,L,B,void 0,Jr({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),Zr(J),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 Ft(j);if(me?.kind===`failure`){It(w,me.failure,`agent-patch`);return}if(me?.kind===`divergence`){Lt(w,`agent-patch`);return}Mt(j,`agent-patch`),se?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),ue?.();let ge=Dt(j),_e=jt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=Yr(J),ye=Rt(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`}),Ns=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=Et(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=qr(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,Jr({clientName:k,clientVersion:j,label:F}))}finally{ce?.touchMode(E,`idle`)}if(q){let e=await Ft(w);if(e?.kind===`failure`){It(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Lt(g,`agent-undo`);return}Mt(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`}),Ps=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}),Is=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=Et(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}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{try{await L?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$4.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),$s=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=Et(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}),ec=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}),tc=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}await 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}),nc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=qr(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`}),rc=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`)??J?.()??`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=yl(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,ee=g.searchParams.get(`excludeAuthor`)??void 0,Y=Date.now();try{let e=await getDocumentHistory(s,{docName:S,branch:E,limit:L,offset:B,type:H,author:q,excludeAuthor:ee},D),g=Date.now()-Y;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 ic(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=J?.()??`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 ac=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,J?.()??`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 ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,Y;q.transact(()=>{replaceRawBody(q,F,ee),Y=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),Y!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:Y.intendedBytes,actualBytes:Y.actualBytes,byteDelta:Y.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,Y);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=Yr(s);te=t||!g.response?g.response:Xr(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),Zr(s,!t);break}case`principal`:{let e=Yr(w.summary);te=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),Zr(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 Ft(O);if(ne?.kind===`failure`){It(g,ne.failure,`rollback`);return}if(ne?.kind===`divergence`){Lt(g,`rollback`);return}Mt(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}:{},...Y===void 0?{}:{warning:toContentDivergenceWarning(Y)}},{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`}),oc=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}),sc=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}),cc=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=Y?.();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 lc(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 uc(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 dc(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 fc(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 pc=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=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$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}),mc=1048576,hc=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>mc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${mc}-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}),gc=1440*60*1e3,_c=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>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$4.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=J?.()??`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}),vc=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`}),yc=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}),Ue(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`}),bc=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]:Ur(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))Ue(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`}),xc=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=nt(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}),Sc=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 Gr(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Ut(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=Qr(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)]:Ur(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 Kr(E,D,w,F?{actor:F}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Ht(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&&Xe();let H;if(L.renamed.length>0&&(H=Qr(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}=Ut(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Cc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{qr(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`?Hr(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]:Ur(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 Wt(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}),We(E)),Xe();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`}),wc=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`){Xe(),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(Xe(),j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Wt(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`&&We(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`}),Tc=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}),Ec=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 Dc(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}=qr(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 ee=await fileTypeFromFile(w),J=ee?.mime,Y=ee?.ext;if(!J){let e=readTempFileHead(w,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(J=`image/svg+xml`,Y=`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:J??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=Y??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:J??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 Oc=`/api/local-op/clone`,kc=`/api/local-op/ok-init`,Ac=600*1e3,jc=45e3,Mc=`local-op-clone`,Nc=withValidation(LocalOpCloneRequestSchema,Pc,{handler:Mc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Mc})});async function Pc(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:Mc,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:Mc,cause:Error(`dir=${S}`)});return}if(!Ie.tryAcquire(Oc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Mc,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,Mc),D=null,O=runCloneSubprocess({cliArgs:fe,url:g,dir:S,branch:w,timeoutMs:Ac,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 Fc(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:Mc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ie.release(Oc)}})(),t.on(`close`,()=>{O.cancel()})}async function Fc(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/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$4.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let 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(!Ie.tryAcquire(kc)){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{Ie.release(kc)}},{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=null,Uc=`local-op-auth-login`,Wc=withValidation(LocalOpAuthHostRequestSchema,Gc,{handler:Uc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Uc})});async function Gc(e,t,s){let g=s.host??`github.com`;if(!Ie.tryAcquire(Rc)){let e=Hc;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:Uc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Hc=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,Uc),w=runDeviceFlowSubprocess({cliArgs:fe,host:g,timeoutMs:Ac,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,de),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Hc=w;let E=()=>{w.cancel(),Hc===w&&(Hc=null,Ie.release(Rc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Hc===w&&(Hc=null,Ie.release(Rc))})}let Kc=`local-op-auth-status`,qc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ie.tryAcquire(zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Kc,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(`
1704
+ `:``)+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;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]:oe.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(de&&me.length>0){if(recordContributor(D,O,k,j,void 0,Jr({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),Zr(ee),fe){let e=await Ft(D);if(e?.kind===`failure`){It(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Lt(w,`frontmatter-patch`);return}}Mt(D,`frontmatter-patch`)}se?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),ue?.();let ge=Dt(D),_e=jt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Rt(ne);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:ge,systemSubscriberCount:_e,appliedKeys:me,...J?{summary:J}:{},...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 Xi(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 Zi=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=Et(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:Xi(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:Xi(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}),ka=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=Re.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;Re.set(e,E),w.finally(()=>{Re.get(e)===E&&Re.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(),Re.get(e)===w&&Re.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=Ke(k);ze?.signature!==e&&(ze={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=ze?.assets??[]}catch(e){ze=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}),_s=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:rt(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}),xs=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}),Cs=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=zt();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ne.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:it(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),Ts=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=zt();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=vt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:it(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),Ds=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:rt(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}),Os=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=zt();successResponse(t,200,HubsSuccessSchema,{hubs:ne.getHubs(S).map(e=>({docName:e.docName,title:it(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),ks=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=>Et(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ne.getDeadLinks(zt(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:rt(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}),As=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=Et(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=qr(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,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(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){de=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));fe=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),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}=Yr(J);recordContributor(j,F,L,B,void 0,Jr({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),Zr(J),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 Ft(j);if(me?.kind===`failure`){It(w,me.failure,`agent-patch`);return}if(me?.kind===`divergence`){Lt(w,`agent-patch`);return}Mt(j,`agent-patch`),se?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),ue?.();let ge=Dt(j),_e=jt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=Yr(J),ye=Rt(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`}),Ns=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=Et(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=qr(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,Jr({clientName:k,clientVersion:j,label:F}))}finally{ce?.touchMode(E,`idle`)}if(q){let e=await Ft(w);if(e?.kind===`failure`){It(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Lt(g,`agent-undo`);return}Mt(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`}),Ps=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}),Is=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=Et(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}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{try{await L?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$4.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),$s=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=Et(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}),ec=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}),tc=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}await 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}),nc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=qr(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`}),rc=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`)??J?.()??`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=yl(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,ee=g.searchParams.get(`excludeAuthor`)??void 0,Y=Date.now();try{let e=await getDocumentHistory(s,{docName:S,branch:E,limit:L,offset:B,type:H,author:q,excludeAuthor:ee},D),g=Date.now()-Y;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 ic(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=J?.()??`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 ac=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,J?.()??`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 ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,Y;q.transact(()=>{replaceRawBody(q,F,ee),Y=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),Y!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:Y.intendedBytes,actualBytes:Y.actualBytes,byteDelta:Y.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,Y);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=Yr(s);te=t||!g.response?g.response:Xr(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),Zr(s,!t);break}case`principal`:{let e=Yr(w.summary);te=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),Zr(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 Ft(O);if(ne?.kind===`failure`){It(g,ne.failure,`rollback`);return}if(ne?.kind===`divergence`){Lt(g,`rollback`);return}Mt(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}:{},...Y===void 0?{}:{warning:toContentDivergenceWarning(Y)}},{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`}),oc=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}),sc=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}),cc=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=Y?.();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 lc(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 uc(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 dc(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 fc(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 pc=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=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$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}),mc=1048576,hc=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>mc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${mc}-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}),gc=1440*60*1e3,_c=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>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$4.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=J?.()??`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}),vc=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`}),yc=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}),Ue(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`}),bc=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]:Ur(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))Ue(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`}),xc=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=nt(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}),Sc=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 Gr(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Ut(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=Qr(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)]:Ur(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 Kr(E,D,w,F?{actor:F}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Ht(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&&Xe();let H;if(L.renamed.length>0&&(H=Qr(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}=Ut(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Cc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{qr(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`?Hr(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]:Ur(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 Wt(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}),We(E)),Xe();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`}),wc=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`){Xe(),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(Xe(),j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Wt(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`&&We(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`}),Tc=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}),Ec=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 Dc(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}=qr(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 ee=await fileTypeFromFile(w),J=ee?.mime,Y=ee?.ext;if(!J){let e=readTempFileHead(w,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(J=`image/svg+xml`,Y=`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:J??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=Y??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:J??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 Oc=`/api/local-op/clone`,kc=`/api/local-op/ok-init`,Ac=600*1e3,jc=45e3,Mc=`local-op-clone`,Nc=withValidation(LocalOpCloneRequestSchema,Pc,{handler:Mc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Mc})});async function Pc(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:Mc,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:Mc,cause:Error(`dir=${S}`)});return}if(!Ie.tryAcquire(Oc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Mc,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,Mc),D=null,O=runCloneSubprocess({cliArgs:fe,url:g,dir:S,branch:w,timeoutMs:Ac,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 Fc(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:Mc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ie.release(Oc)}})(),t.on(`close`,()=>{O.cancel()})}async function Fc(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/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$4.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let 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(!Ie.tryAcquire(kc)){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{Ie.release(kc)}},{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=null,Uc=`local-op-auth-login`,Wc=withValidation(LocalOpAuthHostRequestSchema,Gc,{handler:Uc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Uc})});async function Gc(e,t,s){let g=s.host??`github.com`;if(!Ie.tryAcquire(Rc)){let e=Hc;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:Uc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Hc=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,Uc),w=runDeviceFlowSubprocess({cliArgs:fe,host:g,timeoutMs:Ac,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,de),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Hc=w;let E=()=>{w.cancel(),Hc===w&&(Hc=null,Ie.release(Rc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Hc===w&&(Hc=null,Ie.release(Rc))})}let Kc=`local-op-auth-status`,qc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ie.tryAcquire(zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Kc,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
1705
  `).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:Kc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:Kc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Kc,cause:e})}finally{Ie.release(zc)}},{handler:Kc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Kc})}),Jc=`local-op-auth-repos`,Yc=withValidation(LocalOpAuthHostRequestSchema,Xc,{handler:Jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Jc})});async function Xc(e,t,s){let g=s.host??`github.com`;if(!Ie.tryAcquire(Bc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Jc,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,Jc),[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`)},Ac);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(),Ie.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()),Ie.release(Bc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ie.release(Bc))})}let Zc=`local-op-auth-signout`,Qc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ie.tryAcquire(Vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Zc,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:Zc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Zc,cause:e})}finally{Ie.release(Vc)}},{handler:Zc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Zc})}),$c=`/api/local-op/auth/set-identity`,nl=`local-op-auth-set-identity`,il=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:nl});return}if(!Ie.tryAcquire($c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:nl,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(me,g,S),de?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:nl})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:nl,cause:e})}finally{Ie.release($c)}},{handler:nl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:nl})});async function al(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 cl=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 ll(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 ul=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 dl(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 fl(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 pl=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 ml(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let hl=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function gl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,$e.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}))}}let _l=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 vl(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:rt(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 yl(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 xl=/^[A-Za-z0-9_-]+$/;function Cl(e,t,s=`template`){return!e||!xl.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 Tl(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 El(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 Dl(e,t){if(e.method===`GET`)return Ol(e,t);if(e.method===`PUT`)return kl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Ol=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=yl(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}),kl=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(Pe){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,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=yl(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`&&(Hi(e,ji(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Ui(`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 jl(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 Ml=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 Pl(e,t){if(e.method===`GET`)return Ll(e,t);if(e.method===`PUT`)return Rl(e,t);if(e.method===`POST`)return Bl(e,t);if(e.method===`DELETE`)return zl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Fl=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Il=e=>{let t=e.match(Fl),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}},Ll=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Cl(g,t,`template-get`))return;let S=yl(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Tl(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}=Il(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}),Rl=withValidation(TemplatePutRequestSchema,async(e,t,s)=>{try{if(Pe){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}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(!Cl(g,t,`template-put`))return;let S=yl(s.folder,t,`folder`,`template-put`);if(!S||jl(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:El(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}Hi(e,ji(`template`,S.folderRel,g),`${w.created?`template-create`:`template-edit`}: ${w.path}`),await Ui(`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`}),zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Cl(g,t,`template-delete`))return;let S=yl(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(jl(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&&(Hi(E,ji(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Ui(`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}),Bl=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(!Cl(s.fromName,t,`template-move`)||!Cl(s.toName,t,`template-move`))return;let g=yl(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=yl(s.toFolder,t,`folder`,`template-move`);if(!S||jl(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=Tl(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=Il(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:El(s.frontmatter)});t.ok||(E=t.error)}}if(Hi(e,ji(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Ui(`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 Vl(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 Hl(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 Ul(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Wl(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}function Gl(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Kl(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function ql(e,t,s,g){let S=g.documents.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!De?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:S,capable:!1};De.embedCorpus(g.documents);let w,E=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await De.queryScores(e,g.documents);if(E=performance.now()-t,s&&s.size>0){let e=je?.();w=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let D=De.getStatus();return{input:w,status:{capable:D.capable,applied:!1,coverage:{embedded:D.embeddedCount,total:S}},queryEmbedMs:E,pageTotal:S,capable:D.capable}}function Jl(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Hl(e.document.content,t):void 0}}async function Yl(e){let t=performance.now(),s=await Ql(),g=await ql(e.query,e.intent,e.semanticParam,s),S=searchWorkspaceCorpus(s,e.query,{intent:e.intent,scopes:e.scopes,limit:e.limit,semantic:g.input}).map(t=>Jl(t,e.query)),w;if(g.status){let t=S.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;w={...g.status,applied:s},recordSemanticQuery({outcome:g.capable?s?`applied`:g.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:g.capable,embedded:g.status.coverage.embedded,total:g.pageTotal,queryEmbedMs:g.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:S,elapsedMs:Math.max(0,performance.now()-t),...w?{semantic:w}:{}}}async function Xl(){let e=[];for(let[t,s]of w()){if(isSystemDoc(t)||isConfigDoc(t)||isHiddenDocName(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,...Vl(e)]}function Zl(){return[...w()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(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 Ql(){let e=`${g}${me??``}`,t=Zl(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return s.corpus;if(s?.fingerprint===t&&s.pending)return s.pending;let S=Xl().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 $l(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Ql().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}$l();async function eu(e,t){if(e.method===`GET`)return tu(e,t);if(e.method===`POST`)return nu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let tu=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Ul(s.searchParams.get(`intent`)),E=Wl(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),D=Gl(s.searchParams.get(`semantic`)),O=Kl(s.searchParams.get(`source`)),k=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await Yl({query:S,intent:w,scopes:E,limit:k,semanticParam:D,source:O}),{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}),nu=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Ul(s.intent),w=Wl(s.scopes??s.scope),E=typeof s.limit==`number`?s.limit:void 0,D=Gl(s.semantic),O=Kl(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await Yl({query:g,intent:S,scopes:w,limit:E,semanticParam:D,source:O}),{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`}),ru=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 iu(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 au(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 ou=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})}),su=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}),cu=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 lu(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 uu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ie.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 lu([`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{Ie.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})}),du=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(!Ie.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 lu([`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{Ie.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})}),fu=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(!Ie.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 lu(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{Ie.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),pu=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`})}),mu=me?getLocalDir(me):null;async function hu(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}mu&&clearArmedPaneTarget(mu),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:mu?readServerLock(mu)?.port??0:0,paneTarget:mu?readArmedPaneTarget(mu):null,singleFile:Pe};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 gu=`local-op-embeddings-set-key`,_u=`local-op-embeddings-clear-key`,vu=`/api/local-op/embeddings`,yu=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ie.tryAcquire(vu)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:gu,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Me).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:gu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:gu,cause:e})}finally{Ie.release(vu)}},{handler:gu,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:gu})}),bu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ie.tryAcquire(vu)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:_u,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Me),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:_u,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:_u,cause:e})}finally{Ie.release(vu)}},{handler:_u,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:_u})}),xu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(De){let t=De.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Me).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Su={"/api/config":hu,"/api/asset":pc,"/api/asset-text":hc,"/api/document":Zi,"/api/documents":ka,"/api/backlinks":_s,"/api/backlink-counts":xs,"/api/forward-links":Cs,"/api/link-graph":Ts,"/api/dead-links":ks,"/api/orphans":Ds,"/api/hubs":Os,"/api/tags":_l,"/api/pages":Tc,"/api/folder-config":Dl,"/api/template":Pl,"/api/templates":Ml,"/api/search":eu,"/api/semantic-status":xu,"/api/suggest-links":Ec,"/api/page-headings":xc,"/api/create-page":vc,"/api/create-folder":yc,"/api/duplicate-path":bc,"/api/rename-path":Sc,"/api/delete-path":Cc,"/api/trash/cleanup":wc,"/api/upload":Dc,"/api/agent-write":Gi,"/api/agent-write-md":Ki,"/api/frontmatter-patch":Yi,"/api/agent-patch":As,"/api/agent-undo":Ns,"/api/agent-activity":Ps,"/api/agent-burst-diff":Is,"/api/save-version":nc,"/api/history":rc,"/api/rollback":ac,"/api/metrics/reconciliation":oc,"/api/metrics/parse-health":sc,"/api/metrics/agent-presence":uc,"/api/__embed-detect":dc,"/api/server-info":cc,"/api/share/construct-url":ou,"/api/git/branch-info":su,"/api/git/checkout":cu,"/api/share/publish/owners":uu,"/api/share/publish/name-check":du,"/api/share/publish":fu,"/api/principal":lc,"/api/rescue":_c,"/api/workspace":fc,"/api/sync/status":al,"/api/sync/trigger":cl,"/api/sync/conflicts":ll,"/api/sync/conflict-content":dl,"/api/sync/resolve-conflict":ul,"/api/local-op/clone":Nc,"/api/local-op/ok-init":Lc,"/api/local-op/auth/login":Wc,"/api/local-op/auth/status":qc,"/api/local-op/auth/repos":Yc,"/api/local-op/auth/signout":Qc,"/api/local-op/auth/set-identity":il,"/api/local-op/embeddings/set-key":yu,"/api/local-op/embeddings/clear-key":bu,"/api/installed-agents":gl,"/api/spawn-cursor":au,"/api/handoff":iu,"/api/install-skill":hl,"/api/skill/install-state":ru,"/api/seed/plan":fl,"/api/seed/apply":pl,"/api/seed/packs":ml,"/api/client-logs":pu};j&&(Su[`/api/test-reset`]=$s,Su[`/api/test-flush-git`]=Rs,Su[`/api/test-rescan-backlinks`]=ec,Su[`/api/test-rescan-files`]=tc);let Cu=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/seed/apply./api/client-logs`.split(`.`)),wu=[`/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(Cu.has(s)||wu.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(Pe&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Su[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=Su[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await ic(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await vl(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 seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=relative(t,w);if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}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-BaZ9y3AC-B05Md-6F.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(`
1706
+ `);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(),Ie.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()),Ie.release(Bc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ie.release(Bc))})}let Zc=`local-op-auth-signout`,Qc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ie.tryAcquire(Vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Zc,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:Zc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Zc,cause:e})}finally{Ie.release(Vc)}},{handler:Zc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Zc})}),$c=`/api/local-op/auth/set-identity`,nl=`local-op-auth-set-identity`,il=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:nl});return}if(!Ie.tryAcquire($c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:nl,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(me,g,S),de?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:nl})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:nl,cause:e})}finally{Ie.release($c)}},{handler:nl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:nl})});async function al(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 cl=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 ll(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 ul=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 dl(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 fl(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 pl=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 ml(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let hl=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function gl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,$e.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}))}}let _l=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 vl(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:rt(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 yl(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 xl=/^[A-Za-z0-9_-]+$/;function Cl(e,t,s=`template`){return!e||!xl.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 Tl(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 El(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 Dl(e,t){if(e.method===`GET`)return Ol(e,t);if(e.method===`PUT`)return kl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Ol=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=yl(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}),kl=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(Pe){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,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=yl(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`&&(Hi(e,ji(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Ui(`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 jl(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 Ml=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 Pl(e,t){if(e.method===`GET`)return Il(e,t);if(e.method===`PUT`)return Ll(e,t);if(e.method===`POST`)return zl(e,t);if(e.method===`DELETE`)return Rl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Fl=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},Il=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Cl(g,t,`template-get`))return;let S=yl(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Tl(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}=Fl(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}),Ll=withValidation(TemplatePutRequestSchema,async(e,t,s)=>{try{if(Pe){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}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(!Cl(g,t,`template-put`))return;let S=yl(s.folder,t,`folder`,`template-put`);if(!S||jl(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:El(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}Hi(e,ji(`template`,S.folderRel,g),`${w.created?`template-create`:`template-edit`}: ${w.path}`),await Ui(`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`}),Rl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Cl(g,t,`template-delete`))return;let S=yl(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(jl(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&&(Hi(E,ji(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Ui(`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}),zl=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(!Cl(s.fromName,t,`template-move`)||!Cl(s.toName,t,`template-move`))return;let g=yl(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=yl(s.toFolder,t,`folder`,`template-move`);if(!S||jl(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=Tl(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=Fl(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:El(s.frontmatter)});t.ok||(E=t.error)}}if(Hi(e,ji(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Ui(`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 Bl(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 Vl(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 Hl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Ul(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}function Wl(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Gl(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Kl(e,t,s,g){let S=g.documents.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!De?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:S,capable:!1};De.embedCorpus(g.documents);let w,E=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await De.queryScores(e,g.documents);if(E=performance.now()-t,s&&s.size>0){let e=je?.();w=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let D=De.getStatus();return{input:w,status:{capable:D.capable,applied:!1,coverage:{embedded:D.embeddedCount,total:S}},queryEmbedMs:E,pageTotal:S,capable:D.capable}}function ql(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Vl(e.document.content,t):void 0}}async function Jl(e){let t=performance.now(),s=await Zl(),g=await Kl(e.query,e.intent,e.semanticParam,s),S=searchWorkspaceCorpus(s,e.query,{intent:e.intent,scopes:e.scopes,limit:e.limit,semantic:g.input}).map(t=>ql(t,e.query)),w;if(g.status){let t=S.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;w={...g.status,applied:s},recordSemanticQuery({outcome:g.capable?s?`applied`:g.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:g.capable,embedded:g.status.coverage.embedded,total:g.pageTotal,queryEmbedMs:g.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:S,elapsedMs:Math.max(0,performance.now()-t),...w?{semantic:w}:{}}}async function Yl(){let e=[];for(let[t,s]of w()){if(isSystemDoc(t)||isConfigDoc(t)||isHiddenDocName(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,...Bl(e)]}function Xl(){return[...w()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(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 Zl(){let e=`${g}${me??``}`,t=Xl(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return s.corpus;if(s?.fingerprint===t&&s.pending)return s.pending;let S=Yl().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 Ql(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Zl().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}Ql();async function $l(e,t){if(e.method===`GET`)return eu(e,t);if(e.method===`POST`)return tu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let eu=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Hl(s.searchParams.get(`intent`)),E=Ul(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),D=Wl(s.searchParams.get(`semantic`)),O=Gl(s.searchParams.get(`source`)),k=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await Jl({query:S,intent:w,scopes:E,limit:k,semanticParam:D,source:O}),{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}),tu=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Hl(s.intent),w=Ul(s.scopes??s.scope),E=typeof s.limit==`number`?s.limit:void 0,D=Wl(s.semantic),O=Gl(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await Jl({query:g,intent:S,scopes:w,limit:E,semanticParam:D,source:O}),{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`}),nu=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 ru(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 iu(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 au=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})}),ou=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}),su=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 cu(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 lu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ie.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 cu([`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{Ie.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})}),uu=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(!Ie.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 cu([`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{Ie.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})}),du=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(!Ie.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 cu(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{Ie.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),fu=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`})}),pu=me?getLocalDir(me):null;async function mu(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}pu&&clearArmedPaneTarget(pu),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:pu?readServerLock(pu)?.port??0:0,paneTarget:pu?readArmedPaneTarget(pu):null,singleFile:Pe};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 hu=`local-op-embeddings-set-key`,gu=`local-op-embeddings-clear-key`,_u=`/api/local-op/embeddings`,vu=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ie.tryAcquire(_u)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:hu,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Me).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:hu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:hu,cause:e})}finally{Ie.release(_u)}},{handler:hu,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:hu})}),yu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ie.tryAcquire(_u)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:gu,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Me),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:gu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:gu,cause:e})}finally{Ie.release(_u)}},{handler:gu,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:gu})}),bu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(De){let t=De.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Me).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),xu={"/api/config":mu,"/api/asset":pc,"/api/asset-text":hc,"/api/document":Zi,"/api/documents":ka,"/api/backlinks":_s,"/api/backlink-counts":xs,"/api/forward-links":Cs,"/api/link-graph":Ts,"/api/dead-links":ks,"/api/orphans":Ds,"/api/hubs":Os,"/api/tags":_l,"/api/pages":Tc,"/api/folder-config":Dl,"/api/template":Pl,"/api/templates":Ml,"/api/search":$l,"/api/semantic-status":bu,"/api/suggest-links":Ec,"/api/page-headings":xc,"/api/create-page":vc,"/api/create-folder":yc,"/api/duplicate-path":bc,"/api/rename-path":Sc,"/api/delete-path":Cc,"/api/trash/cleanup":wc,"/api/upload":Dc,"/api/agent-write":Gi,"/api/agent-write-md":Ki,"/api/frontmatter-patch":Yi,"/api/agent-patch":As,"/api/agent-undo":Ns,"/api/agent-activity":Ps,"/api/agent-burst-diff":Is,"/api/save-version":nc,"/api/history":rc,"/api/rollback":ac,"/api/metrics/reconciliation":oc,"/api/metrics/parse-health":sc,"/api/metrics/agent-presence":uc,"/api/__embed-detect":dc,"/api/server-info":cc,"/api/share/construct-url":au,"/api/git/branch-info":ou,"/api/git/checkout":su,"/api/share/publish/owners":lu,"/api/share/publish/name-check":uu,"/api/share/publish":du,"/api/principal":lc,"/api/rescue":_c,"/api/workspace":fc,"/api/sync/status":al,"/api/sync/trigger":cl,"/api/sync/conflicts":ll,"/api/sync/conflict-content":dl,"/api/sync/resolve-conflict":ul,"/api/local-op/clone":Nc,"/api/local-op/ok-init":Lc,"/api/local-op/auth/login":Wc,"/api/local-op/auth/status":qc,"/api/local-op/auth/repos":Yc,"/api/local-op/auth/signout":Qc,"/api/local-op/auth/set-identity":il,"/api/local-op/embeddings/set-key":vu,"/api/local-op/embeddings/clear-key":yu,"/api/installed-agents":gl,"/api/spawn-cursor":iu,"/api/handoff":ru,"/api/install-skill":hl,"/api/skill/install-state":nu,"/api/seed/plan":fl,"/api/seed/apply":pl,"/api/seed/packs":ml,"/api/client-logs":fu};j&&(xu[`/api/test-reset`]=$s,xu[`/api/test-flush-git`]=Rs,xu[`/api/test-rescan-backlinks`]=ec,xu[`/api/test-rescan-files`]=tc);let Su=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/seed/apply./api/client-logs`.split(`.`)),Cu=[`/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(Su.has(s)||Cu.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(Pe&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:xu[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=xu[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await ic(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await vl(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 seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=relative(t,w);if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$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-BaZ9y3AC-B05Md-6F.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(`
1712
1707
  `).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(`
1713
1708
  `)}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(`
1714
- `)}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(`
1709
+ `)}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` auto-starts the backend on demand (same `OK_MCP_AUTOSTART` gate as writes; a cold first call can take seconds) and reports `running: false` + `url: null` only when no UI could be reached — its hint names the right command.\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**Working in a git worktree?** Pass the worktree's absolute path as `cwd` on your OK tool calls once — it sticks for the rest of the session, so reads, writes, and the preview all target that worktree instead of the main checkout. If a tool warns that it routed to the main checkout while you're in a worktree, passing `cwd` once is the fix.\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(`
1715
1710
  `).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),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(`
1716
1711
  `);function register$16(e,t){e.registerTool(`checkpoint`,{description:DESCRIPTION$16,inputSchema:{summary:summaryArgSchema.describe(`Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({version:string().describe(VERSION_FIELD_DESCRIBE),previewUrl:previewUrlOutputField.describe(`Always null — a checkpoint is project-wide, not scoped to one doc.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=t.identityRef?.current,w=await httpPost(g,`/api/save-version`,{...e.summary===void 0?{}:{summary:e.summary},...S?{writers:[{id:`agent-${S.connectionId}`,name:S.displayName,email:`agent-${S.connectionId}@openknowledge.local`}]}:{}});if(!w.ok)return textResult(`Error: ${w.error}`,!0);let E=typeof w.checkpointRef==`string`?w.checkpointRef:``,D=E.split(`/`).pop()??``;return/^[0-9a-f]{40}$/i.test(D)?textPlusStructured(`Checkpoint saved. Version: ${D}`,{version:D,previewUrl:null}):textResult(`Error: checkpoint committed but the server returned no usable version ref ("${E}"). Find the latest checkpoint via \`history\`.`,!0)})}const DESCRIPTION$15=[`[Operates on disk; no running OK server required] Read the effective merged Open Knowledge config (defaults → user → project).`,``,`Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.`,``,"Read returns the FULL merged config or a sub-tree when `key` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, and `github.*` config sub-trees, plus `preview.baseUrl` and `preview.scriptSrc`, were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or, for the preview iframe, a fixed open network policy). Reading those keys returns `exists: false`. (`appearance.preview.autoOpen` is still a live key.)",``,`**Parameters:**`,'- `key` (optional) — Dotted config key. `"content"` returns the content sub-tree; `"appearance.theme"` returns just that leaf. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
1717
1712
  `),InputSchema$3={key:string().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$5=outputSchemaWithText({value:unknown().describe(`Resolved config value at the requested path (or full config).`),exists:boolean().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:string().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)});function readConfigPath(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s)return;s=s[e]}return s}function register$15(e,t){e.registerTool(`config`,{description:DESCRIPTION$15,inputSchema:InputSchema$3,outputSchema:OutputSchema$5,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=e.key?e.key.split(`.`).filter(e=>e.length>0):[],S=g.length>0?readConfigPath(s.config,g):s.config;return g.length>0&&S===void 0?textPlusStructured(`(no value at ${e.key})`,{value:null,exists:!1,...e.key?{key:e.key}:{}}):textPlusStructured(JSON.stringify(S,null,2),{value:S,exists:!0,...e.key?{key:e.key}:{}})})}const DESCRIPTION$14=["[Requires: Hocuspocus server] Read GitHub-sync merge conflicts. Dispatches on `kind`:",``,'- `kind: "list"` — enumerate every doc currently tracked in a merge-conflict state. Returns `{ list: [{ file, detectedAt, ... }] }` (empty when none). The entry point to the resolve flow.','- `kind: "content"` — fetch the three merge stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, lifecycleStatus } }`. `ours` reflects the live Y.Text (what the human sees) when the doc is loaded server-side.',``,`**Parameters:**`,"- `kind` — `list` | `content`.",'- `file` — Required for `kind: "content"`. Relative path WITH the `.md`/`.mdx` extension (e.g. `notes/sso.md`) — git stages key on the exact path, so do NOT strip the extension.',``,"The `shape` field discriminates the conflict: `both-modified` (both sides edited), `delete-modify` (you deleted, they edited — `ours` empty), or `modify-delete` (you edited, they deleted — `theirs` empty). Use it to pick the `resolve_conflict` strategy."].join(`
1718
1713
  `);function register$14(e,t){e.registerTool(`conflicts`,{description:DESCRIPTION$14,inputSchema:{kind:_enum([`list`,`content`]).describe("`list` enumerates tracked conflicts; `content` fetches one file's stages."),file:string().min(1).optional().describe('Required when `kind: "content"`. Conflicted file WITH extension (e.g. `notes/sso.md`) — git stages key on the exact path, so keep the extension (DD2).'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({list:looseObjectArray.optional().describe('`kind: "list"` — every tracked conflict (`{ file, detectedAt, ... }`).'),content:object$1({file:string().describe(`The conflicted file.`),base:string().describe(`Merge-base stage content.`),ours:string().describe(`Our stage (live Y.Text when loaded server-side).`),theirs:string().describe(`Their stage content.`),shape:_enum([`both-modified`,`delete-modify`,`modify-delete`]).describe("Conflict shape — pick the `resolve_conflict` strategy from it."),lifecycleStatus:string().nullable().describe(`The doc's lifecycle status, or null.`)}).optional().describe('`kind: "content"` — the three merge stages + shape + lifecycle.')}),annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.kind===`content`){if(!e.file)return textResult('Error: `kind: "content"` requires `file` — the conflicted file WITH extension, e.g. conflicts({ kind: "content", file: "notes/sso.md" }).',!0);let t=await httpGet(g,`/api/sync/conflict-content${`?file=${encodeURIComponent(e.file)}&source=ytext`}`);if(!t.ok){let e=t.error,s=typeof t.detail==`string`?t.detail:void 0;return textResult(`Error: ${s?`${e} — ${s}`:e}`,!0)}let s=t,S=typeof s.file==`string`?s.file:e.file,w=typeof s.base==`string`?s.base:``,E=typeof s.ours==`string`?s.ours:``,D=typeof s.theirs==`string`?s.theirs:``,O=s.kind===`delete-modify`||s.kind===`modify-delete`?s.kind:`both-modified`,k=typeof s.lifecycleStatus==`string`?s.lifecycleStatus:null;return textPlusStructured(`Conflict stages for ${S} (shape: ${O})${k?` (lifecycle: ${k})`:``}:\n--- base ---\n${w}\n--- ours ---\n${E}\n--- theirs ---\n${D}`,{content:{file:S,base:w,ours:E,theirs:D,shape:O,lifecycleStatus:k}})}let S=await httpGet(g,`/api/sync/conflicts`);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let w=S.conflicts,E=Array.isArray(w)?w:[];return textPlusStructured(E.length===0?`No conflicts tracked.`:`Tracked conflicts (${E.length}):\n${E.map(e=>`- ${e&&typeof e==`object`&&`file`in e?String(e.file??``):``}`).join(`
1719
- `)}`,{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(`
1714
+ `)}`,{list:E})})}const PREVIEW_URL_SOURCES=[`lock`];function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function encodeFolderRoute(e){let t=e.replace(/^\/+|\/+$/g,``);return t?`${encodeDocName(t)}/`:``}const START_UI_MESSAGE='No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',ATTACH_PREVIEW_ONCE_MESSAGE=`No browser is attached to the preview. Open it 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 awaitUiBaseUrl(e,t){let s=Date.now()+t.timeoutMs;for(;;){let{baseUrl:g}=resolveUiInfo(e);if(g!==null)return g;if(Date.now()>=s)return null;await new Promise(e=>setTimeout(e,t.pollIntervalMs))}}async function buildListResolver(e,t){let s={lockDir:resolveLockDir(t??await e.resolveCwd())};return{resolve:e=>resolvePreviewUrl(e,s)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let s=`/#/${encodeDocName(e)}`;try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:s,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const FrontmatterPatchValue=union([FrontmatterValueSchema,_null()]),FrontmatterArg=record(string(),FrontmatterPatchValue).describe(`Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a top-level key to null to delete it; keys you omit are unchanged. A nested object REPLACES the existing subtree at that key (send the full subtree you want). Example: { title: "Q3 Planning", tags: ["planning"], metadata: { version: "1.0", author: "Inkeep" } }.`),PositionArg=_enum([`append`,`prepend`,`replace`]).describe(`Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). append / prepend = add to the end / start.`);function splitTargetPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),s=t.lastIndexOf(`/`);return s===-1?{folder:``,name:t}:{folder:t.slice(0,s),name:t.slice(s+1)}}const TEMPLATE_NAME_REGEX=/^[A-Za-z0-9_-]+$/,TEMPLATE_PATH_DESCRIBE='Template path = `<folder>/<name>` (e.g. "fishing-log/trip-log"). The slashes are the folder it belongs to; the final segment is the template name (letters, digits, `_`, `-` only — no dots/spaces). Stored at `<folder>/.ok/templates/<name>.md`.',TEMPLATE_CONTENT_DESCRIBE="Template Markdown body. Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time.";function resolveTemplatePath(e){let{folder:t,name:s}=splitTargetPath(e);return TEMPLATE_NAME_REGEX.test(s)?{ok:!0,folder:t,name:s}:{ok:!1,error:`the final segment of a template path is its name — "${s}" must be letters, digits, \`_\`, \`-\` only (no dots/spaces). e.g. { template: { path: "fishing-log/trip-log" } }.`}}function exactlyOneTargetError(e,t){let s=t.filter(t=>e[t]!==void 0);if(s.length===1)return null;let g=t.map(e=>`\`${e}\``).join(`, `);return s.length===0?`Name exactly one of ${g} — the one thing you are addressing. Nest that target's fields under its key (e.g. \`{ document: { path, … } }\`); see this tool's parameter docs for which fields each target takes.`:`You named ${s.map(e=>`\`${e}\``).join(` and `)} — name exactly ONE target.`}const DESCRIPTION$13=["Delete one thing. Pass EXACTLY ONE of `document`, `folder`, `template`, or `asset`.",``,"- `document` — Doc path(s) to delete (a single path or an array). Inbound links become redlinks. Irreversible. [Requires: Hocuspocus server]","- `folder` — Folder path to delete (recursive). [Requires: Hocuspocus server]",'- `template` — `{ path: "<folder>/<name>" }` — a template to delete (server-routed, attributed; auto-cleans empty `.ok/`). [Requires: Hocuspocus server]','- `asset` — `{ path: "<folder>/<file.ext>" }` — a binary asset to delete. [Requires: Hocuspocus server]',``,'Call `links({ kind: "backlinks", document })` BEFORE deleting a doc to see what links here.'].join(`
1720
1715
  `);function parseDeletedDocNames(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}async function deleteOneDoc(e,t,s,g){let S=normalizeDocName(e);if(!S.ok)return{docName:e,ok:!1,error:S.error.replace(/^Error:\s*/,``)};let w=await httpPost(t,`/api/delete-path`,{kind:`file`,path:S.docName,...agentIdentityFields(g.identityRef?.current)});if(!w.ok)return{docName:S.docName,ok:!1,error:w.error};let E=parseDeletedDocNames(w.deletedDocNames),D=await resolvePreviewUrlForTool(S.docName,{config:g.config,resolveCwd:g.resolveCwd},s);return{docName:S.docName,ok:!0,deletedDocNames:E.length>0?E:[S.docName],...D?{previousPreviewUrl:D.url}:{}}}function register$13(e,t){e.registerTool(`delete`,{description:DESCRIPTION$13,inputSchema:{document:union([string(),array(string()).min(1),object$1({path:union([string(),array(string()).min(1)])})]).optional().describe("Doc path(s) to delete — a string, an array, or `{ path }`. Inbound links become redlinks. Irreversible."),folder:union([string(),object$1({path:string()})]).optional().describe("Folder path to delete (recursive) — a string or `{ path }`."),template:object$1({path:string().describe("Template path = `<folder>/<name>`.")}).optional().describe(`A template to delete.`),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are its folder. Example: "images/diagram.png".`)}).optional().describe(`A binary asset to delete.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({ok:boolean(),deletedDocNames:array(string()).optional().describe(`The single docName removed (a document delete never cascades to descendants).`),error:string().optional().describe("Present when `ok` is false.")}).optional().describe(`Single-document delete result.`),folder:object$1({ok:boolean(),deletedDocNames:array(string())}).optional().describe(`Folder delete result (docNames removed).`),template:object$1({ok:boolean(),existed:boolean()}).optional().describe(`Template delete result.`),asset:object$1({ok:boolean(),path:string()}).optional().describe(`Asset delete result.`),documents:looseObjectArray.optional().describe(`Batch doc delete: per-doc result records.`),previousPreviewUrl:previousPreviewUrlField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s,w=typeof e.folder==`object`?e.folder.path:e.folder,E=e.document&&typeof e.document==`object`&&!Array.isArray(e.document)?e.document.path:e.document,D=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`]);if(D)return textResult(`Error: ${D}`,!0);if(e.template!==void 0){let s=resolveTemplatePath(e.template.path);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{folder:g,name:w}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=new URLSearchParams({folder:g,name:w});for(let[e,s]of Object.entries(agentIdentityFields(t.identityRef?.current)))typeof s==`string`&&s.length>0&&E.set(e,s);let D=await httpDelete(S,`/api/template?${E.toString()}`);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.existed===!0;return textPlusStructured(O?`Deleted template "${w}" from ${g||`(root)`}.`:`Template "${w}" did not exist in ${g||`(root)`} — nothing to delete.`,{template:{ok:!0,existed:O}})}if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.folder!==void 0){let e=await httpPost(S,`/api/delete-path`,{kind:`folder`,path:w,...agentIdentityFields(t.identityRef?.current)});if(!e.ok)return textResult(`Error: ${e.error}`,!0);let s=parseDeletedDocNames(e.deletedDocNames);return textPlusStructured(`Deleted folder ${w}${s.length?` (${s.length} doc(s))`:``}.`,{folder:{ok:!0,deletedDocNames:s}})}if(e.asset!==void 0){let s=e.asset.path.replace(/^\/+/,``).replace(/\/+$/,``),g=await httpPost(S,`/api/delete-path`,{kind:`asset`,path:s,...agentIdentityFields(t.identityRef?.current)});return g.ok?textPlusStructured(`Deleted asset ${s}.`,{asset:{ok:!0,path:s}}):textResult(`Error: ${g.error}`,!0)}let O=E;if(Array.isArray(O)){let e=await Promise.all(O.map(e=>deleteOneDoc(e,S,g,t))),s=e.filter(e=>e.ok).length,w=s===e.length,E=e.map(e=>e.ok?`Deleted ${e.docName}.`:`Failed ${e.docName}: ${e.error}`);return textPlusStructured(`${s}/${e.length} deleted.\n${E.join(`
1721
1716
  `)}`,{documents:e},!w)}let k=await deleteOneDoc(O,S,g,t);if(!k.ok)return textPlusStructured(`Error: ${k.error??`unknown error`}`,{document:{ok:!1,error:k.error}},!0);let j=k.deletedDocNames??[k.docName];return textPlusStructured(j.length===1?`Deleted ${j[0]}.`:`Deleted ${j.length} documents: ${j.join(`, `)}.`,{document:{ok:!0,deletedDocNames:j},...k.previousPreviewUrl?{previousPreviewUrl:k.previousPreviewUrl}:{}})})}function 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(`
1722
1717
  `)}\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(`
1723
1718
  `)}`:`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(`
1724
- `);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 ee=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(!ee.ok)return textResult(`Error: ${ee.error}`,!0);let J=typeof ee.path==`string`?ee.path:void 0;return textPlusStructured(`Edited template "${O}"${J?` (${J})`:``}.`,{template:{ok:!0,path:J}})}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(`
1719
+ `);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=unwrapFrontmatterFences(e).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 ee=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(!ee.ok)return textResult(`Error: ${ee.error}`,!0);let J=typeof ee.path==`string`?ee.path:void 0;return textPlusStructured(`Edited template "${O}"${J?` (${J})`:``}.`,{template:{ok:!0,path:J}})}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(`
1725
1720
  `)){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(`
1726
1721
  `)){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(`
1727
1722
  `)){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=32768-8*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(`
1728
1723
  `);function applySoftCap(e){let t=e.split(`
1729
1724
  `),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(`
1730
1725
  `),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(`
1731
- `),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(`
1732
- `)}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),ee=extractReferencedPaths(F,D).filter(e=>resolveWithinRoot(g,e).ok),{files:J,dirs:Y}=await classifyPaths(g,ee),te=D.length===1&&D[0].command===`cat`&&J.length===1,ne=await Promise.all(J.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(Y.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 ee){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(`
1733
- `)}\n\n`:``}${buildStdoutProvenance(D,se,oe)+q.text}${formatEnrichedBlock(ce)}`,{resolve:ge}=await buildListResolver({config:S,resolveCwd:async()=>g});return textPlusStructured(me,{enrichedPaths:withPreviewUrls(ce,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.`),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(`
1734
- `),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(`
1726
+ `),w=S[S.length-1]===``?S.length-1:S.length;if(w<g)return null;let E=S.slice(0,w),D=new Set(E.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,O=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${s.command} -${g}\` cap (${w} lines, ${D} unique file${D===1?``:`s`}). The \`${O}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${s.command}\` or widen the cap.`}}function isDirectoryMeta(e){return e.type===`directory`}function formatDirectoryEntry(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`);let s=[];return s.push(`${e.recursiveMdCount} md file${e.recursiveMdCount===1?``:`s`}`),e.childDirCount>0&&s.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(s.join(`, `)),e.mostRecentMd&&t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path})`),e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function formatFileEntry(e){let t=[`**${e.title??e.path}** (${e.path})`];if(e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.backlinkCount!==null&&t.push(`backlinks: ${e.backlinkCount}`),e.forwardLinkCount!==null&&t.push(`forward links: ${e.forwardLinkCount}`),e.history&&e.history.length>0){let s=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${s.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let s=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${s.join(` · `)}`)}return`- ${t.join(` — `)}`}function buildStdoutProvenance(e,t,s,g){let S=null;for(let t=e.length-1;t>=0;t--){let s=e[t],g=s.command;if(g===`ls`||g===`cat`){S=s;break}if((g===`head`||g===`tail`)&&nonFlagArgs(argsOf(s)).length>0){S=s;break}}if(!S)return``;let w=nonFlagArgs(argsOf(S));if(S.command===`ls`){let e=w[w.length-1];if(!e||e===`.`)return``;let s=e.replace(/\/+/g,`/`);if(s.startsWith(`./`)&&(s=s.slice(2)),s.endsWith(`/`)&&(s=s.slice(0,-1)),!s)return``;let S=g(s);return t.has(S)?`${S}/:\n`:``}let E=w.filter(e=>/\.(md|mdx)$/.test(e)&&s.has(g(e)));return E.length===1?`==> ${g(E[0])} <==\n`:``}function formatEnrichedBlock(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let s of e)t.push(isDirectoryMeta(s)?formatDirectoryEntry(s):formatFileEntry(s));return t.join(`
1727
+ `)}async function classifyPaths(e,t){let s=[],g=[];return await Promise.all(t.map(async t=>{try{let S=await stat$1(resolve(e,t));S.isDirectory()?g.push(t):S.isFile()&&s.push(t)}catch{/\.(md|mdx)$/i.test(t)&&s.push(t)}})),{files:s,dirs:g}}function errorCategoryResult(e,t){return textPlusStructured(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function withPreviewUrls(e,t){return e.map(e=>{let s=t(docNameFromPath(e.path));return{...e,previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}})}async function buildExecResult(e,t){let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return errorCategoryResult(`shell_construct_blocked`,`exec failed: ${s.error}`);let{cwd:g,executionCwd:S,config:w,url:E}=s,D=S===g?e=>e:e=>relative(g,resolve(S,e)),O=parseCommand(e.command);if(`error`in O)return errorCategoryResult(O.error.category,O.error.message);let k=augmentStagesWithExcludes(O.stages),j=serializeStages(k),F=await snapshotMtimes(S),L=createBashInstance(S),B=``,H=``;try{let e=await execBash(L,j);B=e.stdout,H=e.stderr}catch(e){return e instanceof StdoutOverflowError?errorCategoryResult(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`):errorCategoryResult(`shell_construct_blocked`,`exec failed: ${e instanceof Error?e.message:String(e)}`)}let q=await snapshotMtimes(S),ee=diffMtimes(F.snapshot,q.snapshot);if(ee.changed.length>0)return errorCategoryResult(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${ee.changed.join(`, `)}. This indicates a parser bug; the command has been logged.`);let J=applySoftCap(B),Y=extractReferencedPaths(B,k).filter(e=>resolveWithinRoot(S,e).ok).map(D),{files:te,dirs:ne}=await classifyPaths(g,Y),ae=k.length===1&&k[0].command===`cat`&&te.length===1,oe=await Promise.all(te.map(e=>enrichPath(e,{projectDir:g,serverUrl:E},{includeRichFields:ae}).catch(()=>({path:e,tags:[],frontmatter:{},backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null})))),se=await Promise.all(ne.map(e=>enrichDirectoryRecursive(e,1,{projectDir:g}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!ae&&E&&oe.length>0){let e=await fetchBacklinkCountsBatch(E,oe.map(e=>pathToDocName$1(e.path))).catch(()=>null);if(e)for(let t of oe){let s=e.get(pathToDocName$1(t.path));typeof s==`number`&&(t.backlinkCount=s)}}let ce=new Map(oe.map(e=>[e.path,e])),ue=new Map(se.map(e=>[e.path,e])),de=[];for(let e of Y){let t=ce.get(e);if(t){de.push(t);continue}let s=ue.get(e);s&&de.push(s)}let fe=detectBinaryArgs(k),me=[];fe.length>0&&me.push(`File${fe.length>1?`s`:``} ${fe.join(`, `)} appear${fe.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let ge=detectHeadTailTruncation(k,B);ge&&me.push(ge.banner),H&&me.push(`stderr: ${H.trim()}`);let _e=`${me.length>0?`${me.join(`
1728
+ `)}\n\n`:``}${buildStdoutProvenance(k,ue,ce,D)+J.text}${formatEnrichedBlock(de)}`,{resolve:ve}=await buildListResolver({config:w,resolveCwd:async()=>g});return textPlusStructured(_e,{enrichedPaths:withPreviewUrls(de,ve),stdoutTruncated:J.truncated,cwd:S,...me.length>0?{warnings:me}:{}})}function register$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.`),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=["Resolve the browser-reachable preview URL for an Open Knowledge project (optionally for a specific doc). Opening a preview counts as demand: when no OK server is running for the project, this call auto-starts one (same `OK_MCP_AUTOSTART` gate and spawn timeout as the read/write tools) and waits briefly for the preview UI to bind — a cold first call can take a few seconds; calls against a running system answer immediately.",``,"Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.",``,'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 }` + a recovery hint only when no UI could be reached (auto-start disabled via `OK_MCP_AUTOSTART=0`, no spawn authority in this registration, or the UI did not bind in time) — the hint names the right command for the actual state.",``,`**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. Independent of server state; omit it and the call writes nothing.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
1729
+ `),UI_BIND_WAIT_TIMEOUT_MS=3e3,UI_BIND_WAIT_POLL_MS=100,InputSchema$2={document:string().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),folder:string().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),armPaneTarget:boolean().optional().describe("When true with a `document` or `folder`, arm that target so a subsequent Claude-pane base-open (`preview_start`) lands there instead of the presence-driven default. TTL-bounded (~30s) so a stale arm cannot hijack a later open."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$4=outputSchemaWithText({url:string().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:string().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:boolean().describe(`Whether a UI is running for the project.`),autoOpen:boolean().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`.")}),NO_UI_SERVER_RUNNING_MESSAGE='The OK server is running but no UI has bound for this project yet. Retry in a few seconds, or start one: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',NO_SERVER_MESSAGE='No Open Knowledge server is running for this project. Start it with `ok start` (also starts the preview UI), use `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.',AUTOSTART_DISABLED_NOTE=` Auto-start is disabled (OK_MCP_AUTOSTART=0).`;function isServerLive(e){try{let t=readServerLock(e);return t!==null&&t.port>0&&isProcessAlive(t.pid)}catch(t){return process.stderr.write(`[preview-url] readServerLock failed at ${e} while checking server liveness: ${t instanceof Error?t.message:String(t)}\n`),!1}}function register$10(e,t){e.registerTool(`preview_url`,{description:DESCRIPTION$10,inputSchema:InputSchema$2,outputSchema:OutputSchema$4,annotations:{readOnlyHint:!1,idempotentHint:!0}},async e=>{if(e.document&&e.folder)return{isError:!0,content:[{type:`text`,text:`Error: document and folder are mutually exclusive — pass exactly one.`}]};let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=resolveLockDir(s.cwd),S={lockDir:g},w=s.config.appearance.preview.autoOpen,E=e.document?`#/${encodeDocName(e.document)}`:e.folder?`#/${encodeFolderRoute(e.folder)}`:null;if(e.armPaneTarget&&E)try{armPaneTarget(g,E)}catch{}let D=e.armPaneTarget&&!E?` (note: armPaneTarget was set but no document/folder was given, so nothing was armed)`:``,O=isServerLive(g),k=!1;if(t.serverUrl!==void 0)try{await resolveServerUrl(t.serverUrl,s.cwd)}catch(e){if(e instanceof AutoStartDisabledError)k=!0;else return{isError:!0,content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}]}}let{baseUrl:j}=resolveUiInfo(S);if(j===null&&!O&&isServerLive(g)&&(j=await awaitUiBaseUrl(S,{timeoutMs:t.uiBindWait?.timeoutMs??UI_BIND_WAIT_TIMEOUT_MS,pollIntervalMs:t.uiBindWait?.pollIntervalMs??UI_BIND_WAIT_POLL_MS})),j===null)return textPlusStructured(`${isServerLive(g)?NO_UI_SERVER_RUNNING_MESSAGE:`${NO_SERVER_MESSAGE}${k?AUTOSTART_DISABLED_NOTE:``}`}${D}`,{url:null,baseUrl:null,running:!1,autoOpen:w});let F=E?`${j}/${E}`:j;return textPlusStructured(`Preview URL: ${F}${D}`,{url:F,baseUrl:j,running:!0,autoOpen:w})})}const HistoryEntryOutputSchema=object$1({version:string().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:string().describe(`ISO timestamp of the entry.`),author:string().describe(`Author display name.`),authorEmail:string().describe(`Author email.`),kind:_enum([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:string().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:looseObjectArray.describe(`Per-contributor records parsed from the commit (writer id, name, docs, summaries).`),checkpoint:unknown().nullable().describe(`Checkpoint metadata when this entry is a checkpoint, else null.`)}),DESCRIPTION$9=[`[Requires: Hocuspocus server] List version history for a document, or the activity timeline for a folder.`,`Returns timeline entries from the shadow repo, sorted by timestamp descending.`,"Each entry carries a `version` (40-char commit SHA) you pass straight to `restore_version({ document, version })` — same field name on both sides.",``,"**Parameters (pass EXACTLY ONE of `document` / `folder`):**","- `document` — Document name to query history for, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",'- `folder` — Folder path for the FOLDER timeline: attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter) — who created / edited / renamed / moved / deleted them, when. `""` = project root.',"- `branch` (optional) — Branch name (default: current branch)","- `limit` (optional) — Maximum entries to return (default 50, max 200)","- `offset` (optional) — Number of entries to skip for pagination (default 0)",'- `kind` (optional) — Filter by entry type: "checkpoint", "upstream", or "wip"',"- `author` (optional) — Filter to entries by this author name or email","- `excludeAuthor` (optional) — Exclude entries by this author name or email"].join(`
1735
1730
  `);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(`
1736
1731
  `);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(`
1737
1732
  `);function parseRenameMappings(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromDocName:t,toDocName:s}]:[]}):[]}function parseRewrittenDocs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:s}=e;return typeof t==`string`&&typeof s==`number`?[{docName:t,rewrites:s}]:[]}):[]}function parseRenamedAssets(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromPath:t,toPath:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromPath:t,toPath:s}]:[]}):[]}function isValidFolderPath(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`..`))}function pluralize(e,t,s=`${t}s`){return e===1?t:s}function resolveMoveKind(e,t){let s=resolveWithinRoot(e,t);if(!s.ok)return null;let g=s.abs;if(existsSync(g))try{let e=statSync(g);if(e.isDirectory())return`folder`;if(e.isFile())return g.endsWith(`.md`)||g.endsWith(`.mdx`)?`file`:`asset`}catch(e){let t=e.code;if(t===`EACCES`||t===`EPERM`)return`file`}for(let e of[`.md`,`.mdx`])if(existsSync(`${g}${e}`))return`file`;return null}function register$7(e,t){e.registerTool(`move`,{description:DESCRIPTION$7,inputSchema:{from:string().optional().describe(`Current path of a document, folder, or asset (auto-detected).`),to:string().optional().describe(`New path. All inbound wiki-links + inline links are rewritten automatically.`),template:object$1({from:string(),to:string()}).optional().describe('Move/rename a TEMPLATE instead: `{ from: "<folder>/<name>", to: "<folder>/<name>" }`. Nested because a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc. Mutually exclusive with flat `from`/`to`.'),summary:summaryArgSchema.describe(`Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({ok:boolean().describe(`Whether the move succeeded.`),kind:_enum([`file`,`folder`,`asset`,`template`]).optional().describe("What was moved (`file`/`folder`/`asset` auto-detected from `from`; `template` when the `template` target was used)."),committed:boolean().optional().describe("Template move only: `true` = tracked `git mv` (history preserved), `false` = plain disk rename (untracked / local-only `.ok/`)."),renamed:array(object$1({fromDocName:string(),toDocName:string()})).optional().describe(`docName remappings performed.`),rewrittenDocs:looseObjectArray.optional().describe(`Docs whose inbound links were rewritten.`),renamedAssets:looseObjectArray.optional().describe(`Referenced assets that were moved alongside.`),previewUrls:record(string(),string()).optional().describe(`Route-only preview URL per new docName.`),previewUrlSource:previewUrlSourceField,previousPreviewUrl:previousPreviewUrlField,summary:summaryOutputSchema.optional(),error:string().optional().describe("Present when `ok` is false."),colliding:looseObjectArray.optional().describe(`On a 409 collision: the conflicting from→to pairs.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.template!==void 0){if(e.from!==void 0||e.to!==void 0)return textResult("Error: pass EITHER flat `from`/`to` (document/folder/asset) OR `template: { from, to }` — not both.",!0);let s=resolveTemplatePath(e.template.from);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let g=resolveTemplatePath(e.template.to);if(!g.ok)return textResult(`Error: ${g.error}`,!0);let S=await httpPost(w,`/api/template`,{fromFolder:s.folder,fromName:s.name,toFolder:g.folder,toName:g.name,...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(t.identityRef?.current)});if(!S.ok){let e=typeof S.error==`string`?S.error:`Template move failed`;return textPlusStructured(`Error: ${e}`,{ok:!1,kind:`template`,error:e},!0)}let E=S.committed===!0,D=typeof S.from==`string`?S.from:e.template.from,O=typeof S.to==`string`?S.to:e.template.to;return textPlusStructured(`${E?`Renamed`:`Moved`} template ${D} → ${O}.${E?``:" (Untracked `.ok/` — moved on disk without git history.)"}`,{ok:!0,kind:`template`,committed:E})}if(e.from===void 0||e.to===void 0)return textResult("Error: provide both `from` and `to` (or use `template: { from, to }` to move a template).",!0);let E=join(g,S.content.dir),D=resolveMoveKind(E,e.from);if(D===null){let t=resolveTemplatePath(e.from);return t.ok&&existsSync(join(E,t.folder,`.ok`,`templates`,`${t.name}.md`))?textResult(`Error: \`${e.from}\` is a template, not a doc/folder/asset. Move it with \`move({ template: { from: "${e.from}", to: "<folder>/<newName>" } })\`.`,!0):textResult(`Error: \`${e.from}\` does not exist as a doc, folder, or asset under the content directory.`,!0)}let O=e.from,k=e.to;if(D===`file`){let t=normalizeDocName(e.from);if(!t.ok)return textResult(t.error,!0);let s=normalizeDocName(e.to);if(!s.ok)return textResult(s.error,!0);O=t.docName,k=s.docName}else if(D===`folder`&&(!isValidFolderPath(e.from)||!isValidFolderPath(e.to)))return textResult("Error: folder `from`/`to` must be relative paths with no leading/trailing slash.",!0);let j=await httpPost(w,`/api/rename-path`,{kind:D,fromPath:O,toPath:k,...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(t.identityRef?.current)});if(!j.ok){let e=j.error,t=parseRenameCollidingPairs(j.colliding),s={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return textPlusStructured(`Error: ${e}`,s,!0)}let F=parseRenameMappings(j.renamed),L=parseRewrittenDocs(j.rewrittenDocs),B=parseRenamedAssets(j.renamedAssets),H={config:t.config,resolveCwd:t.resolveCwd},q={},ee,J;if(D===`file`){let e=await resolvePreviewUrlForTool(k,H,g),t=await resolvePreviewUrlForTool(O,H,g);e&&(q[k]=e.url,ee=e.source),t&&(J=t.url)}else if(D===`folder`)for(let{toDocName:e}of F){let t=await resolvePreviewUrlForTool(e,H,g);t&&(q[e]=t.url,ee??=t.source)}let Y=j.summary&&typeof j.summary==`object`?j.summary:void 0,te=typeof Y?.hint==`string`?Y.hint:void 0,ne=[];if(D===`asset`)ne.push(`Moved asset ${O} → ${k}.`);else if(D===`folder`)ne.push(F.length===0?`No managed docs under ${e.from}/ — nothing to rename. Empty folders are not tracked.`:`Renamed folder ${e.from}/ → ${e.to}/ (${F.length} doc${F.length===1?``:`s`}, ${L.length} rewrite${L.length===1?``:`s`}).`);else{let e=F.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${O} -> ${k}`,t=L.length===0?`No inbound links required updates.`:`Rewrote ${L.length} ${pluralize(L.length,`document`)}.`;ne.push(`Renamed ${e}. ${t}`)}return B.length>0&&ne.push(`Moved ${B.length} referenced ${pluralize(B.length,`asset`)}.`),te&&ne.push(te),textPlusStructured(ne.join(`
@@ -2811,7 +2806,7 @@ In headless mode, write the recap into the research article's "Further reading"
2811
2806
  `),{folder:{ok:!0,path:e.path}})}async function handleTemplate(e,t,s,g){let S=resolveTemplatePath(e.path);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let{folder:w,name:E}=S;if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let D=await httpPut(s,`/api/template`,{folder:w,name:E,body:e.content,frontmatter:{title:e.frontmatter.title,...typeof e.frontmatter.description==`string`?{description:e.frontmatter.description}:{},...Array.isArray(e.frontmatter.tags)?{tags:e.frontmatter.tags}:{}},...t===void 0?{}:{summary:t},...agentIdentityFields(g.identityRef?.current)});if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.created===!0,k=typeof D.path==`string`?D.path:void 0;return textPlusStructured(`${O?`Created`:`Updated`} template "${E}" in ${w||`(root)`}${k?` (${k})`:``}.`,{template:{ok:!0,path:k,created:O}})}async function handleAsset(e,t,s,g){if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.content===void 0==(e.source===void 0))return textResult("Error: provide exactly one of `content` (base64) or `source` (local file path) for an asset.",!0);let S;try{S=e.content===void 0?readFileSync(resolve(t,e.source)):Buffer.from(e.content,`base64`)}catch(e){return textResult(`Error: could not read asset bytes: ${e.message}`,!0)}if(S.byteLength===0)return textResult(`Error: asset is empty (0 bytes).`,!0);let{folder:w,name:E}=splitTargetPath(e.path),D=w?`${w}/${E}`:E,O=g.identityRef?.current,k=new URLSearchParams;O?.connectionId&&k.set(`agentId`,O.connectionId),O?.displayName&&k.set(`agentName`,O.displayName);let j=k.toString(),F=new FormData;F.append(`parentDocName`,D),F.append(`file`,new Blob([new Uint8Array(S)]),E);let L;try{let e=await fetch(`${s}/api/upload${j?`?${j}`:``}`,{method:`POST`,body:F}),t=await e.json().catch(()=>null);L=e.ok?{ok:!0,status:e.status,data:t??{}}:{ok:!1,status:e.status,error:t&&(typeof t.title==`string`?t.title:t.error)||`Upload failed (HTTP ${e.status}).`}}catch(e){return textResult(`Error: upload request failed: ${e.message}`,!0)}if(!L.ok)return textResult(`Error: ${L.error}`,!0);let B=typeof L.data?.src==`string`?L.data.src:void 0,H=typeof L.data?.path==`string`?L.data.path:void 0,q=L.data?.deduped===!0,ee=B??H??E;return textPlusStructured([`Uploaded asset to ${D}${q?` (deduplicated — identical bytes already present)`:``}.`,`Reference it in a doc with: ![${E}](${ee})`].join(`
2812
2807
  `),{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(`
2813
2808
  `),H={documents:O},q=D.find(e=>e.ok);return q&&q.raw.systemSubscriberCount===0&&(H.warning=buildPreviewAttachWarning(resolvePreviewUrl(q.docName,{lockDir:w}),E)),textPlusStructured(B,H,!j)}async function handleSingleDoc(e,t,s,g,S,w,E){let D=await writeOneDoc(e,t,s,g,S);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.raw,k=resolvePreviewUrl(D.docName,{lockDir:w}),j=typeof O.subscriberCount==`number`?O.subscriberCount:void 0,F=(typeof O.systemSubscriberCount==`number`?O.systemSubscriberCount:void 0)===0,L=j===0,B=Array.isArray(O.hints)?O.hints:void 0,H=O.summary&&typeof O.summary==`object`?O.summary:void 0,q=typeof H?.hint==`string`?H.hint:void 0,ee=parseContentDivergence(O.warning),J=[emptyAppendNoOpNote(D.position,e.content)??(D.fromTemplate===void 0?`Written successfully (${D.position}).`:`Written successfully (instantiated from template "${D.fromTemplate}").`)],Y=frontmatterIgnoredNote(D.position,e.content);if(Y&&J.push(Y),D.extensionNote&&J.push(D.extensionNote),F&&!k&&J.push(START_UI_TEXT_HINT),q&&J.push(q),B)for(let e of B)e.message&&J.push(e.message);ee&&J.push(formatContentDivergenceLine(ee));let te=J.join(`
2814
- `);if(!k&&!F&&!L&&!B&&!H&&!ee)return textResult(te);let ne={};return B&&(ne.hints=B),H&&(ne.summary=H),ee&&(ne.contentDivergence=ee),textPlusStructured(te,nestDocResult(k,F?buildPreviewAttachWarning(k,E):void 0,ne))}function register(e,t){let s={path:string().describe(`Document path, no extension. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup".`),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe(`Single-document write result (present when there is a doc-specific signal).`),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, 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,ephemeral:j}=e,F=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,L=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});L.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let B=new Map,H=new Set,q=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`));for(let[e,s]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,s);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(w?.startsWith(`/api/`)){s.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${w}`})}).catch(e=>{S.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},D=s=>{if(j===!0&&O!==void 0&&(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host))){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`content-asset`});return}E(O,`content-asset`,s)},F=e=>E(k,`react-shell`,e),L=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(k!==void 0&&w?.startsWith(`/assets/`)){F(()=>D(L));return}if(O!==void 0||k!==void 0){D(()=>F(L));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),L.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=B.get(s);e!==void 0&&(clearTimeout(e),B.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(B.delete(s),q)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`)}})();H.add(e),e.finally(()=>H.delete(e))},F);e.unref?.(),B.set(s,e),S.info({connectionId:s,graceMs:F},`[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`)}),L.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:L,shutdown:async()=>{if(!q){q=!0;for(let e of B.values())clearTimeout(e);B.clear(),H.size>0&&await Promise.allSettled(H)}}}}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-BDjANGpQ.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-BDjANGpQ.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&s.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&s.debug({path:e},`config file disappeared between event and read; dropping`);return}s.warn({err:t,path:e},`config file read failed; dropping event`);return}if(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=relative(g,join(s,e.file));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}const BUILTIN_SKIP_FILES=new Set([`.DS_Store`,`.localized`]);function isAlwaysSkipFile(e){return BUILTIN_SKIP_FILES.has(e.slice(e.lastIndexOf(`/`)+1))}function isSingleDocAncestorDir(e,t){return t===e||t.startsWith(`${e}/`)}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D,O,k,j=0,F=0,L=0;function B(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],S=0,B=0;for(let s of IGNORE_FILE_NAMES){let w=join(t,s);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);S+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${w}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);S+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,w));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:S};B+=loadNestedIgnoreFiles(s,t,e,H),S=H.value;let q=loadGitExcludeSources(t,H);S=H.value,q.length>0&&(g.push(...q),e.add(q));let ee=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return D=e,O=g,k=ee,j=g.length,F=B,L=S,{patternCount:j,nestedFileCount:F,bytes:L}}B();let H=new Map;function q(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}let ee=()=>{S===void 0&&populateDirCount(s,``,q,H)};ee();function J(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function Y(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:q(e)}return{isExcluded(e,t){if(J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((H.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:Y(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;H.set(t,(H.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=H.get(t)??0;s<=1?H.delete(t):H.set(t,s-1)},rebuildDirCount(){let e=new Map(H);H.clear();try{ee()}catch(t){for(let[t,s]of e)H.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=k,w=j,E=F,q=L,J=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async Y=>{try{let t=B();H.clear(),ee();let s=Date.now()-J;if(Y.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s}}catch(g){D=t,O=s,k=S,j=w,F=E,L=q,H.clear();try{ee()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let B=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(B)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:B}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
2809
+ `);if(!k&&!F&&!L&&!B&&!H&&!ee)return textResult(te);let ne={};return B&&(ne.hints=B),H&&(ne.summary=H),ee&&(ne.contentDivergence=ee),textPlusStructured(te,nestDocResult(k,F?buildPreviewAttachWarning(k,E):void 0,ne))}function register(e,t){let s={path:string().describe(`Document path, no extension. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup".`),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe(`Single-document write result (present when there is a doc-specific signal).`),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, 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`),serverUrl:t.serverUrl}),register$14(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`conflicts`)}),register$5(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,s){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(s))}function createSessionServer(e,t,s){let g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{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,ephemeral:j}=e,F=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,L=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});L.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let B=new Map,H=new Set,q=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`));for(let[e,s]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,s);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(w?.startsWith(`/api/`)){s.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${w}`})}).catch(e=>{S.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},D=s=>{if(j===!0&&O!==void 0&&(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host))){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`content-asset`});return}E(O,`content-asset`,s)},F=e=>E(k,`react-shell`,e),L=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(k!==void 0&&w?.startsWith(`/assets/`)){F(()=>D(L));return}if(O!==void 0||k!==void 0){D(()=>F(L));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),L.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=B.get(s);e!==void 0&&(clearTimeout(e),B.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(B.delete(s),q)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`)}})();H.add(e),e.finally(()=>H.delete(e))},F);e.unref?.(),B.set(s,e),S.info({connectionId:s,graceMs:F},`[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`)}),L.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:L,shutdown:async()=>{if(!q){q=!0;for(let e of B.values())clearTimeout(e);B.clear(),H.size>0&&await Promise.allSettled(H)}}}}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-BDjANGpQ.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-BDjANGpQ.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&s.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&s.debug({path:e},`config file disappeared between event and read; dropping`);return}s.warn({err:t,path:e},`config file read failed; dropping event`);return}if(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=relative(g,join(s,e.file));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}const BUILTIN_SKIP_FILES=new Set([`.DS_Store`,`.localized`]);function isAlwaysSkipFile(e){return BUILTIN_SKIP_FILES.has(e.slice(e.lastIndexOf(`/`)+1))}function isSingleDocAncestorDir(e,t){return t===e||t.startsWith(`${e}/`)}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D,O,k,j=0,F=0,L=0;function B(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],S=0,B=0;for(let s of IGNORE_FILE_NAMES){let w=join(t,s);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);S+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${w}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);S+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,w));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:S};B+=loadNestedIgnoreFiles(s,t,e,H),S=H.value;let q=loadGitExcludeSources(t,H);S=H.value,q.length>0&&(g.push(...q),e.add(q));let ee=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return D=e,O=g,k=ee,j=g.length,F=B,L=S,{patternCount:j,nestedFileCount:F,bytes:L}}B();let H=new Map;function q(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}let ee=()=>{S===void 0&&populateDirCount(s,``,q,H)};ee();function J(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function Y(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:q(e)}return{isExcluded(e,t){if(J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((H.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:Y(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;H.set(t,(H.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=H.get(t)??0;s<=1?H.delete(t):H.set(t,s-1)},rebuildDirCount(){let e=new Map(H);H.clear();try{ee()}catch(t){for(let[t,s]of e)H.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=k,w=j,E=F,q=L,J=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async Y=>{try{let t=B();H.clear(),ee();let s=Date.now()-J;if(Y.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s}}catch(g){D=t,O=s,k=S,j=w,F=E,L=q,H.clear();try{ee()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let B=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(B)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:B}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
2815
2810
  `).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,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D=(0,import_ignore.default)(),O=[],k=new Map,j=()=>{S===void 0&&populateDirCount(s,``,F,k)};function F(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}function L(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function B(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:F(e)}async function H(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[];for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=parseIgnorePatterns(await readFile$1(g,`utf-8`));e.add(t.map(e=>prefixPattern(e,w)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let j=await loadGitExcludeSourcesAsync(t,{value:0});j.length>0&&(g.push(...j),e.add(j));let F=new Map;S===void 0&&await initContentDirStateAsync(s,``,t,e,w,E,F),D=e,O=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),k.clear();for(let[e,t]of F)k.set(e,t)}return await H(),{isExcluded(e,t){if(L(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(B(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((k.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return L(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:B(e)},getWatcherIgnoreGlobs(){return O},incrementMdDir(e){let t=e===`.`?``:e;k.set(t,(k.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=k.get(t)??0;s<=1?k.delete(t):k.set(t,s-1)},rebuildDirCount(){let e=new Map(k);k.clear();try{j()}catch(t){for(let[t,s]of e)k.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=new Map(k),w=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async E=>{try{await H();let t=Date.now()-w;if(E.setAttributes({"ok.ignore.pattern_count":O.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:O.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(g){D=t,O=s,k.clear();for(let[e,t]of S)k.set(e,t);let w=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(w)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:w}}}})}}}function runDocLineageGuard(e,t,s){try{if(typeof t!=`string`||t.length===0||isSystemDoc(e)||isConfigDoc(e))return;let g=s.getLoadedDoc(e);if(g===void 0)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch: claim against unloaded ${e} is stale by construction`);let S=g.getMap(`lifecycle`).get(LINEAGE_EPOCH_KEY);if(typeof S!=`string`||S.length===0||S!==t)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch for ${e}: claimed epoch does not match the live lineage`)}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthDocLineageGuardError(),console.warn(JSON.stringify({event:`doc-lineage-guard-error`,documentName:e,errorName:t instanceof Error?t.name:typeof t,message:t instanceof Error?t.message:String(t)}))}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let s=resolve(e,t.slice(5));try{return readFileSync(s,`utf-8`).trim()}catch{try{let s=readFileSync(resolve(e,`packed-refs`),`utf-8`),g=t.slice(5),S=s.split(`
2816
2811
  `).find(e=>e.endsWith(` ${g}`));if(S)return S.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}function watchedGitFile(e){let t=e.split(`/`).pop()??``;return WATCHED_FILES.has(t)?t:null}async function tryStartParcelHeadWatcher(e,t){let s;try{s=await import(`@parcel/watcher`)}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher unavailable; falling back to chokidar`),null}try{let g=await s.subscribe(e,(e,s)=>{if(e){getLogger(`head-watcher`).warn({err:e},`[head-watcher] parcel subscription error`);return}for(let e of s)t(e.path)});return()=>g.unsubscribe()}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar`),null}}async function startChokidarHeadWatcher(e,t){let{watch:s}=await import(`./chokidar-BDjANGpQ.mjs`),g=s(e,{ignoreInitial:!0,depth:0,followSymlinks:!1});return g.on(`all`,(e,s)=>t(s)),g.on(`error`,e=>{getLogger(`head-watcher`).warn({err:e},`[head-watcher] chokidar watcher error`)}),()=>g.close()}async function startHeadWatcher(e,t,s,g={}){let S=resolveGitDir(e);if(!S)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let w=S,E=!1,D=null,O=null,k=null,j=null;async function F(e){if(B&&await B,!E)return;D&&=(clearTimeout(D),null),O&&=(clearTimeout(O),null);let t=readHeadSha(w),g=k!==t,S=readBranchFromHead(w),F;F=S?.startsWith(`detached-`)?`detached-head`:j===S?`within-branch`:`cross-branch`;let L=j;try{await s({headMoved:g,oldHead:k,newHead:t,timeout:e,batchKind:F,oldBranch:L,newBranch:S})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{E=!1,k=t,j=S}}function L(){D&&clearTimeout(D),D=setTimeout(()=>{D=null,F(!1)},QUIET_WINDOW_MS)}let B=null;async function H(e){if(!E){E=!0,k=readHeadSha(w);let s=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();B=s,await s,B=null,O=setTimeout(()=>{O=null,F(!0)},BATCH_TIMEOUT_MS)}L()}let q=e=>{let t=watchedGitFile(e);t!==null&&H(t)},ee=null,J=`chokidar`;if(g.forceBackend!==`chokidar`&&(ee=await tryStartParcelHeadWatcher(w,q),ee&&(J=`parcel`)),!ee){if(g.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable for HEAD watching (forced backend)`);ee=await startChokidarHeadWatcher(w,q),J=`chokidar`}let Y=ee;return k=readHeadSha(w),j=readBranchFromHead(w),getLogger(`head-watcher`).info({gitDir:w,backend:J},`watching for HEAD changes`),{unsubscribe:async()=>{E&&await F(!1),D&&clearTimeout(D),O&&clearTimeout(O),await Y()},getLastKnownBranch:()=>j}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:s,signalChannel:g,debounceMs:S=100}=e,w=new Map;function E(e){let t=w.get(e);t&&(clearTimeout(t),w.delete(e))}function D(e,D){E(e),w.set(e,setTimeout(()=>{w.delete(e);try{let S=serializeLiveDocument(D);t.updateDocumentFromMarkdown(e,S),g?.(`backlinks`),g?.(`graph`),s&&(s.updateDocumentFromMarkdown(e,S),g?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},S))}return{async onChange({documentName:e,document:t,transactionOrigin:s}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(s)&&s.context?.origin===`file-watcher`||D(e,t)},async beforeUnloadDocument({documentName:e}){E(e)},async onDestroy(){for(let e of w.values())clearTimeout(e);w.clear()}}}const 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===`auth`&&t===`no-credential`?`auth-no-credential`: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],NO_CREDENTIAL_PATTERNS=[/could not read (username|password)/i,/terminal prompts disabled/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,NO_CREDENTIAL_PATTERNS)?{class:`auth`,subclass:`no-credential`,retryable:!1,message:`No GitHub credential available — reconnect to resume syncing`,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 DEFAULT_TTL_MS=6e4;function createGhTokenSource(e,t={}){let s=t.ttlMs??DEFAULT_TTL_MS,g=t.now??Date.now,S=new Map;return{get(t){if(!e)return null;let w=g(),E=S.get(t);if(E&&E.expiresAt>w)return E.token==null?null:{token:E.token,host:t};let D=e(t),O=D.available&&D.token?D.token:null;return S.set(t,{token:O,expiresAt:w+s}),O==null?null:{token:O,host:t}},invalidate(){S.clear()}}}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,SYNC_GH_TOKEN_HOST=`github.com`;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;ghTokenSource;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.ghTokenSource=createGhTokenSource(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)}gitHandle(e){return createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(SYNC_GH_TOKEN_HOST)??void 0})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();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 this.gitHandle().git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
2817
2812
  `).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 this.gitHandle().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 notifyCredentialsChanged(){if(this.syncEnabled&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!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 this.gitHandle().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 this.gitHandle().git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),s=new Set(t?t.split(`
@@ -2825,7 +2820,7 @@ In headless mode, write the recap into the research article's "Further reading"
2825
2820
  `,`
2826
2821
  `).split(`
2827
2822
  `),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();initChain=Promise.resolve();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){let e=this.initChain.then(()=>this.initOnce());return this.initChain=e.catch(e=>{console.warn(`[tag-index] init failed (chain cleared for next init):`,e)}),e}async initOnce(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=await this.listDocsWithPaths(),t=50;for(let t=0;t<e.length;t+=50){let s=e.slice(t,t+50),g=await Promise.all(s.map(async({docName:e,filePath:t})=>{try{return{docName:e,markdown:await readFile$1(t,`utf-8`)}}catch(t){return console.warn(`[tag-index] Failed to read ${e} during init:`,t),null}}));for(let e of g)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown)}catch(t){console.warn(`[tag-index] Failed to index ${e.docName} during init:`,t)}}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}async listDocsWithPaths(){let e=[];await this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}async walkContentDir(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1,singleDocRelPath:ee,ephemeral:J=!1}=e,Y=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}function ne(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function ae(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}initTelemetry();let oe=randomUUID(),se=getLocalDir(s);if(acquireServerLock(se,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:se,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(se),e}let ce=createBasenameIndex(),ue=(e,t)=>ce.resolveEmbed(e,t),de=(e,s)=>{let g=ce.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g),w=resolve(t);if(S!==w&&!S.startsWith(`${w}/`))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},fe,me,ge,_e,ve,ye,Ce,we=null,Te=null,De=null,je=null,Me=ne(),Pe=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ne();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Me.enabled,providerFingerprint:ae(Me)}),Ie=null,Re=new Set,ze=!1,Be,Ve,Ue,We=new Promise((e,t)=>{Ve=e,Ue=t});function Ge(e){we?.signal(e)}let Ke=2e3,Xe=null;function $e(){Xe!==null&&clearTimeout(Xe),Xe=setTimeout(()=>{Xe=null,me.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let nt=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),rt=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||nt.setRenamed(e,t)},it=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(nt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}nt.setDeleted(e)}},at=e=>{isSystemDoc(e)||isConfigDoc(e)||nt.delete(e)};try{fe=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{me.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ge.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild(Ut).then(({prunedFiles:e,prunedFolders:t})=>{let s=e+t;s>0?getLogger(`server-factory`).info({pruned:s,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),me=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:fe}),ge=new TagIndex({contentDir:t,contentFilter:fe}),ge.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),_e={current:F},ve=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:_e,ephemeral:J,contentRoot:L,backlinkIndex:me,configHomedirOverride:k,getCurrentBranch:()=>Wt?.getLastKnownBranch()??null,resolveEmbed:ue,resolveSize:de,getPrincipal:()=>Ie,onAgentCommit:()=>we?.signal(`session-activity`),onDiskFlush:(e,t,s,g)=>{we?.emitDiskAck(e,t),!(isSystemDoc(e)||isConfigDoc(e))&&assetReferencesChanged(g,s)&&(je?.(),Ge(`files`))},onConfigRejected:(e,t)=>we?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),ye=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[ve.extension]});let B=ye.shouldUnloadDocument.bind(ye);ye.shouldUnloadDocument=e=>{if(Re.has(e)||ze&&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)},Be=async e=>{Re.add(e);try{await ye.unloadDocument(e)}finally{Re.delete(e)}},we=new CC1Broadcaster(ye),Te=new AgentFocusBroadcaster(ye),De=new AgentPresenceBroadcaster(ye),Ce=new AgentSessionManager(ye);let q=createLiveDerivedIndexExtension({backlinkIndex:me,tagIndex:ge,signalChannel:Ge});ye.configuration.extensions.push(q),ye.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==oe)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${oe}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(Ie&&s.principalId===Ie.id?E.principalId=Ie.id:Ie?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Ie.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),ye.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,s=t.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s))throw Error(`config-doc admission requires loopback peer (peer=${s}, doc=${e.documentName})`);let g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let Y=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(Y,`${e}${getDocExtension(e)}`);return!t.startsWith(`${Y}/`)&&t!==Y?null:t}ye.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:nt,resolveFilePath:te,fileExists:existsSync})}}),ye.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>ye.documents.get(e)})}}),ye.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ae=createApiExtension({hocuspocus:ye,sessionManager:Ce,contentDir:t,contentFilter:fe,serverInstanceId:oe,getFileIndex:()=>Ut?Ut.getFileIndex():new Map,getFolderIndex:()=>Ut?Ut.getFolderIndex():new Map,getAliasMap:()=>Ut?Ut.getAliasMap():new Map,rescanFiles:()=>Ut?.rescanFromDisk(),enableTestRoutes:j,shadowRef:_e,flushGitCommit:()=>ve.flushPendingGitCommit(),flushContributors:()=>ve.flushContributors(),takeStoreFailure:e=>ve.takeStoreFailure(e),takeStoreDivergence:e=>ve.takeStoreDivergence(e),markAgentWriteStore:e=>ve.markAgentWriteStore(e),getCurrentBranch:()=>Wt?.getLastKnownBranch()??null,getDiskAckSVs:()=>we?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:me,tagIndex:ge,signalChannel:Ge,agentFocusBroadcaster:Te,agentPresenceBroadcaster:De,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Kt,localOpCliArgs:H,projectDir:s,resolveEmbed:ue,getPrincipal:()=>Ie,forceUnloadDocument:Be,ready:We,recentlyRemovedDocs:nt,serializeDoc:Dt,semanticSearch:Pe,getSemanticSimilarityFloor:()=>ne().similarityFloor,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{je=e}});ye.configuration.extensions.push(ae),ye.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:_e,contentRoot:L,getCurrentBranch:()=>Wt?.getLastKnownBranch()??null,resolveEmbed:ue,resolveSize:de})),ye.configuration.extensions.push(createSyncHandshakeSpanExtension()),ye.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Kt,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(se),e}let st=null,vt=new Map,Tt=[];function Et(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function Dt(e){let t=ye.documents.get(e);if(!t)return null;let{frontmatter:s,body:g}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(s,g)}let jt=(e,t)=>applyExternalChange(ye,e,t,ue,de);function Mt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ft=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of ye.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=ye.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,ue,s)},FILE_WATCHER_ORIGIN)}catch(t){Y.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},It=null,Lt=e=>{e&&(It===null&&(It=new Set,setImmediate(()=>{let e=It;if(It=null,e)try{for(let t of e)Ft(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),It.add(e))};function Rt(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 zt(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),me.updateDocumentFromMarkdown(e.docName,e.content),$e(),ge.updateDocumentFromMarkdown(e.docName,e.content),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),at(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=ye.documents.get(t);if(!g){me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`);return}let S=getReconciledBase(t)??``,w=Dt(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(Y.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:Mt(g),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`);break;case`clean`:try{jt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Mt(g),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Mt(g)}break;case`merged`:try{jt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Mt(g),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Mt(g)}break;case`conflicts`:try{jt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),me.updateDocumentFromMarkdown(t,s),$e(),ge.updateDocumentFromMarkdown(t,s),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}{let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=ye.documents.get(t);if(!s){me.deleteDocument(t),$e(),ge.deleteDocument(t),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),it(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=Dt(t)??``,w=S!==g;if(w&&_e.current){let e=_e.current,s=Wt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{Y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),me.deleteDocument(t),$e(),ge.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),ye.closeConnections(t),await Be(s),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),it(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=ye.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),me.renameDocument(t,s,g),$e(),ge.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}Y.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`),rt(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=ye.documents.get(t);if(!s)return;let g=Dt(t);g===null?Y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,g);let S=s.getMap(`lifecycle`);S.set(`status`,`conflict`),S.set(`reason`,`conflict-markers`),Y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ce.add(e.relativePath),Ge(`files`),Lt(basename(e.relativePath));break;case`asset-delete`:ce.remove(e.relativePath),Ge(`files`),Lt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Ge(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Rt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Bt=[];async function Vt(e){if(isBatchInProgress()){Bt.push(e);return}await zt(e)}async function Ht(){let e=Bt.splice(0,Bt.length);for(let t of e)await zt(t)}let Ut=null,Wt=null,Kt=null,$t=null;async function en(e){if(ye.documents.size===0)return;let t=!1,s=new Promise(e=>{ye.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(ye.documents.keys());ye.closeConnections(),ye.flushPendingStores();for(let e of ye.documents.values())e.getConnectionsCount()===0&&ye.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(ye.documents.keys()),S=[],E=[];if(_e.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=Dt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Et(_e.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:_e.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),Y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),Y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else Y.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function jr(){return $t||($t=(async()=>{let e=Date.now(),t=[];ze=!0,Xe!==null&&(clearTimeout(Xe),Xe=null);let g,S=await Promise.race([We.then(()=>`completed`,e=>(Y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&Y.warn({},`[server] init did not complete within 5s during shutdown`);let w=ye.documents.size;try{try{try{Wt&&=(await Wt.unsubscribe(),null),Ut&&=(await Ut.unsubscribe(),null);for(let{docName:e,cleanup:t}of Tt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Tt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{we?.destroy(),De?.destroy(),st&&=(await st.disconnect(),null);for(let[e,t]of vt)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}vt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await Ce.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await en(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ve.flushPendingGitCommit(),await ve.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Kt&&=(await Kt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(_e.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(_e.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(_e.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?Y.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):Y.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(se)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),$t)}let Mr=[];async function Fr(){try{Ie=await loadPrincipal(s),Y.info({principalId:Ie.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!_e.current)try{_e.current=await initShadowRepo(s),Y.info({gitDir:_e.current.gitDir},`[server] history repo initialized at ${_e.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Mr.push(`shadow-repo`)}if(_e.current){let e=null;try{e=loadRenameLogIndex(_e.current.gitDir),sweepLazyPopOrphans(_e.current.gitDir,e),setRenameLogIndex(_e.current.gitDir,e),Y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){Y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(_e.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){Y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(_e.current)try{await shadowGit(_e.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){Y.warn({},`[server] history repo appears corrupted — reinitializing`);try{_e.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),_e.current=void 0,Mr.includes(`shadow-repo`)||Mr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(_e.current)try{let e=resolve(_e.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==t){let e=`main`;try{let t=(await esm_default({baseDir:s,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}Y.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(_e.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){Y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else Y.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){Y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){Y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,s);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,s=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;Y.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){Y.error({err:e},`[server] managed rename recovery failed`),Mr.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&Y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){Y.error({err:e},`[server] upload-tempfile sweep failed`),Mr.push(`upload-tempfile-sweep`)}try{st=await ye.openDirectConnection(SYSTEM_DOC_NAME),we?.emitServerInfo(oe,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Mr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await ye.openDirectConnection(e);vt.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Mr.push(`config-doc:${e}`)}let S=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,s)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,s)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,s,k)]]);for(let e of g){let t=S.get(e);if(t)try{Y.info({docName:e,path:t},`[config-file-watcher] starting`);let s=await startConfigFileWatcher(t,t=>{let s=ye.documents.get(e);Y.info({docName:e,hasDocument:s!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,e,t,ve.configPersistenceCtx);if(Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=te();Kt?.setEnabled(e).catch(t=>{Y.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}let S=ne();Pe.applyConfig({enabled:S.enabled,providerFingerprint:ae(S)})});Tt.push({docName:e,cleanup:s}),Y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(s){Y.warn({err:s,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Mr.push(`config-file-watcher:${e}`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:s,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(s,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(S=t)}}catch{}let w=S?[e,g,S]:[e,g],E=Y;E.info({okignorePath:e,gitignorePath:g,gitInfoExcludePath:S,ephemeral:J},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let D=J?null:await startMultiPathConfigFileWatcher(w,(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(ye.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,ve.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let S=await fe.rebuildIgnorePatterns();if(S.ok)E.info({changedPath:relative(s,t),patternCount:S.patternCount,nestedFileCount:S.nestedFileCount,durationMs:S.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),we?.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`),we?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Tt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`))}catch(e){Y.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Mr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),me.switchBranch(E);try{{let e=getActiveBranch();try{if(await me.loadFromDisk(e)){let t=await me.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await me.rebuildFromDisk(e);me.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){Y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Ut=await startWatcher(t,Vt,fe);try{await ge.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Mr.push(`tag-index`)}let e=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:fe,basenameIndex:ce,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during seed (${t}${s?` ${s}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:ce,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during single-file seed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Mr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Mr.push(`basename-index`)}}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Mr.push(`file-watcher`)}try{Wt=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),ye.flushPendingStores(),await ve.flushPendingGitCommit(),setBatchInProgress(!0),_e.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of ye.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=Dt(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(_e.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),Y.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){Y.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Bt.length,g=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:s,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${s}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Ht(),await ve.flushDeferredStores(`within-branch`),Kt!==null)try{await Kt.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Bt.splice(0,Bt.length),switchReconciledBaseScope(g),Xe!==null&&(clearTimeout(Xe),Xe=null),me.switchBranch(g),fe.rebuildDirCount();try{let e=0;ce.clear(),await seedBasenameIndex({contentDir:t,contentFilter:fe,basenameIndex:ce,onSkip:(t,s,S)=>{e++,Y.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Mr.includes(`basename-index-partial`)||Mr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of ye.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=Dt(e)??``;if(S!==t&&_e.current){let t=_e.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{Y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Y.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);jt(e,w),setReconciledBase(e,w),Y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){Y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}Y.info({branch:g,docCount:ye.documents.size},`[branch-switch] loaded branch ${g} (${ye.documents.size} docs)`);try{if(await me.loadFromDisk(g)){let e=await me.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await me.rebuildFromDisk(g);me.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){Y.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ge.init(),_e.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of ye.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(_e.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:jt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:jt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=ye.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){Y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&Y.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&_e.current)try{let t=shadowGit(_e.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
2828
- `))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ve.flushDeferredStores(`discard-stale`),we?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&_e.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(_e.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Mr.push(`head-watcher`)}function D(e){for(let g of e)try{let e=relative(t,join(s,g));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=ye.documents.get(S);if(!w)continue;let E=Dt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let O=buildSyncCredentialArgs(H);try{Kt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:fe,contentRoot:L,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:we,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ve.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:D,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Kt.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Kt=null}Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}return Fr().then(Ve,Ue),{hocuspocus:ye,sessionManager:Ce,cc1Broadcaster:we,agentFocusBroadcaster:Te,agentPresenceBroadcaster:De,contentFilter:fe,basenameIndex:ce,serverInstanceId:oe,destroy:jr,ready:We,degraded:Mr,lockDir:se,get syncEngine(){return Kt}}}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-C-zDqt0G.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe}=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=e.ephemeral?void 0: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 ee().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,ephemeral:e.ephemeral}),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 ee().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()),ue!==void 0&&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`,()=>ee()),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:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
2823
+ `))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ve.flushDeferredStores(`discard-stale`),we?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&_e.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(_e.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Mr.push(`head-watcher`)}function D(e){for(let g of e)try{let e=relative(t,join(s,g));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=ye.documents.get(S);if(!w)continue;let E=Dt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let O=buildSyncCredentialArgs(H);try{Kt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:fe,contentRoot:L,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:we,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ve.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:D,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Kt.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Kt=null}Ge(`files`),Ge(`backlinks`),Ge(`graph`),Ge(`tags`)}return Fr().then(Ve,Ue),{hocuspocus:ye,sessionManager:Ce,cc1Broadcaster:we,agentFocusBroadcaster:Te,agentPresenceBroadcaster:De,contentFilter:fe,basenameIndex:ce,serverInstanceId:oe,destroy:jr,ready:We,degraded:Mr,lockDir:se,get syncEngine(){return Kt}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-CyhBidkz-CEUtTbEY.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe}=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=e.ephemeral?void 0: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 ee().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,ephemeral:e.ephemeral}),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 ee().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()),ue!==void 0&&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`,()=>ee()),me&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:de,destroy:ve,lockDir:te,contentDir:e.contentDir,port:we,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
2829
2824
  `).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let w=``;try{w=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,w);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`Open Knowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
2830
- `,`utf-8`),t}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);mkdirSync(t,{recursive:!0});let s=resolve(t,TELEMETRY_FILENAME);setToleranceTelemetryHook(e=>{let t=JSON.stringify({event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity});try{appendFileSync(s,`${t}\n`)}catch{}})}function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null)}export{STATE_MANIFEST_FILENAME as $,resolveShadowDir as $i,listRescueCheckpoints as $n,safetyCheckpoint as $r,createServerObserverExtension as $t,LOG_MD_TEMPLATE as A,validateAgentId as Ai,handleSpawnCursor as An,registerWrite as Ar,clearContributors as At,OK_OKIGNORE_TEMPLATE as B,JSONRPCMessageSchema as Bi,isAllowedApiOrigin as Bn,resolvePackageVersion as Br,createApiExtension as Bt,GitNotAvailableError as C,tracedRmSync as Ci,getLogFilePath as Cn,readTargetRecordedAt as Cr,buildInstructions as Ct,HocuspocusAuthTokenSchema as D,tracedWriteFileSync as Di,getMetrics as Dn,recordContributor as Dr,classifyEvents as Dt,HocuspocusAuthRejection as E,tracedWriteFile as Ei,getMeter as En,reconcile as Er,buildWipTree as Et,MIN_GIT_VERSION as F,writeRootGitignoreForNewRepo as Fi,initTelemetry as Fn,resolveContentDir as Fr,commitWipFromTree as Ft,ROOT_GITIGNORE_TEMPLATE as G,atomicWriteFileSync as Gi,isLoopbackAddress as Gn,rewriteWikiLinksForDocumentRename as Gr,createEphemeralProjectDir as Gt,PinoLogger as H,isInitializedNotification as Hi,isConfigDoc as Hn,restoreContributors as Hr,createContentFilter as Ht,MISSING_OK_CONFIG_MESSAGE as I,writeStateManifest as Ii,initToleranceTelemetryWriter as In,resolveCursorBinaryDefault as Ir,compareSemver as It,STARTER_FOLDERS as J,withFileLockSync as Ji,isProjectRoot as Jn,runCloneSubprocess as Jr,createLiveDerivedIndexExtension as Jt,SERVICE_WRITER as K,readConfigSafely as Ki,isPairedWriteOrigin as Kn,runAuthReposSubprocess as Kr,createExternalChangeHandler as Kt,McpLogger as L,writeTargetVersion as Li,installPrettyZodErrors as Ln,resolveCursorSpawnInvocation as Lr,containsConflictMarkers as Lt,MAX_AGENT_SESSIONS as M,validateSkillZip as Mi,incrementServerObserverFire as Mn,removeLastKnownHash as Mr,coercePackId as Mt,MCP_CONNECTION_ID_HEADER as N,withSpan as Ni,initContent as Nn,resetMetrics as Nr,commitUpstreamImport as Nt,INSTALLED_AGENTS_SCHEMES as O,updateLastKnownHash as Oi,getTracer as On,recordSkillInstallEvent as Or,classifyFsPath as Ot,MCP_SERVER_NAME as P,withSpanSync as Pi,initShadowRepo as Pn,resolveBundledSkillDir as Pr,commitWip as Pt,STARTER_TEMPLATES as Q,resolveGitDirDetailed as Qi,lastKnownHash as Qn,safeSubdir as Qr,createServer$1 as Qt,MissingOkConfigError as R,writeTracker as Ri,installTestLoggers as Rn,resolveLockDir as Rr,contentHash as Rt,GIT_UPSTREAM_WRITER as S,tracedRenameSync as Si,getLocalDir as Sn,readStateManifest as Sr,buildExecResult as St,HOCUSPOCUS_AUTH_REJECTION_REASONS as T,tracedUnlinkSync as Ti,getLogsDir as Tn,readUiLock as Tr,buildStarterFolderFrontmatterYaml as Tt,ProjectGitInitError as U,isJSONRPCRequest as Ui,isHocuspocusAuthRejectionReason as Un,restoreLifecycleFromConflictsJson as Ur,createContentFilterAsync as Ut,PANE_TARGET_TTL_MS as V,LATEST_PROTOCOL_VERSION as Vi,isAllowedWorkspaceHostHeader as Vn,resolveUiInfo as Vr,createAssetServeMiddleware as Vt,ROLLBACK_ORIGIN as W,isJSONRPCResultResponse as Wi,isKnownPackId as Wn,rewriteMarkdownLinksForDocumentRename as Wr,createEmbeddingsSecretStore as Wt,STARTER_PACKS as X,GitDirAccessError as Xi,isSystemDoc as Xn,runWithMcpLogger as Xr,createOsProbe as Xt,STARTER_FOLDER_FRONTMATTER_FILENAME as Y,writeConfigPatch as Yi,isSelfWrite as Yn,runDeviceFlowSubprocess as Yr,createMcpHttpHandler as Yt,STARTER_PACK_IDS as Z,MalformedGitPointerError as Zi,isToleranceTelemetryEnabled as Zn,safeContentPath as Zr,createPersistenceExtension as Zt,EMBEDDINGS_API_KEY_ENV as _,tracedAppendFileSync as _i,formatAuthRejectionWire as _n,readArmedPaneTarget as _r,assertNeverDiskEvent as _t,AgentPresenceBroadcaster as a,setActiveSpanAttributes as ai,detectProjectShape as an,makeLazyEmbeddingsKeyStore as ar,StateManifestError as at,FileEmbeddingsBackend as b,tracedMkdirSync as bi,gcCheckpointRefs as bn,readServerPackageVersion as br,buildAndOpenSkill as bt,BacklinkIndex as c,spansCurrentPath as ci,encodeFolderRoute as cn,packageVersionMajorMinor as cr,__getShowAllWalkStatsForTesting as ct,CONFLICT_MARKER_RE as d,splitMarkdownBlocks as di,evictStaleTrackerEntries as dn,parseHocuspocusAuthToken as dr,applyAgentMarkdownWrite as dt,sanitizeClientName as ei,createStreamingErrorWriter as en,listStarterPacks as er,SeedPrerequisiteError as et,CURSOR_BUNDLE_PATHS_BY_PLATFORM as f,startWatcher as fi,extractWikiLinksFromMarkdown as fn,parseKeepaliveConnectionId as fr,applyExternalChange as ft,DEFAULT_PACK_ID as g,toBroadcasterKey as gi,flushFileLogger as gn,readAllTargets as gr,assertGitAvailable as gt,DEFAULT_EMBEDDINGS_DIMENSIONS as h,teardownToleranceTelemetryWriter as hi,findEnclosingProjectRoot as hn,prepareSingleFileOpen as hr,assertCompatibleStateManifest as ht,AgentFocusBroadcaster as i,serializeError as ii,detectGit as in,logsPreviousPath as ir,SingleFileNotMarkdownError as it,MANAGED_RENAME_ORIGIN as j,validateCloneInputs as ji,incrementCollabSocketFilteredError as jn,releaseUiLock as jr,clearEmbeddingsKeyFromAllBackends as jt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as k,updateUiLockPort as ki,handleCollabSocketError as kn,registerAllTools as kr,clearArmedPaneTarget as kt,CC1Broadcaster as l,spansPreviousPath as li,ensureProjectGit as ln,parseAuthRejectionWire as lr,__resetShowAllWalkStatsForTesting as lt,DEFAULT_CHECKPOINT_RETENTION as m,swapContributors as mi,findEnclosingGitRoot as mn,planSeed as mr,armPaneTarget as mt,AGENT_ID_RE as n,saveVersion as ni,describeStoredEmbeddingsKey as nn,loggerFactory as nr,SingleFileNotAFileError as nt,AgentSessionCapacityError as o,shadowGit as oi,emitPreflightFailureSpan as on,mountMcpAndApi as or,TagIndex as ot,ConfigSchema as p,streamingProblemEvent as pi,fallbackPaths as pn,pathToDocName as pr,applySeed as pt,SKILL_INSTALL_EVENTS_FILE_REL as q,resolveConfigPath as qi,isPathWithinDir as qn,runAuthStatusSubprocess as qr,createFileLogger as qt,AGENT_WRITE_ORIGIN as r,seedBasenameIndex as ri,detectClaudeDesktopPresence as rn,logsCurrentPath as rr,SingleFileNotFoundError as rt,AgentSessionManager as s,shutdownTelemetry as si,encodeDocName as sn,normalizeFsPath as sr,UiLockCollisionError as st,AGENT_ID_MAX_LEN as t,saveInMemoryCheckpoint as ti,createTestLogger as tn,loadPrincipal as tr,SeedRootDirError as tt,CONFIG_FILENAME as u,spawnDetached as ui,errorResponse as un,parseGitVersion as ur,acquireUiLock as ut,FILE_SYSTEM_WRITER as v,tracedLinkSync as vi,formatContributors as vn,readBranchFromHead as vr,attachIdleShutdown as vt,GitTooOldError as w,tracedRmdirSync as wi,getLogger as wn,readTargetVersion as wr,buildSkillZip as wt,GIT_PREFLIGHT_FAIL_SPAN_NAME as x,tracedRename as xi,getCurrentMcpLogger as xn,readSkillInstallStateSnapshot as xr,buildConfigYmlContent as xt,FILE_WATCHER_ORIGIN as y,tracedMkdir as yi,formatContributorsFrom as yn,readProjectLocalSemanticConfig as yr,bootServer as yt,OBSERVER_SYNC_ORIGIN as z,McpServer as zi,installUserSkill as zn,resolvePack as zr,contributorCount as zt};
2831
- //# sourceMappingURL=dist-CwxIEsQy.mjs.map
2825
+ `,`utf-8`),t}export{STARTER_TEMPLATES as $,resolveGitDirDetailed as $i,lastKnownHash as $n,safeSubdir as $r,createServer$1 as $t,LIVE_DERIVED_INDEX_DEBOUNCE_MS as A,updateUiLockPort as Ai,handleCollabSocketError as An,registerAllTools as Ar,clearArmedPaneTarget as At,OBSERVER_SYNC_ORIGIN as B,McpServer as Bi,installUserSkill as Bn,resolvePack as Br,contributorCount as Bt,GIT_UPSTREAM_WRITER as C,tracedRenameSync as Ci,getLocalDir as Cn,readStateManifest as Cr,buildExecResult as Ct,HocuspocusAuthRejection as D,tracedWriteFile as Di,getMeter as Dn,reconcile as Dr,buildWipTree as Dt,HOCUSPOCUS_AUTH_REJECTION_REASONS as E,tracedUnlinkSync as Ei,getLogsDir as En,readUiLock as Er,buildStarterFolderFrontmatterYaml as Et,MCP_SERVER_NAME as F,withSpanSync as Fi,initShadowRepo as Fn,resolveBundledSkillDir as Fr,commitWip as Ft,ROLLBACK_ORIGIN as G,isJSONRPCResultResponse as Gi,isKnownPackId as Gn,rewriteMarkdownLinksForDocumentRename as Gr,createEmbeddingsSecretStore as Gt,PANE_TARGET_TTL_MS as H,LATEST_PROTOCOL_VERSION as Hi,isAllowedWorkspaceHostHeader as Hn,resolveUiInfo as Hr,createAssetServeMiddleware as Ht,MIN_GIT_VERSION as I,writeRootGitignoreForNewRepo as Ii,initTelemetry as In,resolveContentDir as Ir,commitWipFromTree as It,SKILL_INSTALL_EVENTS_FILE_REL as J,resolveConfigPath as Ji,isPathWithinDir as Jn,runAuthStatusSubprocess as Jr,createFileLogger as Jt,ROOT_GITIGNORE_TEMPLATE as K,atomicWriteFileSync as Ki,isLoopbackAddress as Kn,rewriteWikiLinksForDocumentRename as Kr,createEphemeralProjectDir as Kt,MISSING_OK_CONFIG_MESSAGE as L,writeStateManifest as Li,initToleranceTelemetryWriter as Ln,resolveCursorBinaryDefault as Lr,compareSemver as Lt,MANAGED_RENAME_ORIGIN as M,validateCloneInputs as Mi,incrementCollabSocketFilteredError as Mn,releaseUiLock as Mr,clearEmbeddingsKeyFromAllBackends as Mt,MAX_AGENT_SESSIONS as N,validateSkillZip as Ni,incrementServerObserverFire as Nn,removeLastKnownHash as Nr,coercePackId as Nt,HocuspocusAuthTokenSchema as O,tracedWriteFileSync as Oi,getMetrics as On,recordContributor as Or,classifyEvents as Ot,MCP_CONNECTION_ID_HEADER as P,withSpan as Pi,initContent as Pn,resetMetrics as Pr,commitUpstreamImport as Pt,STARTER_PACK_IDS as Q,MalformedGitPointerError as Qi,isToleranceTelemetryEnabled as Qn,safeContentPath as Qr,createPersistenceExtension as Qt,McpLogger as R,writeTargetVersion as Ri,installPrettyZodErrors as Rn,resolveCursorSpawnInvocation as Rr,containsConflictMarkers as Rt,GIT_PREFLIGHT_FAIL_SPAN_NAME as S,tracedRename as Si,getCurrentMcpLogger as Sn,readSkillInstallStateSnapshot as Sr,buildConfigYmlContent as St,GitTooOldError as T,tracedRmdirSync as Ti,getLogger as Tn,readTargetVersion as Tr,buildSkillZip as Tt,PinoLogger as U,isInitializedNotification as Ui,isConfigDoc as Un,restoreContributors as Ur,createContentFilter as Ut,OK_OKIGNORE_TEMPLATE as V,JSONRPCMessageSchema as Vi,isAllowedApiOrigin as Vn,resolvePackageVersion as Vr,createApiExtension as Vt,ProjectGitInitError as W,isJSONRPCRequest as Wi,isHocuspocusAuthRejectionReason as Wn,restoreLifecycleFromConflictsJson as Wr,createContentFilterAsync as Wt,STARTER_FOLDER_FRONTMATTER_FILENAME as X,writeConfigPatch as Xi,isSelfWrite as Xn,runDeviceFlowSubprocess as Xr,createMcpHttpHandler as Xt,STARTER_FOLDERS as Y,withFileLockSync as Yi,isProjectRoot as Yn,runCloneSubprocess as Yr,createLiveDerivedIndexExtension as Yt,STARTER_PACKS as Z,GitDirAccessError as Zi,isSystemDoc as Zn,runWithMcpLogger as Zr,createOsProbe as Zt,DEFAULT_PACK_ID as _,toBroadcasterKey as _i,flushFileLogger as _n,readAllTargets as _r,assertGitAvailable as _t,AgentPresenceBroadcaster as a,serializeError as ai,detectGit as an,logsPreviousPath as ar,SingleFileNotMarkdownError as at,FILE_WATCHER_ORIGIN as b,tracedMkdir as bi,formatContributorsFrom as bn,readProjectLocalSemanticConfig as br,bootServer as bt,AutoStartDisabledError as c,shutdownTelemetry as ci,encodeDocName as cn,normalizeFsPath as cr,UiLockCollisionError as ct,CONFIG_FILENAME as d,spawnDetached as di,errorResponse as dn,parseGitVersion as dr,acquireUiLock as dt,resolveShadowDir as ea,safetyCheckpoint as ei,createServerObserverExtension as en,listRescueCheckpoints as er,STATE_MANIFEST_FILENAME as et,CONFLICT_MARKER_RE as f,splitMarkdownBlocks as fi,evictStaleTrackerEntries as fn,parseHocuspocusAuthToken as fr,applyAgentMarkdownWrite as ft,DEFAULT_EMBEDDINGS_DIMENSIONS as g,teardownToleranceTelemetryWriter as gi,findEnclosingProjectRoot as gn,prepareSingleFileOpen as gr,assertCompatibleStateManifest as gt,DEFAULT_CHECKPOINT_RETENTION as h,swapContributors as hi,findEnclosingGitRoot as hn,planSeed as hr,armPaneTarget as ht,AgentFocusBroadcaster as i,seedBasenameIndex as ii,detectClaudeDesktopPresence as in,logsCurrentPath as ir,SingleFileNotFoundError as it,LOG_MD_TEMPLATE as j,validateAgentId as ji,handleSpawnCursor as jn,registerWrite as jr,clearContributors as jt,INSTALLED_AGENTS_SCHEMES as k,updateLastKnownHash as ki,getTracer as kn,recordSkillInstallEvent as kr,classifyFsPath as kt,BacklinkIndex as l,spansCurrentPath as li,encodeFolderRoute as ln,packageVersionMajorMinor as lr,__getShowAllWalkStatsForTesting as lt,ConfigSchema as m,streamingProblemEvent as mi,fallbackPaths as mn,pathToDocName as mr,applySeed as mt,AGENT_ID_RE as n,saveInMemoryCheckpoint as ni,createTestLogger as nn,loadPrincipal as nr,SeedRootDirError as nt,AgentSessionCapacityError as o,setActiveSpanAttributes as oi,detectProjectShape as on,makeLazyEmbeddingsKeyStore as or,StateManifestError as ot,CURSOR_BUNDLE_PATHS_BY_PLATFORM as p,startWatcher as pi,extractWikiLinksFromMarkdown as pn,parseKeepaliveConnectionId as pr,applyExternalChange as pt,SERVICE_WRITER as q,readConfigSafely as qi,isPairedWriteOrigin as qn,runAuthReposSubprocess as qr,createExternalChangeHandler as qt,AGENT_WRITE_ORIGIN as r,saveVersion as ri,describeStoredEmbeddingsKey as rn,loggerFactory as rr,SingleFileNotAFileError as rt,AgentSessionManager as s,shadowGit as si,emitPreflightFailureSpan as sn,mountMcpAndApi as sr,TagIndex as st,AGENT_ID_MAX_LEN as t,sanitizeClientName as ti,createStreamingErrorWriter as tn,listStarterPacks as tr,SeedPrerequisiteError as tt,CC1Broadcaster as u,spansPreviousPath as ui,ensureProjectGit as un,parseAuthRejectionWire as ur,__resetShowAllWalkStatsForTesting as ut,EMBEDDINGS_API_KEY_ENV as v,tracedAppendFileSync as vi,formatAuthRejectionWire as vn,readArmedPaneTarget as vr,assertNeverDiskEvent as vt,GitNotAvailableError as w,tracedRmSync as wi,getLogFilePath as wn,readTargetRecordedAt as wr,buildInstructions as wt,FileEmbeddingsBackend as x,tracedMkdirSync as xi,gcCheckpointRefs as xn,readServerPackageVersion as xr,buildAndOpenSkill as xt,FILE_SYSTEM_WRITER as y,tracedLinkSync as yi,formatContributors as yn,readBranchFromHead as yr,attachIdleShutdown as yt,MissingOkConfigError as z,writeTracker as zi,installTestLoggers as zn,resolveLockDir as zr,contentHash as zt};
2826
+ //# sourceMappingURL=dist-DYMUIJ9w.mjs.map