@inkeep/open-knowledge 0.10.0-beta.8 → 0.10.0
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.
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +3 -1
- package/dist/cli.mjs +55 -48
- package/dist/config-schema.json +57 -21
- package/dist/config.project-local.schema.json +57 -0
- package/dist/config.project.schema.json +0 -21
- package/dist/constants-DfoUZtqY.mjs +2 -0
- package/dist/dist-CaLi0vY9.mjs +1 -0
- package/dist/{dist-peyy_Xqa.mjs → dist-jSj9zzv0.mjs} +26 -25
- package/dist/{gh-detect-BUPEzJp9.mjs → gh-detect-Bl7eyodQ.mjs} +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{init-DFIeFfDO.mjs → init-C-JifwEm.mjs} +18 -18
- package/dist/init-bD4lWQ2B.mjs +1 -0
- package/dist/{loader-BRV6jbT-.mjs → loader-DYJhIg5U.mjs} +3 -3
- package/dist/loader-DznbAjEH.mjs +1 -0
- package/dist/preview-BEJ6SfIa.mjs +1 -0
- package/dist/{preview-Cj1NaXIB.mjs → preview-CG5C712c.mjs} +2 -2
- package/dist/public/assets/{ActivityModeContent-D2i8Zn71.js → ActivityModeContent-DUcYHbIo.js} +1 -1
- package/dist/public/assets/{DocumentContext-B8GbZdoY.js → DocumentContext-BMFT2k_y.js} +17 -17
- package/dist/public/assets/{GraphPanel-DnTtjLxL.js → GraphPanel-_BCbvLM6.js} +1 -1
- package/dist/public/assets/SettingsDialogBody-DUB7Be0M.js +7 -0
- package/dist/public/assets/SourceEditor-NuqcNnnQ.js +2 -0
- package/dist/public/assets/{config-validation-events-D_EFbncj.js → config-validation-events-BNceQeM2.js} +5 -5
- package/dist/public/assets/{index-srOfVrqh.js → index-BUIBMYs5.js} +8 -8
- package/dist/public/assets/index-Cof56snX.css +1 -0
- package/dist/public/assets/{keyboard-shortcuts-DmIuP6Z1.js → keyboard-shortcuts-D1ntCgJI.js} +1 -1
- package/dist/public/assets/{prop-types-9e5DMg2o.js → prop-types-3UnRySkO.js} +130 -130
- package/dist/public/assets/{target-navigation-intent-BAEzEWPW.js → target-navigation-intent-SROx-nlb.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-C8iPoowF.js → typing-burst-detector-C-vAHUwY.js} +2 -2
- package/dist/public/index.html +8 -8
- package/dist/{repair-launch-json-rjX_x5sN.mjs → repair-launch-json-DFBWIp_2.mjs} +2 -2
- package/dist/{repair-mcp-configs-CeShfDta.mjs → repair-mcp-configs-BZ5j2f4N.mjs} +2 -2
- package/dist/repair-skills-CqSK9MSk.mjs +1 -0
- package/dist/{repair-skills-CDKiT_Bf.mjs → repair-skills-CxXhBfwl.mjs} +2 -2
- package/dist/schemas/v0/config.project-local.schema.json +57 -0
- package/dist/schemas/v0/config.project.schema.json +0 -21
- package/dist/{server-lock-BpjJj3OD-yLJv0roS.mjs → server-lock-BpjJj3OD-BPX9iz2A.mjs} +89 -89
- package/dist/server-lock-CyhBidkz-C_shPhcO.mjs +1 -0
- package/dist/{src-D084_rtj.mjs → src-BX-ipJD9.mjs} +2 -2
- package/dist/start-CrGSyGS2.mjs +3 -0
- package/dist/start-DIcFlFoz.mjs +1 -0
- package/dist/{write-project-skill-BNGFBLtA.mjs → write-project-skill-dGukOGLo.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-BXvmkg7Y.mjs +0 -2
- package/dist/dist-CuFjIU6M.mjs +0 -1
- package/dist/init-CKGWEe26.mjs +0 -1
- package/dist/loader-CTYLzMxp.mjs +0 -1
- package/dist/preview-BItkz8RQ.mjs +0 -1
- package/dist/public/assets/SettingsDialogBody-pdbayjAd.js +0 -7
- package/dist/public/assets/SourceEditor-7WDSLWRs.js +0 -2
- package/dist/public/assets/index-B3eQbsM3.css +0 -1
- package/dist/repair-skills-DnsSeH8x.mjs +0 -1
- package/dist/server-lock-CyhBidkz-B4QDNiiR.mjs +0 -1
- package/dist/start-CUB_B0aW.mjs +0 -3
- package/dist/start-JN3FGdMq.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,$n as TemplateGetSuccessSchema,$r as projectFull,$t as MarkdownManager,A as ApiConfigSuccessSchema,Ai as validatePatchScopes,An as ServerInfoSuccessSchema,Ar as detectFmRegion,At as FrontmatterPatchSuccessSchema,B as CC1DiskAckPayloadSchema,Bi as custom,Bn as StreamingProblemEventSchema,Br as getParseHealth,Bt as LinkGraphSuccessSchema,C as AgentPatchSuccessSchema,Ci as addConfigSpanEvent,Cn as SaveVersionSuccessSchema,Cr as createBasenameIndex,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdSuccessSchema,Di as isKnownConfigError,Dn as SeedApplySuccessSchema,Dr as createWorkspaceSearchDocument,Dt as FolderConfigPutSuccessSchema,E as AgentWriteMdRequestSchema,Ei as humanFormat,En as SeedApplyRequestSchema,Er as createWorkspaceSearchCorpus,Et as FolderConfigPutRequestSchema,F as BridgeMergeContentLossError,Fi as _enum,Fn as SharePublishRequestSchema,Fr as extractFrontmatterTags,Ft as INLINE_RENDERABLE_EXTENSIONS,G as CC1_CHANNEL_DISK_ACK,Gi as number,Gn as SyncResolveConflictRequestSchema,Gr as isOrphanMode,Gt as LocalOpAuthPatSuccessSchema,H as CC1_CHANNEL_BRANCH_SWITCHED,Hi as intersection,Hn as SyncAbortMergeSuccessSchema,Hr as iconFromClientName,Ht as LocalOpAuthHostRequestSchema,I as CC1BranchSwitchedPayloadSchema,Ii as _null,In as SharePublishResponseSchema,Ir as fnv1aDigest,It as InstallSkillRequestSchema,J as CLIENT_VERSION_HEADER,Ji as preprocess,Jn as SyncTriggerRequestSchema,Jr as mergeThreeWay,Jt as LocalOpCloneRequestSchema,K as CC1_CHANNEL_SERVER_INFO,Ki as object$1,Kn as SyncResolveConflictSuccessSchema,Kr as isValidBranchName,Kt as LocalOpAuthSetIdentityRequestSchema,L as CC1ConfigIgnoreNestedErrorPayloadSchema,Ln as SkillInstallStateSuccessSchema,Lr as formatFileSize,Lt as InstallSkillSuccessSchema,M as BacklinksSuccessSchema,Mi as withConfigSpanSync,Mn as ShareConstructUrlResponseSchema,Mr as emptySkillState,Mt as HistorySuccessSchema,N as BranchInfoResponseSchema,Nn as SharePublishNameCheckResponseSchema,Nr as encodeShareUrl,Nt as HistoryVersionSuccessSchema,O as AgentWriteRequestSchema,Oi as locateIssue,On as SeedListPacksSuccessSchema,Or as defaultScheduler,Ot as ForwardLinksSuccessSchema,P as BridgeInvariantViolationError,Pi as ZodOptional$1,Pn as SharePublishOwnersResponseSchema,Pr as expandTagToHierarchy,Pt as HubsSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT_LOCAL,Qi as unknown,Qn as TemplateDeleteSuccessSchema,Qr as previewEmbedFence,Qt as LocalOpOpenSuccessSchema,R as CC1ConfigValidationRejectedPayloadSchema,Ri as array,Rn as SkillStateSchema,Rr as getAgentCanonicalDescriptors,Rt as InstalledAgentsSuccessSchema,S as AgentPatchRequestSchema,Sn as SaveVersionRequestSchema,Sr as colorFromSeed,St as EXECUTABLE_BLOCKLIST_EXTENSIONS,T as AgentUndoSuccessSchema,Ti as detectRemovedKeys,Tn as SearchSuccessSchema,Tr as createTagInTextRegex,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ui as literal,Un as SyncConflictContentSuccessSchema,Ur as isBranchNotFoundGitError,Ut as LocalOpAuthIdentitySuccessSchema,V as CC1ServerInfoPayloadSchema,Vi as discriminatedUnion,Vn as SuggestLinksSuccessSchema,Vr as getWikiLinkText,Vt as LocalOpAuthEmptySuccessSchema,W as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Wi as looseObject,Wn as SyncConflictsSuccessSchema,Wr as isFrontmatterValueEmpty,Wt as LocalOpAuthPatRequestSchema,X as CONFIG_DOC_NAME_OKIGNORE,Xi as string,Xn as TagsForNameSuccessSchema,Xr as parseFrontmatterYaml,Xt as LocalOpOkInitResponseSchema,Y as CONFIG_DOC_NAMES,Yi as record,Yn as SyncTriggerSuccessSchema,Yr as normalizeBridge,Yt as LocalOpOkInitRequestSchema,Z as CONFIG_DOC_NAME_PROJECT,Zi as union,Zn as TagsListSuccessSchema,Zr as prependFrontmatter,Zt as LocalOpOpenRequestSchema,_ as AGENT_ICON_COLORS,_a as require_dist$1,_i as DEFAULT_LOGS_MAX_BYTES,_n as SKILL_STATE_REL,_r as applyPatchToFm,_t as DocumentListSuccessSchema,a as acquireProcessLock,aa as $ZodObject,ai as sharedExtensions,an as PREVIEW_EMBED_STARTERS,ar as TestRescanBacklinksSuccessSchema,at as CreateFolderSuccessSchema,b as AgentActivitySuccessSchema,bi as LOCAL_DIR,br as classifyWikiLinkTarget,bt as DuplicatePathSuccessSchema,c as isValidLockPid,ca as parseAsync,ci as toBridgeInvariantLog,cn as PageHeadingsSuccessSchema,cr as TrashCleanupRequestSchema,ct as DEFAULT_DEDUP_MODE,da as prettifyError,di as validateDocName,dn as ProblemDetailsSchema,dr as UploadAssetSuccessSchema,ea as datetime,ei as readFmMap,en as MetricsAgentPresenceSuccessSchema,er as TemplateMoveRequestSchema,et as CheckoutRequestSchema,f as readServerLock,fa as clone,fi as getSchema,fn as RenamePathRequestSchema,fr as UploadRequestSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,gi as ConfigSchema$1,gn as RollbackSuccessSchema,gr as applyIncrementalDiff,gt as DiffSuccessSchema,h as updateProcessLockPort,ha as $constructor,hi as CONFIG_SCHEMA_MAJOR_PATH,hn as RollbackRequestSchema,hr as applyFastDiff,ht as DeletePathSuccessSchema,ia as meta$1,ii as searchWorkspaceCorpus,in as OrphansSuccessSchema,ir as TemplatesListSuccessSchema,it as CreateFolderRequestSchema,j as BacklinkCountsSuccessSchema,ji as withConfigSpan,jn as ShareConstructUrlRequestSchema,jr as displayNameFromClientName,jt as FrontmatterValueSchema,k as AgentWriteSuccessSchema,ki as toConfigIssue,kn as SeedPlanSuccessSchema,kr as detectAppliedToleranceClasses,kt as FrontmatterPatchRequestSchema,la as safeParse$1,li as toWikiLinkSlug,ln as PagesSuccessSchema,lr as TrashCleanupSuccessSchema,m as releaseServerLock,ma as normalizeParams,mi as Fragment,mn as RescueListSuccessSchema,mr as WriteWarningSchema,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,ni as resolveAssetProjectPath,nn as MetricsReconciliationSuccessSchema,nr as TemplatePutRequestSchema,nt as ClientLogsRequestSchema,o as acquireServerLock,oa as $ZodType,oi as stripFrontmatter,on as PREVIEW_THEME_TOKENS,or as TestRescanFilesSuccessSchema,ot as CreatePageRequestSchema,p as releaseProcessLock,pa as defineLazy,pi as PluginKey,pn as RenamePathSuccessSchema,pr as WorkspaceSuccessSchema,pt as DeadLinksSuccessSchema,q as CC1_CONTRACT_VERSION,qi as optional,qn as SyncStatusSchema,qr as mediaKindForSidebarAssetExtension,qt as LocalOpAuthStatusSuccessSchema,ra as describe$1,ri as resolveInternalHref,rn as ORPHAN_MODES,rr as TemplatePutSuccessSchema,rt as ClientLogsSuccessSchema,s as isProcessAlive,sa as parse$1,si as tagsMatchingPrefix,sn as PROTOCOL_VERSION,sr as TestResetSuccessSchema,st as CreatePageSuccessSchema,t as ProcessLockCollisionError,ta as toJSONSchema,ti as renderInventoryFooter,tn as MetricsParseHealthSuccessSchema,tr as TemplateMoveSuccessSchema,tt as CheckoutResponseSchema,u as readProcessLock,ua as safeParseAsync$1,ui as unwrapFrontmatterFences,un as PrincipalSuccessSchema,ur as UA_PATTERNS,vi as DEFAULT_SPANS_MAX_BYTES,vn as SKILL_STATE_TARGETS,vr as assertNeverProblemType,vt as DocumentReadSuccessSchema,w as AgentUndoRequestSchema,wi as applyPatchToDocument,wn as SearchRequestSchema,wr as createCodeFenceTracker,wt as EmptyRequestSchema,x as AgentBurstDiffSuccessSchema,xi as OK_PROJECT_MARKER,xn as SYSTEM_DOC_NAME,y as ASSET_EXTENSIONS,yi as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,yn as SKILL_STATE_VERSION_RE,yr as classifyMarkdownHref,yt as DuplicatePathRequestSchema,z as CC1DerivedViewPayloadSchema,zi as boolean,zn as SpawnCursorSuccessSchema,zr as getHeadingSlug,zt as LINKABLE_ASSET_EXTENSIONS}from"./server-lock-BpjJj3OD-yLJv0roS.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-s2X3YAg-.mjs";import{a as require_src$15,i as simpleGit,n as withParentLock,r as esm_default,t as createGitInstance}from"./git-handle-BSAUg1L_-Bn2h-fYS.mjs";import{r as diffLines,t as createPatch}from"./libesm-B_qVEpZ1.mjs";import{n as mimes,t as build_default}from"./build-Dt6UA4sF.mjs";import{t as require_yazl}from"./yazl-DjRp4wSy.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DesxOVHh.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-DnjwTqP3.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-C25Und0M.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-53eJIPK0.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-FwG_Za20.mjs";import{r as o$1}from"./chunk-CWQS3NFK-Co4ALolT.mjs";import"./chunk-DXB73IDG-DIKSLkPq.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-CAp625aG.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DvJz5Cpw.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-ikvLWpfV.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-B6yIPkk2.mjs";import{n as n$1}from"./chunk-3THT3N7L-DztAF386.mjs";import{t as n$2}from"./chunk-44UOCSGV-CaFxJDHm.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as I from"node:fs";import{appendFileSync,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{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import crypto$2 from"crypto";import*as zlib$1 from"zlib";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{Http2ServerRequest,constants as constants$2}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
|
|
1
|
+
import{a as __toCommonJS,i as __require$2,n as __esmMin,o as __toESM$2,r as __exportAll,t as __commonJSMin$2}from"./chunk-FK9Q3tQk.mjs";import{$ as CONFIG_DOC_NAME_USER,$i as number,$n as SyncTriggerRequestSchema,$r as mediaKindForSidebarAssetExtension,$t as LocalOpOpenRequestSchema,A as ApiConfigSuccessSchema,An as SeedApplyRequestSchema,Ar as createTagInTextRegex,At as FrontmatterPatchSuccessSchema,B as CC1DiskAckPayloadSchema,Bi as withConfigSpanSync,Bn as SharePublishRequestSchema,Br as extractFrontmatterTags,Bt as LinkGraphSuccessSchema,C as AgentPatchSuccessSchema,Ca as $constructor,Ci as DEFAULT_EMBEDDINGS_BASE_URL,Cn as SKILL_STATE_VERSION_RE,Cr as assertNeverProblemType,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdSuccessSchema,Di as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,Dn as SaveVersionSuccessSchema,Dr as colorFromSeed,Dt as FolderConfigPutSuccessSchema,E as AgentWriteMdRequestSchema,Ei as DEFAULT_SPANS_MAX_BYTES,En as SaveVersionRequestSchema,Et as FolderConfigPutRequestSchema,F as BridgeMergeContentLossError,Fi as isKnownConfigError,Fn as ServerInfoSuccessSchema,Fr as detectFmRegion,Ft as INLINE_RENDERABLE_EXTENSIONS,G as CC1_CHANNEL_DISK_ACK,Gn as StreamingProblemEventSchema,Gr as getParseHealth,Gt as LocalOpAuthPatSuccessSchema,H as CC1_CHANNEL_BRANCH_SWITCHED,Hi as ZodOptional$1,Hn as SkillInstallStateSuccessSchema,Hr as formatFileSize,Ht as LocalOpAuthHostRequestSchema,I as CC1BranchSwitchedPayloadSchema,Ii as locateIssue,In as ShareConstructUrlRequestSchema,Ir as displayNameFromClientName,It as InstallSkillRequestSchema,J as CLIENT_VERSION_HEADER,Ji as custom,Jn as SyncConflictContentSuccessSchema,Jr as isBranchNotFoundGitError,Jt as LocalOpCloneRequestSchema,K as CC1_CHANNEL_SERVER_INFO,Ki as array,Kn as SuggestLinksSuccessSchema,Kr as getWikiLinkText,Kt as LocalOpAuthSetIdentityRequestSchema,L as CC1ConfigIgnoreNestedErrorPayloadSchema,Li as toConfigIssue,Ln as ShareConstructUrlResponseSchema,Lr as emptySkillState,Lt as InstallSkillSuccessSchema,M as BacklinksSuccessSchema,Mi as applyPatchToDocument,Mn as SeedListPacksSuccessSchema,Mr as createWorkspaceSearchDocument,Mt as HistorySuccessSchema,N as BranchInfoResponseSchema,Ni as detectRemovedKeys,Nn as SeedPlanSuccessSchema,Nr as defaultScheduler,Nt as HistoryVersionSuccessSchema,O as AgentWriteRequestSchema,Oi as LOCAL_DIR,On as SearchRequestSchema,Or as createBasenameIndex,Ot as ForwardLinksSuccessSchema,P as BridgeInvariantViolationError,Pi as humanFormat,Pn as SemanticIndexStatusSchema,Pr as detectAppliedToleranceClasses,Pt as HubsSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT_LOCAL,Qi as looseObject,Qn as SyncStatusSchema,Qr as isValidBranchName,Qt as LocalOpOkInitResponseSchema,R as CC1ConfigValidationRejectedPayloadSchema,Ri as validatePatchScopes,Rn as SharePublishNameCheckResponseSchema,Rr as encodeShareUrl,Rt as InstalledAgentsSuccessSchema,S as AgentPatchRequestSchema,Sa as normalizeParams,Si as ConfigSchema$1,Sn as SKILL_STATE_TARGETS,Sr as applyPatchToFm,St as EXECUTABLE_BLOCKLIST_EXTENSIONS,T as AgentUndoSuccessSchema,Ta as require_dist$1,Ti as DEFAULT_LOGS_MAX_BYTES,Tn as SYSTEM_DOC_NAME,Tr as classifyWikiLinkTarget,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ui as _enum,Un as SkillStateSchema,Ur as getAgentCanonicalDescriptors,Ut as LocalOpAuthIdentitySuccessSchema,V as CC1ServerInfoPayloadSchema,Vn as SharePublishResponseSchema,Vr as fnv1aDigest,Vt as LocalOpAuthEmptySuccessSchema,W as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Wi as _null,Wn as SpawnCursorSuccessSchema,Wr as getHeadingSlug,Wt as LocalOpAuthPatRequestSchema,X as CONFIG_DOC_NAME_OKIGNORE,Xi as intersection,Xn as SyncResolveConflictRequestSchema,Xr as isHiddenDocName,Xt as LocalOpEmbeddingsSetKeyRequestSchema,Y as CONFIG_DOC_NAMES,Yi as discriminatedUnion,Yn as SyncConflictsSuccessSchema,Yr as isFrontmatterValueEmpty,Yt as LocalOpEmbeddingsMutationSuccessSchema,Z as CONFIG_DOC_NAME_PROJECT,Zi as literal,Zn as SyncResolveConflictSuccessSchema,Zr as isOrphanMode,Zt as LocalOpOkInitRequestSchema,_ as AGENT_ICON_COLORS,_a as safeParse$1,_i as validateDocName,_n as RollbackRequestSchema,_r as UploadRequestSchema,_t as DocumentListSuccessSchema,a as acquireProcessLock,aa as union,ai as projectFull,an as ORPHAN_MODES,ar as TemplateMoveRequestSchema,at as CreateFolderSuccessSchema,b as AgentActivitySuccessSchema,ba as clone,bi as Fragment,bn as SANDBOXED_HTML_EXTENSIONS,br as applyFastDiff,bt as DuplicatePathSuccessSchema,c as isValidLockPid,ca as datetime,ci as resolveAssetProjectPath,cn as PREVIEW_THEME_TOKENS,cr as TemplatePutSuccessSchema,ct as DEFAULT_DEDUP_MODE,da as describe$1,di as sharedExtensions,dn as PagesSuccessSchema,dr as TestRescanFilesSuccessSchema,ea as object$1,ei as mergeThreeWay,en as LocalOpOpenSuccessSchema,er as SyncTriggerSuccessSchema,et as CheckoutRequestSchema,f as readServerLock,fa as meta$1,fi as stripFrontmatter,fn as PrincipalSuccessSchema,fr as TestResetSuccessSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as parseAsync,gi as unwrapFrontmatterFences,gn as RescueListSuccessSchema,gr as UploadAssetSuccessSchema,gt as DiffSuccessSchema,h as updateProcessLockPort,ha as parse$1,hi as toWikiLinkSlug,hn as RenamePathSuccessSchema,hr as UA_PATTERNS,ht as DeletePathSuccessSchema,ia as string,ii as previewEmbedFence,in as MetricsReconciliationSuccessSchema,ir as TemplateGetSuccessSchema,it as CreateFolderRequestSchema,j as BacklinkCountsSuccessSchema,ji as addConfigSpanEvent,jn as SeedApplySuccessSchema,jr as createWorkspaceSearchCorpus,jt as FrontmatterValueSchema,k as AgentWriteSuccessSchema,ki as OK_PROJECT_MARKER,kn as SearchSuccessSchema,kr as createCodeFenceTracker,kt as FrontmatterPatchRequestSchema,la as toJSONSchema,li as resolveInternalHref,ln as PROTOCOL_VERSION,lr as TemplatesListSuccessSchema,m as releaseServerLock,ma as $ZodType,mi as toBridgeInvariantLog,mn as RenamePathRequestSchema,mr as TrashCleanupSuccessSchema,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as preprocess,ni as parseFrontmatterYaml,nn as MetricsAgentPresenceSuccessSchema,nr as TagsListSuccessSchema,nt as ClientLogsRequestSchema,o as acquireServerLock,oa as unknown,oi as readFmMap,on as OrphansSuccessSchema,or as TemplateMoveSuccessSchema,ot as CreatePageRequestSchema,p as releaseProcessLock,pa as $ZodObject,pi as tagsMatchingPrefix,pn as ProblemDetailsSchema,pr as TrashCleanupRequestSchema,pt as DeadLinksSuccessSchema,q as CC1_CONTRACT_VERSION,qi as boolean,qn as SyncAbortMergeSuccessSchema,qr as iconFromClientName,qt as LocalOpAuthStatusSuccessSchema,ra as record,ri as prependFrontmatter,rn as MetricsParseHealthSuccessSchema,rr as TemplateDeleteSuccessSchema,rt as ClientLogsSuccessSchema,s as isProcessAlive,si as renderInventoryFooter,sn as PREVIEW_EMBED_STARTERS,sr as TemplatePutRequestSchema,st as CreatePageSuccessSchema,t as ProcessLockCollisionError,ta as optional,ti as normalizeBridge,tn as MarkdownManager,tr as TagsForNameSuccessSchema,tt as CheckoutResponseSchema,u as readProcessLock,ui as searchWorkspaceCorpus,un as PageHeadingsSuccessSchema,ur as TestRescanBacklinksSuccessSchema,va as safeParseAsync$1,vi as getSchema,vn as RollbackSuccessSchema,vr as WorkspaceSuccessSchema,vt as DocumentReadSuccessSchema,w as AgentUndoRequestSchema,wi as DEFAULT_EMBEDDINGS_MODEL,wr as classifyMarkdownHref,wt as EmptyRequestSchema,x as AgentBurstDiffSuccessSchema,xa as defineLazy,xi as CONFIG_SCHEMA_MAJOR_PATH,xn as SKILL_STATE_REL,xr as applyIncrementalDiff,y as ASSET_EXTENSIONS,ya as prettifyError,yi as PluginKey,yn as SANDBOXED_HTML_CSP,yr as WriteWarningSchema,yt as DuplicatePathRequestSchema,z as CC1DerivedViewPayloadSchema,zi as withConfigSpan,zn as SharePublishOwnersResponseSchema,zr as expandTagToHierarchy,zt as LINKABLE_ASSET_EXTENSIONS}from"./server-lock-BpjJj3OD-BPX9iz2A.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-s2X3YAg-.mjs";import{a as require_src$15,i as simpleGit,n as withParentLock,r as esm_default,t as createGitInstance}from"./git-handle-BSAUg1L_-Bn2h-fYS.mjs";import{r as diffLines,t as createPatch}from"./libesm-B_qVEpZ1.mjs";import{n as mimes,t as build_default}from"./build-Dt6UA4sF.mjs";import{t as require_yazl}from"./yazl-DjRp4wSy.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DesxOVHh.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-DnjwTqP3.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-C25Und0M.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-53eJIPK0.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-FwG_Za20.mjs";import{r as o$1}from"./chunk-CWQS3NFK-Co4ALolT.mjs";import"./chunk-DXB73IDG-DIKSLkPq.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-CAp625aG.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DvJz5Cpw.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-ikvLWpfV.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-B6yIPkk2.mjs";import{n as n$1}from"./chunk-3THT3N7L-DztAF386.mjs";import{t as n$2}from"./chunk-44UOCSGV-CaFxJDHm.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as 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{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import crypto$2 from"crypto";import*as zlib$1 from"zlib";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{Http2ServerRequest,constants as constants$2}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
|
|
2
2
|
`)){let e=s.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let s=JSON.parse(e.slice(17));if(typeof s==`object`&&s&&`id`in s&&typeof s.id==`string`&&`name`in s&&typeof s.name==`string`&&`docs`in s&&Array.isArray(s.docs)&&s.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in s)||typeof s.colorSeed==`string`)){let e=s;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(s)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
|
|
3
3
|
`)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let s;try{s=JSON.parse(e.slice(18))}catch{return null}if(typeof s!=`object`||!s)return null;let g=s,S=g.kind,w=g.metadata;if(typeof w!=`object`||!w)return null;let E=typeof g.docName==`string`?g.docName:null,D=typeof g.size==`number`&&Number.isFinite(g.size)?g.size:null;if(S===`bridge-merge-loss`){let e=w;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:E,size:D,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(S===`external-change-rescue`){let e=w;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:E,size:D,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}return null}return null}function formatCheckpointBodyLine(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${OK_CHECKPOINT_PREFIX}${JSON.stringify(t)}`}const OK_ACTOR_PREFIX=`ok-actor: `;function formatOkActor(e){let{summaries:t,previous_paths:s,...g}=e,S={...g};return t&&t.length>0&&(S.summaries=t),s&&s.length>0&&(S.previous_paths=s),`${OK_ACTOR_PREFIX}${JSON.stringify(S)}`}function parseOkActorObject(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,s=typeof e.agent_session==`string`?e.agent_session:null,g;if(typeof e.writer_id==`string`&&e.writer_id.length>0)g=e.writer_id;else if(s)g=`agent-${s}`;else if(t)g=t;else switch(e.display_name){case`File System`:g=`file-system`;break;case`Git (upstream)`:g=`git-upstream`;break;default:g=`openknowledge-service`}let S=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,w=parsePreviousPaths(e);return{v:1,writer_id:g,principal:t,agent_session:s,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...S&&S.length>0?{summaries:S}:{},...w&&w.length>0?{previous_paths:w}:{}}}function parsePreviousPaths(e){if(!(`previous_paths`in e)||!Array.isArray(e.previous_paths))return;let t=[];for(let s of e.previous_paths){if(typeof s!=`object`||!s)continue;let e=s;typeof e.from!=`string`||typeof e.to!=`string`||t.push({from:e.from,to:e.to})}return t}function parseOkActors(e){if(!e)return[];let t=[];for(let s of e.split(`
|
|
4
4
|
`)){let e=s.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let g;try{g=JSON.parse(e.slice(10))}catch{continue}if(typeof g!=`object`||!g)continue;let S=parseOkActorObject(g);S&&t.push(S)}return t}function okActorToShadowContributor(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function readContributors(e){let t=parseOkActors(e);return t.length>0?t.map(okActorToShadowContributor):parseContributors(e)}function formatWipSubject(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function formatReconcileSubject(e){return`reconcile: ${e}`}function formatRollbackSubject(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function formatParkSubject(e,t){return`park: ${e} -> ${t}`}function formatRenameSubject(e,t){return`rename: ${e} -> ${t}`}function formatCheckpointSubject(e){return`checkpoint: ${e}`}function formatImportSubject(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const SUBJECT_LINE_BREAK_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function stripLineBreaks(e){return e.replace(SUBJECT_LINE_BREAK_RE,` `)}function composeCommitSubject(e,t){let s=stripLineBreaks(e);if(t.length===0)return s;if(t.length>=2)return`${s} (${t.length} edits)`;let[g]=t;if(g===void 0)return s;let S=stripLineBreaks(g),w=`${s} — ${S}`;if(w.length<=72)return w;let E=`${s} — `,D=72-E.length-1;return D<=0?w.slice(0,72):`${E}${S.slice(0,D)}…`}function parseWriterId(e){return WRITER_ID_RE.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var require_suppress_tracing$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isTracingSuppressed=e.unsuppressTracing=e.suppressTracing=void 0;let t=(0,(init_esm$2(),__toCommonJS(esm_exports$2)).createContextKey)(`OpenTelemetry SDK Context Key SUPPRESS_TRACING`);function s(e){return e.setValue(t,!0)}e.suppressTracing=s;function g(e){return e.deleteValue(t)}e.unsuppressTracing=g;function S(e){return e.getValue(t)===!0}e.isTracingSuppressed=S})),require_constants$7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BAGGAGE_MAX_TOTAL_LENGTH=e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=e.BAGGAGE_MAX_NAME_VALUE_PAIRS=e.BAGGAGE_HEADER=e.BAGGAGE_ITEMS_SEPARATOR=e.BAGGAGE_PROPERTIES_SEPARATOR=e.BAGGAGE_KEY_PAIR_SEPARATOR=void 0,e.BAGGAGE_KEY_PAIR_SEPARATOR=`=`,e.BAGGAGE_PROPERTIES_SEPARATOR=`;`,e.BAGGAGE_ITEMS_SEPARATOR=`,`,e.BAGGAGE_HEADER=`baggage`,e.BAGGAGE_MAX_NAME_VALUE_PAIRS=180,e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,e.BAGGAGE_MAX_TOTAL_LENGTH=8192})),require_utils$16=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_constants$7();function g(e){return e.reduce((e,t)=>{let g=`${e}${e===``?``:s.BAGGAGE_ITEMS_SEPARATOR}${t}`;return g.length>s.BAGGAGE_MAX_TOTAL_LENGTH?e:g},``)}e.serializeKeyPairs=g;function S(e){return e.getAllEntries().map(([e,t])=>{let g=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return t.metadata!==void 0&&(g+=s.BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),g})}e.getKeyPairs=S;function w(e){if(!e)return;let g=e.indexOf(s.BAGGAGE_PROPERTIES_SEPARATOR),S=g===-1?e:e.substring(0,g),w=S.indexOf(s.BAGGAGE_KEY_PAIR_SEPARATOR);if(w<=0)return;let E=S.substring(0,w).trim(),D=S.substring(w+1).trim();if(!E||!D)return;let O,k;try{O=decodeURIComponent(E),k=decodeURIComponent(D)}catch{return}let j;if(g!==-1&&g<e.length-1){let s=e.substring(g+1);j=(0,t.baggageEntryMetadataFromString)(s)}return{key:O,value:k,metadata:j}}e.parsePairKeyValue=w;function E(e){let t={};return typeof e==`string`&&e.length>0&&e.split(s.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let s=w(e);s!==void 0&&s.value.length>0&&(t[s.key]=s.value)}),t}e.parseKeyPairsIntoRecord=E})),require_W3CBaggagePropagator$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_suppress_tracing$3(),g=require_constants$7(),S=require_utils$16();e.W3CBaggagePropagator=class{inject(e,w,E){let D=t.propagation.getBaggage(e);if(!D||(0,s.isTracingSuppressed)(e))return;let O=(0,S.getKeyPairs)(D).filter(e=>e.length<=g.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,g.BAGGAGE_MAX_NAME_VALUE_PAIRS),k=(0,S.serializeKeyPairs)(O);k.length>0&&E.set(w,g.BAGGAGE_HEADER,k)}extract(e,s,w){let E=w.get(s,g.BAGGAGE_HEADER),D=Array.isArray(E)?E.join(g.BAGGAGE_ITEMS_SEPARATOR):E;if(!D)return e;let O={};return D.length===0||(D.split(g.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let t=(0,S.parsePairKeyValue)(e);if(t){let e={value:t.value};t.metadata&&(e.metadata=t.metadata),O[t.key]=e}}),Object.entries(O).length===0)?e:t.propagation.setBaggage(e,t.propagation.createBaggage(O))}fields(){return[g.BAGGAGE_HEADER]}}})),require_anchored_clock$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AnchoredClock=void 0,e.AnchoredClock=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}})),require_attributes$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isAttributeValue=e.isAttributeKey=e.sanitizeAttributes=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function s(e){let s={};if(typeof e!=`object`||!e)return s;for(let w in e){if(!Object.prototype.hasOwnProperty.call(e,w))continue;if(!g(w)){t.diag.warn(`Invalid attribute key: ${w}`);continue}let E=e[w];if(!S(E)){t.diag.warn(`Invalid attribute value set for key: ${w}`);continue}Array.isArray(E)?s[w]=E.slice():s[w]=E}return s}e.sanitizeAttributes=s;function g(e){return typeof e==`string`&&e!==``}e.isAttributeKey=g;function S(e){return e==null?!0:Array.isArray(e)?w(e):E(typeof e)}e.isAttributeValue=S;function w(e){let t;for(let s of e){if(s==null)continue;let e=typeof s;if(e!==t){if(!t){if(E(e)){t=e;continue}return!1}return!1}}return!0}function E(e){switch(e){case`number`:case`boolean`:case`string`:return!0}return!1}})),require_logging_error_handler$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.loggingErrorHandler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2));function s(){return e=>{t.diag.error(g(e))}}e.loggingErrorHandler=s;function g(e){return typeof e==`string`?e:JSON.stringify(S(e))}function S(e){let t={},s=e;for(;s!==null;)Object.getOwnPropertyNames(s).forEach(e=>{if(t[e])return;let g=s[e];g&&(t[e]=String(g))}),s=Object.getPrototypeOf(s);return t}})),require_global_error_handler$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,require_logging_error_handler$3().loggingErrorHandler)();function s(e){t=e}e.setGlobalErrorHandler=s;function g(e){try{t(e)}catch{}}e.globalErrorHandler=g})),require_environment$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e.getNumberFromEnv=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=__require$2(`util`);function g(e){let g=process.env[e];if(g==null||g.trim()===``)return;let S=Number(g);if(isNaN(S)){t.diag.warn(`Unknown value ${(0,s.inspect)(g)} for ${e}, expected a number, using defaults`);return}return S}e.getNumberFromEnv=g;function S(e){let t=process.env[e];if(!(t==null||t.trim()===``))return t}e.getStringFromEnv=S;function w(e){let g=process.env[e]?.trim().toLowerCase();return g==null||g===``?!1:g===`true`?!0:(g===`false`||t.diag.warn(`Unknown value ${(0,s.inspect)(g)} for ${e}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}e.getBooleanFromEnv=w;function E(e){return S(e)?.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}e.getStringListFromEnv=E})),require_globalThis$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=globalThis})),require_version$6=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.7.0`}));function createConstMap(e){let t={},s=e.length;for(let g=0;g<s;g++){let s=e[g];s&&(t[String(s).toUpperCase().replace(/[-.]/g,`_`)]=s)}return t}var init_utils=__esmMin((()=>{})),TMP_AWS_LAMBDA_INVOKED_ARN,TMP_DB_SYSTEM,TMP_DB_CONNECTION_STRING,TMP_DB_USER,TMP_DB_JDBC_DRIVER_CLASSNAME,TMP_DB_NAME,TMP_DB_STATEMENT,TMP_DB_OPERATION,TMP_DB_MSSQL_INSTANCE_NAME,TMP_DB_CASSANDRA_KEYSPACE,TMP_DB_CASSANDRA_PAGE_SIZE,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,TMP_DB_CASSANDRA_TABLE,TMP_DB_CASSANDRA_IDEMPOTENCE,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,TMP_DB_CASSANDRA_COORDINATOR_ID,TMP_DB_CASSANDRA_COORDINATOR_DC,TMP_DB_HBASE_NAMESPACE,TMP_DB_REDIS_DATABASE_INDEX,TMP_DB_MONGODB_COLLECTION,TMP_DB_SQL_TABLE,TMP_EXCEPTION_TYPE,TMP_EXCEPTION_MESSAGE,TMP_EXCEPTION_STACKTRACE,TMP_EXCEPTION_ESCAPED,TMP_FAAS_TRIGGER,TMP_FAAS_EXECUTION,TMP_FAAS_DOCUMENT_COLLECTION,TMP_FAAS_DOCUMENT_OPERATION,TMP_FAAS_DOCUMENT_TIME,TMP_FAAS_DOCUMENT_NAME,TMP_FAAS_TIME,TMP_FAAS_CRON,TMP_FAAS_COLDSTART,TMP_FAAS_INVOKED_NAME,TMP_FAAS_INVOKED_PROVIDER,TMP_FAAS_INVOKED_REGION,TMP_NET_TRANSPORT,TMP_NET_PEER_IP,TMP_NET_PEER_PORT,TMP_NET_PEER_NAME,TMP_NET_HOST_IP,TMP_NET_HOST_PORT,TMP_NET_HOST_NAME,TMP_NET_HOST_CONNECTION_TYPE,TMP_NET_HOST_CONNECTION_SUBTYPE,TMP_NET_HOST_CARRIER_NAME,TMP_NET_HOST_CARRIER_MCC,TMP_NET_HOST_CARRIER_MNC,TMP_NET_HOST_CARRIER_ICC,TMP_PEER_SERVICE,TMP_ENDUSER_ID,TMP_ENDUSER_ROLE,TMP_ENDUSER_SCOPE,TMP_THREAD_ID,TMP_THREAD_NAME,TMP_CODE_FUNCTION,TMP_CODE_NAMESPACE,TMP_CODE_FILEPATH,TMP_CODE_LINENO,TMP_HTTP_METHOD,TMP_HTTP_URL,TMP_HTTP_TARGET,TMP_HTTP_HOST,TMP_HTTP_SCHEME,TMP_HTTP_STATUS_CODE,TMP_HTTP_FLAVOR,TMP_HTTP_USER_AGENT,TMP_HTTP_REQUEST_CONTENT_LENGTH,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_RESPONSE_CONTENT_LENGTH,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_SERVER_NAME,TMP_HTTP_ROUTE,TMP_HTTP_CLIENT_IP,TMP_AWS_DYNAMODB_TABLE_NAMES,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,TMP_AWS_DYNAMODB_CONSISTENT_READ,TMP_AWS_DYNAMODB_PROJECTION,TMP_AWS_DYNAMODB_LIMIT,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,TMP_AWS_DYNAMODB_INDEX_NAME,TMP_AWS_DYNAMODB_SELECT,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,TMP_AWS_DYNAMODB_TABLE_COUNT,TMP_AWS_DYNAMODB_SCAN_FORWARD,TMP_AWS_DYNAMODB_SEGMENT,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,TMP_AWS_DYNAMODB_COUNT,TMP_AWS_DYNAMODB_SCANNED_COUNT,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,TMP_MESSAGING_SYSTEM,TMP_MESSAGING_DESTINATION,TMP_MESSAGING_DESTINATION_KIND,TMP_MESSAGING_TEMP_DESTINATION,TMP_MESSAGING_PROTOCOL,TMP_MESSAGING_PROTOCOL_VERSION,TMP_MESSAGING_URL,TMP_MESSAGING_MESSAGE_ID,TMP_MESSAGING_CONVERSATION_ID,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,TMP_MESSAGING_OPERATION,TMP_MESSAGING_CONSUMER_ID,TMP_MESSAGING_RABBITMQ_ROUTING_KEY,TMP_MESSAGING_KAFKA_MESSAGE_KEY,TMP_MESSAGING_KAFKA_CONSUMER_GROUP,TMP_MESSAGING_KAFKA_CLIENT_ID,TMP_MESSAGING_KAFKA_PARTITION,TMP_MESSAGING_KAFKA_TOMBSTONE,TMP_RPC_SYSTEM,TMP_RPC_SERVICE,TMP_RPC_METHOD,TMP_RPC_GRPC_STATUS_CODE,TMP_RPC_JSONRPC_VERSION,TMP_RPC_JSONRPC_REQUEST_ID,TMP_RPC_JSONRPC_ERROR_CODE,TMP_RPC_JSONRPC_ERROR_MESSAGE,TMP_MESSAGE_TYPE,TMP_MESSAGE_ID,TMP_MESSAGE_COMPRESSED_SIZE,TMP_MESSAGE_UNCOMPRESSED_SIZE,SEMATTRS_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_DB_SYSTEM,SEMATTRS_DB_CONNECTION_STRING,SEMATTRS_DB_USER,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_NAME,SEMATTRS_DB_STATEMENT,SEMATTRS_DB_OPERATION,SEMATTRS_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_TABLE,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_HBASE_NAMESPACE,SEMATTRS_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_MONGODB_COLLECTION,SEMATTRS_DB_SQL_TABLE,SEMATTRS_EXCEPTION_TYPE,SEMATTRS_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_ESCAPED,SEMATTRS_FAAS_TRIGGER,SEMATTRS_FAAS_EXECUTION,SEMATTRS_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_TIME,SEMATTRS_FAAS_CRON,SEMATTRS_FAAS_COLDSTART,SEMATTRS_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION,SEMATTRS_NET_TRANSPORT,SEMATTRS_NET_PEER_IP,SEMATTRS_NET_PEER_PORT,SEMATTRS_NET_PEER_NAME,SEMATTRS_NET_HOST_IP,SEMATTRS_NET_HOST_PORT,SEMATTRS_NET_HOST_NAME,SEMATTRS_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_ICC,SEMATTRS_PEER_SERVICE,SEMATTRS_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE,SEMATTRS_THREAD_ID,SEMATTRS_THREAD_NAME,SEMATTRS_CODE_FUNCTION,SEMATTRS_CODE_NAMESPACE,SEMATTRS_CODE_FILEPATH,SEMATTRS_CODE_LINENO,SEMATTRS_HTTP_METHOD,SEMATTRS_HTTP_URL,SEMATTRS_HTTP_TARGET,SEMATTRS_HTTP_HOST,SEMATTRS_HTTP_SCHEME,SEMATTRS_HTTP_STATUS_CODE,SEMATTRS_HTTP_FLAVOR,SEMATTRS_HTTP_USER_AGENT,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_SERVER_NAME,SEMATTRS_HTTP_ROUTE,SEMATTRS_HTTP_CLIENT_IP,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_URL,SEMATTRS_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION,SEMATTRS_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_RPC_SYSTEM,SEMATTRS_RPC_SERVICE,SEMATTRS_RPC_METHOD,SEMATTRS_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_VERSION,SEMATTRS_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_MESSAGE_TYPE,SEMATTRS_MESSAGE_ID,SEMATTRS_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE,SemanticAttributes,TMP_DBSYSTEMVALUES_OTHER_SQL,TMP_DBSYSTEMVALUES_MSSQL,TMP_DBSYSTEMVALUES_MYSQL,TMP_DBSYSTEMVALUES_ORACLE,TMP_DBSYSTEMVALUES_DB2,TMP_DBSYSTEMVALUES_POSTGRESQL,TMP_DBSYSTEMVALUES_REDSHIFT,TMP_DBSYSTEMVALUES_HIVE,TMP_DBSYSTEMVALUES_CLOUDSCAPE,TMP_DBSYSTEMVALUES_HSQLDB,TMP_DBSYSTEMVALUES_PROGRESS,TMP_DBSYSTEMVALUES_MAXDB,TMP_DBSYSTEMVALUES_HANADB,TMP_DBSYSTEMVALUES_INGRES,TMP_DBSYSTEMVALUES_FIRSTSQL,TMP_DBSYSTEMVALUES_EDB,TMP_DBSYSTEMVALUES_CACHE,TMP_DBSYSTEMVALUES_ADABAS,TMP_DBSYSTEMVALUES_FIREBIRD,TMP_DBSYSTEMVALUES_DERBY,TMP_DBSYSTEMVALUES_FILEMAKER,TMP_DBSYSTEMVALUES_INFORMIX,TMP_DBSYSTEMVALUES_INSTANTDB,TMP_DBSYSTEMVALUES_INTERBASE,TMP_DBSYSTEMVALUES_MARIADB,TMP_DBSYSTEMVALUES_NETEZZA,TMP_DBSYSTEMVALUES_PERVASIVE,TMP_DBSYSTEMVALUES_POINTBASE,TMP_DBSYSTEMVALUES_SQLITE,TMP_DBSYSTEMVALUES_SYBASE,TMP_DBSYSTEMVALUES_TERADATA,TMP_DBSYSTEMVALUES_VERTICA,TMP_DBSYSTEMVALUES_H2,TMP_DBSYSTEMVALUES_COLDFUSION,TMP_DBSYSTEMVALUES_CASSANDRA,TMP_DBSYSTEMVALUES_HBASE,TMP_DBSYSTEMVALUES_MONGODB,TMP_DBSYSTEMVALUES_REDIS,TMP_DBSYSTEMVALUES_COUCHBASE,TMP_DBSYSTEMVALUES_COUCHDB,TMP_DBSYSTEMVALUES_COSMOSDB,TMP_DBSYSTEMVALUES_DYNAMODB,TMP_DBSYSTEMVALUES_NEO4J,TMP_DBSYSTEMVALUES_GEODE,TMP_DBSYSTEMVALUES_ELASTICSEARCH,TMP_DBSYSTEMVALUES_MEMCACHED,TMP_DBSYSTEMVALUES_COCKROACHDB,DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_DB2,DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_EDB,DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA,DBSYSTEMVALUES_H2,DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_COCKROACHDB,DbSystemValues,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_ALL,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_TWO,DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_ANY,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DbCassandraConsistencyLevelValues,TMP_FAASTRIGGERVALUES_DATASOURCE,TMP_FAASTRIGGERVALUES_HTTP,TMP_FAASTRIGGERVALUES_PUBSUB,TMP_FAASTRIGGERVALUES_TIMER,TMP_FAASTRIGGERVALUES_OTHER,FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER,FAASTRIGGERVALUES_OTHER,FaasTriggerValues,TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE,FAASDOCUMENTOPERATIONVALUES_INSERT,FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_DELETE,FaasDocumentOperationValues,TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,TMP_FAASINVOKEDPROVIDERVALUES_AWS,TMP_FAASINVOKEDPROVIDERVALUES_AZURE,TMP_FAASINVOKEDPROVIDERVALUES_GCP,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AWS,FAASINVOKEDPROVIDERVALUES_AZURE,FAASINVOKEDPROVIDERVALUES_GCP,FaasInvokedProviderValues,TMP_NETTRANSPORTVALUES_IP_TCP,TMP_NETTRANSPORTVALUES_IP_UDP,TMP_NETTRANSPORTVALUES_IP,TMP_NETTRANSPORTVALUES_UNIX,TMP_NETTRANSPORTVALUES_PIPE,TMP_NETTRANSPORTVALUES_INPROC,TMP_NETTRANSPORTVALUES_OTHER,NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_IP,NETTRANSPORTVALUES_UNIX,NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_OTHER,NetTransportValues,TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED,NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NetHostConnectionTypeValues,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_LTE,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_GSM,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_NR,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NetHostConnectionSubtypeValues,TMP_HTTPFLAVORVALUES_HTTP_1_0,TMP_HTTPFLAVORVALUES_HTTP_1_1,TMP_HTTPFLAVORVALUES_HTTP_2_0,TMP_HTTPFLAVORVALUES_SPDY,TMP_HTTPFLAVORVALUES_QUIC,HTTPFLAVORVALUES_HTTP_1_0,HTTPFLAVORVALUES_HTTP_1_1,HTTPFLAVORVALUES_HTTP_2_0,HTTPFLAVORVALUES_SPDY,HTTPFLAVORVALUES_QUIC,HttpFlavorValues,TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC,MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC,MessagingDestinationKindValues,TMP_MESSAGINGOPERATIONVALUES_RECEIVE,TMP_MESSAGINGOPERATIONVALUES_PROCESS,MESSAGINGOPERATIONVALUES_RECEIVE,MESSAGINGOPERATIONVALUES_PROCESS,MessagingOperationValues,TMP_RPCGRPCSTATUSCODEVALUES_OK,TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,RPCGRPCSTATUSCODEVALUES_OK,RPCGRPCSTATUSCODEVALUES_CANCELLED,RPCGRPCSTATUSCODEVALUES_UNKNOWN,RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,RPCGRPCSTATUSCODEVALUES_NOT_FOUND,RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,RPCGRPCSTATUSCODEVALUES_ABORTED,RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,RPCGRPCSTATUSCODEVALUES_INTERNAL,RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,RPCGRPCSTATUSCODEVALUES_DATA_LOSS,RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED,RpcGrpcStatusCodeValues,TMP_MESSAGETYPEVALUES_SENT,TMP_MESSAGETYPEVALUES_RECEIVED,MESSAGETYPEVALUES_SENT,MESSAGETYPEVALUES_RECEIVED,MessageTypeValues,init_SemanticAttributes=__esmMin((()=>{init_utils(),TMP_AWS_LAMBDA_INVOKED_ARN=`aws.lambda.invoked_arn`,TMP_DB_SYSTEM=`db.system`,TMP_DB_CONNECTION_STRING=`db.connection_string`,TMP_DB_USER=`db.user`,TMP_DB_JDBC_DRIVER_CLASSNAME=`db.jdbc.driver_classname`,TMP_DB_NAME=`db.name`,TMP_DB_STATEMENT=`db.statement`,TMP_DB_OPERATION=`db.operation`,TMP_DB_MSSQL_INSTANCE_NAME=`db.mssql.instance_name`,TMP_DB_CASSANDRA_KEYSPACE=`db.cassandra.keyspace`,TMP_DB_CASSANDRA_PAGE_SIZE=`db.cassandra.page_size`,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL=`db.cassandra.consistency_level`,TMP_DB_CASSANDRA_TABLE=`db.cassandra.table`,TMP_DB_CASSANDRA_IDEMPOTENCE=`db.cassandra.idempotence`,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT=`db.cassandra.speculative_execution_count`,TMP_DB_CASSANDRA_COORDINATOR_ID=`db.cassandra.coordinator.id`,TMP_DB_CASSANDRA_COORDINATOR_DC=`db.cassandra.coordinator.dc`,TMP_DB_HBASE_NAMESPACE=`db.hbase.namespace`,TMP_DB_REDIS_DATABASE_INDEX=`db.redis.database_index`,TMP_DB_MONGODB_COLLECTION=`db.mongodb.collection`,TMP_DB_SQL_TABLE=`db.sql.table`,TMP_EXCEPTION_TYPE=`exception.type`,TMP_EXCEPTION_MESSAGE=`exception.message`,TMP_EXCEPTION_STACKTRACE=`exception.stacktrace`,TMP_EXCEPTION_ESCAPED=`exception.escaped`,TMP_FAAS_TRIGGER=`faas.trigger`,TMP_FAAS_EXECUTION=`faas.execution`,TMP_FAAS_DOCUMENT_COLLECTION=`faas.document.collection`,TMP_FAAS_DOCUMENT_OPERATION=`faas.document.operation`,TMP_FAAS_DOCUMENT_TIME=`faas.document.time`,TMP_FAAS_DOCUMENT_NAME=`faas.document.name`,TMP_FAAS_TIME=`faas.time`,TMP_FAAS_CRON=`faas.cron`,TMP_FAAS_COLDSTART=`faas.coldstart`,TMP_FAAS_INVOKED_NAME=`faas.invoked_name`,TMP_FAAS_INVOKED_PROVIDER=`faas.invoked_provider`,TMP_FAAS_INVOKED_REGION=`faas.invoked_region`,TMP_NET_TRANSPORT=`net.transport`,TMP_NET_PEER_IP=`net.peer.ip`,TMP_NET_PEER_PORT=`net.peer.port`,TMP_NET_PEER_NAME=`net.peer.name`,TMP_NET_HOST_IP=`net.host.ip`,TMP_NET_HOST_PORT=`net.host.port`,TMP_NET_HOST_NAME=`net.host.name`,TMP_NET_HOST_CONNECTION_TYPE=`net.host.connection.type`,TMP_NET_HOST_CONNECTION_SUBTYPE=`net.host.connection.subtype`,TMP_NET_HOST_CARRIER_NAME=`net.host.carrier.name`,TMP_NET_HOST_CARRIER_MCC=`net.host.carrier.mcc`,TMP_NET_HOST_CARRIER_MNC=`net.host.carrier.mnc`,TMP_NET_HOST_CARRIER_ICC=`net.host.carrier.icc`,TMP_PEER_SERVICE=`peer.service`,TMP_ENDUSER_ID=`enduser.id`,TMP_ENDUSER_ROLE=`enduser.role`,TMP_ENDUSER_SCOPE=`enduser.scope`,TMP_THREAD_ID=`thread.id`,TMP_THREAD_NAME=`thread.name`,TMP_CODE_FUNCTION=`code.function`,TMP_CODE_NAMESPACE=`code.namespace`,TMP_CODE_FILEPATH=`code.filepath`,TMP_CODE_LINENO=`code.lineno`,TMP_HTTP_METHOD=`http.method`,TMP_HTTP_URL=`http.url`,TMP_HTTP_TARGET=`http.target`,TMP_HTTP_HOST=`http.host`,TMP_HTTP_SCHEME=`http.scheme`,TMP_HTTP_STATUS_CODE=`http.status_code`,TMP_HTTP_FLAVOR=`http.flavor`,TMP_HTTP_USER_AGENT=`http.user_agent`,TMP_HTTP_REQUEST_CONTENT_LENGTH=`http.request_content_length`,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=`http.request_content_length_uncompressed`,TMP_HTTP_RESPONSE_CONTENT_LENGTH=`http.response_content_length`,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED=`http.response_content_length_uncompressed`,TMP_HTTP_SERVER_NAME=`http.server_name`,TMP_HTTP_ROUTE=`http.route`,TMP_HTTP_CLIENT_IP=`http.client_ip`,TMP_AWS_DYNAMODB_TABLE_NAMES=`aws.dynamodb.table_names`,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY=`aws.dynamodb.consumed_capacity`,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS=`aws.dynamodb.item_collection_metrics`,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY=`aws.dynamodb.provisioned_read_capacity`,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY=`aws.dynamodb.provisioned_write_capacity`,TMP_AWS_DYNAMODB_CONSISTENT_READ=`aws.dynamodb.consistent_read`,TMP_AWS_DYNAMODB_PROJECTION=`aws.dynamodb.projection`,TMP_AWS_DYNAMODB_LIMIT=`aws.dynamodb.limit`,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET=`aws.dynamodb.attributes_to_get`,TMP_AWS_DYNAMODB_INDEX_NAME=`aws.dynamodb.index_name`,TMP_AWS_DYNAMODB_SELECT=`aws.dynamodb.select`,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES=`aws.dynamodb.global_secondary_indexes`,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES=`aws.dynamodb.local_secondary_indexes`,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE=`aws.dynamodb.exclusive_start_table`,TMP_AWS_DYNAMODB_TABLE_COUNT=`aws.dynamodb.table_count`,TMP_AWS_DYNAMODB_SCAN_FORWARD=`aws.dynamodb.scan_forward`,TMP_AWS_DYNAMODB_SEGMENT=`aws.dynamodb.segment`,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS=`aws.dynamodb.total_segments`,TMP_AWS_DYNAMODB_COUNT=`aws.dynamodb.count`,TMP_AWS_DYNAMODB_SCANNED_COUNT=`aws.dynamodb.scanned_count`,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS=`aws.dynamodb.attribute_definitions`,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES=`aws.dynamodb.global_secondary_index_updates`,TMP_MESSAGING_SYSTEM=`messaging.system`,TMP_MESSAGING_DESTINATION=`messaging.destination`,TMP_MESSAGING_DESTINATION_KIND=`messaging.destination_kind`,TMP_MESSAGING_TEMP_DESTINATION=`messaging.temp_destination`,TMP_MESSAGING_PROTOCOL=`messaging.protocol`,TMP_MESSAGING_PROTOCOL_VERSION=`messaging.protocol_version`,TMP_MESSAGING_URL=`messaging.url`,TMP_MESSAGING_MESSAGE_ID=`messaging.message_id`,TMP_MESSAGING_CONVERSATION_ID=`messaging.conversation_id`,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES=`messaging.message_payload_size_bytes`,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES=`messaging.message_payload_compressed_size_bytes`,TMP_MESSAGING_OPERATION=`messaging.operation`,TMP_MESSAGING_CONSUMER_ID=`messaging.consumer_id`,TMP_MESSAGING_RABBITMQ_ROUTING_KEY=`messaging.rabbitmq.routing_key`,TMP_MESSAGING_KAFKA_MESSAGE_KEY=`messaging.kafka.message_key`,TMP_MESSAGING_KAFKA_CONSUMER_GROUP=`messaging.kafka.consumer_group`,TMP_MESSAGING_KAFKA_CLIENT_ID=`messaging.kafka.client_id`,TMP_MESSAGING_KAFKA_PARTITION=`messaging.kafka.partition`,TMP_MESSAGING_KAFKA_TOMBSTONE=`messaging.kafka.tombstone`,TMP_RPC_SYSTEM=`rpc.system`,TMP_RPC_SERVICE=`rpc.service`,TMP_RPC_METHOD=`rpc.method`,TMP_RPC_GRPC_STATUS_CODE=`rpc.grpc.status_code`,TMP_RPC_JSONRPC_VERSION=`rpc.jsonrpc.version`,TMP_RPC_JSONRPC_REQUEST_ID=`rpc.jsonrpc.request_id`,TMP_RPC_JSONRPC_ERROR_CODE=`rpc.jsonrpc.error_code`,TMP_RPC_JSONRPC_ERROR_MESSAGE=`rpc.jsonrpc.error_message`,TMP_MESSAGE_TYPE=`message.type`,TMP_MESSAGE_ID=`message.id`,TMP_MESSAGE_COMPRESSED_SIZE=`message.compressed_size`,TMP_MESSAGE_UNCOMPRESSED_SIZE=`message.uncompressed_size`,SEMATTRS_AWS_LAMBDA_INVOKED_ARN=TMP_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_DB_SYSTEM=TMP_DB_SYSTEM,SEMATTRS_DB_CONNECTION_STRING=TMP_DB_CONNECTION_STRING,SEMATTRS_DB_USER=TMP_DB_USER,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME=TMP_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_NAME=TMP_DB_NAME,SEMATTRS_DB_STATEMENT=TMP_DB_STATEMENT,SEMATTRS_DB_OPERATION=TMP_DB_OPERATION,SEMATTRS_DB_MSSQL_INSTANCE_NAME=TMP_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_CASSANDRA_KEYSPACE=TMP_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE=TMP_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL=TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_TABLE=TMP_DB_CASSANDRA_TABLE,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE=TMP_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT=TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID=TMP_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC=TMP_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_HBASE_NAMESPACE=TMP_DB_HBASE_NAMESPACE,SEMATTRS_DB_REDIS_DATABASE_INDEX=TMP_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_MONGODB_COLLECTION=TMP_DB_MONGODB_COLLECTION,SEMATTRS_DB_SQL_TABLE=TMP_DB_SQL_TABLE,SEMATTRS_EXCEPTION_TYPE=TMP_EXCEPTION_TYPE,SEMATTRS_EXCEPTION_MESSAGE=TMP_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE=TMP_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_ESCAPED=TMP_EXCEPTION_ESCAPED,SEMATTRS_FAAS_TRIGGER=TMP_FAAS_TRIGGER,SEMATTRS_FAAS_EXECUTION=TMP_FAAS_EXECUTION,SEMATTRS_FAAS_DOCUMENT_COLLECTION=TMP_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_OPERATION=TMP_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME=TMP_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_DOCUMENT_NAME=TMP_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_TIME=TMP_FAAS_TIME,SEMATTRS_FAAS_CRON=TMP_FAAS_CRON,SEMATTRS_FAAS_COLDSTART=TMP_FAAS_COLDSTART,SEMATTRS_FAAS_INVOKED_NAME=TMP_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER=TMP_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION=TMP_FAAS_INVOKED_REGION,SEMATTRS_NET_TRANSPORT=TMP_NET_TRANSPORT,SEMATTRS_NET_PEER_IP=TMP_NET_PEER_IP,SEMATTRS_NET_PEER_PORT=TMP_NET_PEER_PORT,SEMATTRS_NET_PEER_NAME=TMP_NET_PEER_NAME,SEMATTRS_NET_HOST_IP=TMP_NET_HOST_IP,SEMATTRS_NET_HOST_PORT=TMP_NET_HOST_PORT,SEMATTRS_NET_HOST_NAME=TMP_NET_HOST_NAME,SEMATTRS_NET_HOST_CONNECTION_TYPE=TMP_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE=TMP_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CARRIER_NAME=TMP_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CARRIER_MCC=TMP_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC=TMP_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_ICC=TMP_NET_HOST_CARRIER_ICC,SEMATTRS_PEER_SERVICE=TMP_PEER_SERVICE,SEMATTRS_ENDUSER_ID=TMP_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE=TMP_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE=TMP_ENDUSER_SCOPE,SEMATTRS_THREAD_ID=TMP_THREAD_ID,SEMATTRS_THREAD_NAME=TMP_THREAD_NAME,SEMATTRS_CODE_FUNCTION=TMP_CODE_FUNCTION,SEMATTRS_CODE_NAMESPACE=TMP_CODE_NAMESPACE,SEMATTRS_CODE_FILEPATH=TMP_CODE_FILEPATH,SEMATTRS_CODE_LINENO=TMP_CODE_LINENO,SEMATTRS_HTTP_METHOD=TMP_HTTP_METHOD,SEMATTRS_HTTP_URL=TMP_HTTP_URL,SEMATTRS_HTTP_TARGET=TMP_HTTP_TARGET,SEMATTRS_HTTP_HOST=TMP_HTTP_HOST,SEMATTRS_HTTP_SCHEME=TMP_HTTP_SCHEME,SEMATTRS_HTTP_STATUS_CODE=TMP_HTTP_STATUS_CODE,SEMATTRS_HTTP_FLAVOR=TMP_HTTP_FLAVOR,SEMATTRS_HTTP_USER_AGENT=TMP_HTTP_USER_AGENT,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH=TMP_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH=TMP_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED=TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_SERVER_NAME=TMP_HTTP_SERVER_NAME,SEMATTRS_HTTP_ROUTE=TMP_HTTP_ROUTE,SEMATTRS_HTTP_CLIENT_IP=TMP_HTTP_CLIENT_IP,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES=TMP_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY=TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS=TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY=TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY=TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ=TMP_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_PROJECTION=TMP_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_LIMIT=TMP_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET=TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_INDEX_NAME=TMP_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_SELECT=TMP_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES=TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES=TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE=TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT=TMP_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD=TMP_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT=TMP_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS=TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_DYNAMODB_COUNT=TMP_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT=TMP_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS=TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES=TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_MESSAGING_SYSTEM=TMP_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_DESTINATION=TMP_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND=TMP_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_TEMP_DESTINATION=TMP_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_PROTOCOL=TMP_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION=TMP_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_URL=TMP_MESSAGING_URL,SEMATTRS_MESSAGING_MESSAGE_ID=TMP_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_CONVERSATION_ID=TMP_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES=TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES=TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION=TMP_MESSAGING_OPERATION,SEMATTRS_MESSAGING_CONSUMER_ID=TMP_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY=TMP_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY=TMP_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP=TMP_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID=TMP_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_PARTITION=TMP_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE=TMP_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_RPC_SYSTEM=TMP_RPC_SYSTEM,SEMATTRS_RPC_SERVICE=TMP_RPC_SERVICE,SEMATTRS_RPC_METHOD=TMP_RPC_METHOD,SEMATTRS_RPC_GRPC_STATUS_CODE=TMP_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_VERSION=TMP_RPC_JSONRPC_VERSION,SEMATTRS_RPC_JSONRPC_REQUEST_ID=TMP_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_ERROR_CODE=TMP_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE=TMP_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_MESSAGE_TYPE=TMP_MESSAGE_TYPE,SEMATTRS_MESSAGE_ID=TMP_MESSAGE_ID,SEMATTRS_MESSAGE_COMPRESSED_SIZE=TMP_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE=TMP_MESSAGE_UNCOMPRESSED_SIZE,SemanticAttributes=createConstMap([TMP_AWS_LAMBDA_INVOKED_ARN,TMP_DB_SYSTEM,TMP_DB_CONNECTION_STRING,TMP_DB_USER,TMP_DB_JDBC_DRIVER_CLASSNAME,TMP_DB_NAME,TMP_DB_STATEMENT,TMP_DB_OPERATION,TMP_DB_MSSQL_INSTANCE_NAME,TMP_DB_CASSANDRA_KEYSPACE,TMP_DB_CASSANDRA_PAGE_SIZE,TMP_DB_CASSANDRA_CONSISTENCY_LEVEL,TMP_DB_CASSANDRA_TABLE,TMP_DB_CASSANDRA_IDEMPOTENCE,TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,TMP_DB_CASSANDRA_COORDINATOR_ID,TMP_DB_CASSANDRA_COORDINATOR_DC,TMP_DB_HBASE_NAMESPACE,TMP_DB_REDIS_DATABASE_INDEX,TMP_DB_MONGODB_COLLECTION,TMP_DB_SQL_TABLE,TMP_EXCEPTION_TYPE,TMP_EXCEPTION_MESSAGE,TMP_EXCEPTION_STACKTRACE,TMP_EXCEPTION_ESCAPED,TMP_FAAS_TRIGGER,TMP_FAAS_EXECUTION,TMP_FAAS_DOCUMENT_COLLECTION,TMP_FAAS_DOCUMENT_OPERATION,TMP_FAAS_DOCUMENT_TIME,TMP_FAAS_DOCUMENT_NAME,TMP_FAAS_TIME,TMP_FAAS_CRON,TMP_FAAS_COLDSTART,TMP_FAAS_INVOKED_NAME,TMP_FAAS_INVOKED_PROVIDER,TMP_FAAS_INVOKED_REGION,TMP_NET_TRANSPORT,TMP_NET_PEER_IP,TMP_NET_PEER_PORT,TMP_NET_PEER_NAME,TMP_NET_HOST_IP,TMP_NET_HOST_PORT,TMP_NET_HOST_NAME,TMP_NET_HOST_CONNECTION_TYPE,TMP_NET_HOST_CONNECTION_SUBTYPE,TMP_NET_HOST_CARRIER_NAME,TMP_NET_HOST_CARRIER_MCC,TMP_NET_HOST_CARRIER_MNC,TMP_NET_HOST_CARRIER_ICC,TMP_PEER_SERVICE,TMP_ENDUSER_ID,TMP_ENDUSER_ROLE,TMP_ENDUSER_SCOPE,TMP_THREAD_ID,TMP_THREAD_NAME,TMP_CODE_FUNCTION,TMP_CODE_NAMESPACE,TMP_CODE_FILEPATH,TMP_CODE_LINENO,TMP_HTTP_METHOD,TMP_HTTP_URL,TMP_HTTP_TARGET,TMP_HTTP_HOST,TMP_HTTP_SCHEME,TMP_HTTP_STATUS_CODE,TMP_HTTP_FLAVOR,TMP_HTTP_USER_AGENT,TMP_HTTP_REQUEST_CONTENT_LENGTH,TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_RESPONSE_CONTENT_LENGTH,TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,TMP_HTTP_SERVER_NAME,TMP_HTTP_ROUTE,TMP_HTTP_CLIENT_IP,TMP_AWS_DYNAMODB_TABLE_NAMES,TMP_AWS_DYNAMODB_CONSUMED_CAPACITY,TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,TMP_AWS_DYNAMODB_CONSISTENT_READ,TMP_AWS_DYNAMODB_PROJECTION,TMP_AWS_DYNAMODB_LIMIT,TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET,TMP_AWS_DYNAMODB_INDEX_NAME,TMP_AWS_DYNAMODB_SELECT,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,TMP_AWS_DYNAMODB_TABLE_COUNT,TMP_AWS_DYNAMODB_SCAN_FORWARD,TMP_AWS_DYNAMODB_SEGMENT,TMP_AWS_DYNAMODB_TOTAL_SEGMENTS,TMP_AWS_DYNAMODB_COUNT,TMP_AWS_DYNAMODB_SCANNED_COUNT,TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,TMP_MESSAGING_SYSTEM,TMP_MESSAGING_DESTINATION,TMP_MESSAGING_DESTINATION_KIND,TMP_MESSAGING_TEMP_DESTINATION,TMP_MESSAGING_PROTOCOL,TMP_MESSAGING_PROTOCOL_VERSION,TMP_MESSAGING_URL,TMP_MESSAGING_MESSAGE_ID,TMP_MESSAGING_CONVERSATION_ID,TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,TMP_MESSAGING_OPERATION,TMP_MESSAGING_CONSUMER_ID,TMP_MESSAGING_RABBITMQ_ROUTING_KEY,TMP_MESSAGING_KAFKA_MESSAGE_KEY,TMP_MESSAGING_KAFKA_CONSUMER_GROUP,TMP_MESSAGING_KAFKA_CLIENT_ID,TMP_MESSAGING_KAFKA_PARTITION,TMP_MESSAGING_KAFKA_TOMBSTONE,TMP_RPC_SYSTEM,TMP_RPC_SERVICE,TMP_RPC_METHOD,TMP_RPC_GRPC_STATUS_CODE,TMP_RPC_JSONRPC_VERSION,TMP_RPC_JSONRPC_REQUEST_ID,TMP_RPC_JSONRPC_ERROR_CODE,TMP_RPC_JSONRPC_ERROR_MESSAGE,TMP_MESSAGE_TYPE,TMP_MESSAGE_ID,TMP_MESSAGE_COMPRESSED_SIZE,TMP_MESSAGE_UNCOMPRESSED_SIZE]),TMP_DBSYSTEMVALUES_OTHER_SQL=`other_sql`,TMP_DBSYSTEMVALUES_MSSQL=`mssql`,TMP_DBSYSTEMVALUES_MYSQL=`mysql`,TMP_DBSYSTEMVALUES_ORACLE=`oracle`,TMP_DBSYSTEMVALUES_DB2=`db2`,TMP_DBSYSTEMVALUES_POSTGRESQL=`postgresql`,TMP_DBSYSTEMVALUES_REDSHIFT=`redshift`,TMP_DBSYSTEMVALUES_HIVE=`hive`,TMP_DBSYSTEMVALUES_CLOUDSCAPE=`cloudscape`,TMP_DBSYSTEMVALUES_HSQLDB=`hsqldb`,TMP_DBSYSTEMVALUES_PROGRESS=`progress`,TMP_DBSYSTEMVALUES_MAXDB=`maxdb`,TMP_DBSYSTEMVALUES_HANADB=`hanadb`,TMP_DBSYSTEMVALUES_INGRES=`ingres`,TMP_DBSYSTEMVALUES_FIRSTSQL=`firstsql`,TMP_DBSYSTEMVALUES_EDB=`edb`,TMP_DBSYSTEMVALUES_CACHE=`cache`,TMP_DBSYSTEMVALUES_ADABAS=`adabas`,TMP_DBSYSTEMVALUES_FIREBIRD=`firebird`,TMP_DBSYSTEMVALUES_DERBY=`derby`,TMP_DBSYSTEMVALUES_FILEMAKER=`filemaker`,TMP_DBSYSTEMVALUES_INFORMIX=`informix`,TMP_DBSYSTEMVALUES_INSTANTDB=`instantdb`,TMP_DBSYSTEMVALUES_INTERBASE=`interbase`,TMP_DBSYSTEMVALUES_MARIADB=`mariadb`,TMP_DBSYSTEMVALUES_NETEZZA=`netezza`,TMP_DBSYSTEMVALUES_PERVASIVE=`pervasive`,TMP_DBSYSTEMVALUES_POINTBASE=`pointbase`,TMP_DBSYSTEMVALUES_SQLITE=`sqlite`,TMP_DBSYSTEMVALUES_SYBASE=`sybase`,TMP_DBSYSTEMVALUES_TERADATA=`teradata`,TMP_DBSYSTEMVALUES_VERTICA=`vertica`,TMP_DBSYSTEMVALUES_H2=`h2`,TMP_DBSYSTEMVALUES_COLDFUSION=`coldfusion`,TMP_DBSYSTEMVALUES_CASSANDRA=`cassandra`,TMP_DBSYSTEMVALUES_HBASE=`hbase`,TMP_DBSYSTEMVALUES_MONGODB=`mongodb`,TMP_DBSYSTEMVALUES_REDIS=`redis`,TMP_DBSYSTEMVALUES_COUCHBASE=`couchbase`,TMP_DBSYSTEMVALUES_COUCHDB=`couchdb`,TMP_DBSYSTEMVALUES_COSMOSDB=`cosmosdb`,TMP_DBSYSTEMVALUES_DYNAMODB=`dynamodb`,TMP_DBSYSTEMVALUES_NEO4J=`neo4j`,TMP_DBSYSTEMVALUES_GEODE=`geode`,TMP_DBSYSTEMVALUES_ELASTICSEARCH=`elasticsearch`,TMP_DBSYSTEMVALUES_MEMCACHED=`memcached`,TMP_DBSYSTEMVALUES_COCKROACHDB=`cockroachdb`,DBSYSTEMVALUES_OTHER_SQL=TMP_DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_MSSQL=TMP_DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL=TMP_DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_ORACLE=TMP_DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_POSTGRESQL=TMP_DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_REDSHIFT=TMP_DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_HIVE=TMP_DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_CLOUDSCAPE=TMP_DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_HSQLDB=TMP_DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_PROGRESS=TMP_DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_MAXDB=TMP_DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_HANADB=TMP_DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_INGRES=TMP_DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_FIRSTSQL=TMP_DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_CACHE=TMP_DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_ADABAS=TMP_DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_FIREBIRD=TMP_DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_DERBY=TMP_DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_FILEMAKER=TMP_DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_INFORMIX=TMP_DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INSTANTDB=TMP_DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE=TMP_DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB=TMP_DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_NETEZZA=TMP_DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_PERVASIVE=TMP_DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE=TMP_DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_SQLITE=TMP_DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE=TMP_DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA=TMP_DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA=TMP_DBSYSTEMVALUES_VERTICA,DBSYSTEMVALUES_COLDFUSION=TMP_DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_CASSANDRA=TMP_DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_HBASE=TMP_DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_MONGODB=TMP_DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_REDIS=TMP_DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_COUCHBASE=TMP_DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB=TMP_DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_COSMOSDB=TMP_DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_DYNAMODB=TMP_DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_NEO4J=TMP_DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_GEODE=TMP_DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_ELASTICSEARCH=TMP_DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_MEMCACHED=TMP_DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_COCKROACHDB=TMP_DBSYSTEMVALUES_COCKROACHDB,DbSystemValues=createConstMap([TMP_DBSYSTEMVALUES_OTHER_SQL,TMP_DBSYSTEMVALUES_MSSQL,TMP_DBSYSTEMVALUES_MYSQL,TMP_DBSYSTEMVALUES_ORACLE,TMP_DBSYSTEMVALUES_DB2,TMP_DBSYSTEMVALUES_POSTGRESQL,TMP_DBSYSTEMVALUES_REDSHIFT,TMP_DBSYSTEMVALUES_HIVE,TMP_DBSYSTEMVALUES_CLOUDSCAPE,TMP_DBSYSTEMVALUES_HSQLDB,TMP_DBSYSTEMVALUES_PROGRESS,TMP_DBSYSTEMVALUES_MAXDB,TMP_DBSYSTEMVALUES_HANADB,TMP_DBSYSTEMVALUES_INGRES,TMP_DBSYSTEMVALUES_FIRSTSQL,TMP_DBSYSTEMVALUES_EDB,TMP_DBSYSTEMVALUES_CACHE,TMP_DBSYSTEMVALUES_ADABAS,TMP_DBSYSTEMVALUES_FIREBIRD,TMP_DBSYSTEMVALUES_DERBY,TMP_DBSYSTEMVALUES_FILEMAKER,TMP_DBSYSTEMVALUES_INFORMIX,TMP_DBSYSTEMVALUES_INSTANTDB,TMP_DBSYSTEMVALUES_INTERBASE,TMP_DBSYSTEMVALUES_MARIADB,TMP_DBSYSTEMVALUES_NETEZZA,TMP_DBSYSTEMVALUES_PERVASIVE,TMP_DBSYSTEMVALUES_POINTBASE,TMP_DBSYSTEMVALUES_SQLITE,TMP_DBSYSTEMVALUES_SYBASE,TMP_DBSYSTEMVALUES_TERADATA,TMP_DBSYSTEMVALUES_VERTICA,TMP_DBSYSTEMVALUES_H2,TMP_DBSYSTEMVALUES_COLDFUSION,TMP_DBSYSTEMVALUES_CASSANDRA,TMP_DBSYSTEMVALUES_HBASE,TMP_DBSYSTEMVALUES_MONGODB,TMP_DBSYSTEMVALUES_REDIS,TMP_DBSYSTEMVALUES_COUCHBASE,TMP_DBSYSTEMVALUES_COUCHDB,TMP_DBSYSTEMVALUES_COSMOSDB,TMP_DBSYSTEMVALUES_DYNAMODB,TMP_DBSYSTEMVALUES_NEO4J,TMP_DBSYSTEMVALUES_GEODE,TMP_DBSYSTEMVALUES_ELASTICSEARCH,TMP_DBSYSTEMVALUES_MEMCACHED,TMP_DBSYSTEMVALUES_COCKROACHDB]),TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL=`all`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM=`each_quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM=`quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM=`local_quorum`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE=`one`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO=`two`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE=`three`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE=`local_one`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY=`any`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL=`serial`,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL=`local_serial`,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_THREE=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL=TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DbCassandraConsistencyLevelValues=createConstMap([TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL]),TMP_FAASTRIGGERVALUES_DATASOURCE=`datasource`,TMP_FAASTRIGGERVALUES_HTTP=`http`,TMP_FAASTRIGGERVALUES_PUBSUB=`pubsub`,TMP_FAASTRIGGERVALUES_TIMER=`timer`,TMP_FAASTRIGGERVALUES_OTHER=`other`,FAASTRIGGERVALUES_DATASOURCE=TMP_FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP=TMP_FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_PUBSUB=TMP_FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER=TMP_FAASTRIGGERVALUES_TIMER,FAASTRIGGERVALUES_OTHER=TMP_FAASTRIGGERVALUES_OTHER,FaasTriggerValues=createConstMap([TMP_FAASTRIGGERVALUES_DATASOURCE,TMP_FAASTRIGGERVALUES_HTTP,TMP_FAASTRIGGERVALUES_PUBSUB,TMP_FAASTRIGGERVALUES_TIMER,TMP_FAASTRIGGERVALUES_OTHER]),TMP_FAASDOCUMENTOPERATIONVALUES_INSERT=`insert`,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT=`edit`,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE=`delete`,FAASDOCUMENTOPERATIONVALUES_INSERT=TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,FAASDOCUMENTOPERATIONVALUES_EDIT=TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_DELETE=TMP_FAASDOCUMENTOPERATIONVALUES_DELETE,FaasDocumentOperationValues=createConstMap([TMP_FAASDOCUMENTOPERATIONVALUES_INSERT,TMP_FAASDOCUMENTOPERATIONVALUES_EDIT,TMP_FAASDOCUMENTOPERATIONVALUES_DELETE]),TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD=`alibaba_cloud`,TMP_FAASINVOKEDPROVIDERVALUES_AWS=`aws`,TMP_FAASINVOKEDPROVIDERVALUES_AZURE=`azure`,TMP_FAASINVOKEDPROVIDERVALUES_GCP=`gcp`,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD=TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AZURE=TMP_FAASINVOKEDPROVIDERVALUES_AZURE,FaasInvokedProviderValues=createConstMap([TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,TMP_FAASINVOKEDPROVIDERVALUES_AWS,TMP_FAASINVOKEDPROVIDERVALUES_AZURE,TMP_FAASINVOKEDPROVIDERVALUES_GCP]),TMP_NETTRANSPORTVALUES_IP_TCP=`ip_tcp`,TMP_NETTRANSPORTVALUES_IP_UDP=`ip_udp`,TMP_NETTRANSPORTVALUES_IP=`ip`,TMP_NETTRANSPORTVALUES_UNIX=`unix`,TMP_NETTRANSPORTVALUES_PIPE=`pipe`,TMP_NETTRANSPORTVALUES_INPROC=`inproc`,TMP_NETTRANSPORTVALUES_OTHER=`other`,NETTRANSPORTVALUES_IP_TCP=TMP_NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP=TMP_NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_UNIX=TMP_NETTRANSPORTVALUES_UNIX,NETTRANSPORTVALUES_PIPE=TMP_NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_INPROC=TMP_NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_OTHER=TMP_NETTRANSPORTVALUES_OTHER,NetTransportValues=createConstMap([TMP_NETTRANSPORTVALUES_IP_TCP,TMP_NETTRANSPORTVALUES_IP_UDP,TMP_NETTRANSPORTVALUES_IP,TMP_NETTRANSPORTVALUES_UNIX,TMP_NETTRANSPORTVALUES_PIPE,TMP_NETTRANSPORTVALUES_INPROC,TMP_NETTRANSPORTVALUES_OTHER]),TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI=`wifi`,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED=`wired`,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL=`cell`,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE=`unavailable`,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN=`unknown`,NETHOSTCONNECTIONTYPEVALUES_WIFI=TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED=TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,NETHOSTCONNECTIONTYPEVALUES_CELL=TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE=TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN=TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NetHostConnectionTypeValues=createConstMap([TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI,TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED,TMP_NETHOSTCONNECTIONTYPEVALUES_CELL,TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN]),TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS=`gprs`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE=`edge`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS=`umts`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA=`cdma`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0=`evdo_0`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A=`evdo_a`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT=`cdma2000_1xrtt`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA=`hsdpa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA=`hsupa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA=`hspa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN=`iden`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B=`evdo_b`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE=`lte`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD=`ehrpd`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP=`hspap`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM=`gsm`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA=`td_scdma`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN=`iwlan`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR=`nr`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA=`nrnsa`,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA=`lte_ca`,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA=TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NetHostConnectionSubtypeValues=createConstMap([TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA]),TMP_HTTPFLAVORVALUES_HTTP_1_0=`1.0`,TMP_HTTPFLAVORVALUES_HTTP_1_1=`1.1`,TMP_HTTPFLAVORVALUES_HTTP_2_0=`2.0`,TMP_HTTPFLAVORVALUES_SPDY=`SPDY`,TMP_HTTPFLAVORVALUES_QUIC=`QUIC`,HTTPFLAVORVALUES_SPDY=TMP_HTTPFLAVORVALUES_SPDY,HTTPFLAVORVALUES_QUIC=TMP_HTTPFLAVORVALUES_QUIC,HttpFlavorValues={HTTP_1_0:TMP_HTTPFLAVORVALUES_HTTP_1_0,HTTP_1_1:TMP_HTTPFLAVORVALUES_HTTP_1_1,HTTP_2_0:TMP_HTTPFLAVORVALUES_HTTP_2_0,SPDY:TMP_HTTPFLAVORVALUES_SPDY,QUIC:TMP_HTTPFLAVORVALUES_QUIC},TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE=`queue`,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC=`topic`,MESSAGINGDESTINATIONKINDVALUES_QUEUE=TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC=TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC,MessagingDestinationKindValues=createConstMap([TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE,TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC]),TMP_MESSAGINGOPERATIONVALUES_RECEIVE=`receive`,TMP_MESSAGINGOPERATIONVALUES_PROCESS=`process`,MESSAGINGOPERATIONVALUES_RECEIVE=TMP_MESSAGINGOPERATIONVALUES_RECEIVE,MESSAGINGOPERATIONVALUES_PROCESS=TMP_MESSAGINGOPERATIONVALUES_PROCESS,MessagingOperationValues=createConstMap([TMP_MESSAGINGOPERATIONVALUES_RECEIVE,TMP_MESSAGINGOPERATIONVALUES_PROCESS]),TMP_RPCGRPCSTATUSCODEVALUES_OK=0,TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED=1,TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN=2,TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT=3,TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED=4,TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND=5,TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS=6,TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED=7,TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED=8,TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION=9,TMP_RPCGRPCSTATUSCODEVALUES_ABORTED=10,TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE=11,TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED=12,TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL=13,TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE=14,TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS=15,TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED=16,RpcGrpcStatusCodeValues={OK:TMP_RPCGRPCSTATUSCODEVALUES_OK,CANCELLED:TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED,UNKNOWN:TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN,INVALID_ARGUMENT:TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT,DEADLINE_EXCEEDED:TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED,NOT_FOUND:TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND,ALREADY_EXISTS:TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS,PERMISSION_DENIED:TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED,RESOURCE_EXHAUSTED:TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED,FAILED_PRECONDITION:TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION,ABORTED:TMP_RPCGRPCSTATUSCODEVALUES_ABORTED,OUT_OF_RANGE:TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE,UNIMPLEMENTED:TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED,INTERNAL:TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL,UNAVAILABLE:TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE,DATA_LOSS:TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS,UNAUTHENTICATED:TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED},TMP_MESSAGETYPEVALUES_SENT=`SENT`,TMP_MESSAGETYPEVALUES_RECEIVED=`RECEIVED`,MESSAGETYPEVALUES_SENT=TMP_MESSAGETYPEVALUES_SENT,MESSAGETYPEVALUES_RECEIVED=TMP_MESSAGETYPEVALUES_RECEIVED,MessageTypeValues=createConstMap([TMP_MESSAGETYPEVALUES_SENT,TMP_MESSAGETYPEVALUES_RECEIVED])})),init_trace=__esmMin((()=>{init_SemanticAttributes()})),TMP_CLOUD_PROVIDER,TMP_CLOUD_ACCOUNT_ID,TMP_CLOUD_REGION,TMP_CLOUD_AVAILABILITY_ZONE,TMP_CLOUD_PLATFORM,TMP_AWS_ECS_CONTAINER_ARN,TMP_AWS_ECS_CLUSTER_ARN,TMP_AWS_ECS_LAUNCHTYPE,TMP_AWS_ECS_TASK_ARN,TMP_AWS_ECS_TASK_FAMILY,TMP_AWS_ECS_TASK_REVISION,TMP_AWS_EKS_CLUSTER_ARN,TMP_AWS_LOG_GROUP_NAMES,TMP_AWS_LOG_GROUP_ARNS,TMP_AWS_LOG_STREAM_NAMES,TMP_AWS_LOG_STREAM_ARNS,TMP_CONTAINER_NAME,TMP_CONTAINER_ID,TMP_CONTAINER_RUNTIME,TMP_CONTAINER_IMAGE_NAME,TMP_CONTAINER_IMAGE_TAG,TMP_DEPLOYMENT_ENVIRONMENT,TMP_DEVICE_ID,TMP_DEVICE_MODEL_IDENTIFIER,TMP_DEVICE_MODEL_NAME,TMP_FAAS_NAME,TMP_FAAS_ID,TMP_FAAS_VERSION,TMP_FAAS_INSTANCE,TMP_FAAS_MAX_MEMORY,TMP_HOST_ID,TMP_HOST_NAME,TMP_HOST_TYPE,TMP_HOST_ARCH,TMP_HOST_IMAGE_NAME,TMP_HOST_IMAGE_ID,TMP_HOST_IMAGE_VERSION,TMP_K8S_CLUSTER_NAME,TMP_K8S_NODE_NAME,TMP_K8S_NODE_UID,TMP_K8S_NAMESPACE_NAME,TMP_K8S_POD_UID,TMP_K8S_POD_NAME,TMP_K8S_CONTAINER_NAME,TMP_K8S_REPLICASET_UID,TMP_K8S_REPLICASET_NAME,TMP_K8S_DEPLOYMENT_UID,TMP_K8S_DEPLOYMENT_NAME,TMP_K8S_STATEFULSET_UID,TMP_K8S_STATEFULSET_NAME,TMP_K8S_DAEMONSET_UID,TMP_K8S_DAEMONSET_NAME,TMP_K8S_JOB_UID,TMP_K8S_JOB_NAME,TMP_K8S_CRONJOB_UID,TMP_K8S_CRONJOB_NAME,TMP_OS_TYPE,TMP_OS_DESCRIPTION,TMP_OS_NAME,TMP_OS_VERSION,TMP_PROCESS_PID,TMP_PROCESS_EXECUTABLE_NAME,TMP_PROCESS_EXECUTABLE_PATH,TMP_PROCESS_COMMAND,TMP_PROCESS_COMMAND_LINE,TMP_PROCESS_COMMAND_ARGS,TMP_PROCESS_OWNER,TMP_PROCESS_RUNTIME_NAME,TMP_PROCESS_RUNTIME_VERSION,TMP_PROCESS_RUNTIME_DESCRIPTION,TMP_SERVICE_NAME,TMP_SERVICE_NAMESPACE,TMP_SERVICE_INSTANCE_ID,TMP_SERVICE_VERSION,TMP_TELEMETRY_SDK_NAME,TMP_TELEMETRY_SDK_LANGUAGE,TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRY_AUTO_VERSION,TMP_WEBENGINE_NAME,TMP_WEBENGINE_VERSION,TMP_WEBENGINE_DESCRIPTION,SEMRESATTRS_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_REGION,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM,SEMRESATTRS_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS,SEMRESATTRS_CONTAINER_NAME,SEMRESATTRS_CONTAINER_ID,SEMRESATTRS_CONTAINER_RUNTIME,SEMRESATTRS_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_NAME,SEMRESATTRS_FAAS_ID,SEMRESATTRS_FAAS_VERSION,SEMRESATTRS_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY,SEMRESATTRS_HOST_ID,SEMRESATTRS_HOST_NAME,SEMRESATTRS_HOST_TYPE,SEMRESATTRS_HOST_ARCH,SEMRESATTRS_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_VERSION,SEMRESATTRS_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID,SEMRESATTRS_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_POD_UID,SEMRESATTRS_K8S_POD_NAME,SEMRESATTRS_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_REPLICASET_UID,SEMRESATTRS_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_STATEFULSET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_JOB_UID,SEMRESATTRS_K8S_JOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID,SEMRESATTRS_K8S_CRONJOB_NAME,SEMRESATTRS_OS_TYPE,SEMRESATTRS_OS_DESCRIPTION,SEMRESATTRS_OS_NAME,SEMRESATTRS_OS_VERSION,SEMRESATTRS_PROCESS_PID,SEMRESATTRS_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_OWNER,SEMRESATTRS_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION,SEMRESATTRS_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION,SemanticResourceAttributes,TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,TMP_CLOUDPROVIDERVALUES_AWS,TMP_CLOUDPROVIDERVALUES_AZURE,TMP_CLOUDPROVIDERVALUES_GCP,CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AWS,CLOUDPROVIDERVALUES_AZURE,CLOUDPROVIDERVALUES_GCP,CloudProviderValues,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,TMP_CLOUDPLATFORMVALUES_AWS_EC2,TMP_CLOUDPLATFORMVALUES_AWS_ECS,TMP_CLOUDPLATFORMVALUES_AWS_EKS,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,TMP_CLOUDPLATFORMVALUES_AZURE_VM,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,TMP_CLOUDPLATFORMVALUES_AZURE_AKS,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CloudPlatformValues,TMP_AWSECSLAUNCHTYPEVALUES_EC2,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE,AWSECSLAUNCHTYPEVALUES_EC2,AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues,TMP_HOSTARCHVALUES_AMD64,TMP_HOSTARCHVALUES_ARM32,TMP_HOSTARCHVALUES_ARM64,TMP_HOSTARCHVALUES_IA64,TMP_HOSTARCHVALUES_PPC32,TMP_HOSTARCHVALUES_PPC64,TMP_HOSTARCHVALUES_X86,HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64,HOSTARCHVALUES_X86,HostArchValues,TMP_OSTYPEVALUES_WINDOWS,TMP_OSTYPEVALUES_LINUX,TMP_OSTYPEVALUES_DARWIN,TMP_OSTYPEVALUES_FREEBSD,TMP_OSTYPEVALUES_NETBSD,TMP_OSTYPEVALUES_OPENBSD,TMP_OSTYPEVALUES_DRAGONFLYBSD,TMP_OSTYPEVALUES_HPUX,TMP_OSTYPEVALUES_AIX,TMP_OSTYPEVALUES_SOLARIS,TMP_OSTYPEVALUES_Z_OS,OSTYPEVALUES_WINDOWS,OSTYPEVALUES_LINUX,OSTYPEVALUES_DARWIN,OSTYPEVALUES_FREEBSD,OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD,OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_HPUX,OSTYPEVALUES_AIX,OSTYPEVALUES_SOLARIS,OSTYPEVALUES_Z_OS,OsTypeValues,TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TMP_TELEMETRYSDKLANGUAGEVALUES_GO,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,TELEMETRYSDKLANGUAGEVALUES_CPP,TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_GO,TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PHP,TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS,TelemetrySdkLanguageValues,init_SemanticResourceAttributes=__esmMin((()=>{init_utils(),TMP_CLOUD_PROVIDER=`cloud.provider`,TMP_CLOUD_ACCOUNT_ID=`cloud.account.id`,TMP_CLOUD_REGION=`cloud.region`,TMP_CLOUD_AVAILABILITY_ZONE=`cloud.availability_zone`,TMP_CLOUD_PLATFORM=`cloud.platform`,TMP_AWS_ECS_CONTAINER_ARN=`aws.ecs.container.arn`,TMP_AWS_ECS_CLUSTER_ARN=`aws.ecs.cluster.arn`,TMP_AWS_ECS_LAUNCHTYPE=`aws.ecs.launchtype`,TMP_AWS_ECS_TASK_ARN=`aws.ecs.task.arn`,TMP_AWS_ECS_TASK_FAMILY=`aws.ecs.task.family`,TMP_AWS_ECS_TASK_REVISION=`aws.ecs.task.revision`,TMP_AWS_EKS_CLUSTER_ARN=`aws.eks.cluster.arn`,TMP_AWS_LOG_GROUP_NAMES=`aws.log.group.names`,TMP_AWS_LOG_GROUP_ARNS=`aws.log.group.arns`,TMP_AWS_LOG_STREAM_NAMES=`aws.log.stream.names`,TMP_AWS_LOG_STREAM_ARNS=`aws.log.stream.arns`,TMP_CONTAINER_NAME=`container.name`,TMP_CONTAINER_ID=`container.id`,TMP_CONTAINER_RUNTIME=`container.runtime`,TMP_CONTAINER_IMAGE_NAME=`container.image.name`,TMP_CONTAINER_IMAGE_TAG=`container.image.tag`,TMP_DEPLOYMENT_ENVIRONMENT=`deployment.environment`,TMP_DEVICE_ID=`device.id`,TMP_DEVICE_MODEL_IDENTIFIER=`device.model.identifier`,TMP_DEVICE_MODEL_NAME=`device.model.name`,TMP_FAAS_NAME=`faas.name`,TMP_FAAS_ID=`faas.id`,TMP_FAAS_VERSION=`faas.version`,TMP_FAAS_INSTANCE=`faas.instance`,TMP_FAAS_MAX_MEMORY=`faas.max_memory`,TMP_HOST_ID=`host.id`,TMP_HOST_NAME=`host.name`,TMP_HOST_TYPE=`host.type`,TMP_HOST_ARCH=`host.arch`,TMP_HOST_IMAGE_NAME=`host.image.name`,TMP_HOST_IMAGE_ID=`host.image.id`,TMP_HOST_IMAGE_VERSION=`host.image.version`,TMP_K8S_CLUSTER_NAME=`k8s.cluster.name`,TMP_K8S_NODE_NAME=`k8s.node.name`,TMP_K8S_NODE_UID=`k8s.node.uid`,TMP_K8S_NAMESPACE_NAME=`k8s.namespace.name`,TMP_K8S_POD_UID=`k8s.pod.uid`,TMP_K8S_POD_NAME=`k8s.pod.name`,TMP_K8S_CONTAINER_NAME=`k8s.container.name`,TMP_K8S_REPLICASET_UID=`k8s.replicaset.uid`,TMP_K8S_REPLICASET_NAME=`k8s.replicaset.name`,TMP_K8S_DEPLOYMENT_UID=`k8s.deployment.uid`,TMP_K8S_DEPLOYMENT_NAME=`k8s.deployment.name`,TMP_K8S_STATEFULSET_UID=`k8s.statefulset.uid`,TMP_K8S_STATEFULSET_NAME=`k8s.statefulset.name`,TMP_K8S_DAEMONSET_UID=`k8s.daemonset.uid`,TMP_K8S_DAEMONSET_NAME=`k8s.daemonset.name`,TMP_K8S_JOB_UID=`k8s.job.uid`,TMP_K8S_JOB_NAME=`k8s.job.name`,TMP_K8S_CRONJOB_UID=`k8s.cronjob.uid`,TMP_K8S_CRONJOB_NAME=`k8s.cronjob.name`,TMP_OS_TYPE=`os.type`,TMP_OS_DESCRIPTION=`os.description`,TMP_OS_NAME=`os.name`,TMP_OS_VERSION=`os.version`,TMP_PROCESS_PID=`process.pid`,TMP_PROCESS_EXECUTABLE_NAME=`process.executable.name`,TMP_PROCESS_EXECUTABLE_PATH=`process.executable.path`,TMP_PROCESS_COMMAND=`process.command`,TMP_PROCESS_COMMAND_LINE=`process.command_line`,TMP_PROCESS_COMMAND_ARGS=`process.command_args`,TMP_PROCESS_OWNER=`process.owner`,TMP_PROCESS_RUNTIME_NAME=`process.runtime.name`,TMP_PROCESS_RUNTIME_VERSION=`process.runtime.version`,TMP_PROCESS_RUNTIME_DESCRIPTION=`process.runtime.description`,TMP_SERVICE_NAME=`service.name`,TMP_SERVICE_NAMESPACE=`service.namespace`,TMP_SERVICE_INSTANCE_ID=`service.instance.id`,TMP_SERVICE_VERSION=`service.version`,TMP_TELEMETRY_SDK_NAME=`telemetry.sdk.name`,TMP_TELEMETRY_SDK_LANGUAGE=`telemetry.sdk.language`,TMP_TELEMETRY_SDK_VERSION=`telemetry.sdk.version`,TMP_TELEMETRY_AUTO_VERSION=`telemetry.auto.version`,TMP_WEBENGINE_NAME=`webengine.name`,TMP_WEBENGINE_VERSION=`webengine.version`,TMP_WEBENGINE_DESCRIPTION=`webengine.description`,SEMRESATTRS_CLOUD_PROVIDER=TMP_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_ACCOUNT_ID=TMP_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_REGION=TMP_CLOUD_REGION,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE=TMP_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM=TMP_CLOUD_PLATFORM,SEMRESATTRS_AWS_ECS_CONTAINER_ARN=TMP_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_CLUSTER_ARN=TMP_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE=TMP_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN=TMP_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY=TMP_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION=TMP_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN=TMP_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_NAMES=TMP_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_GROUP_ARNS=TMP_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES=TMP_AWS_LOG_STREAM_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS=TMP_AWS_LOG_STREAM_ARNS,SEMRESATTRS_CONTAINER_NAME=TMP_CONTAINER_NAME,SEMRESATTRS_CONTAINER_ID=TMP_CONTAINER_ID,SEMRESATTRS_CONTAINER_RUNTIME=TMP_CONTAINER_RUNTIME,SEMRESATTRS_CONTAINER_IMAGE_NAME=TMP_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG=TMP_CONTAINER_IMAGE_TAG,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT=TMP_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID=TMP_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER=TMP_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME=TMP_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_NAME=TMP_FAAS_NAME,SEMRESATTRS_FAAS_ID=TMP_FAAS_ID,SEMRESATTRS_FAAS_VERSION=TMP_FAAS_VERSION,SEMRESATTRS_FAAS_INSTANCE=TMP_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY=TMP_FAAS_MAX_MEMORY,SEMRESATTRS_HOST_ID=TMP_HOST_ID,SEMRESATTRS_HOST_NAME=TMP_HOST_NAME,SEMRESATTRS_HOST_TYPE=TMP_HOST_TYPE,SEMRESATTRS_HOST_ARCH=TMP_HOST_ARCH,SEMRESATTRS_HOST_IMAGE_NAME=TMP_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_ID=TMP_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_VERSION=TMP_HOST_IMAGE_VERSION,SEMRESATTRS_K8S_CLUSTER_NAME=TMP_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_NODE_NAME=TMP_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID=TMP_K8S_NODE_UID,SEMRESATTRS_K8S_NAMESPACE_NAME=TMP_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_POD_UID=TMP_K8S_POD_UID,SEMRESATTRS_K8S_POD_NAME=TMP_K8S_POD_NAME,SEMRESATTRS_K8S_CONTAINER_NAME=TMP_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_REPLICASET_UID=TMP_K8S_REPLICASET_UID,SEMRESATTRS_K8S_REPLICASET_NAME=TMP_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID=TMP_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME=TMP_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_STATEFULSET_UID=TMP_K8S_STATEFULSET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME=TMP_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID=TMP_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DAEMONSET_NAME=TMP_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_JOB_UID=TMP_K8S_JOB_UID,SEMRESATTRS_K8S_JOB_NAME=TMP_K8S_JOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID=TMP_K8S_CRONJOB_UID,SEMRESATTRS_K8S_CRONJOB_NAME=TMP_K8S_CRONJOB_NAME,SEMRESATTRS_OS_TYPE=TMP_OS_TYPE,SEMRESATTRS_OS_DESCRIPTION=TMP_OS_DESCRIPTION,SEMRESATTRS_OS_NAME=TMP_OS_NAME,SEMRESATTRS_OS_VERSION=TMP_OS_VERSION,SEMRESATTRS_PROCESS_PID=TMP_PROCESS_PID,SEMRESATTRS_PROCESS_EXECUTABLE_NAME=TMP_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH=TMP_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_COMMAND=TMP_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_LINE=TMP_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_COMMAND_ARGS=TMP_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_OWNER=TMP_PROCESS_OWNER,SEMRESATTRS_PROCESS_RUNTIME_NAME=TMP_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION=TMP_PROCESS_RUNTIME_VERSION,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION=TMP_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_SERVICE_NAME=TMP_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE=TMP_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_INSTANCE_ID=TMP_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_VERSION=TMP_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_SDK_NAME=TMP_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE=TMP_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION=TMP_TELEMETRY_SDK_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION=TMP_TELEMETRY_AUTO_VERSION,SEMRESATTRS_WEBENGINE_NAME=TMP_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION=TMP_WEBENGINE_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION=TMP_WEBENGINE_DESCRIPTION,SemanticResourceAttributes=createConstMap([TMP_CLOUD_PROVIDER,TMP_CLOUD_ACCOUNT_ID,TMP_CLOUD_REGION,TMP_CLOUD_AVAILABILITY_ZONE,TMP_CLOUD_PLATFORM,TMP_AWS_ECS_CONTAINER_ARN,TMP_AWS_ECS_CLUSTER_ARN,TMP_AWS_ECS_LAUNCHTYPE,TMP_AWS_ECS_TASK_ARN,TMP_AWS_ECS_TASK_FAMILY,TMP_AWS_ECS_TASK_REVISION,TMP_AWS_EKS_CLUSTER_ARN,TMP_AWS_LOG_GROUP_NAMES,TMP_AWS_LOG_GROUP_ARNS,TMP_AWS_LOG_STREAM_NAMES,TMP_AWS_LOG_STREAM_ARNS,TMP_CONTAINER_NAME,TMP_CONTAINER_ID,TMP_CONTAINER_RUNTIME,TMP_CONTAINER_IMAGE_NAME,TMP_CONTAINER_IMAGE_TAG,TMP_DEPLOYMENT_ENVIRONMENT,TMP_DEVICE_ID,TMP_DEVICE_MODEL_IDENTIFIER,TMP_DEVICE_MODEL_NAME,TMP_FAAS_NAME,TMP_FAAS_ID,TMP_FAAS_VERSION,TMP_FAAS_INSTANCE,TMP_FAAS_MAX_MEMORY,TMP_HOST_ID,TMP_HOST_NAME,TMP_HOST_TYPE,TMP_HOST_ARCH,TMP_HOST_IMAGE_NAME,TMP_HOST_IMAGE_ID,TMP_HOST_IMAGE_VERSION,TMP_K8S_CLUSTER_NAME,TMP_K8S_NODE_NAME,TMP_K8S_NODE_UID,TMP_K8S_NAMESPACE_NAME,TMP_K8S_POD_UID,TMP_K8S_POD_NAME,TMP_K8S_CONTAINER_NAME,TMP_K8S_REPLICASET_UID,TMP_K8S_REPLICASET_NAME,TMP_K8S_DEPLOYMENT_UID,TMP_K8S_DEPLOYMENT_NAME,TMP_K8S_STATEFULSET_UID,TMP_K8S_STATEFULSET_NAME,TMP_K8S_DAEMONSET_UID,TMP_K8S_DAEMONSET_NAME,TMP_K8S_JOB_UID,TMP_K8S_JOB_NAME,TMP_K8S_CRONJOB_UID,TMP_K8S_CRONJOB_NAME,TMP_OS_TYPE,TMP_OS_DESCRIPTION,TMP_OS_NAME,TMP_OS_VERSION,TMP_PROCESS_PID,TMP_PROCESS_EXECUTABLE_NAME,TMP_PROCESS_EXECUTABLE_PATH,TMP_PROCESS_COMMAND,TMP_PROCESS_COMMAND_LINE,TMP_PROCESS_COMMAND_ARGS,TMP_PROCESS_OWNER,TMP_PROCESS_RUNTIME_NAME,TMP_PROCESS_RUNTIME_VERSION,TMP_PROCESS_RUNTIME_DESCRIPTION,TMP_SERVICE_NAME,TMP_SERVICE_NAMESPACE,TMP_SERVICE_INSTANCE_ID,TMP_SERVICE_VERSION,TMP_TELEMETRY_SDK_NAME,TMP_TELEMETRY_SDK_LANGUAGE,TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRY_AUTO_VERSION,TMP_WEBENGINE_NAME,TMP_WEBENGINE_VERSION,TMP_WEBENGINE_DESCRIPTION]),TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD=`alibaba_cloud`,TMP_CLOUDPROVIDERVALUES_AWS=`aws`,TMP_CLOUDPROVIDERVALUES_AZURE=`azure`,TMP_CLOUDPROVIDERVALUES_GCP=`gcp`,CLOUDPROVIDERVALUES_ALIBABA_CLOUD=TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AZURE=TMP_CLOUDPROVIDERVALUES_AZURE,CloudProviderValues=createConstMap([TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD,TMP_CLOUDPROVIDERVALUES_AWS,TMP_CLOUDPROVIDERVALUES_AZURE,TMP_CLOUDPROVIDERVALUES_GCP]),TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS=`alibaba_cloud_ecs`,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC=`alibaba_cloud_fc`,TMP_CLOUDPLATFORMVALUES_AWS_EC2=`aws_ec2`,TMP_CLOUDPLATFORMVALUES_AWS_ECS=`aws_ecs`,TMP_CLOUDPLATFORMVALUES_AWS_EKS=`aws_eks`,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA=`aws_lambda`,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK=`aws_elastic_beanstalk`,TMP_CLOUDPLATFORMVALUES_AZURE_VM=`azure_vm`,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES=`azure_container_instances`,TMP_CLOUDPLATFORMVALUES_AZURE_AKS=`azure_aks`,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS=`azure_functions`,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE=`azure_app_service`,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE=`gcp_compute_engine`,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN=`gcp_cloud_run`,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE=`gcp_kubernetes_engine`,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS=`gcp_cloud_functions`,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE=`gcp_app_engine`,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS=TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC=TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2=TMP_CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS=TMP_CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS=TMP_CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_LAMBDA=TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK=TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AZURE_VM=TMP_CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES=TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_AKS=TMP_CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS=TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE=TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN=TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS=TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_APP_ENGINE=TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CloudPlatformValues=createConstMap([TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,TMP_CLOUDPLATFORMVALUES_AWS_EC2,TMP_CLOUDPLATFORMVALUES_AWS_ECS,TMP_CLOUDPLATFORMVALUES_AWS_EKS,TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA,TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,TMP_CLOUDPLATFORMVALUES_AZURE_VM,TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,TMP_CLOUDPLATFORMVALUES_AZURE_AKS,TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE]),TMP_AWSECSLAUNCHTYPEVALUES_EC2=`ec2`,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE=`fargate`,AWSECSLAUNCHTYPEVALUES_FARGATE=TMP_AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues=createConstMap([TMP_AWSECSLAUNCHTYPEVALUES_EC2,TMP_AWSECSLAUNCHTYPEVALUES_FARGATE]),TMP_HOSTARCHVALUES_AMD64=`amd64`,TMP_HOSTARCHVALUES_ARM32=`arm32`,TMP_HOSTARCHVALUES_ARM64=`arm64`,TMP_HOSTARCHVALUES_IA64=`ia64`,TMP_HOSTARCHVALUES_PPC32=`ppc32`,TMP_HOSTARCHVALUES_PPC64=`ppc64`,TMP_HOSTARCHVALUES_X86=`x86`,HOSTARCHVALUES_AMD64=TMP_HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32=TMP_HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64=TMP_HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64=TMP_HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32=TMP_HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64=TMP_HOSTARCHVALUES_PPC64,HostArchValues=createConstMap([TMP_HOSTARCHVALUES_AMD64,TMP_HOSTARCHVALUES_ARM32,TMP_HOSTARCHVALUES_ARM64,TMP_HOSTARCHVALUES_IA64,TMP_HOSTARCHVALUES_PPC32,TMP_HOSTARCHVALUES_PPC64,TMP_HOSTARCHVALUES_X86]),TMP_OSTYPEVALUES_WINDOWS=`windows`,TMP_OSTYPEVALUES_LINUX=`linux`,TMP_OSTYPEVALUES_DARWIN=`darwin`,TMP_OSTYPEVALUES_FREEBSD=`freebsd`,TMP_OSTYPEVALUES_NETBSD=`netbsd`,TMP_OSTYPEVALUES_OPENBSD=`openbsd`,TMP_OSTYPEVALUES_DRAGONFLYBSD=`dragonflybsd`,TMP_OSTYPEVALUES_HPUX=`hpux`,TMP_OSTYPEVALUES_AIX=`aix`,TMP_OSTYPEVALUES_SOLARIS=`solaris`,TMP_OSTYPEVALUES_Z_OS=`z_os`,OSTYPEVALUES_WINDOWS=TMP_OSTYPEVALUES_WINDOWS,OSTYPEVALUES_LINUX=TMP_OSTYPEVALUES_LINUX,OSTYPEVALUES_DARWIN=TMP_OSTYPEVALUES_DARWIN,OSTYPEVALUES_FREEBSD=TMP_OSTYPEVALUES_FREEBSD,OSTYPEVALUES_NETBSD=TMP_OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD=TMP_OSTYPEVALUES_OPENBSD,OSTYPEVALUES_DRAGONFLYBSD=TMP_OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_HPUX=TMP_OSTYPEVALUES_HPUX,OSTYPEVALUES_SOLARIS=TMP_OSTYPEVALUES_SOLARIS,OSTYPEVALUES_Z_OS=TMP_OSTYPEVALUES_Z_OS,OsTypeValues=createConstMap([TMP_OSTYPEVALUES_WINDOWS,TMP_OSTYPEVALUES_LINUX,TMP_OSTYPEVALUES_DARWIN,TMP_OSTYPEVALUES_FREEBSD,TMP_OSTYPEVALUES_NETBSD,TMP_OSTYPEVALUES_OPENBSD,TMP_OSTYPEVALUES_DRAGONFLYBSD,TMP_OSTYPEVALUES_HPUX,TMP_OSTYPEVALUES_AIX,TMP_OSTYPEVALUES_SOLARIS,TMP_OSTYPEVALUES_Z_OS]),TMP_TELEMETRYSDKLANGUAGEVALUES_CPP=`cpp`,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET=`dotnet`,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG=`erlang`,TMP_TELEMETRYSDKLANGUAGEVALUES_GO=`go`,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA=`java`,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS=`nodejs`,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP=`php`,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON=`python`,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY=`ruby`,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS=`webjs`,TELEMETRYSDKLANGUAGEVALUES_DOTNET=TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG=TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_JAVA=TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS=TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PYTHON=TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY=TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS=TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,TelemetrySdkLanguageValues=createConstMap([TMP_TELEMETRYSDKLANGUAGEVALUES_CPP,TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET,TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG,TMP_TELEMETRYSDKLANGUAGEVALUES_GO,TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA,TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS,TMP_TELEMETRYSDKLANGUAGEVALUES_PHP,TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON,TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS])})),init_resource=__esmMin((()=>{init_SemanticResourceAttributes()})),ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE,ATTR_ASPNETCORE_RATE_LIMITING_POLICY,ATTR_ASPNETCORE_RATE_LIMITING_RESULT,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED,ATTR_CLIENT_ADDRESS,ATTR_CLIENT_PORT,ATTR_CODE_COLUMN_NUMBER,ATTR_CODE_FILE_PATH,ATTR_CODE_FUNCTION_NAME,ATTR_CODE_LINE_NUMBER,ATTR_CODE_STACKTRACE,ATTR_DB_COLLECTION_NAME,ATTR_DB_NAMESPACE,ATTR_DB_OPERATION_BATCH_SIZE,ATTR_DB_OPERATION_NAME,ATTR_DB_QUERY_SUMMARY,ATTR_DB_QUERY_TEXT,ATTR_DB_RESPONSE_STATUS_CODE,ATTR_DB_STORED_PROCEDURE_NAME,ATTR_DB_SYSTEM_NAME,DB_SYSTEM_NAME_VALUE_MARIADB,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER,DB_SYSTEM_NAME_VALUE_MYSQL,DB_SYSTEM_NAME_VALUE_POSTGRESQL,ATTR_DOTNET_GC_HEAP_GENERATION,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2,DOTNET_GC_HEAP_GENERATION_VALUE_LOH,DOTNET_GC_HEAP_GENERATION_VALUE_POH,ATTR_ERROR_TYPE,ERROR_TYPE_VALUE_OTHER,ATTR_EXCEPTION_ESCAPED,ATTR_EXCEPTION_MESSAGE,ATTR_EXCEPTION_STACKTRACE,ATTR_EXCEPTION_TYPE,ATTR_HTTP_REQUEST_HEADER,ATTR_HTTP_REQUEST_METHOD,HTTP_REQUEST_METHOD_VALUE_OTHER,HTTP_REQUEST_METHOD_VALUE_CONNECT,HTTP_REQUEST_METHOD_VALUE_DELETE,HTTP_REQUEST_METHOD_VALUE_GET,HTTP_REQUEST_METHOD_VALUE_HEAD,HTTP_REQUEST_METHOD_VALUE_OPTIONS,HTTP_REQUEST_METHOD_VALUE_PATCH,HTTP_REQUEST_METHOD_VALUE_POST,HTTP_REQUEST_METHOD_VALUE_PUT,HTTP_REQUEST_METHOD_VALUE_TRACE,ATTR_HTTP_REQUEST_METHOD_ORIGINAL,ATTR_HTTP_REQUEST_RESEND_COUNT,ATTR_HTTP_RESPONSE_HEADER,ATTR_HTTP_RESPONSE_STATUS_CODE,ATTR_HTTP_ROUTE,ATTR_JVM_GC_ACTION,ATTR_JVM_GC_NAME,ATTR_JVM_MEMORY_POOL_NAME,ATTR_JVM_MEMORY_TYPE,JVM_MEMORY_TYPE_VALUE_HEAP,JVM_MEMORY_TYPE_VALUE_NON_HEAP,ATTR_JVM_THREAD_DAEMON,ATTR_JVM_THREAD_STATE,JVM_THREAD_STATE_VALUE_BLOCKED,JVM_THREAD_STATE_VALUE_NEW,JVM_THREAD_STATE_VALUE_RUNNABLE,JVM_THREAD_STATE_VALUE_TERMINATED,JVM_THREAD_STATE_VALUE_TIMED_WAITING,JVM_THREAD_STATE_VALUE_WAITING,ATTR_NETWORK_LOCAL_ADDRESS,ATTR_NETWORK_LOCAL_PORT,ATTR_NETWORK_PEER_ADDRESS,ATTR_NETWORK_PEER_PORT,ATTR_NETWORK_PROTOCOL_NAME,ATTR_NETWORK_PROTOCOL_VERSION,ATTR_NETWORK_TRANSPORT,NETWORK_TRANSPORT_VALUE_PIPE,NETWORK_TRANSPORT_VALUE_QUIC,NETWORK_TRANSPORT_VALUE_TCP,NETWORK_TRANSPORT_VALUE_UDP,NETWORK_TRANSPORT_VALUE_UNIX,ATTR_NETWORK_TYPE,NETWORK_TYPE_VALUE_IPV4,NETWORK_TYPE_VALUE_IPV6,ATTR_OTEL_SCOPE_NAME,ATTR_OTEL_SCOPE_VERSION,ATTR_OTEL_STATUS_CODE,OTEL_STATUS_CODE_VALUE_ERROR,OTEL_STATUS_CODE_VALUE_OK,ATTR_OTEL_STATUS_DESCRIPTION,ATTR_SERVER_ADDRESS,ATTR_SERVER_PORT,ATTR_SERVICE_INSTANCE_ID,ATTR_SERVICE_NAME,ATTR_SERVICE_NAMESPACE,ATTR_SERVICE_VERSION,ATTR_SIGNALR_CONNECTION_STATUS,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT,ATTR_SIGNALR_TRANSPORT,SIGNALR_TRANSPORT_VALUE_LONG_POLLING,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS,ATTR_TELEMETRY_SDK_LANGUAGE,TELEMETRY_SDK_LANGUAGE_VALUE_CPP,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG,TELEMETRY_SDK_LANGUAGE_VALUE_GO,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,TELEMETRY_SDK_LANGUAGE_VALUE_PHP,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY,TELEMETRY_SDK_LANGUAGE_VALUE_RUST,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,ATTR_TELEMETRY_SDK_NAME,ATTR_TELEMETRY_SDK_VERSION,ATTR_URL_FRAGMENT,ATTR_URL_FULL,ATTR_URL_PATH,ATTR_URL_QUERY,ATTR_URL_SCHEME,ATTR_USER_AGENT_ORIGINAL,init_stable_attributes=__esmMin((()=>{ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT=`aspnetcore.diagnostics.exception.result`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED=`aborted`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED=`handled`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED=`skipped`,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED=`unhandled`,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE=`aspnetcore.diagnostics.handler.type`,ATTR_ASPNETCORE_RATE_LIMITING_POLICY=`aspnetcore.rate_limiting.policy`,ATTR_ASPNETCORE_RATE_LIMITING_RESULT=`aspnetcore.rate_limiting.result`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED=`acquired`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER=`endpoint_limiter`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER=`global_limiter`,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED=`request_canceled`,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED=`aspnetcore.request.is_unhandled`,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK=`aspnetcore.routing.is_fallback`,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS=`aspnetcore.routing.match_status`,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE=`failure`,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS=`success`,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED=`aspnetcore.user.is_authenticated`,ATTR_CLIENT_ADDRESS=`client.address`,ATTR_CLIENT_PORT=`client.port`,ATTR_CODE_COLUMN_NUMBER=`code.column.number`,ATTR_CODE_FILE_PATH=`code.file.path`,ATTR_CODE_FUNCTION_NAME=`code.function.name`,ATTR_CODE_LINE_NUMBER=`code.line.number`,ATTR_CODE_STACKTRACE=`code.stacktrace`,ATTR_DB_COLLECTION_NAME=`db.collection.name`,ATTR_DB_NAMESPACE=`db.namespace`,ATTR_DB_OPERATION_BATCH_SIZE=`db.operation.batch.size`,ATTR_DB_OPERATION_NAME=`db.operation.name`,ATTR_DB_QUERY_SUMMARY=`db.query.summary`,ATTR_DB_QUERY_TEXT=`db.query.text`,ATTR_DB_RESPONSE_STATUS_CODE=`db.response.status_code`,ATTR_DB_STORED_PROCEDURE_NAME=`db.stored_procedure.name`,ATTR_DB_SYSTEM_NAME=`db.system.name`,DB_SYSTEM_NAME_VALUE_MARIADB=`mariadb`,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER=`microsoft.sql_server`,DB_SYSTEM_NAME_VALUE_MYSQL=`mysql`,DB_SYSTEM_NAME_VALUE_POSTGRESQL=`postgresql`,ATTR_DOTNET_GC_HEAP_GENERATION=`dotnet.gc.heap.generation`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0=`gen0`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1=`gen1`,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2=`gen2`,ATTR_ERROR_TYPE=`error.type`,ERROR_TYPE_VALUE_OTHER=`_OTHER`,ATTR_EXCEPTION_ESCAPED=`exception.escaped`,ATTR_EXCEPTION_MESSAGE=`exception.message`,ATTR_EXCEPTION_STACKTRACE=`exception.stacktrace`,ATTR_EXCEPTION_TYPE=`exception.type`,ATTR_HTTP_REQUEST_HEADER=e=>`http.request.header.${e}`,ATTR_HTTP_REQUEST_METHOD=`http.request.method`,HTTP_REQUEST_METHOD_VALUE_OTHER=`_OTHER`,HTTP_REQUEST_METHOD_VALUE_CONNECT=`CONNECT`,HTTP_REQUEST_METHOD_VALUE_DELETE=`DELETE`,HTTP_REQUEST_METHOD_VALUE_HEAD=`HEAD`,HTTP_REQUEST_METHOD_VALUE_OPTIONS=`OPTIONS`,HTTP_REQUEST_METHOD_VALUE_PATCH=`PATCH`,HTTP_REQUEST_METHOD_VALUE_POST=`POST`,HTTP_REQUEST_METHOD_VALUE_TRACE=`TRACE`,ATTR_HTTP_REQUEST_METHOD_ORIGINAL=`http.request.method_original`,ATTR_HTTP_REQUEST_RESEND_COUNT=`http.request.resend_count`,ATTR_HTTP_RESPONSE_HEADER=e=>`http.response.header.${e}`,ATTR_HTTP_RESPONSE_STATUS_CODE=`http.response.status_code`,ATTR_HTTP_ROUTE=`http.route`,ATTR_JVM_GC_ACTION=`jvm.gc.action`,ATTR_JVM_GC_NAME=`jvm.gc.name`,ATTR_JVM_MEMORY_POOL_NAME=`jvm.memory.pool.name`,ATTR_JVM_MEMORY_TYPE=`jvm.memory.type`,JVM_MEMORY_TYPE_VALUE_HEAP=`heap`,JVM_MEMORY_TYPE_VALUE_NON_HEAP=`non_heap`,ATTR_JVM_THREAD_DAEMON=`jvm.thread.daemon`,ATTR_JVM_THREAD_STATE=`jvm.thread.state`,JVM_THREAD_STATE_VALUE_BLOCKED=`blocked`,JVM_THREAD_STATE_VALUE_RUNNABLE=`runnable`,JVM_THREAD_STATE_VALUE_TERMINATED=`terminated`,JVM_THREAD_STATE_VALUE_TIMED_WAITING=`timed_waiting`,JVM_THREAD_STATE_VALUE_WAITING=`waiting`,ATTR_NETWORK_LOCAL_ADDRESS=`network.local.address`,ATTR_NETWORK_LOCAL_PORT=`network.local.port`,ATTR_NETWORK_PEER_ADDRESS=`network.peer.address`,ATTR_NETWORK_PEER_PORT=`network.peer.port`,ATTR_NETWORK_PROTOCOL_NAME=`network.protocol.name`,ATTR_NETWORK_PROTOCOL_VERSION=`network.protocol.version`,ATTR_NETWORK_TRANSPORT=`network.transport`,NETWORK_TRANSPORT_VALUE_PIPE=`pipe`,NETWORK_TRANSPORT_VALUE_QUIC=`quic`,NETWORK_TRANSPORT_VALUE_UNIX=`unix`,ATTR_NETWORK_TYPE=`network.type`,NETWORK_TYPE_VALUE_IPV4=`ipv4`,NETWORK_TYPE_VALUE_IPV6=`ipv6`,ATTR_OTEL_SCOPE_NAME=`otel.scope.name`,ATTR_OTEL_SCOPE_VERSION=`otel.scope.version`,ATTR_OTEL_STATUS_CODE=`otel.status_code`,OTEL_STATUS_CODE_VALUE_ERROR=`ERROR`,ATTR_OTEL_STATUS_DESCRIPTION=`otel.status_description`,ATTR_SERVER_ADDRESS=`server.address`,ATTR_SERVER_PORT=`server.port`,ATTR_SERVICE_INSTANCE_ID=`service.instance.id`,ATTR_SERVICE_NAME=`service.name`,ATTR_SERVICE_NAMESPACE=`service.namespace`,ATTR_SERVICE_VERSION=`service.version`,ATTR_SIGNALR_CONNECTION_STATUS=`signalr.connection.status`,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN=`app_shutdown`,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE=`normal_closure`,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT=`timeout`,ATTR_SIGNALR_TRANSPORT=`signalr.transport`,SIGNALR_TRANSPORT_VALUE_LONG_POLLING=`long_polling`,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS=`server_sent_events`,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS=`web_sockets`,ATTR_TELEMETRY_SDK_LANGUAGE=`telemetry.sdk.language`,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET=`dotnet`,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG=`erlang`,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA=`java`,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS=`nodejs`,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON=`python`,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY=`ruby`,TELEMETRY_SDK_LANGUAGE_VALUE_RUST=`rust`,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT=`swift`,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS=`webjs`,ATTR_TELEMETRY_SDK_NAME=`telemetry.sdk.name`,ATTR_TELEMETRY_SDK_VERSION=`telemetry.sdk.version`,ATTR_URL_FRAGMENT=`url.fragment`,ATTR_URL_FULL=`url.full`,ATTR_URL_PATH=`url.path`,ATTR_URL_QUERY=`url.query`,ATTR_URL_SCHEME=`url.scheme`,ATTR_USER_AGENT_ORIGINAL=`user_agent.original`})),METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS,METRIC_DB_CLIENT_OPERATION_DURATION,METRIC_DOTNET_ASSEMBLY_COUNT,METRIC_DOTNET_EXCEPTIONS,METRIC_DOTNET_GC_COLLECTIONS,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE,METRIC_DOTNET_GC_PAUSE_TIME,METRIC_DOTNET_JIT_COMPILATION_TIME,METRIC_DOTNET_JIT_COMPILED_IL_SIZE,METRIC_DOTNET_JIT_COMPILED_METHODS,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS,METRIC_DOTNET_PROCESS_CPU_COUNT,METRIC_DOTNET_PROCESS_CPU_TIME,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT,METRIC_DOTNET_TIMER_COUNT,METRIC_HTTP_CLIENT_REQUEST_DURATION,METRIC_HTTP_SERVER_REQUEST_DURATION,METRIC_JVM_CLASS_COUNT,METRIC_JVM_CLASS_LOADED,METRIC_JVM_CLASS_UNLOADED,METRIC_JVM_CPU_COUNT,METRIC_JVM_CPU_RECENT_UTILIZATION,METRIC_JVM_CPU_TIME,METRIC_JVM_GC_DURATION,METRIC_JVM_MEMORY_COMMITTED,METRIC_JVM_MEMORY_LIMIT,METRIC_JVM_MEMORY_USED,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC,METRIC_JVM_THREAD_COUNT,METRIC_KESTREL_ACTIVE_CONNECTIONS,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES,METRIC_KESTREL_CONNECTION_DURATION,METRIC_KESTREL_QUEUED_CONNECTIONS,METRIC_KESTREL_QUEUED_REQUESTS,METRIC_KESTREL_REJECTED_CONNECTIONS,METRIC_KESTREL_TLS_HANDSHAKE_DURATION,METRIC_KESTREL_UPGRADED_CONNECTIONS,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS,METRIC_SIGNALR_SERVER_CONNECTION_DURATION,init_stable_metrics=__esmMin((()=>{METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS=`aspnetcore.diagnostics.exceptions`,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES=`aspnetcore.rate_limiting.active_request_leases`,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS=`aspnetcore.rate_limiting.queued_requests`,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE=`aspnetcore.rate_limiting.request.time_in_queue`,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION=`aspnetcore.rate_limiting.request_lease.duration`,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS=`aspnetcore.rate_limiting.requests`,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS=`aspnetcore.routing.match_attempts`,METRIC_DB_CLIENT_OPERATION_DURATION=`db.client.operation.duration`,METRIC_DOTNET_ASSEMBLY_COUNT=`dotnet.assembly.count`,METRIC_DOTNET_EXCEPTIONS=`dotnet.exceptions`,METRIC_DOTNET_GC_COLLECTIONS=`dotnet.gc.collections`,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED=`dotnet.gc.heap.total_allocated`,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE=`dotnet.gc.last_collection.heap.fragmentation.size`,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE=`dotnet.gc.last_collection.heap.size`,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE=`dotnet.gc.last_collection.memory.committed_size`,METRIC_DOTNET_GC_PAUSE_TIME=`dotnet.gc.pause.time`,METRIC_DOTNET_JIT_COMPILATION_TIME=`dotnet.jit.compilation.time`,METRIC_DOTNET_JIT_COMPILED_IL_SIZE=`dotnet.jit.compiled_il.size`,METRIC_DOTNET_JIT_COMPILED_METHODS=`dotnet.jit.compiled_methods`,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS=`dotnet.monitor.lock_contentions`,METRIC_DOTNET_PROCESS_CPU_COUNT=`dotnet.process.cpu.count`,METRIC_DOTNET_PROCESS_CPU_TIME=`dotnet.process.cpu.time`,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET=`dotnet.process.memory.working_set`,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH=`dotnet.thread_pool.queue.length`,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT=`dotnet.thread_pool.thread.count`,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT=`dotnet.thread_pool.work_item.count`,METRIC_DOTNET_TIMER_COUNT=`dotnet.timer.count`,METRIC_HTTP_CLIENT_REQUEST_DURATION=`http.client.request.duration`,METRIC_HTTP_SERVER_REQUEST_DURATION=`http.server.request.duration`,METRIC_JVM_CLASS_COUNT=`jvm.class.count`,METRIC_JVM_CLASS_LOADED=`jvm.class.loaded`,METRIC_JVM_CLASS_UNLOADED=`jvm.class.unloaded`,METRIC_JVM_CPU_COUNT=`jvm.cpu.count`,METRIC_JVM_CPU_RECENT_UTILIZATION=`jvm.cpu.recent_utilization`,METRIC_JVM_CPU_TIME=`jvm.cpu.time`,METRIC_JVM_GC_DURATION=`jvm.gc.duration`,METRIC_JVM_MEMORY_COMMITTED=`jvm.memory.committed`,METRIC_JVM_MEMORY_LIMIT=`jvm.memory.limit`,METRIC_JVM_MEMORY_USED=`jvm.memory.used`,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC=`jvm.memory.used_after_last_gc`,METRIC_JVM_THREAD_COUNT=`jvm.thread.count`,METRIC_KESTREL_ACTIVE_CONNECTIONS=`kestrel.active_connections`,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES=`kestrel.active_tls_handshakes`,METRIC_KESTREL_CONNECTION_DURATION=`kestrel.connection.duration`,METRIC_KESTREL_QUEUED_CONNECTIONS=`kestrel.queued_connections`,METRIC_KESTREL_QUEUED_REQUESTS=`kestrel.queued_requests`,METRIC_KESTREL_REJECTED_CONNECTIONS=`kestrel.rejected_connections`,METRIC_KESTREL_TLS_HANDSHAKE_DURATION=`kestrel.tls_handshake.duration`,METRIC_KESTREL_UPGRADED_CONNECTIONS=`kestrel.upgraded_connections`,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS=`signalr.server.active_connections`,METRIC_SIGNALR_SERVER_CONNECTION_DURATION=`signalr.server.connection.duration`})),EVENT_EXCEPTION,init_stable_events=__esmMin((()=>{EVENT_EXCEPTION=`exception`})),esm_exports$1=__exportAll({ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED,ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED:()=>ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER,ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED:()=>ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE:()=>ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE,ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS:()=>ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS,ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT:()=>ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT,ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE:()=>ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE,ATTR_ASPNETCORE_RATE_LIMITING_POLICY:()=>ATTR_ASPNETCORE_RATE_LIMITING_POLICY,ATTR_ASPNETCORE_RATE_LIMITING_RESULT:()=>ATTR_ASPNETCORE_RATE_LIMITING_RESULT,ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED:()=>ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED,ATTR_ASPNETCORE_ROUTING_IS_FALLBACK:()=>ATTR_ASPNETCORE_ROUTING_IS_FALLBACK,ATTR_ASPNETCORE_ROUTING_MATCH_STATUS:()=>ATTR_ASPNETCORE_ROUTING_MATCH_STATUS,ATTR_ASPNETCORE_USER_IS_AUTHENTICATED:()=>ATTR_ASPNETCORE_USER_IS_AUTHENTICATED,ATTR_CLIENT_ADDRESS:()=>ATTR_CLIENT_ADDRESS,ATTR_CLIENT_PORT:()=>ATTR_CLIENT_PORT,ATTR_CODE_COLUMN_NUMBER:()=>ATTR_CODE_COLUMN_NUMBER,ATTR_CODE_FILE_PATH:()=>ATTR_CODE_FILE_PATH,ATTR_CODE_FUNCTION_NAME:()=>ATTR_CODE_FUNCTION_NAME,ATTR_CODE_LINE_NUMBER:()=>ATTR_CODE_LINE_NUMBER,ATTR_CODE_STACKTRACE:()=>ATTR_CODE_STACKTRACE,ATTR_DB_COLLECTION_NAME:()=>ATTR_DB_COLLECTION_NAME,ATTR_DB_NAMESPACE:()=>ATTR_DB_NAMESPACE,ATTR_DB_OPERATION_BATCH_SIZE:()=>ATTR_DB_OPERATION_BATCH_SIZE,ATTR_DB_OPERATION_NAME:()=>ATTR_DB_OPERATION_NAME,ATTR_DB_QUERY_SUMMARY:()=>ATTR_DB_QUERY_SUMMARY,ATTR_DB_QUERY_TEXT:()=>ATTR_DB_QUERY_TEXT,ATTR_DB_RESPONSE_STATUS_CODE:()=>ATTR_DB_RESPONSE_STATUS_CODE,ATTR_DB_STORED_PROCEDURE_NAME:()=>ATTR_DB_STORED_PROCEDURE_NAME,ATTR_DB_SYSTEM_NAME:()=>ATTR_DB_SYSTEM_NAME,ATTR_DOTNET_GC_HEAP_GENERATION:()=>ATTR_DOTNET_GC_HEAP_GENERATION,ATTR_ERROR_TYPE:()=>ATTR_ERROR_TYPE,ATTR_EXCEPTION_ESCAPED:()=>ATTR_EXCEPTION_ESCAPED,ATTR_EXCEPTION_MESSAGE:()=>ATTR_EXCEPTION_MESSAGE,ATTR_EXCEPTION_STACKTRACE:()=>ATTR_EXCEPTION_STACKTRACE,ATTR_EXCEPTION_TYPE:()=>ATTR_EXCEPTION_TYPE,ATTR_HTTP_REQUEST_HEADER:()=>ATTR_HTTP_REQUEST_HEADER,ATTR_HTTP_REQUEST_METHOD:()=>ATTR_HTTP_REQUEST_METHOD,ATTR_HTTP_REQUEST_METHOD_ORIGINAL:()=>ATTR_HTTP_REQUEST_METHOD_ORIGINAL,ATTR_HTTP_REQUEST_RESEND_COUNT:()=>ATTR_HTTP_REQUEST_RESEND_COUNT,ATTR_HTTP_RESPONSE_HEADER:()=>ATTR_HTTP_RESPONSE_HEADER,ATTR_HTTP_RESPONSE_STATUS_CODE:()=>ATTR_HTTP_RESPONSE_STATUS_CODE,ATTR_HTTP_ROUTE:()=>ATTR_HTTP_ROUTE,ATTR_JVM_GC_ACTION:()=>ATTR_JVM_GC_ACTION,ATTR_JVM_GC_NAME:()=>ATTR_JVM_GC_NAME,ATTR_JVM_MEMORY_POOL_NAME:()=>ATTR_JVM_MEMORY_POOL_NAME,ATTR_JVM_MEMORY_TYPE:()=>ATTR_JVM_MEMORY_TYPE,ATTR_JVM_THREAD_DAEMON:()=>ATTR_JVM_THREAD_DAEMON,ATTR_JVM_THREAD_STATE:()=>ATTR_JVM_THREAD_STATE,ATTR_NETWORK_LOCAL_ADDRESS:()=>ATTR_NETWORK_LOCAL_ADDRESS,ATTR_NETWORK_LOCAL_PORT:()=>ATTR_NETWORK_LOCAL_PORT,ATTR_NETWORK_PEER_ADDRESS:()=>ATTR_NETWORK_PEER_ADDRESS,ATTR_NETWORK_PEER_PORT:()=>ATTR_NETWORK_PEER_PORT,ATTR_NETWORK_PROTOCOL_NAME:()=>ATTR_NETWORK_PROTOCOL_NAME,ATTR_NETWORK_PROTOCOL_VERSION:()=>ATTR_NETWORK_PROTOCOL_VERSION,ATTR_NETWORK_TRANSPORT:()=>ATTR_NETWORK_TRANSPORT,ATTR_NETWORK_TYPE:()=>ATTR_NETWORK_TYPE,ATTR_OTEL_SCOPE_NAME:()=>ATTR_OTEL_SCOPE_NAME,ATTR_OTEL_SCOPE_VERSION:()=>ATTR_OTEL_SCOPE_VERSION,ATTR_OTEL_STATUS_CODE:()=>ATTR_OTEL_STATUS_CODE,ATTR_OTEL_STATUS_DESCRIPTION:()=>ATTR_OTEL_STATUS_DESCRIPTION,ATTR_SERVER_ADDRESS:()=>ATTR_SERVER_ADDRESS,ATTR_SERVER_PORT:()=>ATTR_SERVER_PORT,ATTR_SERVICE_INSTANCE_ID:()=>ATTR_SERVICE_INSTANCE_ID,ATTR_SERVICE_NAME:()=>ATTR_SERVICE_NAME,ATTR_SERVICE_NAMESPACE:()=>ATTR_SERVICE_NAMESPACE,ATTR_SERVICE_VERSION:()=>ATTR_SERVICE_VERSION,ATTR_SIGNALR_CONNECTION_STATUS:()=>ATTR_SIGNALR_CONNECTION_STATUS,ATTR_SIGNALR_TRANSPORT:()=>ATTR_SIGNALR_TRANSPORT,ATTR_TELEMETRY_SDK_LANGUAGE:()=>ATTR_TELEMETRY_SDK_LANGUAGE,ATTR_TELEMETRY_SDK_NAME:()=>ATTR_TELEMETRY_SDK_NAME,ATTR_TELEMETRY_SDK_VERSION:()=>ATTR_TELEMETRY_SDK_VERSION,ATTR_URL_FRAGMENT:()=>ATTR_URL_FRAGMENT,ATTR_URL_FULL:()=>ATTR_URL_FULL,ATTR_URL_PATH:()=>ATTR_URL_PATH,ATTR_URL_QUERY:()=>ATTR_URL_QUERY,ATTR_URL_SCHEME:()=>ATTR_URL_SCHEME,ATTR_USER_AGENT_ORIGINAL:()=>ATTR_USER_AGENT_ORIGINAL,AWSECSLAUNCHTYPEVALUES_EC2:()=>`ec2`,AWSECSLAUNCHTYPEVALUES_FARGATE:()=>AWSECSLAUNCHTYPEVALUES_FARGATE,AwsEcsLaunchtypeValues:()=>AwsEcsLaunchtypeValues,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS:()=>CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS,CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC:()=>CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC,CLOUDPLATFORMVALUES_AWS_EC2:()=>CLOUDPLATFORMVALUES_AWS_EC2,CLOUDPLATFORMVALUES_AWS_ECS:()=>CLOUDPLATFORMVALUES_AWS_ECS,CLOUDPLATFORMVALUES_AWS_EKS:()=>CLOUDPLATFORMVALUES_AWS_EKS,CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK:()=>CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK,CLOUDPLATFORMVALUES_AWS_LAMBDA:()=>CLOUDPLATFORMVALUES_AWS_LAMBDA,CLOUDPLATFORMVALUES_AZURE_AKS:()=>CLOUDPLATFORMVALUES_AZURE_AKS,CLOUDPLATFORMVALUES_AZURE_APP_SERVICE:()=>CLOUDPLATFORMVALUES_AZURE_APP_SERVICE,CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES:()=>CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES,CLOUDPLATFORMVALUES_AZURE_FUNCTIONS:()=>CLOUDPLATFORMVALUES_AZURE_FUNCTIONS,CLOUDPLATFORMVALUES_AZURE_VM:()=>CLOUDPLATFORMVALUES_AZURE_VM,CLOUDPLATFORMVALUES_GCP_APP_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_APP_ENGINE,CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS:()=>CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS,CLOUDPLATFORMVALUES_GCP_CLOUD_RUN:()=>CLOUDPLATFORMVALUES_GCP_CLOUD_RUN,CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE,CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE:()=>CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE,CLOUDPROVIDERVALUES_ALIBABA_CLOUD:()=>CLOUDPROVIDERVALUES_ALIBABA_CLOUD,CLOUDPROVIDERVALUES_AWS:()=>`aws`,CLOUDPROVIDERVALUES_AZURE:()=>CLOUDPROVIDERVALUES_AZURE,CLOUDPROVIDERVALUES_GCP:()=>`gcp`,CloudPlatformValues:()=>CloudPlatformValues,CloudProviderValues:()=>CloudProviderValues,DBCASSANDRACONSISTENCYLEVELVALUES_ALL:()=>`all`,DBCASSANDRACONSISTENCYLEVELVALUES_ANY:()=>`any`,DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL:()=>DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_ONE:()=>`one`,DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM:()=>DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM,DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL:()=>DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL,DBCASSANDRACONSISTENCYLEVELVALUES_THREE:()=>DBCASSANDRACONSISTENCYLEVELVALUES_THREE,DBCASSANDRACONSISTENCYLEVELVALUES_TWO:()=>`two`,DBSYSTEMVALUES_ADABAS:()=>DBSYSTEMVALUES_ADABAS,DBSYSTEMVALUES_CACHE:()=>DBSYSTEMVALUES_CACHE,DBSYSTEMVALUES_CASSANDRA:()=>DBSYSTEMVALUES_CASSANDRA,DBSYSTEMVALUES_CLOUDSCAPE:()=>DBSYSTEMVALUES_CLOUDSCAPE,DBSYSTEMVALUES_COCKROACHDB:()=>DBSYSTEMVALUES_COCKROACHDB,DBSYSTEMVALUES_COLDFUSION:()=>DBSYSTEMVALUES_COLDFUSION,DBSYSTEMVALUES_COSMOSDB:()=>DBSYSTEMVALUES_COSMOSDB,DBSYSTEMVALUES_COUCHBASE:()=>DBSYSTEMVALUES_COUCHBASE,DBSYSTEMVALUES_COUCHDB:()=>DBSYSTEMVALUES_COUCHDB,DBSYSTEMVALUES_DB2:()=>`db2`,DBSYSTEMVALUES_DERBY:()=>DBSYSTEMVALUES_DERBY,DBSYSTEMVALUES_DYNAMODB:()=>DBSYSTEMVALUES_DYNAMODB,DBSYSTEMVALUES_EDB:()=>`edb`,DBSYSTEMVALUES_ELASTICSEARCH:()=>DBSYSTEMVALUES_ELASTICSEARCH,DBSYSTEMVALUES_FILEMAKER:()=>DBSYSTEMVALUES_FILEMAKER,DBSYSTEMVALUES_FIREBIRD:()=>DBSYSTEMVALUES_FIREBIRD,DBSYSTEMVALUES_FIRSTSQL:()=>DBSYSTEMVALUES_FIRSTSQL,DBSYSTEMVALUES_GEODE:()=>DBSYSTEMVALUES_GEODE,DBSYSTEMVALUES_H2:()=>`h2`,DBSYSTEMVALUES_HANADB:()=>DBSYSTEMVALUES_HANADB,DBSYSTEMVALUES_HBASE:()=>DBSYSTEMVALUES_HBASE,DBSYSTEMVALUES_HIVE:()=>DBSYSTEMVALUES_HIVE,DBSYSTEMVALUES_HSQLDB:()=>DBSYSTEMVALUES_HSQLDB,DBSYSTEMVALUES_INFORMIX:()=>DBSYSTEMVALUES_INFORMIX,DBSYSTEMVALUES_INGRES:()=>DBSYSTEMVALUES_INGRES,DBSYSTEMVALUES_INSTANTDB:()=>DBSYSTEMVALUES_INSTANTDB,DBSYSTEMVALUES_INTERBASE:()=>DBSYSTEMVALUES_INTERBASE,DBSYSTEMVALUES_MARIADB:()=>DBSYSTEMVALUES_MARIADB,DBSYSTEMVALUES_MAXDB:()=>DBSYSTEMVALUES_MAXDB,DBSYSTEMVALUES_MEMCACHED:()=>DBSYSTEMVALUES_MEMCACHED,DBSYSTEMVALUES_MONGODB:()=>DBSYSTEMVALUES_MONGODB,DBSYSTEMVALUES_MSSQL:()=>DBSYSTEMVALUES_MSSQL,DBSYSTEMVALUES_MYSQL:()=>DBSYSTEMVALUES_MYSQL,DBSYSTEMVALUES_NEO4J:()=>DBSYSTEMVALUES_NEO4J,DBSYSTEMVALUES_NETEZZA:()=>DBSYSTEMVALUES_NETEZZA,DBSYSTEMVALUES_ORACLE:()=>DBSYSTEMVALUES_ORACLE,DBSYSTEMVALUES_OTHER_SQL:()=>DBSYSTEMVALUES_OTHER_SQL,DBSYSTEMVALUES_PERVASIVE:()=>DBSYSTEMVALUES_PERVASIVE,DBSYSTEMVALUES_POINTBASE:()=>DBSYSTEMVALUES_POINTBASE,DBSYSTEMVALUES_POSTGRESQL:()=>DBSYSTEMVALUES_POSTGRESQL,DBSYSTEMVALUES_PROGRESS:()=>DBSYSTEMVALUES_PROGRESS,DBSYSTEMVALUES_REDIS:()=>DBSYSTEMVALUES_REDIS,DBSYSTEMVALUES_REDSHIFT:()=>DBSYSTEMVALUES_REDSHIFT,DBSYSTEMVALUES_SQLITE:()=>DBSYSTEMVALUES_SQLITE,DBSYSTEMVALUES_SYBASE:()=>DBSYSTEMVALUES_SYBASE,DBSYSTEMVALUES_TERADATA:()=>DBSYSTEMVALUES_TERADATA,DBSYSTEMVALUES_VERTICA:()=>DBSYSTEMVALUES_VERTICA,DB_SYSTEM_NAME_VALUE_MARIADB:()=>DB_SYSTEM_NAME_VALUE_MARIADB,DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER:()=>DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER,DB_SYSTEM_NAME_VALUE_MYSQL:()=>DB_SYSTEM_NAME_VALUE_MYSQL,DB_SYSTEM_NAME_VALUE_POSTGRESQL:()=>DB_SYSTEM_NAME_VALUE_POSTGRESQL,DOTNET_GC_HEAP_GENERATION_VALUE_GEN0:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN0,DOTNET_GC_HEAP_GENERATION_VALUE_GEN1:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN1,DOTNET_GC_HEAP_GENERATION_VALUE_GEN2:()=>DOTNET_GC_HEAP_GENERATION_VALUE_GEN2,DOTNET_GC_HEAP_GENERATION_VALUE_LOH:()=>`loh`,DOTNET_GC_HEAP_GENERATION_VALUE_POH:()=>`poh`,DbCassandraConsistencyLevelValues:()=>DbCassandraConsistencyLevelValues,DbSystemValues:()=>DbSystemValues,ERROR_TYPE_VALUE_OTHER:()=>ERROR_TYPE_VALUE_OTHER,EVENT_EXCEPTION:()=>EVENT_EXCEPTION,FAASDOCUMENTOPERATIONVALUES_DELETE:()=>FAASDOCUMENTOPERATIONVALUES_DELETE,FAASDOCUMENTOPERATIONVALUES_EDIT:()=>FAASDOCUMENTOPERATIONVALUES_EDIT,FAASDOCUMENTOPERATIONVALUES_INSERT:()=>FAASDOCUMENTOPERATIONVALUES_INSERT,FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD:()=>FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD,FAASINVOKEDPROVIDERVALUES_AWS:()=>`aws`,FAASINVOKEDPROVIDERVALUES_AZURE:()=>FAASINVOKEDPROVIDERVALUES_AZURE,FAASINVOKEDPROVIDERVALUES_GCP:()=>`gcp`,FAASTRIGGERVALUES_DATASOURCE:()=>FAASTRIGGERVALUES_DATASOURCE,FAASTRIGGERVALUES_HTTP:()=>FAASTRIGGERVALUES_HTTP,FAASTRIGGERVALUES_OTHER:()=>FAASTRIGGERVALUES_OTHER,FAASTRIGGERVALUES_PUBSUB:()=>FAASTRIGGERVALUES_PUBSUB,FAASTRIGGERVALUES_TIMER:()=>FAASTRIGGERVALUES_TIMER,FaasDocumentOperationValues:()=>FaasDocumentOperationValues,FaasInvokedProviderValues:()=>FaasInvokedProviderValues,FaasTriggerValues:()=>FaasTriggerValues,HOSTARCHVALUES_AMD64:()=>HOSTARCHVALUES_AMD64,HOSTARCHVALUES_ARM32:()=>HOSTARCHVALUES_ARM32,HOSTARCHVALUES_ARM64:()=>HOSTARCHVALUES_ARM64,HOSTARCHVALUES_IA64:()=>HOSTARCHVALUES_IA64,HOSTARCHVALUES_PPC32:()=>HOSTARCHVALUES_PPC32,HOSTARCHVALUES_PPC64:()=>HOSTARCHVALUES_PPC64,HOSTARCHVALUES_X86:()=>`x86`,HTTPFLAVORVALUES_HTTP_1_0:()=>`1.0`,HTTPFLAVORVALUES_HTTP_1_1:()=>`1.1`,HTTPFLAVORVALUES_HTTP_2_0:()=>`2.0`,HTTPFLAVORVALUES_QUIC:()=>HTTPFLAVORVALUES_QUIC,HTTPFLAVORVALUES_SPDY:()=>HTTPFLAVORVALUES_SPDY,HTTP_REQUEST_METHOD_VALUE_CONNECT:()=>HTTP_REQUEST_METHOD_VALUE_CONNECT,HTTP_REQUEST_METHOD_VALUE_DELETE:()=>HTTP_REQUEST_METHOD_VALUE_DELETE,HTTP_REQUEST_METHOD_VALUE_GET:()=>`GET`,HTTP_REQUEST_METHOD_VALUE_HEAD:()=>HTTP_REQUEST_METHOD_VALUE_HEAD,HTTP_REQUEST_METHOD_VALUE_OPTIONS:()=>HTTP_REQUEST_METHOD_VALUE_OPTIONS,HTTP_REQUEST_METHOD_VALUE_OTHER:()=>HTTP_REQUEST_METHOD_VALUE_OTHER,HTTP_REQUEST_METHOD_VALUE_PATCH:()=>HTTP_REQUEST_METHOD_VALUE_PATCH,HTTP_REQUEST_METHOD_VALUE_POST:()=>HTTP_REQUEST_METHOD_VALUE_POST,HTTP_REQUEST_METHOD_VALUE_PUT:()=>`PUT`,HTTP_REQUEST_METHOD_VALUE_TRACE:()=>HTTP_REQUEST_METHOD_VALUE_TRACE,HostArchValues:()=>HostArchValues,HttpFlavorValues:()=>HttpFlavorValues,JVM_MEMORY_TYPE_VALUE_HEAP:()=>JVM_MEMORY_TYPE_VALUE_HEAP,JVM_MEMORY_TYPE_VALUE_NON_HEAP:()=>JVM_MEMORY_TYPE_VALUE_NON_HEAP,JVM_THREAD_STATE_VALUE_BLOCKED:()=>JVM_THREAD_STATE_VALUE_BLOCKED,JVM_THREAD_STATE_VALUE_NEW:()=>`new`,JVM_THREAD_STATE_VALUE_RUNNABLE:()=>JVM_THREAD_STATE_VALUE_RUNNABLE,JVM_THREAD_STATE_VALUE_TERMINATED:()=>JVM_THREAD_STATE_VALUE_TERMINATED,JVM_THREAD_STATE_VALUE_TIMED_WAITING:()=>JVM_THREAD_STATE_VALUE_TIMED_WAITING,JVM_THREAD_STATE_VALUE_WAITING:()=>JVM_THREAD_STATE_VALUE_WAITING,MESSAGETYPEVALUES_RECEIVED:()=>MESSAGETYPEVALUES_RECEIVED,MESSAGETYPEVALUES_SENT:()=>MESSAGETYPEVALUES_SENT,MESSAGINGDESTINATIONKINDVALUES_QUEUE:()=>MESSAGINGDESTINATIONKINDVALUES_QUEUE,MESSAGINGDESTINATIONKINDVALUES_TOPIC:()=>MESSAGINGDESTINATIONKINDVALUES_TOPIC,MESSAGINGOPERATIONVALUES_PROCESS:()=>MESSAGINGOPERATIONVALUES_PROCESS,MESSAGINGOPERATIONVALUES_RECEIVE:()=>MESSAGINGOPERATIONVALUES_RECEIVE,METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS:()=>METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS,METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES:()=>METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES,METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS:()=>METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION,METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE:()=>METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE,METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS:()=>METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS,METRIC_DB_CLIENT_OPERATION_DURATION:()=>METRIC_DB_CLIENT_OPERATION_DURATION,METRIC_DOTNET_ASSEMBLY_COUNT:()=>METRIC_DOTNET_ASSEMBLY_COUNT,METRIC_DOTNET_EXCEPTIONS:()=>METRIC_DOTNET_EXCEPTIONS,METRIC_DOTNET_GC_COLLECTIONS:()=>METRIC_DOTNET_GC_COLLECTIONS,METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED:()=>METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE,METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE:()=>METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE,METRIC_DOTNET_GC_PAUSE_TIME:()=>METRIC_DOTNET_GC_PAUSE_TIME,METRIC_DOTNET_JIT_COMPILATION_TIME:()=>METRIC_DOTNET_JIT_COMPILATION_TIME,METRIC_DOTNET_JIT_COMPILED_IL_SIZE:()=>METRIC_DOTNET_JIT_COMPILED_IL_SIZE,METRIC_DOTNET_JIT_COMPILED_METHODS:()=>METRIC_DOTNET_JIT_COMPILED_METHODS,METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS:()=>METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS,METRIC_DOTNET_PROCESS_CPU_COUNT:()=>METRIC_DOTNET_PROCESS_CPU_COUNT,METRIC_DOTNET_PROCESS_CPU_TIME:()=>METRIC_DOTNET_PROCESS_CPU_TIME,METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET:()=>METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET,METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH:()=>METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH,METRIC_DOTNET_THREAD_POOL_THREAD_COUNT:()=>METRIC_DOTNET_THREAD_POOL_THREAD_COUNT,METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT:()=>METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT,METRIC_DOTNET_TIMER_COUNT:()=>METRIC_DOTNET_TIMER_COUNT,METRIC_HTTP_CLIENT_REQUEST_DURATION:()=>METRIC_HTTP_CLIENT_REQUEST_DURATION,METRIC_HTTP_SERVER_REQUEST_DURATION:()=>METRIC_HTTP_SERVER_REQUEST_DURATION,METRIC_JVM_CLASS_COUNT:()=>METRIC_JVM_CLASS_COUNT,METRIC_JVM_CLASS_LOADED:()=>METRIC_JVM_CLASS_LOADED,METRIC_JVM_CLASS_UNLOADED:()=>METRIC_JVM_CLASS_UNLOADED,METRIC_JVM_CPU_COUNT:()=>METRIC_JVM_CPU_COUNT,METRIC_JVM_CPU_RECENT_UTILIZATION:()=>METRIC_JVM_CPU_RECENT_UTILIZATION,METRIC_JVM_CPU_TIME:()=>METRIC_JVM_CPU_TIME,METRIC_JVM_GC_DURATION:()=>METRIC_JVM_GC_DURATION,METRIC_JVM_MEMORY_COMMITTED:()=>METRIC_JVM_MEMORY_COMMITTED,METRIC_JVM_MEMORY_LIMIT:()=>METRIC_JVM_MEMORY_LIMIT,METRIC_JVM_MEMORY_USED:()=>METRIC_JVM_MEMORY_USED,METRIC_JVM_MEMORY_USED_AFTER_LAST_GC:()=>METRIC_JVM_MEMORY_USED_AFTER_LAST_GC,METRIC_JVM_THREAD_COUNT:()=>METRIC_JVM_THREAD_COUNT,METRIC_KESTREL_ACTIVE_CONNECTIONS:()=>METRIC_KESTREL_ACTIVE_CONNECTIONS,METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES:()=>METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES,METRIC_KESTREL_CONNECTION_DURATION:()=>METRIC_KESTREL_CONNECTION_DURATION,METRIC_KESTREL_QUEUED_CONNECTIONS:()=>METRIC_KESTREL_QUEUED_CONNECTIONS,METRIC_KESTREL_QUEUED_REQUESTS:()=>METRIC_KESTREL_QUEUED_REQUESTS,METRIC_KESTREL_REJECTED_CONNECTIONS:()=>METRIC_KESTREL_REJECTED_CONNECTIONS,METRIC_KESTREL_TLS_HANDSHAKE_DURATION:()=>METRIC_KESTREL_TLS_HANDSHAKE_DURATION,METRIC_KESTREL_UPGRADED_CONNECTIONS:()=>METRIC_KESTREL_UPGRADED_CONNECTIONS,METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS:()=>METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS,METRIC_SIGNALR_SERVER_CONNECTION_DURATION:()=>METRIC_SIGNALR_SERVER_CONNECTION_DURATION,MessageTypeValues:()=>MessageTypeValues,MessagingDestinationKindValues:()=>MessagingDestinationKindValues,MessagingOperationValues:()=>MessagingOperationValues,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_CDMA,NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT:()=>NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT,NETHOSTCONNECTIONSUBTYPEVALUES_EDGE:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EDGE,NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A,NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B:()=>NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B,NETHOSTCONNECTIONSUBTYPEVALUES_GPRS:()=>NETHOSTCONNECTIONSUBTYPEVALUES_GPRS,NETHOSTCONNECTIONSUBTYPEVALUES_GSM:()=>`gsm`,NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSPA,NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP,NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA,NETHOSTCONNECTIONSUBTYPEVALUES_IDEN:()=>NETHOSTCONNECTIONSUBTYPEVALUES_IDEN,NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN:()=>NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN,NETHOSTCONNECTIONSUBTYPEVALUES_LTE:()=>`lte`,NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA,NETHOSTCONNECTIONSUBTYPEVALUES_NR:()=>`nr`,NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA,NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA:()=>NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA,NETHOSTCONNECTIONSUBTYPEVALUES_UMTS:()=>NETHOSTCONNECTIONSUBTYPEVALUES_UMTS,NETHOSTCONNECTIONTYPEVALUES_CELL:()=>NETHOSTCONNECTIONTYPEVALUES_CELL,NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE:()=>NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE,NETHOSTCONNECTIONTYPEVALUES_UNKNOWN:()=>NETHOSTCONNECTIONTYPEVALUES_UNKNOWN,NETHOSTCONNECTIONTYPEVALUES_WIFI:()=>NETHOSTCONNECTIONTYPEVALUES_WIFI,NETHOSTCONNECTIONTYPEVALUES_WIRED:()=>NETHOSTCONNECTIONTYPEVALUES_WIRED,NETTRANSPORTVALUES_INPROC:()=>NETTRANSPORTVALUES_INPROC,NETTRANSPORTVALUES_IP:()=>`ip`,NETTRANSPORTVALUES_IP_TCP:()=>NETTRANSPORTVALUES_IP_TCP,NETTRANSPORTVALUES_IP_UDP:()=>NETTRANSPORTVALUES_IP_UDP,NETTRANSPORTVALUES_OTHER:()=>NETTRANSPORTVALUES_OTHER,NETTRANSPORTVALUES_PIPE:()=>NETTRANSPORTVALUES_PIPE,NETTRANSPORTVALUES_UNIX:()=>NETTRANSPORTVALUES_UNIX,NETWORK_TRANSPORT_VALUE_PIPE:()=>NETWORK_TRANSPORT_VALUE_PIPE,NETWORK_TRANSPORT_VALUE_QUIC:()=>NETWORK_TRANSPORT_VALUE_QUIC,NETWORK_TRANSPORT_VALUE_TCP:()=>`tcp`,NETWORK_TRANSPORT_VALUE_UDP:()=>`udp`,NETWORK_TRANSPORT_VALUE_UNIX:()=>NETWORK_TRANSPORT_VALUE_UNIX,NETWORK_TYPE_VALUE_IPV4:()=>NETWORK_TYPE_VALUE_IPV4,NETWORK_TYPE_VALUE_IPV6:()=>NETWORK_TYPE_VALUE_IPV6,NetHostConnectionSubtypeValues:()=>NetHostConnectionSubtypeValues,NetHostConnectionTypeValues:()=>NetHostConnectionTypeValues,NetTransportValues:()=>NetTransportValues,OSTYPEVALUES_AIX:()=>`aix`,OSTYPEVALUES_DARWIN:()=>OSTYPEVALUES_DARWIN,OSTYPEVALUES_DRAGONFLYBSD:()=>OSTYPEVALUES_DRAGONFLYBSD,OSTYPEVALUES_FREEBSD:()=>OSTYPEVALUES_FREEBSD,OSTYPEVALUES_HPUX:()=>OSTYPEVALUES_HPUX,OSTYPEVALUES_LINUX:()=>OSTYPEVALUES_LINUX,OSTYPEVALUES_NETBSD:()=>OSTYPEVALUES_NETBSD,OSTYPEVALUES_OPENBSD:()=>OSTYPEVALUES_OPENBSD,OSTYPEVALUES_SOLARIS:()=>OSTYPEVALUES_SOLARIS,OSTYPEVALUES_WINDOWS:()=>OSTYPEVALUES_WINDOWS,OSTYPEVALUES_Z_OS:()=>OSTYPEVALUES_Z_OS,OTEL_STATUS_CODE_VALUE_ERROR:()=>OTEL_STATUS_CODE_VALUE_ERROR,OTEL_STATUS_CODE_VALUE_OK:()=>`OK`,OsTypeValues:()=>OsTypeValues,RPCGRPCSTATUSCODEVALUES_ABORTED:()=>10,RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS:()=>6,RPCGRPCSTATUSCODEVALUES_CANCELLED:()=>1,RPCGRPCSTATUSCODEVALUES_DATA_LOSS:()=>15,RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED:()=>4,RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION:()=>9,RPCGRPCSTATUSCODEVALUES_INTERNAL:()=>13,RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT:()=>3,RPCGRPCSTATUSCODEVALUES_NOT_FOUND:()=>5,RPCGRPCSTATUSCODEVALUES_OK:()=>0,RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE:()=>11,RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED:()=>7,RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED:()=>8,RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED:()=>16,RPCGRPCSTATUSCODEVALUES_UNAVAILABLE:()=>14,RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED:()=>12,RPCGRPCSTATUSCODEVALUES_UNKNOWN:()=>2,RpcGrpcStatusCodeValues:()=>RpcGrpcStatusCodeValues,SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET:()=>SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET,SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS:()=>SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS,SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ:()=>SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ,SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY,SEMATTRS_AWS_DYNAMODB_COUNT:()=>SEMATTRS_AWS_DYNAMODB_COUNT,SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE:()=>SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES:()=>SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES:()=>SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES,SEMATTRS_AWS_DYNAMODB_INDEX_NAME:()=>SEMATTRS_AWS_DYNAMODB_INDEX_NAME,SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS:()=>SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS,SEMATTRS_AWS_DYNAMODB_LIMIT:()=>SEMATTRS_AWS_DYNAMODB_LIMIT,SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES:()=>SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES,SEMATTRS_AWS_DYNAMODB_PROJECTION:()=>SEMATTRS_AWS_DYNAMODB_PROJECTION,SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY,SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY:()=>SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY,SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT:()=>SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT,SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD:()=>SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD,SEMATTRS_AWS_DYNAMODB_SEGMENT:()=>SEMATTRS_AWS_DYNAMODB_SEGMENT,SEMATTRS_AWS_DYNAMODB_SELECT:()=>SEMATTRS_AWS_DYNAMODB_SELECT,SEMATTRS_AWS_DYNAMODB_TABLE_COUNT:()=>SEMATTRS_AWS_DYNAMODB_TABLE_COUNT,SEMATTRS_AWS_DYNAMODB_TABLE_NAMES:()=>SEMATTRS_AWS_DYNAMODB_TABLE_NAMES,SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS:()=>SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS,SEMATTRS_AWS_LAMBDA_INVOKED_ARN:()=>SEMATTRS_AWS_LAMBDA_INVOKED_ARN,SEMATTRS_CODE_FILEPATH:()=>SEMATTRS_CODE_FILEPATH,SEMATTRS_CODE_FUNCTION:()=>SEMATTRS_CODE_FUNCTION,SEMATTRS_CODE_LINENO:()=>SEMATTRS_CODE_LINENO,SEMATTRS_CODE_NAMESPACE:()=>SEMATTRS_CODE_NAMESPACE,SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL:()=>SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL,SEMATTRS_DB_CASSANDRA_COORDINATOR_DC:()=>SEMATTRS_DB_CASSANDRA_COORDINATOR_DC,SEMATTRS_DB_CASSANDRA_COORDINATOR_ID:()=>SEMATTRS_DB_CASSANDRA_COORDINATOR_ID,SEMATTRS_DB_CASSANDRA_IDEMPOTENCE:()=>SEMATTRS_DB_CASSANDRA_IDEMPOTENCE,SEMATTRS_DB_CASSANDRA_KEYSPACE:()=>SEMATTRS_DB_CASSANDRA_KEYSPACE,SEMATTRS_DB_CASSANDRA_PAGE_SIZE:()=>SEMATTRS_DB_CASSANDRA_PAGE_SIZE,SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT:()=>SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT,SEMATTRS_DB_CASSANDRA_TABLE:()=>SEMATTRS_DB_CASSANDRA_TABLE,SEMATTRS_DB_CONNECTION_STRING:()=>SEMATTRS_DB_CONNECTION_STRING,SEMATTRS_DB_HBASE_NAMESPACE:()=>SEMATTRS_DB_HBASE_NAMESPACE,SEMATTRS_DB_JDBC_DRIVER_CLASSNAME:()=>SEMATTRS_DB_JDBC_DRIVER_CLASSNAME,SEMATTRS_DB_MONGODB_COLLECTION:()=>SEMATTRS_DB_MONGODB_COLLECTION,SEMATTRS_DB_MSSQL_INSTANCE_NAME:()=>SEMATTRS_DB_MSSQL_INSTANCE_NAME,SEMATTRS_DB_NAME:()=>SEMATTRS_DB_NAME,SEMATTRS_DB_OPERATION:()=>SEMATTRS_DB_OPERATION,SEMATTRS_DB_REDIS_DATABASE_INDEX:()=>SEMATTRS_DB_REDIS_DATABASE_INDEX,SEMATTRS_DB_SQL_TABLE:()=>SEMATTRS_DB_SQL_TABLE,SEMATTRS_DB_STATEMENT:()=>SEMATTRS_DB_STATEMENT,SEMATTRS_DB_SYSTEM:()=>SEMATTRS_DB_SYSTEM,SEMATTRS_DB_USER:()=>SEMATTRS_DB_USER,SEMATTRS_ENDUSER_ID:()=>SEMATTRS_ENDUSER_ID,SEMATTRS_ENDUSER_ROLE:()=>SEMATTRS_ENDUSER_ROLE,SEMATTRS_ENDUSER_SCOPE:()=>SEMATTRS_ENDUSER_SCOPE,SEMATTRS_EXCEPTION_ESCAPED:()=>SEMATTRS_EXCEPTION_ESCAPED,SEMATTRS_EXCEPTION_MESSAGE:()=>SEMATTRS_EXCEPTION_MESSAGE,SEMATTRS_EXCEPTION_STACKTRACE:()=>SEMATTRS_EXCEPTION_STACKTRACE,SEMATTRS_EXCEPTION_TYPE:()=>SEMATTRS_EXCEPTION_TYPE,SEMATTRS_FAAS_COLDSTART:()=>SEMATTRS_FAAS_COLDSTART,SEMATTRS_FAAS_CRON:()=>SEMATTRS_FAAS_CRON,SEMATTRS_FAAS_DOCUMENT_COLLECTION:()=>SEMATTRS_FAAS_DOCUMENT_COLLECTION,SEMATTRS_FAAS_DOCUMENT_NAME:()=>SEMATTRS_FAAS_DOCUMENT_NAME,SEMATTRS_FAAS_DOCUMENT_OPERATION:()=>SEMATTRS_FAAS_DOCUMENT_OPERATION,SEMATTRS_FAAS_DOCUMENT_TIME:()=>SEMATTRS_FAAS_DOCUMENT_TIME,SEMATTRS_FAAS_EXECUTION:()=>SEMATTRS_FAAS_EXECUTION,SEMATTRS_FAAS_INVOKED_NAME:()=>SEMATTRS_FAAS_INVOKED_NAME,SEMATTRS_FAAS_INVOKED_PROVIDER:()=>SEMATTRS_FAAS_INVOKED_PROVIDER,SEMATTRS_FAAS_INVOKED_REGION:()=>SEMATTRS_FAAS_INVOKED_REGION,SEMATTRS_FAAS_TIME:()=>SEMATTRS_FAAS_TIME,SEMATTRS_FAAS_TRIGGER:()=>SEMATTRS_FAAS_TRIGGER,SEMATTRS_HTTP_CLIENT_IP:()=>SEMATTRS_HTTP_CLIENT_IP,SEMATTRS_HTTP_FLAVOR:()=>SEMATTRS_HTTP_FLAVOR,SEMATTRS_HTTP_HOST:()=>SEMATTRS_HTTP_HOST,SEMATTRS_HTTP_METHOD:()=>SEMATTRS_HTTP_METHOD,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH:()=>SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH,SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED:()=>SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH:()=>SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED:()=>SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,SEMATTRS_HTTP_ROUTE:()=>SEMATTRS_HTTP_ROUTE,SEMATTRS_HTTP_SCHEME:()=>SEMATTRS_HTTP_SCHEME,SEMATTRS_HTTP_SERVER_NAME:()=>SEMATTRS_HTTP_SERVER_NAME,SEMATTRS_HTTP_STATUS_CODE:()=>SEMATTRS_HTTP_STATUS_CODE,SEMATTRS_HTTP_TARGET:()=>SEMATTRS_HTTP_TARGET,SEMATTRS_HTTP_URL:()=>SEMATTRS_HTTP_URL,SEMATTRS_HTTP_USER_AGENT:()=>SEMATTRS_HTTP_USER_AGENT,SEMATTRS_MESSAGE_COMPRESSED_SIZE:()=>SEMATTRS_MESSAGE_COMPRESSED_SIZE,SEMATTRS_MESSAGE_ID:()=>SEMATTRS_MESSAGE_ID,SEMATTRS_MESSAGE_TYPE:()=>SEMATTRS_MESSAGE_TYPE,SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE:()=>SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE,SEMATTRS_MESSAGING_CONSUMER_ID:()=>SEMATTRS_MESSAGING_CONSUMER_ID,SEMATTRS_MESSAGING_CONVERSATION_ID:()=>SEMATTRS_MESSAGING_CONVERSATION_ID,SEMATTRS_MESSAGING_DESTINATION:()=>SEMATTRS_MESSAGING_DESTINATION,SEMATTRS_MESSAGING_DESTINATION_KIND:()=>SEMATTRS_MESSAGING_DESTINATION_KIND,SEMATTRS_MESSAGING_KAFKA_CLIENT_ID:()=>SEMATTRS_MESSAGING_KAFKA_CLIENT_ID,SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP:()=>SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP,SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY:()=>SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY,SEMATTRS_MESSAGING_KAFKA_PARTITION:()=>SEMATTRS_MESSAGING_KAFKA_PARTITION,SEMATTRS_MESSAGING_KAFKA_TOMBSTONE:()=>SEMATTRS_MESSAGING_KAFKA_TOMBSTONE,SEMATTRS_MESSAGING_MESSAGE_ID:()=>SEMATTRS_MESSAGING_MESSAGE_ID,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES:()=>SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES,SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES:()=>SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES,SEMATTRS_MESSAGING_OPERATION:()=>SEMATTRS_MESSAGING_OPERATION,SEMATTRS_MESSAGING_PROTOCOL:()=>SEMATTRS_MESSAGING_PROTOCOL,SEMATTRS_MESSAGING_PROTOCOL_VERSION:()=>SEMATTRS_MESSAGING_PROTOCOL_VERSION,SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY:()=>SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY,SEMATTRS_MESSAGING_SYSTEM:()=>SEMATTRS_MESSAGING_SYSTEM,SEMATTRS_MESSAGING_TEMP_DESTINATION:()=>SEMATTRS_MESSAGING_TEMP_DESTINATION,SEMATTRS_MESSAGING_URL:()=>SEMATTRS_MESSAGING_URL,SEMATTRS_NET_HOST_CARRIER_ICC:()=>SEMATTRS_NET_HOST_CARRIER_ICC,SEMATTRS_NET_HOST_CARRIER_MCC:()=>SEMATTRS_NET_HOST_CARRIER_MCC,SEMATTRS_NET_HOST_CARRIER_MNC:()=>SEMATTRS_NET_HOST_CARRIER_MNC,SEMATTRS_NET_HOST_CARRIER_NAME:()=>SEMATTRS_NET_HOST_CARRIER_NAME,SEMATTRS_NET_HOST_CONNECTION_SUBTYPE:()=>SEMATTRS_NET_HOST_CONNECTION_SUBTYPE,SEMATTRS_NET_HOST_CONNECTION_TYPE:()=>SEMATTRS_NET_HOST_CONNECTION_TYPE,SEMATTRS_NET_HOST_IP:()=>SEMATTRS_NET_HOST_IP,SEMATTRS_NET_HOST_NAME:()=>SEMATTRS_NET_HOST_NAME,SEMATTRS_NET_HOST_PORT:()=>SEMATTRS_NET_HOST_PORT,SEMATTRS_NET_PEER_IP:()=>SEMATTRS_NET_PEER_IP,SEMATTRS_NET_PEER_NAME:()=>SEMATTRS_NET_PEER_NAME,SEMATTRS_NET_PEER_PORT:()=>SEMATTRS_NET_PEER_PORT,SEMATTRS_NET_TRANSPORT:()=>SEMATTRS_NET_TRANSPORT,SEMATTRS_PEER_SERVICE:()=>SEMATTRS_PEER_SERVICE,SEMATTRS_RPC_GRPC_STATUS_CODE:()=>SEMATTRS_RPC_GRPC_STATUS_CODE,SEMATTRS_RPC_JSONRPC_ERROR_CODE:()=>SEMATTRS_RPC_JSONRPC_ERROR_CODE,SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE:()=>SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE,SEMATTRS_RPC_JSONRPC_REQUEST_ID:()=>SEMATTRS_RPC_JSONRPC_REQUEST_ID,SEMATTRS_RPC_JSONRPC_VERSION:()=>SEMATTRS_RPC_JSONRPC_VERSION,SEMATTRS_RPC_METHOD:()=>SEMATTRS_RPC_METHOD,SEMATTRS_RPC_SERVICE:()=>SEMATTRS_RPC_SERVICE,SEMATTRS_RPC_SYSTEM:()=>SEMATTRS_RPC_SYSTEM,SEMATTRS_THREAD_ID:()=>SEMATTRS_THREAD_ID,SEMATTRS_THREAD_NAME:()=>SEMATTRS_THREAD_NAME,SEMRESATTRS_AWS_ECS_CLUSTER_ARN:()=>SEMRESATTRS_AWS_ECS_CLUSTER_ARN,SEMRESATTRS_AWS_ECS_CONTAINER_ARN:()=>SEMRESATTRS_AWS_ECS_CONTAINER_ARN,SEMRESATTRS_AWS_ECS_LAUNCHTYPE:()=>SEMRESATTRS_AWS_ECS_LAUNCHTYPE,SEMRESATTRS_AWS_ECS_TASK_ARN:()=>SEMRESATTRS_AWS_ECS_TASK_ARN,SEMRESATTRS_AWS_ECS_TASK_FAMILY:()=>SEMRESATTRS_AWS_ECS_TASK_FAMILY,SEMRESATTRS_AWS_ECS_TASK_REVISION:()=>SEMRESATTRS_AWS_ECS_TASK_REVISION,SEMRESATTRS_AWS_EKS_CLUSTER_ARN:()=>SEMRESATTRS_AWS_EKS_CLUSTER_ARN,SEMRESATTRS_AWS_LOG_GROUP_ARNS:()=>SEMRESATTRS_AWS_LOG_GROUP_ARNS,SEMRESATTRS_AWS_LOG_GROUP_NAMES:()=>SEMRESATTRS_AWS_LOG_GROUP_NAMES,SEMRESATTRS_AWS_LOG_STREAM_ARNS:()=>SEMRESATTRS_AWS_LOG_STREAM_ARNS,SEMRESATTRS_AWS_LOG_STREAM_NAMES:()=>SEMRESATTRS_AWS_LOG_STREAM_NAMES,SEMRESATTRS_CLOUD_ACCOUNT_ID:()=>SEMRESATTRS_CLOUD_ACCOUNT_ID,SEMRESATTRS_CLOUD_AVAILABILITY_ZONE:()=>SEMRESATTRS_CLOUD_AVAILABILITY_ZONE,SEMRESATTRS_CLOUD_PLATFORM:()=>SEMRESATTRS_CLOUD_PLATFORM,SEMRESATTRS_CLOUD_PROVIDER:()=>SEMRESATTRS_CLOUD_PROVIDER,SEMRESATTRS_CLOUD_REGION:()=>SEMRESATTRS_CLOUD_REGION,SEMRESATTRS_CONTAINER_ID:()=>SEMRESATTRS_CONTAINER_ID,SEMRESATTRS_CONTAINER_IMAGE_NAME:()=>SEMRESATTRS_CONTAINER_IMAGE_NAME,SEMRESATTRS_CONTAINER_IMAGE_TAG:()=>SEMRESATTRS_CONTAINER_IMAGE_TAG,SEMRESATTRS_CONTAINER_NAME:()=>SEMRESATTRS_CONTAINER_NAME,SEMRESATTRS_CONTAINER_RUNTIME:()=>SEMRESATTRS_CONTAINER_RUNTIME,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT:()=>SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,SEMRESATTRS_DEVICE_ID:()=>SEMRESATTRS_DEVICE_ID,SEMRESATTRS_DEVICE_MODEL_IDENTIFIER:()=>SEMRESATTRS_DEVICE_MODEL_IDENTIFIER,SEMRESATTRS_DEVICE_MODEL_NAME:()=>SEMRESATTRS_DEVICE_MODEL_NAME,SEMRESATTRS_FAAS_ID:()=>SEMRESATTRS_FAAS_ID,SEMRESATTRS_FAAS_INSTANCE:()=>SEMRESATTRS_FAAS_INSTANCE,SEMRESATTRS_FAAS_MAX_MEMORY:()=>SEMRESATTRS_FAAS_MAX_MEMORY,SEMRESATTRS_FAAS_NAME:()=>SEMRESATTRS_FAAS_NAME,SEMRESATTRS_FAAS_VERSION:()=>SEMRESATTRS_FAAS_VERSION,SEMRESATTRS_HOST_ARCH:()=>SEMRESATTRS_HOST_ARCH,SEMRESATTRS_HOST_ID:()=>SEMRESATTRS_HOST_ID,SEMRESATTRS_HOST_IMAGE_ID:()=>SEMRESATTRS_HOST_IMAGE_ID,SEMRESATTRS_HOST_IMAGE_NAME:()=>SEMRESATTRS_HOST_IMAGE_NAME,SEMRESATTRS_HOST_IMAGE_VERSION:()=>SEMRESATTRS_HOST_IMAGE_VERSION,SEMRESATTRS_HOST_NAME:()=>SEMRESATTRS_HOST_NAME,SEMRESATTRS_HOST_TYPE:()=>SEMRESATTRS_HOST_TYPE,SEMRESATTRS_K8S_CLUSTER_NAME:()=>SEMRESATTRS_K8S_CLUSTER_NAME,SEMRESATTRS_K8S_CONTAINER_NAME:()=>SEMRESATTRS_K8S_CONTAINER_NAME,SEMRESATTRS_K8S_CRONJOB_NAME:()=>SEMRESATTRS_K8S_CRONJOB_NAME,SEMRESATTRS_K8S_CRONJOB_UID:()=>SEMRESATTRS_K8S_CRONJOB_UID,SEMRESATTRS_K8S_DAEMONSET_NAME:()=>SEMRESATTRS_K8S_DAEMONSET_NAME,SEMRESATTRS_K8S_DAEMONSET_UID:()=>SEMRESATTRS_K8S_DAEMONSET_UID,SEMRESATTRS_K8S_DEPLOYMENT_NAME:()=>SEMRESATTRS_K8S_DEPLOYMENT_NAME,SEMRESATTRS_K8S_DEPLOYMENT_UID:()=>SEMRESATTRS_K8S_DEPLOYMENT_UID,SEMRESATTRS_K8S_JOB_NAME:()=>SEMRESATTRS_K8S_JOB_NAME,SEMRESATTRS_K8S_JOB_UID:()=>SEMRESATTRS_K8S_JOB_UID,SEMRESATTRS_K8S_NAMESPACE_NAME:()=>SEMRESATTRS_K8S_NAMESPACE_NAME,SEMRESATTRS_K8S_NODE_NAME:()=>SEMRESATTRS_K8S_NODE_NAME,SEMRESATTRS_K8S_NODE_UID:()=>SEMRESATTRS_K8S_NODE_UID,SEMRESATTRS_K8S_POD_NAME:()=>SEMRESATTRS_K8S_POD_NAME,SEMRESATTRS_K8S_POD_UID:()=>SEMRESATTRS_K8S_POD_UID,SEMRESATTRS_K8S_REPLICASET_NAME:()=>SEMRESATTRS_K8S_REPLICASET_NAME,SEMRESATTRS_K8S_REPLICASET_UID:()=>SEMRESATTRS_K8S_REPLICASET_UID,SEMRESATTRS_K8S_STATEFULSET_NAME:()=>SEMRESATTRS_K8S_STATEFULSET_NAME,SEMRESATTRS_K8S_STATEFULSET_UID:()=>SEMRESATTRS_K8S_STATEFULSET_UID,SEMRESATTRS_OS_DESCRIPTION:()=>SEMRESATTRS_OS_DESCRIPTION,SEMRESATTRS_OS_NAME:()=>SEMRESATTRS_OS_NAME,SEMRESATTRS_OS_TYPE:()=>SEMRESATTRS_OS_TYPE,SEMRESATTRS_OS_VERSION:()=>SEMRESATTRS_OS_VERSION,SEMRESATTRS_PROCESS_COMMAND:()=>SEMRESATTRS_PROCESS_COMMAND,SEMRESATTRS_PROCESS_COMMAND_ARGS:()=>SEMRESATTRS_PROCESS_COMMAND_ARGS,SEMRESATTRS_PROCESS_COMMAND_LINE:()=>SEMRESATTRS_PROCESS_COMMAND_LINE,SEMRESATTRS_PROCESS_EXECUTABLE_NAME:()=>SEMRESATTRS_PROCESS_EXECUTABLE_NAME,SEMRESATTRS_PROCESS_EXECUTABLE_PATH:()=>SEMRESATTRS_PROCESS_EXECUTABLE_PATH,SEMRESATTRS_PROCESS_OWNER:()=>SEMRESATTRS_PROCESS_OWNER,SEMRESATTRS_PROCESS_PID:()=>SEMRESATTRS_PROCESS_PID,SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION:()=>SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION,SEMRESATTRS_PROCESS_RUNTIME_NAME:()=>SEMRESATTRS_PROCESS_RUNTIME_NAME,SEMRESATTRS_PROCESS_RUNTIME_VERSION:()=>SEMRESATTRS_PROCESS_RUNTIME_VERSION,SEMRESATTRS_SERVICE_INSTANCE_ID:()=>SEMRESATTRS_SERVICE_INSTANCE_ID,SEMRESATTRS_SERVICE_NAME:()=>SEMRESATTRS_SERVICE_NAME,SEMRESATTRS_SERVICE_NAMESPACE:()=>SEMRESATTRS_SERVICE_NAMESPACE,SEMRESATTRS_SERVICE_VERSION:()=>SEMRESATTRS_SERVICE_VERSION,SEMRESATTRS_TELEMETRY_AUTO_VERSION:()=>SEMRESATTRS_TELEMETRY_AUTO_VERSION,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE:()=>SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_NAME:()=>SEMRESATTRS_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_VERSION:()=>SEMRESATTRS_TELEMETRY_SDK_VERSION,SEMRESATTRS_WEBENGINE_DESCRIPTION:()=>SEMRESATTRS_WEBENGINE_DESCRIPTION,SEMRESATTRS_WEBENGINE_NAME:()=>SEMRESATTRS_WEBENGINE_NAME,SEMRESATTRS_WEBENGINE_VERSION:()=>SEMRESATTRS_WEBENGINE_VERSION,SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN:()=>SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN,SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE:()=>SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE,SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT:()=>SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT,SIGNALR_TRANSPORT_VALUE_LONG_POLLING:()=>SIGNALR_TRANSPORT_VALUE_LONG_POLLING,SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS:()=>SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS,SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS:()=>SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS,SemanticAttributes:()=>SemanticAttributes,SemanticResourceAttributes:()=>SemanticResourceAttributes,TELEMETRYSDKLANGUAGEVALUES_CPP:()=>`cpp`,TELEMETRYSDKLANGUAGEVALUES_DOTNET:()=>TELEMETRYSDKLANGUAGEVALUES_DOTNET,TELEMETRYSDKLANGUAGEVALUES_ERLANG:()=>TELEMETRYSDKLANGUAGEVALUES_ERLANG,TELEMETRYSDKLANGUAGEVALUES_GO:()=>`go`,TELEMETRYSDKLANGUAGEVALUES_JAVA:()=>TELEMETRYSDKLANGUAGEVALUES_JAVA,TELEMETRYSDKLANGUAGEVALUES_NODEJS:()=>TELEMETRYSDKLANGUAGEVALUES_NODEJS,TELEMETRYSDKLANGUAGEVALUES_PHP:()=>`php`,TELEMETRYSDKLANGUAGEVALUES_PYTHON:()=>TELEMETRYSDKLANGUAGEVALUES_PYTHON,TELEMETRYSDKLANGUAGEVALUES_RUBY:()=>TELEMETRYSDKLANGUAGEVALUES_RUBY,TELEMETRYSDKLANGUAGEVALUES_WEBJS:()=>TELEMETRYSDKLANGUAGEVALUES_WEBJS,TELEMETRY_SDK_LANGUAGE_VALUE_CPP:()=>`cpp`,TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET:()=>TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET,TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG:()=>TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG,TELEMETRY_SDK_LANGUAGE_VALUE_GO:()=>`go`,TELEMETRY_SDK_LANGUAGE_VALUE_JAVA:()=>TELEMETRY_SDK_LANGUAGE_VALUE_JAVA,TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS:()=>TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,TELEMETRY_SDK_LANGUAGE_VALUE_PHP:()=>`php`,TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON:()=>TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON,TELEMETRY_SDK_LANGUAGE_VALUE_RUBY:()=>TELEMETRY_SDK_LANGUAGE_VALUE_RUBY,TELEMETRY_SDK_LANGUAGE_VALUE_RUST:()=>TELEMETRY_SDK_LANGUAGE_VALUE_RUST,TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT:()=>TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT,TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS:()=>TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,TelemetrySdkLanguageValues:()=>TelemetrySdkLanguageValues}),init_esm$1=__esmMin((()=>{init_trace(),init_resource(),init_stable_attributes(),init_stable_metrics(),init_stable_events()})),require_semconv$7=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),require_sdk_info$3=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=require_version$6(),s=(init_esm$1(),__toCommonJS(esm_exports$1)),g=require_semconv$7();e.SDK_INFO={[s.ATTR_TELEMETRY_SDK_NAME]:`opentelemetry`,[g.ATTR_PROCESS_RUNTIME_NAME]:`node`,[s.ATTR_TELEMETRY_SDK_LANGUAGE]:s.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[s.ATTR_TELEMETRY_SDK_VERSION]:t.VERSION}})),require_node$11=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=e.SDK_INFO=e._globalThis=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=void 0;var t=require_environment$3();Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}});var s=require_globalThis$3();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return s._globalThis}});var g=require_sdk_info$3();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return g.SDK_INFO}}),e.otperformance=performance})),require_platform$11=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getNumberFromEnv=e.getStringFromEnv=e.getBooleanFromEnv=e.otperformance=e._globalThis=e.SDK_INFO=void 0;var t=require_node$11();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return t.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return t._globalThis}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return t.otperformance}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}})})),require_time$4=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.addHrTimes=e.isTimeInput=e.isTimeInputHrTime=e.hrTimeToMicroseconds=e.hrTimeToMilliseconds=e.hrTimeToNanoseconds=e.hrTimeToTimeStamp=e.hrTimeDuration=e.timeInputToHrTime=e.hrTime=e.getTimeOrigin=e.millisToHrTime=void 0;let t=require_platform$11(),s=9,g=10**6,S=10**9;function w(e){let t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*g)]}e.millisToHrTime=w;function E(){return t.otperformance.timeOrigin}e.getTimeOrigin=E;function D(e){return 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}var PinoLogger=class{name;transportConfigs=[];fileSinkOpts;redactPaths;activeFileSink;pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),t.fileSink&&(this.fileSinkOpts=t.fileSink),t.redactPaths&&t.redactPaths.length>0&&(this.redactPaths=t.redactPaths,this.options={...this.options,redact:{paths:[...t.redactPaths],censor:`[REDACTED]`}}),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.activeFileSink=void 0,this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));let e;try{e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`})}catch(e){if(console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),this.fileSinkOpts){let e=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=e,(0,import_pino.default)(this.options,import_pino.default.multistream([{stream:e}]))}return(0,import_pino.default)(this.options)}if(this.fileSinkOpts){let t=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=t,(0,import_pino.default)(this.options,import_pino.default.multistream([{stream:e},{stream:t}]))}return(0,import_pino.default)(this.options,e)}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}getPinoInstance(){return this.pinoInstance}async flushFileSink(){this.activeFileSink&&await this.activeFileSink.drain()}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let s;return s=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,s),s}reset(){this.config={},this.loggers.clear()}async flushAllFileSinks(){let e=[];for(let t of this.loggers.values())e.push(t.flushFileSink());await Promise.all(e)}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(s=>({...s,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:s,...g}=t;return g})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let s=t.getLocalState()??{},g=e(s.agentFocus??{});t.setLocalState({...s,agentFocus:g})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let s=0;this.mutateAgentPresence(g=>{let S=Date.now(),w={};for(let[t,E]of Object.entries(g)){if(S-E.ts>=2e4&&t!==e){s++;continue}w[t]=E}return w[e]=t,w})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),s>0&&this.log.info({evictedCount:s,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(s=>{if(!s[e])return s;t=!0;let{[e]:g,...S}=s;return S})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let s=[],g=!1,S=this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;g=!0;let E=Date.now();return s.push({currentDoc:w.currentDoc,ts:E}),{...S,[e]:{...w,mode:t,ts:E}}}),w=s[0];S&&w?this.log.debug({agentId:e,action:`touchMode`,currentDoc:w.currentDoc,ts:w.ts,mode:t},`[agent-presence] touchMode`):g||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(s=>{let g=s[e];if(!g)return s;let S=Date.now();return t=S,{...s,[e]:{...g,ts:S}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let s=t.getLocalState()??{},g=e(s.agentPresence??{});return t.setLocalState({...s,agentPresence:g}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null,fileSpanExporter=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(e={}){let t=e.localSink!==void 0,s=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!s||tracerProvider)return noopResult();try{let g=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),S=new import_src$2.AsyncLocalStorageContextManager;context.setGlobalContextManager(S);let w=[],E=e.localSink?.attributeDenylist??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;w.push(new ScrubbingSpanProcessor({attributeDenylist:E})),t&&e.localSink!==void 0&&(fileSpanExporter=new FileSpanExporter({projectDir:e.localSink.projectDir,maxBytes:e.localSink.spansMaxBytes}),w.push(new import_src$7.SimpleSpanProcessor(fileSpanExporter))),s&&w.push(new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter));let D=new import_src$7.BasicTracerProvider({resource:g,spanProcessors:w});trace.setGlobalTracerProvider(D),tracerProvider=D;try{propagation.setGlobalPropagator(new import_src.W3CTraceContextPropagator)}catch(e){getLogger(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let O=null;s&&(O=new import_src$6.MeterProvider({resource:g,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]}),metrics.setGlobalMeterProvider(O)),meterProvider=O,getLogger(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:s,otlp_endpoint:s?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:g.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized`)}catch(e){let t=getLogger(`telemetry`);tracerProvider===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),meterProvider=null,fileSpanExporter=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),meterProvider=null)}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3,shutdownHooks=new Set;function onTelemetryShutdown(e){shutdownHooks.add(e)}async function shutdownTelemetry(){let e=getLogger(`telemetry`);for(let t of shutdownHooks)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!tracerProvider&&!meterProvider)return;let t=(fileSpanExporter?fileSpanExporter.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),s;await Promise.race([t.then(()=>(s!==void 0&&clearTimeout(s),!1)),new Promise(e=>{s=setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS),s.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,fileSpanExporter=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,s){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await s(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,s){return getTracer().startActiveSpan(e,t??{},e=>{try{return s(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,s,g){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:s,"body.bytes":t.length,"doc.name":e.guid}},()=>{let s=e.getXmlFragment(`default`),S=e.getText(`source`),w=S.toString(),{body:E}=stripFrontmatter(t),D=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":E.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(E,buildParseOpts(g))),O=schema.nodeFromJSON(D);w!==t&&applyFastDiff(S,w,t),updateYFragment(e,s,O,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,s){withSpanSync(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let g=e.getXmlFragment(`default`),S=e.getText(`source`),{body:w}=stripFrontmatter(t),E=mdManager.parseWithFallback(w,buildParseOpts(s)),D=schema.nodeFromJSON(E),O=S.toString();O!==t&&(S.delete(0,O.length),S.insert(0,t)),updateYFragment(e,g,D,{mapping:new Map,isOMark:new Map})})}function deriveFragmentFromYtext(e,t){let s=e.getXmlFragment(`default`),{body:g}=stripFrontmatter(e.getText(`source`).toString()),S=mdManager.parseWithFallback(g,buildParseOpts(t));updateYFragment(e,s,schema.nodeFromJSON(S),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(e)??0)+1;this.seqs.set(e,s);let g=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:s});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(e,s),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let g=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});s.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,s);let g=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:s,branch:e});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,s)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,g);let S=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:g,docName:e,sv:Buffer.from(t).toString(`base64`)});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,s]of this.latestDiskAckSVs)e[t]=Buffer.from(s).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g);let S=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:g,docName:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g);let S=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:g,path:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let s=extname(e).slice(1).toLowerCase();return s.length>0&&t.has(s)}function stripDocExtension(e){let t=e.toLowerCase();for(let s of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(s))return e.slice(0,-s.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let s=canonicalize(t);if(!s)throw Error(`registerDocExtension: unsupported extension "${t}"`);let g=docExtensionByName.get(e);if(!g)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let S=canonicalize(g);return S?S===s?{effective:g,changed:!1,shadowed:null}:rank(s)<rank(S)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g}):{effective:g,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$10=()=>getLogger(`http`);let _apiErrorCounter=null;function apiErrorCounter(){return _apiErrorCounter||=getMeter().createCounter(`ok.api.error.count`,{description:`API error responses by problem type and handler`,unit:`1`}),_apiErrorCounter}function errorResponse(e,t,s,g,S={}){let w=S.instance??`urn:uuid:${randomUUID()}`;if(e.headersSent||e.writableEnded||e.destroyed){log$10().error({event:`api.error.double-write`,instance:w,type:s,status:t,handler:S.handler},`errorResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let E={type:s,title:g,status:t,instance:w,detail:S.detail??void 0},D=ProblemDetailsSchema.safeParse(E);if(!D.success){log$10().error({event:`api.error.malformed-envelope`,issues:D.error.issues,body:E,handler:S.handler,originalStatus:t},`errorResponse produced an invalid ProblemDetails body — emitting fallback`);let s=500;apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}let O=S.extensions?{...S.extensions,...E}:E;apiErrorCounter().add(1,{type:s,...S.handler?{handler:S.handler}:{}});let k=t>=500?`error`:`warn`;log$10()[k]({event:`api.error`,instance:w,type:s,status:t,handler:S.handler,detail:S.detail,err:S.cause},g);let j;try{j=JSON.stringify(O)}catch(s){log$10().error({event:`api.error.unserializable-body`,bodyKeys:Object.keys(O),handler:S.handler,originalStatus:t,instance:w,err:s},`errorResponse wireBody is not JSON-serializable — emitting hardcoded fallback`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(j)}function streamingProblemEvent(e,t,s,g={}){let S=g.instance??`urn:uuid:${randomUUID()}`,w={type:`error`,problem:{type:t,title:s,status:e,instance:S,detail:g.detail??void 0}},E=StreamingProblemEventSchema.safeParse(w);if(!E.success){log$10().error({event:`api.streaming.malformed-envelope`,issues:E.error.issues,body:w,handler:g.handler,originalStatus:e},`streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback`);let t=500;return apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...g.handler?{handler:g.handler}:{}}),{type:`error`,problem:{type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:S}}}apiErrorCounter().add(1,{type:t,...g.handler?{handler:g.handler}:{}});let D=e>=500?`error`:`warn`;return log$10()[D]({event:`api.streaming.error`,instance:S,type:t,status:e,handler:g.handler,detail:g.detail,err:g.cause},s),w}function createStreamingErrorWriter(e,t){return(s,g,S,w={})=>{if(e.writableEnded||e.destroyed){log$10().error({event:`api.streaming.error.suppressed`,type:g,status:s,handler:t,detail:w.detail,err:w.cause},`createStreamingErrorWriter called after writableEnded/destroyed — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...t?{handler:t}:{}});return}let E=streamingProblemEvent(s,g,S,{handler:t,...w});try{e.write(`${JSON.stringify(E)}\n`)}catch(e){log$10().error({event:`api.streaming.error.write-failed`,type:g,status:s,handler:t,err:w.cause,writeErr:e},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const RESOLUTION_OPTIONS=[`mine`,`theirs`,`content`,`delete`];function isDocInConflict(e){return e.getMap(`lifecycle`).get(`status`)===`conflict`}var DocInConflictError=class extends Error{file;name=`DocInConflictError`;constructor(e){super(`Document is in conflict: ${e.file}`),this.file=e.file}};function respondDocInConflict(e,t,s){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:s,"doc.name":stripDocExtension(t.file)})),errorResponse(e,409,`urn:ok:error:doc-in-conflict`,`Document is in conflict.`,{handler:s,detail:`The document is in a merge-conflict state. Call conflicts({ kind: "content" }) + resolve_conflict before retrying.`,extensions:{file:t.file,resolutionOptions:RESOLUTION_OPTIONS}})}const byteLength$1=e=>Buffer.byteLength(e,`utf8`);function capContent(e){let t=byteLength$1(e);return t<=51200?{kind:`inline`,content:e}:{kind:`truncated`,byteLength:t,hint:`Converged content exceeds the inline cap — re-read via exec("cat <doc>") for the full document.`}}function evaluateContentDivergence(e,t,s){if(e===t)return;let g=byteLength$1(t),S=byteLength$1(e);return{intendedBytes:g,actualBytes:S,byteDelta:S-g,divergenceType:`${s}-content-mismatch`,currentState:capContent(e)}}const DEFAULT_DIVERGENCE_HINT="The converged document differs from the bytes you composed. The write landed; `currentState` carries what is in the document now — re-read only if it is truncated.";function toContentDivergenceWarning(e,t=DEFAULT_DIVERGENCE_HINT){return{kind:`content-divergence`,intendedBytes:e.intendedBytes,actualBytes:e.actualBytes,byteDelta:e.byteDelta,divergenceType:e.divergenceType,currentState:e.currentState,hint:t}}const FIX_HINT='Frontmatter must be a flat mapping where each value is a string, number, boolean, or array of scalars. Quote string values containing YAML-significant characters (`:`, `#`, leading `-`), e.g. `title: "Foo: bar"`.';var FrontmatterMalformedError=class extends Error{file;parseError;name=`FrontmatterMalformedError`;constructor(e){super(`Frontmatter YAML is malformed in ${e.file}: ${e.parseError}`),this.file=e.file,this.parseError=e.parseError}};function respondFrontmatterMalformed(e,t,s){console.warn(JSON.stringify({event:`frontmatter-malformed-write-refused`,handler:s,"doc.name":stripDocExtension(t.file),parseError:t.parseError})),errorResponse(e,400,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,{handler:s,detail:`${t.parseError}. ${FIX_HINT}`,extensions:{file:t.file,parseError:t.parseError}})}let _editSurfaceCounter=null;function editSurfaceCounter(){return _editSurfaceCounter||=getMeter().createCounter(`ok.frontmatter.edit_surface_total`,{description:`Count of frontmatter edits by surface. Bounded label: source ∈ {source-mode, mcp-write, file-watcher}.`}),_editSurfaceCounter}function recordFrontmatterEditSurface(e){editSurfaceCounter().add(1,{source:e})}const log$9=getLogger(`agent-sessions`),AGENT_WRITE_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function docNameToFile(e){return e.endsWith(`.md`)||e.endsWith(`.mdx`)?e:`${stripDocExtension(e)}${getDocExtension(e)}`}function applyAgentMarkdownWrite(e,t,s,g){if(isDocInConflict(e))throw new DocInConflictError({file:docNameToFile(e.name)});return withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":s,"agent.markdown.bytes":t.length}},()=>{let S=applyAgentMarkdownWriteInner(e,t,s,g);return S!==void 0&&setActiveSpanAttributes({"agent.content_divergent":!0,"agent.intended_bytes":S.intendedBytes,"agent.actual_bytes":S.actualBytes,"agent.byte_delta":S.byteDelta,"agent.divergence_type":S.divergenceType}),S})}function applyAgentMarkdownWriteInner(e,t,s,g){try{let{frontmatter:S,body:w}=stripFrontmatter(e.getText(`source`).toString()),{frontmatter:E,body:D}=stripFrontmatter(t);if((s===`append`||s===`prepend`)&&D===``)return;let O,k;switch(s){case`replace`:O=E||S,k=D;break;case`patch`:O=E||S,k=D;break;case`prepend`:O=S,k=w.length>0?`${D.replace(/\n+$/,``)}\n\n${w.replace(/^\n+/,``)}`:D;break;case`append`:O=S,k=w.length>0?`${w.replace(/\n+$/,``)}\n\n${D.replace(/^\n+/,``)}`:D;break}if(O!==S){let t=parseFrontmatterYaml(unwrapFrontmatterFences(O));if(t.map===null)throw new FrontmatterMalformedError({file:docNameToFile(e.name),parseError:t.parseError??`unknown YAML parse error`});recordFrontmatterEditSurface(`mcp-write`)}let j=prependFrontmatter(O,k);return s===`replace`?replaceRawBody(e,j,g):composeAndWriteRawBody(e,j,`agent`,g),evaluateContentDivergence(e.getText(`source`).toString(),j,s)}catch(g){throw g instanceof FrontmatterMalformedError||log$9.error({err:g,docName:e.name,position:s,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),g}}function applyAgentUndo(e,t,s){let g=e.dc.document;if(isDocInConflict(g))throw new DocInConflictError({file:docNameToFile(g.name)});return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let g=applyAgentUndoInner(e,t,s);return setActiveSpanAttributes({"agent.undo_effective":g}),g})}function applyAgentUndoInner(e,t,s){let{dc:g,um:S,undoOrigin:w}=e,E=g.document,D=!1;return E.transact(()=>{if(t===`last`){if(S.undoStack.length===0)return;S.undo(),D=!0}else for(;S.undoStack.length>0;)S.undo(),D=!0;deriveFragmentFromYtext(E,s)},w),D}function createSessionOrigin(e,t,s,g,S){let w={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(w.agent_type=t),s!==void 0&&(w.principal=s),g!==void 0&&(w.display_name=g),S!==void 0&&(w.color_seed=S),Object.freeze(w);let E={source:`local`,skipStoreHooks:!1,context:w};return Object.freeze(E),E}function createUndoOrigin(e,t){let s={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(s.agent_type=t),Object.freeze(s);let g={source:`local`,skipStoreHooks:!1,context:s};return Object.freeze(g),g}const MAX_AGENT_SESSIONS=256;var AgentSessionCapacityError=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}},AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;maxSessions;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,s]of this.sessions)e.endsWith(t)&&(yield s)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,s){if(isSystemDoc(e)||isConfigDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let g=this.sessionKey(e,t),S=this.sessions.get(g);if(S)return S;let w=this.pendingSessions.get(g);if(w)return w;if(this.sessions.size+this.pendingSessions.size>=this.maxSessions)throw new AgentSessionCapacityError(this.maxSessions);let E=this._createSession(e,t,s);this.pendingSessions.set(g,E);try{let e=await E;return this.sessions.set(g,e),e}finally{this.pendingSessions.delete(g)}}async _createSession(e,t,s){let g=s?.clientName,S=t.startsWith(`agent-`)?t.slice(6):t,w=createSessionOrigin(S,g,s?.principalId,s?.displayName,s?.colorSeed),E=createUndoOrigin(S,g),D={session_id:S,...g===void 0?{}:{agent_type:g},...s?.clientName===void 0?{}:{client_name:s.clientName},...s?.principalId===void 0?{}:{principalId:s.principalId}},O=await this.hocuspocus.openDirectConnection(e,D),k=new UndoManager([O.document.getText(`source`),O.document.getMap(`agent-flash`)],{trackedOrigins:new Set([w]),captureTimeout:500,captureTransaction:e=>e.origin!==E,ignoreRemoteMapChanges:!0}),j=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return k.on(`stack-item-added`,j),k.on(`stack-item-updated`,j),log$9.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:O,origin:w,undoOrigin:E,um:k,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,s){try{try{t.um.destroy()}catch(e){log$9.error({err:e,...s},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){log$9.error({err:e,...s},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=`claude-1`){let s=this.sessionKey(e,t),g=this.sessions.get(s);g&&(await this.cleanupSession(s,g,{docName:e,agentId:t}),log$9.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,s=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));s.length>0&&await Promise.allSettled(s.map(e=>this.pendingSessions.get(e)));let g=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of g){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,s=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of s){let s=this.sessions.get(t);s&&await this.cleanupSession(t,s,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RING_BUFFER_LIMIT=50;let _effectCounter=0;const EFFECT_CAPTURE_ORIGIN=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function captureEffect(e,t,s,g){let S=e.doc;if(!S)return;let w=++_effectCounter,E=S.getMap(`agent-effects`),D=k=>{e.unobserve(D),S.off(`destroy`,O);let j=`${t}:${w}`,F={sessionId:t,timestamp:Date.now(),delta:k.delta,agent_type:g??`agent`,color_seed:s??t};try{S.transact(()=>{if(E.set(j,F),E.size>RING_BUFFER_LIMIT){let e=[...E.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,E.size-RING_BUFFER_LIMIT))E.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let s=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:s})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},O=()=>{e.unobserve(D)};e.observe(D),S.once(`destroy`,O)}function collectItemsInDeleteSet(e,t,s){iterateDeletedStructs(e,t,e=>{e instanceof Item&&s.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let s=[],g=[],S=t.doc,w=new Set,E=new Set;S&&S.transact(t=>{collectItemsInDeleteSet(t,e.insertions,w),collectItemsInDeleteSet(t,e.deletions,E)});let D=``,O=``,k=0,j=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,S=t.length,F=w.has(e),L=E.has(e);e.deleted?L&&(g.push({position:k,content:t,length:S}),D+=t,k+=S):(O+=t,F?s.push({position:j,content:t,length:S}):(D+=t,k+=S),j+=S)}return{insertions:s,deletions:g,before:D,after:O}}function synthesizeStackItemDiffText(e,t,s){let{before:g,after:S}=synthesizeStackItemDiff(e,t);return g===S?``:createPatch(s,g,S,void 0,void 0,{context:3})}function getBurstTs(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function countStackItemChanges(e,t){let s=t.doc,g=new Set,S=new Set;s&&s.transact(t=>{collectItemsInDeleteSet(t,e.insertions,g),collectItemsInDeleteSet(t,e.deletions,S)});let w=0,E=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&g.has(e)&&(w+=t),S.has(e)&&(E+=t)}return{additions:w,deletions:E}}function listAgentActivity(e,t){let s=[],g=null,S=!1;for(let w of e.sessionsForConnection(t)){if(S=!0,!g){let e=w.origin.context,s=typeof e?.agent_type==`string`?e.agent_type:void 0,S=typeof e?.color_seed==`string`?e.color_seed:t,E=iconFromClientName(s),D=AGENT_ICON_COLORS[E]??colorFromSeed(S);g={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:D,icon:E,connectionId:t}}let e=w.docName,E=w.um,D=w.dc.document.getText(`source`),O=[];for(let e=0;e<E.undoStack.length;e++){let t=E.undoStack[e],s=getBurstTs(t),{additions:g,deletions:S}=countStackItemChanges(t,D);O.push({stackIndex:e,ts:s,additions:g,deletions:S})}if(O.length===0)continue;O.sort((e,t)=>t.stackIndex-e.stackIndex);let k=O.reduce((e,t)=>e+t.additions,0),j=O.reduce((e,t)=>e+t.deletions,0),F=Math.max(...O.map(e=>e.ts));s.push({docName:e,additionsTotal:k,deletionsTotal:j,lastTs:F,bursts:O})}return S?(s.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:g,files:s}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`,LINE_TERMINATOR_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function normalizeSummary(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(LINE_TERMINATOR_RE,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}const counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let s=getCounters(e);s.lastUserTxGen=++globalCounter,s.lastUserTxAtMs=Date.now()},s=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,s),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,s)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let s=counters.get(e);return s?s.settledGen>s.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let s=counters.get(e);return!s||s.lastUserTxAtMs===null?null:Math.max(0,t-s.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,s=Date.now()){let g=rateKey(e,t),S=lastEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)s-t>=w&&lastEmitMs.delete(e);return lastEmitMs.set(g,s),!0}function shouldEmitBridgeToleranceApplied(e,t,s=Date.now()){let g=toleranceRateKey(e,t),S=lastToleranceEmitMs.get(g),w=readDebounceMs();return S!==void 0&&s-S<w?!1:(lastToleranceEmitMs.set(g,s),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let s=e??`__nodoc__`,g=lastPathBEmitMs.get(s),S=readDebounceMs();if(g!==void 0&&t-g<S)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,s]of lastPathBEmitMs)t-s>=S&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(s,t),!0}function emitObserverAPathBFired(e,t){let s=shouldEmitObserverAPathBFired(e,t);return s||incrementObserverAPathBFiresSuppressed(),s}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,s){let g=normalizeBridge(e),S=normalizeBridge(t);if(g===S){if(e!==t){let g=detectAppliedToleranceClasses(e,t);for(let e of g)shouldEmitBridgeToleranceApplied(s.site,e,s.nowMs)&&(incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:s.site,class:e})))}return!0}let w={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${g.slice(0,300)}\n frag: ${S.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(w);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let E=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(w,{verbose:E}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,s){let g={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return s&&Object.assign(g,s),g}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,s){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,s)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,s){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,s)})}function tracedAppendFileSync(e,t,s){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,s)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,s){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,s)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
|
|
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}var PinoLogger=class{name;transportConfigs=[];fileSinkOpts;redactPaths;activeFileSink;pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:import_pino.default.stdSerializers.err,error:import_pino.default.stdSerializers.err},mixin:otelMixin,...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),t.fileSink&&(this.fileSinkOpts=t.fileSink),t.redactPaths&&t.redactPaths.length>0&&(this.redactPaths=t.redactPaths,this.options={...this.options,redact:{paths:[...t.redactPaths],censor:`[REDACTED]`}}),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.activeFileSink=void 0,this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));let e;try{e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`})}catch(e){if(console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),this.fileSinkOpts){let e=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=e,(0,import_pino.default)(this.options,import_pino.default.multistream([{stream:e}]))}return(0,import_pino.default)(this.options)}if(this.fileSinkOpts){let t=new PinoFileSink(this.fileSinkOpts);return this.activeFileSink=t,(0,import_pino.default)(this.options,import_pino.default.multistream([{stream:e},{stream:t}]))}return(0,import_pino.default)(this.options,e)}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}getPinoInstance(){return this.pinoInstance}async flushFileSink(){this.activeFileSink&&await this.activeFileSink.drain()}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}},LoggerFactory=class{config={};loggers=new Map;configure(e){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let s;return s=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,s),s}reset(){this.config={},this.loggers.clear()}async flushAllFileSinks(){let e=[];for(let t of this.loggers.values())e.push(t.flushFileSink());await Promise.all(e)}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}function createTestLogger(e=`test`){return new PinoLogger(e,{options:{level:`silent`}})}function installTestLoggers(){loggerFactory.configure({pinoConfig:{options:{level:`silent`}}})}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(s=>({...s,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:s,...g}=t;return g})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let s=t.getLocalState()??{},g=e(s.agentFocus??{});t.setLocalState({...s,agentFocus:g})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),getAwareness$1(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function getAwareness$1(e){return e?.awareness??null}const counters$1={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0};function incrementReconcile(){counters$1.reconcileCount++}function incrementConflict(){counters$1.conflictCount++}function incrementBatch(){counters$1.batchCount++}function incrementUpstreamImport(){counters$1.upstreamImportCount++}function incrementRescueBuffer(){counters$1.rescueBufferCount++}function incrementBranchSwitch(){counters$1.branchSwitchCount++}function incrementPark(){counters$1.parkCount++}function incrementGitAutoSaveFailure(){counters$1.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters$1.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters$1.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters$1.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters$1.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters$1.serverObserverFiresA++:counters$1.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters$1.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters$1.serverObserverErrorsA++:counters$1.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters$1.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters$1.agentWriteCalls++}function incrementSummariesProvided(){counters$1.summariesProvided++}function incrementSummariesTruncated(){counters$1.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters$1.bridgeMergeCheckpointCreated++}function incrementBridgeInvariantViolations(){counters$1.bridgeInvariantViolations++}function incrementBridgeInvariantViolationsSuppressed(){counters$1.bridgeInvariantViolationsSuppressed++}function incrementPersistenceSkipNonQuiescent(){counters$1.persistenceSkipNonQuiescent++}function incrementPersistenceForceFlushDuringBurst(){counters$1.persistenceForceFlushDuringBurst++}function incrementAgentPatchFindMismatches(){counters$1.agentPatchFindMismatches++}function incrementBridgeToleranceApplied(e){counters$1.bridgeToleranceApplied[e]=(counters$1.bridgeToleranceApplied[e]??0)+1}function incrementObserverAPathBFires(){counters$1.observerAPathBFires++}function incrementObserverAPathBFiresSuppressed(){counters$1.observerAPathBFiresSuppressed++}function incrementPersistenceReconciliationFailures(){counters$1.persistenceReconciliationFailures++}function incrementExternalChangeHandlerErrors(){counters$1.externalChangeHandlerErrors++}function incrementPersistenceSanityCheckSerializeFailures(){counters$1.persistenceSanityCheckSerializeFailures++}function incrementDeferredStoreFailures(){counters$1.deferredStoreFailures++}function incrementAuthRenameRedirect(){counters$1.authRenameRedirectCount++}function incrementAuthDocDeleted(){counters$1.authDocDeletedCount++}function incrementRecentlyRemovedDocsEviction(){counters$1.recentlyRemovedDocsEvictions++}function setRecentlyRemovedDocsSize(e){counters$1.recentlyRemovedDocsSize=e}function incrementAuthRemovalGuardError(){counters$1.authRemovalGuardErrors++}function incrementRemovalRedirectChainCycle(){counters$1.removalRedirectChainCycles++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters$1.collabSocketEpipeCount++:counters$1.collabSocketEconnresetCount++}function incrementCollabMessageTooLarge(){counters$1.collabMessageTooLargeCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters$1.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters$1.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters$1.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters$1.cc1LastSeq[e]=t}function getMetrics(){return{...counters$1,cc1LastSeq:{...counters$1.cc1LastSeq},bridgeToleranceApplied:{...counters$1.bridgeToleranceApplied}}}function resetMetrics(){counters$1.reconcileCount=0,counters$1.conflictCount=0,counters$1.batchCount=0,counters$1.upstreamImportCount=0,counters$1.rescueBufferCount=0,counters$1.branchSwitchCount=0,counters$1.parkCount=0,counters$1.gitAutoSaveFailureCount=0,counters$1.gitWriterCommitFailureCount=0,counters$1.cc1BroadcastCount=0,counters$1.cc1BroadcastDropCount=0,counters$1.cc1SubscriberCount=0,counters$1.cc1LastSeq={},counters$1.serverObserverFiresA=0,counters$1.serverObserverFiresB=0,counters$1.serverObserverErrorsA=0,counters$1.serverObserverErrorsB=0,counters$1.persistenceDiskWrites=0,counters$1.bridgeMergeContentLoss=0,counters$1.bridgeMergeCheckpointCreated=0,counters$1.bridgeInvariantViolations=0,counters$1.bridgeInvariantViolationsSuppressed=0,counters$1.persistenceSkipNonQuiescent=0,counters$1.persistenceForceFlushDuringBurst=0,counters$1.collabSocketEpipeCount=0,counters$1.collabSocketEconnresetCount=0,counters$1.collabMessageTooLargeCount=0,counters$1.shadowMigrationLegacyRefsDeleted=0,counters$1.effectDiffCaptureFailures=0,counters$1.agentPresenceMutationErrors=0,counters$1.agentWriteCalls=0,counters$1.summariesProvided=0,counters$1.summariesTruncated=0,counters$1.agentPatchFindMismatches=0,counters$1.bridgeToleranceApplied={},counters$1.observerAPathBFires=0,counters$1.observerAPathBFiresSuppressed=0,counters$1.persistenceReconciliationFailures=0,counters$1.externalChangeHandlerErrors=0,counters$1.persistenceSanityCheckSerializeFailures=0,counters$1.deferredStoreFailures=0,counters$1.authRenameRedirectCount=0,counters$1.authDocDeletedCount=0,counters$1.recentlyRemovedDocsEvictions=0,counters$1.recentlyRemovedDocsSize=0,counters$1.authRemovalGuardErrors=0,counters$1.removalRedirectChainCycles=0}const BROADCASTER_EVICTION_MS=5e3*4;var AgentPresenceBroadcaster=class{hocuspocus;log=getLogger(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!isPresenceEligibleAgentId(e))return;let s=0;this.mutateAgentPresence(g=>{let S=Date.now(),w={};for(let[t,E]of Object.entries(g)){if(S-E.ts>=2e4&&t!==e){s++;continue}w[t]=E}return w[e]=t,w})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),s>0&&this.log.info({evictedCount:s,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(s=>{if(!s[e])return s;t=!0;let{[e]:g,...S}=s;return S})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let s=[],g=!1,S=this.mutateAgentPresence(S=>{let w=S[e];if(!w)return S;g=!0;let E=Date.now();return s.push({currentDoc:w.currentDoc,ts:E}),{...S,[e]:{...w,mode:t,ts:E}}}),w=s[0];S&&w?this.log.debug({agentId:e,action:`touchMode`,currentDoc:w.currentDoc,ts:w.ts,mode:t},`[agent-presence] touchMode`):g||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!isPresenceEligibleAgentId(e))return;let t=null;this.mutateAgentPresence(s=>{let g=s[e];if(!g)return s;let S=Date.now();return t=S,{...s,[e]:{...g,ts:S}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let s=t.getLocalState()??{},g=e(s.agentPresence??{});return t.setLocalState({...s,agentPresence:g}),!0}catch(e){return incrementAgentPresenceMutationError(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),getAwareness(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function getAwareness(e){return e?.awareness??null}const mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null,fileSpanExporter=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(e={}){let t=e.localSink!==void 0,s=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!s||tracerProvider)return noopResult();try{let g=(0,import_src$5.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),S=new import_src$2.AsyncLocalStorageContextManager;context.setGlobalContextManager(S);let w=[],E=e.localSink?.attributeDenylist??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;w.push(new ScrubbingSpanProcessor({attributeDenylist:E})),t&&e.localSink!==void 0&&(fileSpanExporter=new FileSpanExporter({projectDir:e.localSink.projectDir,maxBytes:e.localSink.spansMaxBytes}),w.push(new import_src$7.SimpleSpanProcessor(fileSpanExporter))),s&&w.push(new import_src$7.BatchSpanProcessor(new import_src$4.OTLPTraceExporter));let D=new import_src$7.BasicTracerProvider({resource:g,spanProcessors:w});trace.setGlobalTracerProvider(D),tracerProvider=D;try{propagation.setGlobalPropagator(new import_src.W3CTraceContextPropagator)}catch(e){getLogger(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let O=null;s&&(O=new import_src$6.MeterProvider({resource:g,readers:[new import_src$6.PeriodicExportingMetricReader({exporter:new import_src$3.OTLPMetricExporter})]}),metrics.setGlobalMeterProvider(O)),meterProvider=O,getLogger(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:s,otlp_endpoint:s?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:g.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized`)}catch(e){let t=getLogger(`telemetry`);tracerProvider===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),meterProvider=null,fileSpanExporter=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),meterProvider=null)}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3,shutdownHooks=new Set;function onTelemetryShutdown(e){shutdownHooks.add(e)}async function shutdownTelemetry(){let e=getLogger(`telemetry`);for(let t of shutdownHooks)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!tracerProvider&&!meterProvider)return;let t=(fileSpanExporter?fileSpanExporter.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([tracerProvider?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),meterProvider?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),s;await Promise.race([t.then(()=>(s!==void 0&&clearTimeout(s),!1)),new Promise(e=>{s=setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS),s.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=null,fileSpanExporter=null,trace.disable(),metrics.disable(),context.disable()}function getTracer(){return trace.getTracer(TRACER_NAME)}function getMeter(){return metrics.getMeter(TRACER_NAME)}async function withSpan(e,t,s){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await s(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function withSpanSync(e,t,s){return getTracer().startActiveSpan(e,t??{},e=>{try{return s(e)}catch(t){throw e.recordException(t),e.setStatus({code:SpanStatusCode.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function setActiveSpanAttributes(e){let t=trace.getSpan(context.active());t&&t.setAttributes(e)}function buildParseOpts(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function composeAndWriteRawBody(e,t,s,g){withSpanSync(`bridge.composeAndWriteRawBody`,{attributes:{surface:s,"body.bytes":t.length,"doc.name":e.guid}},()=>{let s=e.getXmlFragment(`default`),S=e.getText(`source`),w=S.toString(),{body:E}=stripFrontmatter(t),D=withSpanSync(`md.parseWithFallback`,{attributes:{"body.bytes":E.length,"doc.name":e.guid}},()=>mdManager.parseWithFallback(E,buildParseOpts(g))),O=schema.nodeFromJSON(D);w!==t&&applyFastDiff(S,w,t),updateYFragment(e,s,O,{mapping:new Map,isOMark:new Map})})}function replaceRawBody(e,t,s){withSpanSync(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let g=e.getXmlFragment(`default`),S=e.getText(`source`),{body:w}=stripFrontmatter(t),E=mdManager.parseWithFallback(w,buildParseOpts(s)),D=schema.nodeFromJSON(E),O=S.toString();O!==t&&(S.delete(0,O.length),S.insert(0,t)),updateYFragment(e,g,D,{mapping:new Map,isOMark:new Map})})}function deriveFragmentFromYtext(e,t){let s=e.getXmlFragment(`default`),{body:g}=stripFrontmatter(e.getText(`source`).toString()),S=mdManager.parseWithFallback(g,buildParseOpts(t));updateYFragment(e,s,schema.nodeFromJSON(S),{mapping:new Map,isOMark:new Map})}const DEBOUNCE_MS=100,MAX_DISK_ACK_SVS=1e3;function isSystemDoc(e){return e===SYSTEM_DOC_NAME}const CONFIG_DOC_NAME_SET=new Set(CONFIG_DOC_NAMES);function isConfigDoc(e){return CONFIG_DOC_NAME_SET.has(e)}var CC1Broadcaster=class{hocuspocus;seqs=new Map;timers=new Map;log=getLogger(`cc1`);warnedMissing=!1;latestDiskAckSVs=new Map;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},DEBOUNCE_MS))}broadcast(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(e)??0)+1;this.seqs.set(e,s);let g=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:s});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(e,s),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let g=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});s.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_SERVER_INFO,0)}catch(e){this.log.error({err:e},`[cc1] emitServerInfo failed`)}}emitBranchSwitched(e){try{let t=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitBranchSwitched — dropped`),!0),incrementCC1BroadcastDrop();return}let s=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,s);let g=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:s,branch:e});t.broadcastStateless(JSON.stringify(g)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,s)}catch(e){this.log.error({err:e},`[cc1] emitBranchSwitched failed`)}}emitDiskAck(e,t){if(this.latestDiskAckSVs.delete(e),this.latestDiskAckSVs.set(e,t),this.latestDiskAckSVs.size>MAX_DISK_ACK_SVS){let e=this.latestDiskAckSVs.keys().next().value;e!==void 0&&this.latestDiskAckSVs.delete(e)}try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,g);let S=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:g,docName:e,sv:Buffer.from(t).toString(`base64`)});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,s]of this.latestDiskAckSVs)e[t]=Buffer.from(s).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g);let S=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:g,docName:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,g)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected failed`)}}emitConfigIgnoreNestedError(e,t){try{let s=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!s){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigIgnoreNestedError — dropped`),!0),incrementCC1BroadcastDrop();return}let g=(this.seqs.get(`config-ignore-nested-error`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g);let S=CC1ConfigIgnoreNestedErrorPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,seq:g,path:e,error:t});s.broadcastStateless(JSON.stringify(S)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,g)}catch(t){this.log.error({err:t,path:e},`[cc1] emitConfigIgnoreNestedError failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const SUPPORTED_DOC_EXTENSIONS=[`.mdx`,`.md`],DEFAULT_EXTENSION=`.md`;function isSupportedDocFile(e){let t=extname(e).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.includes(t)}function isSupportedAssetFile(e,t){let s=extname(e).slice(1).toLowerCase();return s.length>0&&t.has(s)}function stripDocExtension(e){let t=e.toLowerCase();for(let s of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(s))return e.slice(0,-s.length);return e}function canonicalize(e){let t=e.toLowerCase();return t===`.mdx`?`.mdx`:t===`.md`?`.md`:null}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let s=canonicalize(t);if(!s)throw Error(`registerDocExtension: unsupported extension "${t}"`);let g=docExtensionByName.get(e);if(!g)return docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null};let S=canonicalize(g);return S?S===s?{effective:g,changed:!1,shadowed:null}:rank(s)<rank(S)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g}):{effective:g,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:g})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const log$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 counters=new WeakMap;let globalCounter=0;function getCounters(e){let t=counters.get(e);return t||(t={lastUserTxGen:0,settledGen:0,lastUserTxAtMs:null},counters.set(e,t)),t}function isObserverSelfOrigin(e){if(!e||typeof e!=`object`)return!1;let t=e.context;return t!=null&&t.origin===`observer-sync`}function attachQuiescenceTracker(e){let t=t=>{if(isObserverSelfOrigin(t.origin))return;let s=getCounters(e);s.lastUserTxGen=++globalCounter,s.lastUserTxAtMs=Date.now()},s=()=>{getCounters(e).settledGen=++globalCounter};return e.on(`afterTransaction`,t),e.on(`afterAllTransactions`,s),()=>{e.off(`afterTransaction`,t),e.off(`afterAllTransactions`,s)}}const overrides=new WeakMap;function isDocQuiescent(e){let t=overrides.get(e);if(t!==void 0)return t;let s=counters.get(e);return s?s.settledGen>s.lastUserTxGen:!0}function getMsSinceLastUserTx(e,t=Date.now()){let s=counters.get(e);return!s||s.lastUserTxAtMs===null?null:Math.max(0,t-s.lastUserTxAtMs)}const DEFAULT_DEBOUNCE_S=60,lastEmitMs=new Map,MAX_VIOLATION_RATE_TUPLES=1024,lastToleranceEmitMs=new Map,lastPathBEmitMs=new Map;function toleranceRateKey(e,t){return`${e}::${t}`}function readDebounceMs(){let e=process.env.OK_BRIDGE_VIOLATION_DEBOUNCE_S;if(e===void 0)return DEFAULT_DEBOUNCE_S*1e3;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?DEFAULT_DEBOUNCE_S*1e3:t*1e3}function rateKey(e,t){return`${e}::${t??`__nodoc__`}`}function shouldEmitBridgeInvariantViolation(e,t,s=Date.now()){let g=rateKey(e,t),S=lastEmitMs.get(g),w=readDebounceMs();if(S!==void 0&&s-S<w)return!1;if(lastEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,t]of lastEmitMs)s-t>=w&&lastEmitMs.delete(e);return lastEmitMs.set(g,s),!0}function shouldEmitBridgeToleranceApplied(e,t,s=Date.now()){let g=toleranceRateKey(e,t),S=lastToleranceEmitMs.get(g),w=readDebounceMs();return S!==void 0&&s-S<w?!1:(lastToleranceEmitMs.set(g,s),!0)}function shouldEmitObserverAPathBFired(e,t=Date.now()){let s=e??`__nodoc__`,g=lastPathBEmitMs.get(s),S=readDebounceMs();if(g!==void 0&&t-g<S)return!1;if(lastPathBEmitMs.size>=MAX_VIOLATION_RATE_TUPLES)for(let[e,s]of lastPathBEmitMs)t-s>=S&&lastPathBEmitMs.delete(e);return lastPathBEmitMs.set(s,t),!0}function emitObserverAPathBFired(e,t){let s=shouldEmitObserverAPathBFired(e,t);return s||incrementObserverAPathBFiresSuppressed(),s}function shouldThrowOnBridgeInvariantViolation(e=process.env){return e.NODE_ENV===`test`||e.OK_BRIDGE_THROW_ON_VIOLATION===`1`}function assertBridgeInvariant(e,t,s){let g=normalizeBridge(e),S=normalizeBridge(t);if(g===S){if(e!==t){let g=detectAppliedToleranceClasses(e,t);for(let e of g)shouldEmitBridgeToleranceApplied(s.site,e,s.nowMs)&&(incrementBridgeToleranceApplied(e),console.warn(JSON.stringify({event:`bridge-tolerance-applied`,site:s.site,class:e})))}return!0}let w={site:s.site,origin:s.origin,docName:s.docName,ytextSnapshot:e,fragmentMdSnapshot:t,unifiedDiff:` ytext: ${g.slice(0,300)}\n frag: ${S.slice(0,300)}`,stack:Error().stack};if(shouldThrowOnBridgeInvariantViolation()&&!s.suppressDevThrow)throw new BridgeInvariantViolationError(w);if(!shouldEmitBridgeInvariantViolation(s.site,s.docName,s.nowMs))return incrementBridgeInvariantViolationsSuppressed(),!1;incrementBridgeInvariantViolations();let E=process.env.OK_TELEMETRY_VERBOSE===`1`;return console.warn(JSON.stringify(toBridgeInvariantLog(w,{verbose:E}))),!1}const CONFIG_VALIDATION_REVERT_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},CONFIG_FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function normalizeFsPath(e){let t=e.split(sep).filter(Boolean);return t.length<=2?e:`...${sep}${t.slice(-2).join(sep)}`}function classifyFsPath(e){return e.includes(`${sep}.git${sep}ok${sep}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${sep}.git${sep}`)?`git`:basename(e).endsWith(`.lock`)||basename(e)===`lock`?`lock`:basename(e)===`principal.json`?`principal`:e.includes(`${sep}.ok${sep}`)&&(basename(e)===`conflicts.json`||e.includes(`${sep}conflicts${sep}`))?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,s){let g={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return s&&Object.assign(g,s),g}function byteLength(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function tracedWriteFile(e,t,s){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,s)})}async function tracedRename(e,t){return withSpan(`fs.rename`,{attributes:buildAttrs(`rename`,t,{"fs.source_path":normalizeFsPath(e)})},async()=>{await rename(e,t)})}async function tracedMkdir(e,t){return withSpan(`fs.mkdir`,{attributes:buildAttrs(`mkdir`,e)},async()=>mkdir(e,t))}function tracedWriteFileSync(e,t,s){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,s)})}function tracedAppendFileSync(e,t,s){withSpanSync(`fs.appendFileSync`,{attributes:buildAttrs(`appendFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{appendFileSync(e,t,s)})}function tracedMkdirSync(e,t){return withSpanSync(`fs.mkdirSync`,{attributes:buildAttrs(`mkdirSync`,e)},()=>mkdirSync(e,t))}function tracedRenameSync(e,t){withSpanSync(`fs.renameSync`,{attributes:buildAttrs(`renameSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{renameSync(e,t)})}function tracedCpSync(e,t,s){withSpanSync(`fs.cpSync`,{attributes:buildAttrs(`cpSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{cpSync(e,t,s)})}function tracedUnlinkSync(e){withSpanSync(`fs.unlinkSync`,{attributes:buildAttrs(`unlinkSync`,e)},()=>{unlinkSync(e)})}function tracedLinkSync(e,t){withSpanSync(`fs.linkSync`,{attributes:buildAttrs(`linkSync`,t,{"fs.source_path":normalizeFsPath(e)})},()=>{linkSync(e,t)})}function tracedRmSync(e,t){withSpanSync(`fs.rmSync`,{attributes:buildAttrs(`rmSync`,e)},()=>{rmSync(e,t)})}function tracedRmdirSync(e){withSpanSync(`fs.rmdirSync`,{attributes:buildAttrs(`rmdirSync`,e)},()=>{rmdirSync(e)})}function configScopeAttr(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let _okignoreRejectionCounter=null;function okignoreRejectionCounter(){return _okignoreRejectionCounter||=getMeter().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),_okignoreRejectionCounter}function emitSchemaInvalidIssueEvents(e){if(isKnownConfigError(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function configDocAbsPath(e,t){if(e===`__config__/project`)return resolveConfigPath(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return resolveConfigPath(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return resolveConfigPath(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return resolve(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let cachedDefaultsYaml=null;function serializedDefaults(){return cachedDefaultsYaml===null&&(cachedDefaultsYaml=(0,import_dist$1.stringify)(ConfigSchema$1.parse({}))),cachedDefaultsYaml}function validateOkignore(e){if(e.length===0)return{ok:!0};let t=e.split(`
|
|
775
775
|
`);for(let e=0;e<t.length;e++){let s=t[e]??``;if(s.length!==0&&/^\s+$/.test(s))return{ok:!1,error:{code:`OKIGNORE_INVALID`,detail:`Whitespace-only pattern is not allowed.`,lineNumber:e+1}}}return{ok:!0}}function validateConfigContent(e,t){return e===`__config__/okignore`?validateOkignore(t):validateConfigYaml(t)}function defaultLkgFor(e){return e===`__config__/okignore`?``:serializedDefaults()}function validateConfigYaml(e){let t=(0,import_dist$1.parseDocument)(e);if(t.errors.length>0)return{ok:!1,error:{code:`YAML_PARSE`,detail:t.errors.map(e=>e.message).join(`; `)}};let s=t.toJSON()??{},g=ConfigSchema$1.safeParse(s);return g.success?{ok:!0}:{ok:!1,error:{code:`SCHEMA_INVALID`,issues:g.error.issues.map(e=>({path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}))}}}function loadConfigDoc(e,t,s){let g=e.getText(`source`);if(g.length>0)return;let S=configDocAbsPath(t,s),w=``;if(existsSync(S))try{w=readFileSync(S,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[config] Could not read ${S}: ${t}. Seeding with empty content.`),w=``}let E=validateConfigContent(t,w);!E.ok&&w.length>0&&getLogger(`config-persistence`).warn({docName:t,path:S},`[config-persistence] loadConfigDoc seeding invalid content for ${t} into Y.Text — first mutation will revert to LKG`),e.transact(()=>{w.length>0&&g.insert(0,w)},CONFIG_VALIDATION_REVERT_ORIGIN),E.ok&&w.length>0?s.lkgCache.set(t,w):s.lkgCache.set(t,defaultLkgFor(t))}async function atomicWriteConfig(e,t){await tracedMkdir(dirname(e),{recursive:!0});let s=`${e}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(s,t,`utf-8`),await tracedRename(s,e)}catch(e){try{tracedUnlinkSync(s)}catch{}throw e}}async function storeConfigDoc(e,t,s,g){return withConfigSpan(`config.persist`,{"config.scope":configScopeAttr(t),"config.transport":`fs`},async S=>{let w=await storeConfigDocInner(e,t,s,g);return S.setAttribute(`config.outcome`,persistOutcomeAttr(w)),w})}function persistOutcomeAttr(e){return e===`reverted`?`reverted`:e===`write-failed`?`rejected`:`success`}async function storeConfigDocInner(e,t,s,g){if(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(`
|
|
@@ -797,14 +797,14 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
|
|
|
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
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}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 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=``,O=!1,k=!1,j=()=>stripFrontmatter(g.toString()).frontmatter;try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e);D=prependFrontmatter(j(),t)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),D=``}let F=()=>{try{let O=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),k=S.serialize(O),F=prependFrontmatter(j(),k);if(D===F)return;let L=g.toString();if(normalizeBridge(L)===normalizeBridge(F)){D=F;return}let B=D,H={mergedText:null};t.transact(()=>{if(L===D)applyIncrementalDiff(g,L,F);else try{let e=mergeThreeWay(D,F,L);applyFastDiff(g,L,e),H.mergedText=e}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(E(e,B),shouldRethrowBridgeMergeLoss()))throw e;applyFastDiff(g,L,e.info.result),H.mergedText=e.info.result}},OBSERVER_SYNC_ORIGIN),H.mergedText!==null&&emitObserverAPathBFired(e.docName)&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!0,mergeBytesChanged:Math.abs(H.mergedText.length-L.length)}))),incrementServerObserverFire(`a`),D=g.toString()}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{D=g.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},L=()=>{withSpanSync(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},F)},B=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=j();D=g.toString(),H=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)),O=!0}return}O=!0}};if(s.length>0&&g.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(e),O=prependFrontmatter(j(),E);t.transact(()=>{g.insert(0,O)},OBSERVER_SYNC_ORIGIN),D=O}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),D=``}let H=j(),q=()=>{try{let w=g.toString(),{frontmatter:E,body:O}=stripFrontmatter(w);if(normalizeBridge(D)===normalizeBridge(w)){H!==E&&(recordFrontmatterEditSurface(`source-mode`),H=E);return}let k=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,j=S.parseWithFallback(O,k),F=e.schema.nodeFromJSON(j);t.transact(()=>{updateYFragment(t,s,F,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),H!==E&&(recordFrontmatterEditSurface(`source-mode`),H=E),incrementServerObserverFire(`b`);try{let t=prependFrontmatter(E,S.serialize(j));assertBridgeInvariant(g.toString(),t,{site:`observer-b`,docName:e.docName}),D=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),D=prependFrontmatter(E,O)}}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);D=prependFrontmatter(j(),t)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},ee=()=>{withSpanSync(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},q)},J=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=j();D=g.toString(),H=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)),k=!0}return}k=!0}},Y=(t,s)=>{withSpanSync(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!O&&!k){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(s.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){O=!1,k=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}let g=O,S=k;O&&(O=!1,e.onDispatch?.(`a`),L()),k&&(k=!1,e.onDispatch?.(`b`),ee()),t.setAttribute(`observer.dispatch`,g&&S?`a-then-b`:g?`a`:S?`b`:`none`)})};s.observeDeep(B),g.observe(J),t.on(`afterAllTransactions`,Y);let te=attachQuiescenceTracker(t);return()=>{te(),t.off(`afterAllTransactions`,Y),s.unobserveDeep(B),g.unobserve(J)}}const log$8=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$8.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$8.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){de++,incrementGitAutoSaveFailure(),log$8.error({err:e,attempt:de},`[persistence] Shadow commit failed (attempt ${de})`),de>=3&&log$8.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$8.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$8.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$8.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}w.startsWith(`agent-`)&&O?.()}catch(e){restoreContributorEntry(w,E),incrementGitWriterCommitFailure(),log$8.error({err:e,writer:w},`[persistence] Per-writer shadow commit failed for ${w}`)}}S?de=0:(de++,incrementGitAutoSaveFailure(),de>=3&&log$8.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$8.info({},`[persistence] Empty repo — starting with empty index`):log$8.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$8.info({sha:S.slice(0,8),wipRef:se},`[persistence] Git commit: ${S.slice(0,8)} on ${se}`)}catch(e){de++,incrementGitAutoSaveFailure(),log$8.error({err:e,attempt:de},`[persistence] Git commit failed (attempt ${de})`),de>=3&&log$8.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$8.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$8.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$8.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$8.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$8.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$8.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$8.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$8.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$8.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$8.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=``,O=!1,k=!1,j=()=>stripFrontmatter(g.toString()).frontmatter;try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e);D=prependFrontmatter(j(),t)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),D=``}let F=()=>{try{let O=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),k=S.serialize(O),F=prependFrontmatter(j(),k);if(D===F)return;let L=g.toString();if(normalizeBridge(L)===normalizeBridge(F)){D=F;return}let B=D,H={mergedText:null};t.transact(()=>{if(L===D)applyIncrementalDiff(g,L,F);else try{let e=mergeThreeWay(D,F,L);applyFastDiff(g,L,e),H.mergedText=e}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(E(e,B),shouldRethrowBridgeMergeLoss()))throw e;applyFastDiff(g,L,e.info.result),H.mergedText=e.info.result}},OBSERVER_SYNC_ORIGIN),H.mergedText!==null&&emitObserverAPathBFired(e.docName)&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!0,mergeBytesChanged:Math.abs(H.mergedText.length-L.length)}))),incrementServerObserverFire(`a`),D=g.toString()}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{D=g.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},L=()=>{withSpanSync(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},F)},B=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=j();D=g.toString(),H=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)),O=!0}return}O=!0}};if(s.length>0&&g.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(e),O=prependFrontmatter(j(),E);t.transact(()=>{g.insert(0,O)},OBSERVER_SYNC_ORIGIN),D=O}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),D=``}let H=j(),q=()=>{try{let w=g.toString(),{frontmatter:E,body:O}=stripFrontmatter(w);if(normalizeBridge(D)===normalizeBridge(w)){H!==E&&(recordFrontmatterEditSurface(`source-mode`),H=E);return}let k=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,j=S.parseWithFallback(O,k),F=e.schema.nodeFromJSON(j);t.transact(()=>{updateYFragment(t,s,F,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),H!==E&&(recordFrontmatterEditSurface(`source-mode`),H=E),incrementServerObserverFire(`b`);try{let t=prependFrontmatter(E,S.serialize(j));assertBridgeInvariant(g.toString(),t,{site:`observer-b`,docName:e.docName}),D=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),D=prependFrontmatter(E,O)}}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);D=prependFrontmatter(j(),t)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},ee=()=>{withSpanSync(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},q)},J=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=j();D=g.toString(),H=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)),k=!0}return}k=!0}},Y=(t,s)=>{withSpanSync(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!O&&!k){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(s.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){O=!1,k=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}let g=O,S=k;O&&(O=!1,e.onDispatch?.(`a`),L()),k&&(k=!1,e.onDispatch?.(`b`),ee()),t.setAttribute(`observer.dispatch`,g&&S?`a-then-b`:g?`a`:S?`b`:`none`)})};s.observeDeep(B),g.observe(J),t.on(`afterAllTransactions`,Y);let te=attachQuiescenceTracker(t);return()=>{te(),t.off(`afterAllTransactions`,Y),s.unobserveDeep(B),g.unobserve(J)}}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
|
-
`,`utf-8`),S&&se!==void 0){let s=null;try{existsSync(me)&&(s=readFileSync(me,`utf-8`))}catch(e){s=null,log$
|
|
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)},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
|
|
804
804
|
`,`
|
|
805
805
|
`).replaceAll(`\r`,`
|
|
806
806
|
`).split(`
|
|
807
|
-
`))s(S)||collectHrefsFromLine(stripHtmlComments(S,g).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let s=extname(t).slice(1).toLowerCase();if(!LINKABLE_ASSET_EXTENSIONS.has(s))return null;let g=resolveAssetProjectPath(t,e.fromDocName);if(!g)return null;let S=resolve(e.contentDir,g),w,E;try{if(w=normalize(realpathSync(S)),!isWithinContentDir(w,e.contentDir))return null;E=statSync(w)}catch(t){let s=errnoCode$1(t);return s!==`ENOENT`&&s!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return E.isFile()?{absolutePath:w,relativePath:toContentRelativePath(e.contentDir,w),stat:E}:null}function toContentRelativePath(e,t){let s=normalize(realpathSync(e));return normalize(t).slice(s.length+(s.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let s=new Map;for(let[g,S]of e.fileIndex){let w=e.readMarkdown(S.canonicalPath);if(w!==null)for(let S of extractLocalAssetHrefs(w)){let w=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:g,href:S});if(!w||e.isExcluded?.(w.relativePath))continue;let E=mediaKindForAssetPath(w.absolutePath),D=s.get(w.relativePath);if(D){D.referencedBy.includes(g)||D.referencedBy.push(g);continue}s.set(w.relativePath,{kind:`asset`,path:w.relativePath,assetExt:extname(w.relativePath).toLowerCase(),mediaKind:E,size:w.stat.size,modified:w.stat.mtime.toISOString(),referencedBy:[g]})}}return[...s.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:s,inlineExtensions:g,assetExtensions:S,blocklistExtensions:w}=e;return(e,E,D)=>{let O;try{O=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return D()}let k=extname(O).slice(1).toLowerCase(),j=k===`md`||k===`mdx`;if(!O||t.isPathIgnored(O)||!j&&!S.has(k))return D();E.setHeader(`X-Content-Type-Options`,`nosniff`)
|
|
807
|
+
`))s(S)||collectHrefsFromLine(stripHtmlComments(S,g).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let s=extname(t).slice(1).toLowerCase();if(!LINKABLE_ASSET_EXTENSIONS.has(s))return null;let g=resolveAssetProjectPath(t,e.fromDocName);if(!g)return null;let S=resolve(e.contentDir,g),w,E;try{if(w=normalize(realpathSync(S)),!isWithinContentDir(w,e.contentDir))return null;E=statSync(w)}catch(t){let s=errnoCode$1(t);return s!==`ENOENT`&&s!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return E.isFile()?{absolutePath:w,relativePath:toContentRelativePath(e.contentDir,w),stat:E}:null}function toContentRelativePath(e,t){let s=normalize(realpathSync(e));return normalize(t).slice(s.length+(s.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let s=new Map;for(let[g,S]of e.fileIndex){let w=e.readMarkdown(S.canonicalPath);if(w!==null)for(let S of extractLocalAssetHrefs(w)){let w=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:g,href:S});if(!w||e.isExcluded?.(w.relativePath))continue;let E=mediaKindForAssetPath(w.absolutePath),D=s.get(w.relativePath);if(D){D.referencedBy.includes(g)||D.referencedBy.push(g);continue}s.set(w.relativePath,{kind:`asset`,path:w.relativePath,assetExt:extname(w.relativePath).toLowerCase(),mediaKind:E,size:w.stat.size,modified:w.stat.mtime.toISOString(),referencedBy:[g]})}}return[...s.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`,"7z":`application/x-7z-compressed`,tar:`application/x-tar`,rar:`application/vnd.rar`,xls:`application/vnd.ms-excel`,ppt:`application/vnd.ms-powerpoint`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,pages:`application/vnd.apple.pages`,numbers:`application/vnd.apple.numbers`,key:`application/vnd.apple.keynote`,mobi:`application/x-mobipocket-ebook`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:s,inlineExtensions:g,assetExtensions:S,blocklistExtensions:w}=e;return(e,E,D)=>{let O;try{O=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return D()}let k=extname(O).slice(1).toLowerCase(),j=k===`md`||k===`mdx`;if(!O||t.isPathIgnored(O)||!j&&!S.has(k))return D();E.setHeader(`X-Content-Type-Options`,`nosniff`);let F=SANDBOXED_HTML_EXTENSIONS.has(k);j||(g.has(k)||F?E.setHeader(`Content-Disposition`,`inline`):E.setHeader(`Content-Disposition`,`attachment`)),k===`svg`?E.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`):F&&(E.setHeader(`Content-Security-Policy`,SANDBOXED_HTML_CSP),E.setHeader(`Cache-Control`,`no-store`)),s(e,E,()=>{if(E.headersSent)return;let e=SANDBOXED_HTML_EXTENSIONS.has(k);if(!e&&(S.has(k)||w.has(k))){E.statusCode=404,E.end();return}e&&(E.removeHeader(`Content-Security-Policy`),E.removeHeader(`Content-Disposition`),E.removeHeader(`X-Content-Type-Options`),E.removeHeader(`Cache-Control`)),D()})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let s=resolve(e),g=resolve(s,t),S=relative(s,g);return S===``?{ok:!0,abs:g,rel:``}:S===`..`||S.startsWith(`../`)||isAbsolute(S)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:g,rel:S}}function agentIdentityFields(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target Open Knowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),VERSION_FIELD_DESCRIBE="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",versionInputSchema=string().length(40).regex(/^[0-9a-f]+$/i).describe(VERSION_FIELD_DESCRIBE),previewUrlOutputField=string().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),previewUrlSourceField=string().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),previousPreviewUrlField=string().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),summaryOutputSchema=object$1({value:string(),truncatedFrom:number().optional(),hint:string().optional()}).describe(`Normalized change-note summary, when one was recorded.`),looseObjectArray=array(record(string(),unknown())),previewAttachWarningField=record(string(),unknown()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),documentResultBaseShape={summary:summaryOutputSchema.optional(),contentDivergence:WriteWarningSchema.optional().describe(`Present when the converged Y.Text didn't byte-match the bytes you composed, or when an out-of-band disk edit was reconciled in before your write landed.`)};function nestDocResult(e,t,s){let g={};return e&&(g.previewUrl=e.url,g.previewUrlSource=e.source),t&&(g.warning=t),Object.keys(s).length>0&&(g.document=s),g}function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const TEXT_CHANNEL_FIELD=string().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function outputSchemaWithText(e){return{text:TEXT_CHANNEL_FIELD,...e}}function textPlusStructured(e,t,s){let g={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:g,...s?{isError:!0}:{}}}const HOCUSPOCUS_NOT_RUNNING_ERROR="Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",ROLE_LABEL={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},ROLE_BEFORE={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},ROLE_AFTER={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function buildWorkflowFrame(e){return`## Where this fits
|
|
808
808
|
|
|
809
809
|
Open Knowledge accretes a persistent wiki through three workflow tools, mapped to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f):
|
|
810
810
|
|
|
@@ -823,7 +823,8 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
|
|
|
823
823
|
|
|
824
824
|
`}function buildWorkflowHandler(e,t,s,g){return async S=>{let w=typeof S.cwd==`string`?S.cwd:void 0,E=await resolveProjectConfigContext(t.resolveCwd,t.config,w);if(!E.ok)return textResult(`Error: ${E.error}`,!0);let D=S[s],O=typeof D==`string`?D:``;return textPlusStructured(`${buildWorkflowFrame(e)}${g(O,E.config.content.dir)}`,{previewUrl:null})}}async function resolveServerUrl(e,t){return typeof e==`function`?await e(t):e}async function resolveConfig(e,t){return typeof e==`function`?await e(t):e}async function resolveProjectConfigContext(e,t,s){let g;try{g=await e(s)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await resolveConfig(t,g);return{ok:!0,cwd:g,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function resolveProjectServerContext(e,t,s,g){let S=await resolveProjectConfigContext(e,t,g);if(!S.ok)return S;let{cwd:w,config:E}=S;try{return{ok:!0,cwd:w,config:E,url:await resolveServerUrl(s,w)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function normalizeDocName(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let s=e,g=t;for(;g.endsWith(`.mdx`)||g.endsWith(`.md`);)s=s.slice(0,g.endsWith(`.mdx`)?-4:-3),g=s.toLowerCase();let S=validateDocName(s);return S.ok?{ok:!0,docName:s}:{ok:!1,error:`Error: "${e}" is invalid — ${S.reason}.`}}function normalizeResponse(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...s}=t;return{ok:!0,...s}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let s=t;if(typeof s.type==`string`&&typeof s.title==`string`){let{type:e,title:t,status:g,instance:S,detail:w,...E}=s;return{...E,ok:!1,error:t,type:e,...typeof g==`number`?{status:g}:{},...typeof S==`string`?{instance:S}:{},...typeof w==`string`?{detail:w}:{}}}let{ok:g,error:S,...w}=s,E=typeof S==`string`?S:typeof s.message==`string`?s.message:`Server returned HTTP ${e.status}`;return{...w,ok:!1,error:E}}async function httpGet(e,t){let s;try{s=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let g;try{g=await s.json()}catch(e){let t=e instanceof Error?e.message:String(e);return s.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${s.status} with non-JSON body: ${t}`}}return normalizeResponse(s,g)}async function httpSend(e,t,s,g){let S;if(g!==void 0)try{S=JSON.stringify(g)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}let w;try{w=await fetch(`${t}${s}`,{method:e,headers:S===void 0?void 0:{"Content-Type":`application/json`},body:S,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let E;try{E=await w.json()}catch(e){let t=e instanceof Error?e.message:String(e);return w.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${w.status} with non-JSON body: ${t}`}}return normalizeResponse(w,E)}function httpPost(e,t,s){return httpSend(`POST`,e,t,s)}function httpPut(e,t,s){return httpSend(`PUT`,e,t,s)}function httpDelete(e,t){return httpSend(`DELETE`,e,t)}function parseRenameCollidingPairs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:s,to:g}=e;return typeof t==`string`&&typeof s==`string`&&typeof g==`string`?[{existing:t,incoming:s,to:g}]:[]}):[]}function readFolderFrontmatter(e,t){let s=nestedOkPath(e,t,`frontmatter.yml`);if(!existsSync(s))return{};let g=readFrontmatterYaml(s);return g==null?{}:coerceWellKnown(g)}function coerceWellKnown(e){let t={};for(let[s,g]of Object.entries(e))t[s]=g;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const warnedPaths=new Set;function readFrontmatterYaml(e){let t;try{t=readFileSync(e,`utf-8`)}catch{return null}let s;try{s=(0,import_dist$1.parse)(t)}catch(t){if(!warnedPaths.has(e)){warnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-folder-frontmatter] malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${s}`)}return null}return typeof s!=`object`||!s||Array.isArray(s)?null:(warnedPaths.delete(e),s)}function nestedOkPath(e,t,s){let g=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return g===``||g===`.`?join(e,`.ok`,s):join(e,g,`.ok`,s)}function parentFolderOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}const GIT_TIMEOUT_MS$2=5e3;function projectHasGitDir(e){try{return statSync(resolve(e,`.git`)).isDirectory()}catch{return!1}}function openProjectGit(e){return esm_default({baseDir:resolve(e),timeout:{block:GIT_TIMEOUT_MS$2}})}async function readProjectGitLog(e,t,s=5){if(!projectHasGitDir(e))return{commits:[],source:`git-absent`};let g=openProjectGit(e),S=``;try{S=await g.raw(`log`,`-${Math.max(1,s)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let w=[];for(let e of S.split(`
|
|
825
825
|
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let s=e.indexOf(`|`,t+1);if(s<0)continue;let g=e.indexOf(`|`,s+1);g<0||w.push({hash:e.slice(0,t),date:e.slice(t+1,s),authorName:e.slice(s+1,g),subject:e.slice(g+1)})}return{commits:w,source:`git`}}const GIT_TIMEOUT_MS$1=5e3;async function currentProjectBranch(e){try{let t=(await esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS$1}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function openShadowGit(e,t){return esm_default({baseDir:t,timeout:{block:GIT_TIMEOUT_MS$1}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function writerIdFromRef(e,t){let s=getWipRefPattern(t);return e.startsWith(s)?e.slice(s.length):e}async function logOnRef(e,t,s,g,S){let w=``;try{w=await e.raw(`log`,t,`-${Math.max(1,S*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,s)}catch{return[]}let E=writerIdFromRef(t,g),D=parseWriterId(E),O=[];for(let e of w.split(``)){let t=e.trimStart();if(!t)continue;let[s=``,S=``,w=``,k=``,j=``]=t.split(`\0`),F=s.trim();F.length===40&&O.push({hash:F,date:S,writerName:w,message:k,contributors:readContributors(j),writerId:E,isAgent:D.isAgent,writerClassification:D.classification,branch:g})}return O}async function readShadowLog(e,t,s=5){let g=getShadowRepoPath(e);if(!g)return{commits:[],source:`shadow-repo-absent`};let S=await currentProjectBranch(e);if(!S)return{commits:[],source:`shadow-repo`};let w=openShadowGit(g,resolve(e)),E=``;try{E=await w.raw(`for-each-ref`,getWipRefPattern(S),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let D=E.split(`
|
|
826
|
-
`).map(e=>e.trim()).filter(Boolean);return D.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(D.map(e=>logOnRef(w,e,t,S,s)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s),source:`shadow-repo`}}function resolveTemplatesAvailable(e,t,s={}){let g=normalizeFolderPath(t),S=g===``?[]:g.split(`/`),w=new Set,E=[];collectFromFolder(e,g,`local`,w,E);for(let t=S.length-1;t>=1;t--)collectFromFolder(e,S.slice(0,t).join(`/`),`inherited`,w,E);return S.length>0&&collectFromFolder(e,``,`inherited`,w,E),E}function resolveProjectTemplates(e){let t=[],s=new Map,g=e=>{let t=s.get(e);return t||(t=new Set,s.set(e,t)),t},S=0,w=!1,E=[``];for(;E.length>0;){let s=E.shift()??``;if(S++>=PROJECT_TEMPLATE_SCAN_CAP){w=!0,console.warn(`[ok-templates] project scan hit the ${PROJECT_TEMPLATE_SCAN_CAP}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${E.length}.`);break}collectFromFolder(e,s,`local`,g(s),t);let D=s?join(e,s):e,O;try{O=readdirSync(D).sort()}catch(e){if(e?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(D)){templateMetaWarnedPaths.add(D);let t=e instanceof Error?e.message:String(e);console.warn(`[ok-templates] failed to read directory ${D} during project scan — skipped. Reason: ${t}`)}continue}for(let e of O){if(PROJECT_TEMPLATE_DIR_SKIP.has(e)||e.startsWith(`.`))continue;let t=join(D,e),g;try{g=statSync(t)}catch{continue}if(!g.isDirectory())continue;let S=s?posix.join(s,e):e;E.push(S)}}return{templates:t,truncated:w}}const PROJECT_TEMPLATE_SCAN_CAP=2e3,PROJECT_TEMPLATE_DIR_SKIP=new Set([`node_modules`,`dist`,`build`]);function collectFromFolder(e,t,s,g,S){let w=t?join(e,t,`.ok`,`templates`):join(e,`.ok`,`templates`);if(!existsSync(w))return;let E;try{E=readdirSync(w)}catch{return}for(let e of E){if(!e.endsWith(`.md`))continue;let E=e.slice(0,-3);if(g.has(E))continue;let D=join(w,e),O;try{O=statSync(D)}catch{continue}if(!O.isFile())continue;let k=readTemplateMeta(D),j={name:E,path:t?posix.join(t,`.ok`,`templates`,e):posix.join(`.ok`,`templates`,e),source_folder:t,scope:s};k.title!==void 0&&(j.title=k.title),k.description!==void 0&&(j.description=k.description),g.add(E),S.push(j)}}function normalizeFolderPath(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const templateMetaWarnedPaths=new Set;function readTemplateMeta(e){let t;try{t=readFileSync(e,`utf-8`)}catch(t){if(t?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] failed to read template at ${e} — metadata skipped. Reason: ${s}`)}return{}}let s=extractFrontmatterYaml(t);if(s===null)return{};let g;try{g=(0,import_dist$1.parse)(s)}catch(t){if(!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] malformed YAML frontmatter at ${e} — title/description unavailable. Reason: ${s}`)}return{}}if(typeof g!=`object`||!g)return{};let S=g,w={};return typeof S.title==`string`&&(w.title=S.title),typeof S.description==`string`&&(w.description=S.description),w}function extractFrontmatterYaml(e){let t=e.replace(/^/,``),s=/^[ \t]*---\r?\n([\s\S]*?)\r?\n[ \t]*---(\r?\n|$)/.exec(t);return s?s[1]??null:null}const FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function parseFrontmatterRaw(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]);if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i;function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${s}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.backlinks??s.results??s.links;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e,s=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;s&&S.push({source:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let s=[...new Set(t)],g=[];for(let e=0;e<s.length;e+=BACKLINK_COUNT_CHUNK)g.push(s.slice(e,e+BACKLINK_COUNT_CHUNK));let S=await Promise.all(g.map(async t=>{let s=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return s.ok?s.counts??{}:null})),w=new Map,E=!1;for(let e of S)if(e){E=!0;for(let[t,s]of Object.entries(e))typeof s==`number`&&Number.isFinite(s)&&w.set(t,s)}return E?w:null}async function fetchForwardLinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.forwardLinks??s.links??s.results;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){S.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let s=typeof t.docName==`string`?t.docName:void 0;s&&S.push({kind:`doc`,docName:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}function liftOwnFrontmatter(e){let t=e??{};return{title:typeof t.title==`string`?t.title:void 0,description:typeof t.description==`string`?t.description:void 0,tags:Array.isArray(t.tags)?t.tags.filter(e=>typeof e==`string`):[],frontmatter:t}}async function enrichPath(e,t,s={}){let g=resolveWithinRoot(t.projectDir,e);if(!g.ok)throw Error(`enrichPath: ${g.reason}`);let S=g.rel,w=g.abs,E=t.historyDepth??5,D=s.includeRichFields===!0,O=readFrontmatter(w);if(!D){let e=liftOwnFrontmatter(await O);return{path:S,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[k,j,F,L,B]=await Promise.all([O,fetchBacklinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),readShadowLog(t.projectDir,S,E).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,S,E).catch(()=>({commits:[],source:`git`}))]),H=liftOwnFrontmatter(k);return{path:S,title:H.title,description:H.description,tags:H.tags,frontmatter:H.frontmatter,backlinkCount:j?.length??null,backlinks:j,forwardLinkCount:F?.length??null,forwardLinks:F,history:L.commits,historySource:L.source,projectHistory:B.commits,projectHistorySource:B.source}}async function scanDirectory(e,t){let s={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},g=0,S=[{path:e,depth:0}];for(;S.length>0;){let e=S.shift();if(!e)break;if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}let w;try{w=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let E of w){if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}g++;let w=E.name;if(E.isDirectory()){if(DIR_SKIP.has(w)||w.startsWith(`.`))continue;e.depth===0&&s.childDirCount++,S.push({path:`${e.path}/${w}`,depth:e.depth+1})}else if(E.isFile()&&WIKI_EXT_RE.test(w)){s.recursiveMdCount++,e.depth===0&&s.directMdCount++;let g=`${e.path}/${w}`;try{let e=await stat$1(g);(!s.mostRecent||e.mtimeMs>s.mostRecent.mtimeMs)&&(s.mostRecent={absPath:g,relPath:relative(t,g).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return s}async function enrichDirectory(e,t){let s=resolveWithinRoot(t.projectDir,e);if(!s.ok)throw Error(`enrichDirectory: ${s.reason}`);let g=s.rel,S=s.abs,w=await scanDirectory(S,t.projectDir),E;if(w.mostRecent){let e=await readFrontmatter(w.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;E={path:w.mostRecent.relPath,title:t??basename(w.mostRecent.relPath),updatedAt:new Date(w.mostRecent.mtimeMs).toISOString()}}let D={path:g,type:`directory`,directMdCount:w.directMdCount,recursiveMdCount:w.recursiveMdCount,childDirCount:w.childDirCount,mostRecentMd:E,truncated:w.truncated},O=readFolderFrontmatter(t.projectDir,g);O.title!==void 0&&(D.title=O.title),O.description!==void 0&&(D.description=O.description),(O.tags?.length??0)>0&&(D.tags=O.tags);let k=resolveTemplatesAvailable(t.projectDir,g);return k.length>0&&(D.templates_available=k),D}async function enrichDirectoryRecursive(e,t,s){let g=await enrichDirectory(e,s);if(t<=1)return g;let S=g.path,w=resolve(s.projectDir,S),E;try{E=await readdir(w,{withFileTypes:!0})}catch{return g}let D=[];for(let e of E){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let g=await enrichDirectoryRecursive(S?`${S}/${e.name}`:e.name,t-1,s);D.push(g)}return D.length>0&&(g.subfolders=D),g}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function mergePatch(e,t){let s={...e};for(let[e,g]of Object.entries(t))if(g!==void 0){if(isEmpty$1(g)){delete s[e];continue}s[e]=g}return s}function dropEmpties(e){let t={};for(let[s,g]of Object.entries(e))g!=null&&(typeof g==`string`&&g===``||Array.isArray(g)&&g.length===0||(t[s]=g));return t}function isEmpty$1(e){return isFrontmatterValueEmpty(e)}function applyFolderFrontmatterPatch(e){if(!isAbsolute(e.anchorDir))return{ok:!1,error:{code:`BAD_CONTENT_DIR`,message:`anchorDir must be absolute`}};let t=resolve(e.anchorDir),s=e.folderRel.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(s.split(`/`).some(e=>e===`..`))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Folder path escapes the content directory: ${e.folderRel}`}};let g=s===``?t:resolve(t,s);if(g!==t&&!g.startsWith(t+sep))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder escapes the content directory: ${g}`}};let S=join(g,`.ok`),w=join(S,`frontmatter.yml`);try{let s=readExistingFrontmatter(w),g=Object.keys(e.patch).length===0?{}:mergePatch(s,e.patch);if(Object.keys(g).length===0)return existsSync(w)?(unlinkSync(w),autoCleanOkDir(S),{ok:!0,path:relPathOf$1(t,w),action:`deleted`}):{ok:!0,path:relPathOf$1(t,w),action:`noop`};mkdirSync(S,{recursive:!0});let E=(0,import_dist$1.stringify)(g),D=`${w}.tmp.${process.pid}.${Date.now()}`;return writeFileSync(D,E,`utf-8`),renameSync(D,w),{ok:!0,path:relPathOf$1(t,w),action:`written`}}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write folder frontmatter for "${s||`.`}": ${e.message}`}}}}function readExistingFrontmatter(e){if(!existsSync(e))return{};let t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:{...t}}function autoCleanOkDir(e){if(!existsSync(e))return;let t;try{t=readdirSync(e)}catch{return}if(t.length===0)try{rmdirSync(e)}catch{}}function relPathOf$1(e,t){return t.startsWith(e+sep)?t.slice(e.length+1).split(sep).join(`/`):t}const SUBSTITUTION_ALLOWLIST=[`date`,`user`],TOKEN_PATTERN=/\{\{([^{}\n]+?)\}\}/g;function validateSubstitution(e){let t=[];for(let s of e.matchAll(TOKEN_PATTERN)){let e=(s[1]??``).trim();isAllowedToken(e)||t.push({token:e,offset:s.index??0})}return t}function applySubstitution(e,t){return e.replace(TOKEN_PATTERN,(e,s)=>{let g=s.trim();return isAllowedToken(g)?t[g]:e})}function isAllowedToken(e){return SUBSTITUTION_ALLOWLIST.includes(e)}function todayIsoUtc(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}const NAME_RE=/^[A-Za-z0-9_-]+$/;function applyTemplateWrite(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let s=validateTitle(e.frontmatter.title);if(!s.ok)return{ok:!1,error:s.error};let g=validateSubstitutionAllowlist(e.body);if(!g.ok)return{ok:!1,error:g.error};let{templatesDir:S,filePath:w}=templatePaths(e.projectDir,t.folderRel,e.name),E=serializeFrontmatter(e.frontmatter),D=E?`---\n${E}---\n${e.body}`:e.body;try{mkdirSync(S,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${relPathOf(e.projectDir,S)}: ${t.message}`}}}let O=!existsSync(w),k=`${w}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(k,D,`utf-8`),renameSync(k,w)}catch(t){try{unlinkSync(k)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${relPathOf(e.projectDir,w)}: ${t.message}`}}}let j=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&j.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,path:relPathOf(e.projectDir,w),created:O,warnings:j}}function applyTemplateDelete(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:s,okDir:g,filePath:S}=templatePaths(e.projectDir,t.folderRel,e.name),w=existsSync(S);if(w)try{unlinkSync(S)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${relPathOf(e.projectDir,S)}: ${t.message}`}}}return{ok:!0,path:relPathOf(e.projectDir,S),existed:w,cleanedEmpty:cleanEmptyOkDirs(s,g)}}function cleanEmptyOkDirs(e,t){let s=!1,g=!1;if(existsSync(e)&&isEmpty(e))try{rmdirSync(e),s=!0}catch{}if(existsSync(t)&&isEmpty(t))try{rmdirSync(t),g=!0}catch{}return{templatesDir:s,okDir:g}}async function applyTemplateMove(e){let t=validateInputs(e.projectDir,e.fromFolder,e.fromName);if(!t.ok)return{ok:!1,error:t.error};let s=validateInputs(e.projectDir,e.toFolder,e.toName);if(!s.ok)return{ok:!1,error:s.error};let g=templatePaths(e.projectDir,t.folderRel,e.fromName),S=templatePaths(e.projectDir,s.folderRel,e.toName);if(g.filePath===S.filePath)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same template.`}};if(!existsSync(g.filePath))return{ok:!1,error:{code:`TEMPLATE_NOT_FOUND`,message:`No template at ${relPathOf(e.projectDir,g.filePath)}.`}};if(existsSync(S.filePath))return{ok:!1,error:{code:`TEMPLATE_EXISTS`,message:`A template already exists at ${relPathOf(e.projectDir,S.filePath)}.`}};try{mkdirSync(S.templatesDir,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create destination template directory at ${relPathOf(e.projectDir,S.templatesDir)}: ${t.message}`}}}let w;try{w=await e.relocate(g.filePath,S.filePath)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move template: ${e.message}`}}}let E=cleanEmptyOkDirs(g.templatesDir,g.okDir);return{ok:!0,fromPath:relPathOf(e.projectDir,g.filePath),toPath:relPathOf(e.projectDir,S.filePath),committed:w,cleanedEmpty:E}}function validateInputs(e,t,s){if(!isAbsolute(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!NAME_RE.test(s))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(s)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let g=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(g.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let S=g?resolve(e,g):e,w=resolve(e);return!S.startsWith(w+sep)&&S!==w?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${S}`}}:{ok:!0,folderRel:g}}function validateTitle(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function validateSubstitutionAllowlist(e){let t=validateSubstitution(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function templatePaths(e,t,s){let g=t?join(e,t,`.ok`):join(e,`.ok`),S=join(g,`templates`);return{okDir:g,templatesDir:S,filePath:join(S,`${s}.md`)}}function relPathOf(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function serializeFrontmatter(e){let t={};return e.title!==void 0&&(t.title=e.title),e.description!==void 0&&(t.description=e.description),Array.isArray(e.tags)&&e.tags.length>0&&(t.tags=e.tags),Object.keys(t).length===0?``:(0,import_dist$1.stringify)(t)}function isEmpty(e){try{return readdirSync(e).length===0}catch{return!1}}var RingBuffer=class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let s=1;s<=t;s++){let t=(this.writeIndex-s+this.capacity)%this.capacity,g=this.store[t];g!==void 0&&e.push(g)}return e}get size(){return this.filled?this.capacity:this.writeIndex}};const embedProbeRing=new RingBuffer(256);function recordEmbedProbe(e){embedProbeRing.push(e)}const CURSOR_UA_RE=UA_PATTERNS.cursor,CODEX_UA_RE=UA_PATTERNS.codex,CLAUDE_UA_RE=UA_PATTERNS[`claude-desktop`],CURSOR_REFERER_STRATEGY_LITERAL=`?strategy=C_iframe`,EMPTY_DETECTION={app:null,signals_fired:[]};function deriveDetection(e){if(!e)return{...EMPTY_DETECTION};let t=[],s=e.ua,g=e.referer,S=!!s&&CURSOR_UA_RE.test(s),w=!!g&&g.includes(CURSOR_REFERER_STRATEGY_LITERAL);if(S&&t.push(`cursor_ua_regex`),w&&t.push(`cursor_referer_strategy_iframe`),S||w)return{app:`cursor`,signals_fired:t};let E=!!s&&CODEX_UA_RE.test(s);if(E&&t.push(`codex_ua_regex`),E)return{app:`codex`,signals_fired:t};let D=!!s&&CLAUDE_UA_RE.test(s);return D&&t.push(`claude_ua_regex`),D?{app:`claude`,signals_fired:t}:{...EMPTY_DETECTION}}const log$7=()=>getLogger(`http`);function successResponse(e,t,s,g,S={}){if(e.headersSent||e.writableEnded||e.destroyed){log$7().error({event:`api.success.double-write`,status:t,handler:S.handler},`successResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let w=s.safeParse(g);if(!w.success){log$7().error({event:`api.success.malformed-body`,issues:w.error.issues,bodyKeys:typeof g==`object`&&g?Object.keys(g):null,handler:S.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}let E;try{E=JSON.stringify(w.data)}catch(s){log$7().error({event:`api.success.unserializable-body`,bodyKeys:typeof w.data==`object`&&w.data!==null?Object.keys(w.data):null,handler:S.handler,originalStatus:t,err:s},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(E)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,s=e.now??Date.now,g=e.ttlMs??6e4;async function S(S){let w=t.get(S);if(w?.status===`resolved`&&w.expiresAt>s())return w.installed;if(w?.status===`inflight`)return w.promise;let E=(async()=>{try{let w=await e.probe(S);return t.set(S,{status:`resolved`,installed:w,expiresAt:s()+g}),w}catch{return t.set(S,{status:`resolved`,installed:!1,expiresAt:s()+g}),!1}})();return t.set(S,{status:`inflight`,promise:E}),E}async function w(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await S(e)]));return Object.fromEntries(e)}return{probeAll:w,probeWithCache:S}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let s=e.headers.origin;if(typeof s==`string`&&s.length>0)try{return isLoopbackHostname(new URL(s).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await s():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return s=>e===`darwin`?probeMacOs(s,t):e===`win32`?probeWindows(s,t):probeLinux(s,t)}function probeMacOs(e,t){let s=MACOS_APP_NAMES[e];function g(e){return new Promise(s=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}return(async()=>{for(let e of s)if(await g(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(s=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{s(!e)})})}function probeLinux(e,t){return new Promise(s=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let s=[],g=0,S=AbortSignal.timeout(t.timeoutMs),w=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));S.addEventListener(`abort`,w,{once:!0});try{for await(let S of e){if(g+=S.length,g>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);s.push(S)}return Buffer.concat(s)}finally{S.removeEventListener(`abort`,w)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,s,g={}){let S=e.safeParse(t);if(S.success)return{ok:!0,value:S.data};let w=S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(s,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:g.handler,detail:w}),{ok:!1}}function withValidation(e,t,s={}){return async(g,S)=>{if(s.method!==void 0&&g.method!==s.method){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:s.handler,extraHeaders:{Allow:s.method}});return}if(s.preBodyGate!==void 0&&!s.preBodyGate(g,S)){!S.headersSent&&!S.writableEnded&&!S.destroyed&&errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(s.skipBodyParse){let w=validateBody(e,{},S,s);if(!w.ok)return;await t(g,S,w.value);return}let w;try{w=await readRequestBody(g)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(S,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(S,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s.handler,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s.handler,cause:e});return}let E;try{E=w.length===0?{}:JSON.parse(w.toString(`utf8`))}catch(e){errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:s.handler,cause:e});return}let D=validateBody(e,E,S,s);D.ok&&await t(g,S,D.value)}}function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,s){return new Promise(g=>{let S=!1,w=e=>{S||(S=!0,g(e))},E=setTimeout(()=>w({ok:!1,reason:`timeout`}),s);try{let s=spawn(e,[...t],{detached:!0,stdio:`ignore`,shell:!1});s.once(`error`,e=>{clearTimeout(E),w(classifySpawnError(e))}),s.once(`spawn`,()=>{if(!S){try{s.unref()}catch{}clearTimeout(E),w({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(E),w(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let w=typeof S.path==`string`?S.path:``;if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(w,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let E=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!E){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let D=resolveCursorSpawnInvocation(E,w,s.platform),O=await(s.spawnDetached??spawnDetached)(D.exec,D.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(O.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(O.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(O.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let s of t){let t=s(e);try{return await access(t,constants$1.X_OK),t}catch(e){let s=e?.code;s!==`ENOENT`&&s!==`EACCES`&&s!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,s,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],{timeout:e,encoding:`utf-8`},(e,s)=>{if(e){t(null);return}let g=s.split(/\r?\n/)[0]?.trim();t(g&&g.length>0?g:null)})})}function resolveCursorSpawnInvocation(e,t,s){return s===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:{exec:e,args:[t]}}function isPathWithinDir(e,t,s){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(s===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let g=s===`win32`?win32:posix;try{let S=g.resolve(e),w=g.resolve(t);if(s===`win32`){let e=g.parse(S).root.toLowerCase(),t=g.parse(w).root.toLowerCase();if(!e||!t||e!==t)return!1}if(S===w)return!0;let E=g.relative(w,S);return E===``||E===`.`?!0:!(E===`..`||E.startsWith(`..${g.sep}`)||s===`win32`&&(/^[a-zA-Z]:[\\/]/.test(E)||E.startsWith(`\\\\`))||s!==`win32`&&E.startsWith(`/`))}catch(e){return console.warn(`[spawn-cursor] unexpected path-resolution error:`,e),!1}}const HANDLER=`handoff`,HANDOFF_MAX_BODY_BYTES=4*1024,HANDOFF_BODY_READ_TIMEOUT_MS=5e3,SPAWN_TIMEOUT_MS=2e3,WHICH_TIMEOUT_MS=500,QUIT_SETTLE_MS=3e3,APP_BUNDLE_SETTLE_MS=5e3,CURSOR_SETTLE_MS=1500,RECIPES={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},TARGET_VALUES=Object.keys(RECIPES),HandoffRequestSchema=object$1({target:_enum(TARGET_VALUES),url:string().min(1).max(4096),workspacePath:string().optional()}),HandoffSuccessSchema=object$1({}).loose();function defaultSleep(e){return new Promise(t=>setTimeout(t,e))}async function handleHandoffDispatch(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER,extraHeaders:{Allow:`POST`}});return}if(s.platform!==`darwin`){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Handoff is currently macOS-only.`,{handler:HANDLER});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:HANDOFF_MAX_BODY_BYTES,timeoutMs:HANDOFF_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER,cause:e});return}let w=HandoffRequestSchema.safeParse(S);if(!w.success){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:HANDLER});return}let{target:E,url:D,workspacePath:O}=w.data,k=RECIPES[E];if(!D.startsWith(k.urlScheme)){errorResponse(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${k.urlScheme} for target ${E}.`,{handler:HANDLER});return}let j=s.sleep??defaultSleep,F=s.spawnDetached??spawnDetached;if(k.type===`app-bundle`){k.quitFirst&&(await F(`/usr/bin/osascript`,[`-e`,`tell application "${k.appName}" to quit`],SPAWN_TIMEOUT_MS).catch(()=>void 0),await j(QUIT_SETTLE_MS));let e=await F(`/usr/bin/open`,[`-a`,k.appName],SPAWN_TIMEOUT_MS);if(!e.ok){emitSpawnFailure(t,E,e.reason);return}await j(APP_BUNDLE_SETTLE_MS);let s=await F(`/usr/bin/open`,[D],SPAWN_TIMEOUT_MS);if(!s.ok){emitSpawnFailure(t,E,s.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER});return}if(!O){errorResponse(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:HANDLER});return}if(!isPathWithinDir(O,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER});return}let L=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!L){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let B=resolveCursorSpawnInvocation(L,O,s.platform),H=await F(B.exec,B.args,SPAWN_TIMEOUT_MS);if(!H.ok){emitSpawnFailure(t,E,H.reason);return}await j(CURSOR_SETTLE_MS);let q=await F(`/usr/bin/open`,[D],SPAWN_TIMEOUT_MS);if(!q.ok){emitSpawnFailure(t,E,q.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}function emitSpawnFailure(e,t,s){switch(s){case`not-installed`:errorResponse(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:t}});return;case`timeout`:errorResponse(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:HANDLER,extensions:{target:t}});return;case`spawn-error`:errorResponse(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:HANDLER,extensions:{target:t}});return;default:assertNeverReason(s)}}function assertNeverReason(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let s=[],g=new Set,S=t=>{!t||g.has(t)||t!==e&&(g.add(t),s.push(t))},w=buildLowerDocNameIndex(t),E=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES)return s;let e=E===``?null:basename$1(E);if(e&&(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES))return s;if(E===``)break;E=parentFolder(E)}return s}function lookup$1(e,t,s){return e.has(s)?s:t.get(s.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let s of e.keys()){let e=s.toLowerCase();t.has(e)||t.set(e,s)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}function splitFrontmatterLines(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let s=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(s))return normalizeFrontmatterScalar(t.slice(s.length))||null;return null}function parseInlineAliases(e){let t=[],s=``,g=null;for(let S of e){if(g){s+=S,S===g&&(g=null);continue}if(S===`"`||S===`'`){g=S,s+=S;continue}if(S===`,`){let e=normalizeFrontmatterScalar(s);e&&t.push(e),s=``;continue}s+=S}let S=normalizeFrontmatterScalar(s);return S&&t.push(S),t}function dedupeExact(e){let t=[],s=new Set;for(let g of e)!g||s.has(g)||(s.add(g),t.push(g));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let s=splitFrontmatterLines(t);for(let e=0;e<s.length;e+=1){let t=s[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let g=t[1]?.trim()??``;if(g){if(g.startsWith(`[`)&&g.endsWith(`]`))return dedupeExact(parseInlineAliases(g.slice(1,-1)));let e=normalizeFrontmatterScalar(g);return e?[e]:[]}let S=[];for(let t=e+1;t<s.length;t+=1){let e=s[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&S.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(S)}return[]}function extractPageTitle(e,t){let{frontmatter:s,body:g}=stripFrontmatter(e),S=extractFrontmatterScalar(s,`title`);if(S)return S;let w=g.match(/^# (.+)$/m);return w?w[1].trim():t}const ICON_VALUE_LENGTH_CAP=2048;function extractPageIcon(e){let{frontmatter:t}=stripFrontmatter(e),s=extractFrontmatterScalar(t,`icon`);if(!(!s||s.length>ICON_VALUE_LENGTH_CAP))return s}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let s=`${t}:`,g=splitFrontmatterLines(e);for(let e=0;e<g.length;e+=1){let t=g[e];if(!t?.startsWith(s))continue;let S=t.slice(s.length).trim();if(S){if(S.startsWith(`[`)&&S.endsWith(`]`)){let e=parseInlineAliases(S.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(S);return e?[e]:void 0}let w=[];for(let t=e+1;t<g.length;t+=1){let e=g[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&w.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return w.length>0?w:void 0}}function extractPageIdentity(e,t){let s=extractPageTitle(e,t),g=extractPageAliases(e),S=dedupeExact([s,...g]),w=[],E=new Set;for(let e of S){let t=toWikiLinkSlug(e);!t||E.has(t)||(E.add(t),w.push(t))}return{docName:t,title:s,aliases:g,matchLabels:S,normalizedMatchLabels:w}}const PANE_TARGET_FILE=`pane-target.json`,PANE_TARGET_TTL_MS=3e4;function armPaneTarget(e,t,s=Date.now()){if(!t.startsWith(`#/`))return!1;tracedMkdirSync(e,{recursive:!0});let g={route:t,armedAtMs:s};return tracedWriteFileSync(resolve(e,PANE_TARGET_FILE),JSON.stringify(g)),!0}function readArmedPaneTarget(e,t=Date.now(),s=PANE_TARGET_TTL_MS){let g=resolve(e,PANE_TARGET_FILE);if(!existsSync(g))return null;try{let e=JSON.parse(readFileSync(g,`utf-8`));return typeof e.route!=`string`||typeof e.armedAtMs!=`number`||t-e.armedAtMs>s?null:e.route}catch(e){let t=e.code;return(t===`EACCES`||t===`EPERM`||t===`EIO`)&&process.stderr.write(`[pane-target] readArmedPaneTarget failed at ${g}: ${e instanceof Error?e.message:String(e)}\n`),null}}function clearArmedPaneTarget(e){let t=resolve(e,PANE_TARGET_FILE);if(existsSync(t))try{tracedUnlinkSync(t)}catch{}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidSharePath(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,s,g){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(s)}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function buildGitHubTreeUrl(e,t,s,g){let S=`https://github.com/${e}/${t}/tree/${encodeURIComponent(s)}`;return g===``?S:`${S}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let s=t?.branchExists,g=t?.kind;getLogger(`share`).info({action:`construct-url`,result:e,...s===void 0?{}:{branchExists:s},...g===void 0?{}:{kind:g}},`share action`)}function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let s;try{s=statSync(t)}catch{return null}if(s.isDirectory())return t;if(s.isFile()){let s;try{s=readFileSync(t,`utf-8`)}catch{return null}let g=/^gitdir:\s*(.+)$/m.exec(s.trim());if(!g)return null;let S=g[1].trim(),w=isAbsolute(S)?S:resolve(e,S);return existsSync(w)?w:null}return null}function resolveCommonDir(e){let t=join(e,`commondir`);if(!existsSync(t))return e;let s;try{s=readFileSync(t,`utf-8`).trim()}catch{return e}return s.length===0?e:isAbsolute(s)?s:resolve(e,s)}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(t,`HEAD`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=/^ref:\s*refs\/heads\/(.+)$/.exec(g.trim());return S?S[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),s=e.indexOf(`;`),g=-1;return t>=0&&s>=0?g=Math.min(t,s):t>=0?g=t:s>=0&&(g=s),(g===-1?e:e.slice(0,g)).trim()}function extractOriginUrl(e){let t=!1;for(let s of e.split(/\r?\n/)){let e=stripCommentAndTrim(s);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let g=/^url\s*=\s*(.+)$/.exec(e);if(!g)continue;let S=g[1].trim();if((S.startsWith(`"`)&&S.endsWith(`"`)||S.startsWith(`'`)&&S.endsWith(`'`))&&(S=S.slice(1,-1)),S.length>0)return S}return null}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let s=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return s||(s=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)||(s=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),s)||(s=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)?{owner:s[1],repo:s[2]}:null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(resolveCommonDir(t),`config`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=extractOriginUrl(g);return S?{originUrl:S,github:parseGitHubOriginUrl(S)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}:null}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),s=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(s)return`${s[1]}/${s[2]}`;let g=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return g?g[1]:t}function branchExistsOnOrigin(e,t){let s=resolveGitDir$1(e);if(!s)return!1;let g=resolveCommonDir(s);if(existsSync(join(g,`refs`,`remotes`,`origin`,t)))return!0;let S=join(g,`packed-refs`);if(!existsSync(S))return!1;let w;try{w=readFileSync(S,`utf-8`)}catch{return!1}let E=`refs/remotes/origin/${t}`;for(let e of w.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let s=t.split(/\s+/);if(s.length===2&&s[1]===E)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
|
|
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. Bounded label: outcome ∈ {applied, no_match, warming, incapable, provider_error}.`}),_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}),e.queryEmbedMs!==null&&queryEmbedDurationHist().record(Math.max(0,e.queryEmbedMs)),log$10.debug({outcome:e.outcome,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 EMBEDDINGS_ACCOUNT=`embeddings`;function secretsFilePath(e){return join(e??homedir(),`.ok`,`secrets.yml`)}var FileEmbeddingsBackend=class{backend=`file`;secretsFile;constructor(e){this.secretsFile=e??secretsFilePath()}read(){if(!existsSync(this.secretsFile))return{};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()[EMBEDDINGS_ACCOUNT];return Promise.resolve(typeof e==`string`&&e!==``?e:null)}set(e){let t=this.read();return t[EMBEDDINGS_ACCOUNT]=e,this.write(t),Promise.resolve()}clear(){let e=this.read();if(EMBEDDINGS_ACCOUNT in e)if(delete e[EMBEDDINGS_ACCOUNT],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}}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(`
|
|
827
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(`
|
|
828
829
|
---`,4);if(!e.startsWith(`---
|
|
829
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(`
|
|
@@ -1702,20 +1703,20 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
|
|
|
1702
1703
|
`)||e.startsWith(`---\r
|
|
1703
1704
|
`)){let s=e.indexOf(`
|
|
1704
1705
|
---`,3);s!==-1&&(t=e.slice(s+4))}let s=[],g=new Map,S=createCodeFenceTracker();for(let e of t.split(`
|
|
1705
|
-
`)){if(S(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),S=getHeadingSlug(e,g);S&&s.push({level:t[1].length,text:e,slug:S})}}return s}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function createApiExtension(e){let{hocuspocus:t,sessionManager:s,contentDir:g,serverInstanceId:S,getFileIndex:w,getFolderIndex:E,onReferencedAssetsCacheInvalidator:D,getAliasMap:O,rescanFiles:k,enableTestRoutes:j=!1,shadowRef:F,flushGitCommit:L,flushContributors:B,takeStoreFailure:H,takeStoreDivergence:q,markAgentWriteStore: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,ephemeral:
|
|
1706
|
-
`)}function We(){Pe=null}D?.(We);let Ge=createInstalledAgentsProbe({probe:ve??createOsProbe(process.platform)});function Ke(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 Xe(e){let t=Ke(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function $e(e,t){return t.has(e)?Xe(e):e}let nt={cluster:void 0,category:void 0,tags:void 0};function rt(e){try{let s=t.documents.get(e);if(s){let e=readFmMap(s.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,s=typeof e.category==`string`?e.category:void 0,g;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=Ke(e);if(!t||!existsSync(t))return nt;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):nt}catch{return nt}}function it(e,t){return t.has(e)?rt(e):nt}function at(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 st(e){return O?.().get(e)??e}function vt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Tt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Et(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 Dt(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 jt(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 Mt(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 Ft(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 It(){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 Lt(){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 Rt=Lt(),zt=e=>e.endsWith(`.`)?e:`${e}.`;function Bt(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:zt(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:zt(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:zt(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:zt(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:zt(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:zt(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:zt(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 Vt(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 Ht(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`&®isterWrite(e,contentHash(E))}}function Ut(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 Wt(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 Kt(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 $t(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=jr(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 en(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 jr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=en(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Mr(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=en(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Fr(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=Wt(g);if(typeof s!=`string`)continue;let S=en(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Ir(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 Lr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Mr(S.docName,s):S;e.rewrites!==0&&(Kt(S.docName,e.markdown),ne?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function zr(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 Br(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 Vr(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 Hr(e,t){return Rt(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=Fr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Ir(O.map(e=>e.docName)),await renameTrackedPathInGit(me,w,E)||renamePathOnDisk(w,E);let k=Lr(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 Ur(e,s,S,E){return Rt(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`?Vr(O,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[stripDocExtension(e)]:Br(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=Fr(L);Ir(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(me,O,k)||renamePathOnDisk(O,k),Ve(e,s),oe?.(`files`)),g.push(...Lr(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=Wt(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)??Wt(t);typeof e==`string`&&jr(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))}}Ir(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:Ut([...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)?$t(e,H,L):jr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Kt(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`&&Ve(e,s);let k=await Vt([...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=jr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Ht([{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 Wr(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 Gr(e){return{principalId:ge?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Kr(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 qr(e){return{value:e.value}}function Jr(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Yr(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=Kr(S),E=g||!w.response?w.response:qr(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(),Jr(S,!g);for(let{docName:e}of s)Et(e,`rename-path`);return E}case`principal`:{let t=Kr(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)}Jr(e.summary,!1);for(let{docName:e}of s)Et(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 Xr(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 Zr(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=Kr(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Qr(e){if(B)try{await B()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let ji=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=st(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Wr(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}=Kr(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,Gr({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),Jr(H)}finally{ce?.touchMode(O,`idle`)}let ae=await Dt(D);if(ae?.kind===`failure`){jt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Mt(w,`agent-write`);return}Et(D,`agent-write`),ue?.();let oe=Ft(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`}),Hi=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=st(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Wr(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)&®isterDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=Kr(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,Gr({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),Jr(q)}finally{ce?.touchMode(k,`idle`)}let oe=await Dt(O);if(oe?.kind===`failure`){jt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Mt(w,`agent-write-md`);return}Et(O,`agent-write-md`),se?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),ue?.();let de=at(O),fe=vt(O),me=Tt();me===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let ge=Ft(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`}),Ui=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=st(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Wr(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}=Kr(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(`
|
|
1706
|
+
`)){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,embeddingsSecretsFile:je,ephemeral:Me=!1}=e,Pe=createConcurrencyGuard(),Ie=new Map,Re=null;function ze(){let e=E?.();return e instanceof Map?e:null}function Be(e){let t=ze();if(t)try{upsertFolderIndexEntry(t,g,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function Ve(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)Be(resolve(g,t.slice(0,e).join(`/`)))}function Ue(e){let t=ze();t&&removeFolderIndexEntries(t,e)}function We(e,t){let s=ze();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)&&Be(e);return}for(let[e,t]of S)s.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(g,e)})}function Ge(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 Ke(){Re=null}D?.(Ke);let Xe=createInstalledAgentsProbe({probe:ve??createOsProbe(process.platform)});function $e(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 nt(e){let t=$e(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function rt(e,t){return t.has(e)?nt(e):e}let it={cluster:void 0,category:void 0,tags:void 0};function at(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=$e(e);if(!t||!existsSync(t))return it;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):it}catch{return it}}function st(e,t){return t.has(e)?at(e):it}function vt(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 Tt(e){return O?.().get(e)??e}function Et(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Dt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function jt(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 Mt(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 Ft(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 It(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 Lt(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 Rt(){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 zt(){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 Bt=zt(),Vt=e=>e.endsWith(`.`)?e:`${e}.`;function Ht(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Vt(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Vt(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Vt(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Vt(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Vt(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Vt(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Vt(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 Ut(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 Wt(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`&®isterWrite(e,contentHash(E))}}function Kt(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 $t(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 en(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 jr(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=Fr(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 Mr(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 Fr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=Mr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Ir(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=Mr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Lr(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=$t(g);if(typeof s!=`string`)continue;let S=Mr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function zr(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 Br(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Ir(S.docName,s):S;e.rewrites!==0&&(en(S.docName,e.markdown),ne?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Vr(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 Hr(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 Ur(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 Wr(e,t){return Bt(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=Lr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),zr(O.map(e=>e.docName)),await renameTrackedPathInGit(me,w,E)||renamePathOnDisk(w,E);let k=Br(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 Gr(e,s,S,E){return Bt(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`?Ur(O,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[stripDocExtension(e)]:Hr(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=Lr(L);zr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(me,O,k)||renamePathOnDisk(O,k),We(e,s),oe?.(`files`)),g.push(...Br(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=$t(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)??$t(t);typeof e==`string`&&Fr(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))}}zr(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:Kt([...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)?jr(e,H,L):Fr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(en(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`&&We(e,s);let k=await Ut([...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=Fr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Wt([{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 Kr(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 qr(e){return{principalId:ge?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Jr(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 Yr(e){return{value:e.value}}function Xr(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Zr(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=Jr(S),E=g||!w.response?w.response:Yr(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(),Xr(S,!g);for(let{docName:e}of s)jt(e,`rename-path`);return E}case`principal`:{let t=Jr(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)}Xr(e.summary,!1);for(let{docName:e}of s)jt(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 Qr(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 ji(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=Jr(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Hi(e){if(B)try{await B()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let Ui=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=Tt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Kr(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}=Jr(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,qr({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),Xr(H)}finally{ce?.touchMode(O,`idle`)}let ae=await Mt(D);if(ae?.kind===`failure`){Ft(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){It(w,`agent-write`);return}jt(D,`agent-write`),ue?.();let oe=Lt(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`}),Gi=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=Tt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Kr(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)&®isterDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=Jr(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,qr({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),Xr(q)}finally{ce?.touchMode(k,`idle`)}let oe=await Mt(O);if(oe?.kind===`failure`){Ft(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){It(w,`agent-write-md`);return}jt(O,`agent-write-md`),se?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),ue?.();let de=vt(O),fe=Et(O),me=Dt();me===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let ge=Lt(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`}),Ki=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=Tt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Kr(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}=Jr(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(`
|
|
1707
1708
|
`),S=s.nextFenced+(g?`
|
|
1708
|
-
`:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),fe=!0}de=!0},te.origin)})}finally{ce?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(de&&me.length>0){if(recordContributor(D,O,k,j,void 0,Gr({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),Jr(ee),fe){let e=await Dt(D);if(e?.kind===`failure`){jt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Mt(w,`frontmatter-patch`);return}}Et(D,`frontmatter-patch`)}se?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),ue?.();let ge=vt(D),_e=Tt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Ft(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 Gi(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 Ki=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=st(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:Gi(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:Gi(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}),Yi=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=Me.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;Me.set(e,E),w.finally(()=>{Me.get(e)===E&&Me.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(),Me.get(e)===w&&Me.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=Ue(k);Pe?.signature!==e&&(Pe={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=Pe?.assets??[]}catch(e){Pe=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}),Xi=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:Xe(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}),Zi=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}),ka=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=It();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ne.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:$e(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}),_s=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=It();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=it(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:$e(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}),xs=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:Xe(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}),Cs=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=It();successResponse(t,200,HubsSuccessSchema,{hubs:ne.getHubs(S).map(e=>({docName:e.docName,title:$e(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}),Ts=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=>st(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ne.getDeadLinks(It(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Xe(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}),Ds=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=st(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Wr(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}=Kr(J);recordContributor(j,F,L,B,void 0,Gr({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),Jr(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 Dt(j);if(me?.kind===`failure`){jt(w,me.failure,`agent-patch`);return}if(me?.kind===`divergence`){Mt(w,`agent-patch`);return}Et(j,`agent-patch`),se?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),ue?.();let ge=vt(j),_e=Tt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=Kr(J),ye=Ft(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`}),Os=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=st(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Wr(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,Gr({clientName:k,clientVersion:j,label:F}))}finally{ce?.touchMode(E,`idle`)}if(q){let e=await Dt(w);if(e?.kind===`failure`){jt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Mt(g,`agent-undo`);return}Et(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`}),ks=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}),As=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=st(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}),Ns=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=st(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}),Ps=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}),Is=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!k){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}k(),oe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),Rs=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Wr(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`}),$s=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=kl(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0);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 ec(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 tc=withValidation(EmptyRequestSchema,async(e,s)=>{let g=F?.current;if(!g){errorResponse(s,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`diff`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),w=S.searchParams.get(`docName`)??``,E=S.searchParams.get(`from`)??``,D=S.searchParams.get(`to`)??``;if(!D||!/^[0-9a-f]{40}$/i.test(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`'to' must be a valid 40-char commit SHA.`,{handler:`diff`});return}let O=te??`.`,k=safeDocPath(w,O);if(`error`in k){errorResponse(s,400,`urn:ok:error:invalid-request`,k.error,{handler:`diff`});return}let j=shadowGit(g),L=J?.()??`main`,B=getOrLoadRenameLogIndex(g.gitDir),H=createAncestorShaSetCache(),q=e=>{let t=safeDocPath(e,O);return`error`in t?`${e}.md`:t.path};try{let e=await resolveDocPathAtCommit(g,w,D,L,B,q,H);if(e===null){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document did not exist at the target version.`,{handler:`diff`});return}let S=await j.raw(`show`,`${D}:${e}`),O;if(E&&/^[0-9a-f]{40}$/i.test(E)){let e=await resolveDocPathAtCommit(g,w,E,L,B,q,H);if(e===null){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document did not exist at the source version.`,{handler:`diff`});return}O=await j.raw(`show`,`${E}:${e}`)}else{let e=t.documents.get(w);if(!e){errorResponse(s,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`diff`});return}O=e.getText(`source`).toString()}let k=stripFrontmatter(O).body,F=stripFrontmatter(S).body,ee=diffLines(k,F),J=[],Y=0,te=0;for(let e of ee){let t=e.value.replace(/\n$/,``).split(`
|
|
1709
|
-
`),s=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)J.push({type:s,text:e});e.added&&(Y+=t.length),e.removed&&(te+=t.length)}successResponse(s,200,DiffSuccessSchema,{lines:J,additions:Y,deletions:te},{handler:`diff`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`diff`,cause:e})}},{handler:`diff`,method:`GET`,skipBodyParse:!0}),nc=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=Kr(s);te=t||!g.response?g.response:qr(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),Jr(s,!t);break}case`principal`:{let e=Kr(w.summary);te=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),Jr(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 Dt(O);if(ne?.kind===`failure`){jt(g,ne.failure,`rollback`);return}if(ne?.kind===`divergence`){Mt(g,`rollback`);return}Et(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`}),rc=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}),ic=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}),ac=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 oc(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 sc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=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 cc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function lc(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 uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(_e?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`&&(F[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`),t.writeHead(200,F);try{await pipeline(createReadStream(O),t)}catch(e){log$4.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:s,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),dc=1048576,fc=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>dc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${dc}-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}),pc=1440*60*1e3,mc=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>pc){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});async function hc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`rescue-get`,extraHeaders:{Allow:`GET`}});return}if(!F?.current){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`rescue-get`});return}let g=resolve(F.current.gitDir,`rescue`),S=resolve(g,`${s}${getDocExtension(s)}`);if(!S.startsWith(`${g}/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid document name.`,{handler:`rescue-get`});return}if(existsSync(S)){let e=statSync(S);if(Date.now()-e.mtimeMs>pc)try{unlinkSync(S)}catch{}else{let e=readFileSync(S,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=J?.()??`main`,g=(await listRescueCheckpoints(F.current,e)).filter(e=>e.docName===s).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(g){let e=shadowGit(F.current),s=((await e.raw(`ls-tree`,`-r`,g.sha)).trim().split(`
|
|
1710
|
-
`)[0]??``).split(/\s+/)[2];if(s){let g=await e.raw(`cat-file`,`-p`,s);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(g);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`rescue-get`})}let gc=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`}),_c=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}),ze(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`}),vc=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]:Br(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))ze(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`}),yc=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=Ke(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}),bc=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 Hr(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Bt(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=Yr(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)]:Br(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 Ur(E,D,w,F?{actor:F}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,zt(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&&We();let H;if(L.renamed.length>0&&(H=Yr(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}=Bt(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),xc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Wr(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`?zr(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]:Br(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 Vt(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}),Be(E)),We();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`}),Sc=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`){We(),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(We(),j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Vt(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`&&Be(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`}),Cc=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}),wc=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 Tc(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}=Wr(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 Ec=`/api/local-op/clone`,Dc=`/api/local-op/open`,Oc=`/api/local-op/ok-init`,kc=600*1e3,Ac=45e3,jc=`local-op-clone`,Mc=withValidation(LocalOpCloneRequestSchema,Nc,{handler:jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:jc})});async function Nc(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:jc,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:jc,cause:Error(`dir=${S}`)});return}if(!je.tryAcquire(Ec)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:jc,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,jc),D=null,O=runCloneSubprocess({cliArgs:fe,url:g,dir:S,branch:w,timeoutMs:kc,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 Pc(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:jc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),je.release(Ec)}})(),t.on(`close`,()=>{O.cancel()})}async function Pc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=fe,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$4.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$4.error({cwd:s,cliCmd:e,err:t.message},`[local-op/open] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Fc=`local-op-open`,Ic=withValidation(LocalOpOpenRequestSchema,async(e,t,s)=>{let{dir:g,port:S}=s;if(!isSafeLocalPath(g)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:Fc,cause:Error(`dir=${g}`)});return}if(!je.tryAcquire(Dc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:Fc,extraHeaders:{"Retry-After":`5`}});return}try{let e=await Pc(g,S);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:Fc}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:Fc,cause:Error(e.error)})}finally{je.release(Dc)}},{handler:Fc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Fc})}),Lc=`local-op-ok-init`,Rc=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:Lc,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:Lc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Lc,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:Lc});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:Lc});return}if(!je.tryAcquire(Oc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Lc,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:Lc})}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:Lc})}finally{je.release(Oc)}},{handler:Lc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Lc})}),zc=`/api/local-op/auth/login`,Bc=`/api/local-op/auth/status`,Vc=`/api/local-op/auth/repos`,Hc=`/api/local-op/auth/signout`,Uc=`/api/local-op/auth/pat`,Wc=null,Gc=`local-op-auth-login`,Kc=withValidation(LocalOpAuthHostRequestSchema,qc,{handler:Gc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Gc})});async function qc(e,t,s){let g=s.host??`github.com`;if(!je.tryAcquire(zc)){let e=Wc;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:Gc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Wc=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,Gc),w=runDeviceFlowSubprocess({cliArgs:fe,host:g,timeoutMs:kc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Wc=w;let E=()=>{w.cancel(),Wc===w&&(Wc=null,je.release(zc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Wc===w&&(Wc=null,je.release(zc))})}let Jc=`local-op-auth-status`,Yc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!je.tryAcquire(Bc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Jc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
|
|
1711
|
-
`).map(e=>e.trim()).filter(Boolean),E=null;for(let e=w.length-1;e>=0;e--)try{E=JSON.parse(w[e]);break}catch{}E===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:
|
|
1712
|
-
`);k=s.pop()??``;for(let e of s){if(!e.trim())continue;let s=null;try{s=JSON.parse(e)}catch{}if(s&&s.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof s.message==`string`?s.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),j.stderr.on(`data`,e=>{log$4.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),
|
|
1713
|
-
`).map(e=>e.trim()).filter(Boolean),D=null;for(let e=E.length-1;e>=0;e--)try{D=JSON.parse(E[e]);break}catch{}D===null?successResponse(t,200,LocalOpAuthPatSuccessSchema,{},{handler:il}):successResponse(t,200,LocalOpAuthPatSuccessSchema,D,{handler:il})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:il,cause:e})}finally{je.release(Uc)}},{handler:il,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:il})}),cl=`local-op-auth-identity`;async function ll(e,t){if(checkLocalOpSecurity(e,t,{handler:cl})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:cl,extraHeaders:{Allow:`GET`}});return}if(!me){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:cl});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(me)},{handler:cl})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:cl,cause:e})}}}let ul=`/api/local-op/auth/set-identity`,dl=`local-op-auth-set-identity`,fl=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:dl});return}if(!je.tryAcquire(ul)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:dl,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(me,g,S),de?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:dl})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:dl,cause:e})}finally{je.release(ul)}},{handler:dl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:dl})});async function pl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=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 ml=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 hl(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 gl=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 _l(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 vl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let s=new URL(e.url??`/`,`http://localhost`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let yl=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 xl(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 Cl=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 Tl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Ge.probeAll)}catch(e){t.headersSent||(log$4.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}async function El(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-abort-merge`}))return;if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-abort-merge`,extraHeaders:{Allow:`POST`}});return}let s=de?.();if(!s){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-abort-merge`});return}try{await s.abortMerge(),successResponse(t,200,SyncAbortMergeSuccessSchema,{},{handler:`sync-abort-merge`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to abort merge.`,{handler:`sync-abort-merge`,cause:e})}}let Dl=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 Ol(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:Xe(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function kl(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let jl=/^[A-Za-z0-9_-]+$/;function Ml(e,t,s=`template`){return!e||!jl.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 Pl(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 Fl(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 Il(e,t){if(e.method===`GET`)return Ll(e,t);if(e.method===`PUT`)return Rl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Ll=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=kl(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Rl=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(De){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=kl(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(Zr(e,Xr(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Qr(`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 zl(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 Bl=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 Vl(e,t){if(e.method===`GET`)return Wl(e,t);if(e.method===`PUT`)return Gl(e,t);if(e.method===`POST`)return ql(e,t);if(e.method===`DELETE`)return Kl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Hl=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Ul=e=>{let t=e.match(Hl),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}},Wl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Ml(g,t,`template-get`))return;let S=kl(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Pl(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}=Ul(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}),Gl=withValidation(TemplatePutRequestSchema,async(e,t,s)=>{try{if(De){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(!Ml(g,t,`template-put`))return;let S=kl(s.folder,t,`folder`,`template-put`);if(!S||zl(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:Fl(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}Zr(e,Xr(`template`,S.folderRel,g),`${w.created?`template-create`:`template-edit`}: ${w.path}`),await Qr(`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`}),Kl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Ml(g,t,`template-delete`))return;let S=kl(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},ge);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(zl(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&&(Zr(E,Xr(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Qr(`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}),ql=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(!Ml(s.fromName,t,`template-move`)||!Ml(s.toName,t,`template-move`))return;let g=kl(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=kl(s.toFolder,t,`folder`,`template-move`);if(!S||zl(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=Pl(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=Ul(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:Fl(s.frontmatter)});t.ok||(E=t.error)}}if(Zr(e,Xr(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Qr(`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 Jl(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 Yl(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 Xl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Zl(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let s=t.filter(e=>e===`page`||e===`folder`||e===`content`);return s.length>0?s:void 0}async function Ql(){let e=[];for(let[t,s]of w()){if(isSystemDoc(t)||isConfigDoc(t))continue;let g=``,S=t;try{g=await readFile$1(s.canonicalPath,`utf-8`),S=extractPageTitle(g,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:S,content:g,modifiedTs:Date.parse(s.modified)}))}return[...e,...Jl(e)]}function $l(){return[...w()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function eu(){let e=`${g}${me??``}`,t=$l(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return s.corpus;if(s?.fingerprint===t&&s.pending)return s.pending;let S=Ql().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 tu(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{eu().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}tu();async function nu(e,t){if(e.method===`GET`)return ru(e,t);if(e.method===`POST`)return iu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let ru=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Xl(s.searchParams.get(`intent`)),E=Zl(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),D=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:S,intent:w,results:searchWorkspaceCorpus(await eu(),S,{intent:w,scopes:E,limit:D}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Yl(e.document.content,S):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),iu=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Xl(s.intent),w=Zl(s.scopes??s.scope),E=typeof s.limit==`number`?s.limit:void 0;if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:g,intent:S,results:searchWorkspaceCorpus(await eu(),g,{intent:S,scopes:w,limit:E}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Yl(e.document.content,g):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),au=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 ou(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 su(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 cu=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})}),lu=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}),uu=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 du(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 fu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!je.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 du([`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{je.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})}),pu=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(!je.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 du([`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{je.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})}),mu=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(!je.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 du(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{je.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),hu=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`})}),gu=me?getLocalDir(me):null;async function _u(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}gu&&clearArmedPaneTarget(gu),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:gu?readServerLock(gu)?.port??0:0,paneTarget:gu?readArmedPaneTarget(gu):null,singleFile:De};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 vu={"/api/config":_u,"/api/asset":uc,"/api/asset-text":fc,"/api/document":Ki,"/api/documents":Yi,"/api/backlinks":Xi,"/api/backlink-counts":Zi,"/api/forward-links":ka,"/api/link-graph":_s,"/api/dead-links":Ts,"/api/orphans":xs,"/api/hubs":Cs,"/api/tags":Dl,"/api/pages":Cc,"/api/folder-config":Il,"/api/template":Vl,"/api/templates":Bl,"/api/search":nu,"/api/suggest-links":wc,"/api/page-headings":yc,"/api/create-page":gc,"/api/create-folder":_c,"/api/duplicate-path":vc,"/api/rename-path":bc,"/api/delete-path":xc,"/api/trash/cleanup":Sc,"/api/upload":Tc,"/api/agent-write":ji,"/api/agent-write-md":Hi,"/api/frontmatter-patch":Ui,"/api/agent-patch":Ds,"/api/agent-undo":Os,"/api/agent-activity":ks,"/api/agent-burst-diff":As,"/api/save-version":Rs,"/api/history":$s,"/api/diff":tc,"/api/rollback":nc,"/api/metrics/reconciliation":rc,"/api/metrics/parse-health":ic,"/api/metrics/agent-presence":sc,"/api/__embed-detect":cc,"/api/server-info":ac,"/api/share/construct-url":cu,"/api/git/branch-info":lu,"/api/git/checkout":uu,"/api/share/publish/owners":fu,"/api/share/publish/name-check":pu,"/api/share/publish":mu,"/api/principal":oc,"/api/rescue":mc,"/api/workspace":lc,"/api/sync/status":pl,"/api/sync/trigger":ml,"/api/sync/conflicts":hl,"/api/sync/conflict-content":_l,"/api/sync/resolve-conflict":gl,"/api/sync/abort-merge":El,"/api/local-op/clone":Mc,"/api/local-op/open":Ic,"/api/local-op/ok-init":Rc,"/api/local-op/auth/login":Kc,"/api/local-op/auth/status":Yc,"/api/local-op/auth/repos":Zc,"/api/local-op/auth/signout":nl,"/api/local-op/auth/pat":al,"/api/local-op/auth/identity":ll,"/api/local-op/auth/set-identity":fl,"/api/installed-agents":Tl,"/api/spawn-cursor":su,"/api/handoff":ou,"/api/install-skill":Cl,"/api/skill/install-state":au,"/api/seed/plan":vl,"/api/seed/apply":yl,"/api/seed/packs":xl,"/api/client-logs":hu};j&&(vu[`/api/test-reset`]=Ns,vu[`/api/test-rescan-backlinks`]=Ps,vu[`/api/test-rescan-files`]=Is);let yu=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/sync/abort-merge./api/git/checkout./api/test-reset./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/seed/apply./api/client-logs`.split(`.`)),bu=[`/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(yu.has(s)||bu.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(De&&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/rescue/`)?E=`/api/rescue/:docName`:s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:vu[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=vu[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/rescue/`)){let g=decodeURIComponent(s.slice(12));g&&(E=!0,await hc(e,t,g))}else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await ec(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Ol(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)}function seedBasenameIndex(e){let t=e.contentDir,s=new Set;function g(S){let w;try{w=readdirSync(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=relative(t,w);if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=lstatSync(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=realpathSync(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=statSync(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?g(S):E.isFile()&&isSupportedAssetFile(w,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),g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}g(t)}const HocuspocusAuthTokenSchema=object$1({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional(),clientProtocolVersion:number().optional(),clientRuntimeVersion:string().optional(),clientKind:string().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),s=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(s))return{kind:null,payload:void 0};if(t===-1)return{kind:s,payload:void 0};let g=e.slice(t+1);return{kind:s,payload:g.length>0?g:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,s){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof s==`string`&&s.length>0?s:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let s=HocuspocusAuthTokenSchema.safeParse(t);return s.success?s.data:void 0}const log$3=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$3.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$3.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$3.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-CvT4CaVU-HAzuhDq0.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(`
|
|
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,qr({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),Xr(ee),fe){let e=await Mt(D);if(e?.kind===`failure`){Ft(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){It(w,`frontmatter-patch`);return}}jt(D,`frontmatter-patch`)}se?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),ue?.();let ge=Et(D),_e=Dt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Lt(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 Yi(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 Xi=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=Tt(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:Yi(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:Yi(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}),Zi=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=Ie.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;Ie.set(e,E),w.finally(()=>{Ie.get(e)===E&&Ie.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(),Ie.get(e)===w&&Ie.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=Ge(k);Re?.signature!==e&&(Re={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=Re?.assets??[]}catch(e){Re=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}),ka=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:nt(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}),_s=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}),xs=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=Rt();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ne.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:rt(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}),Cs=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=Rt();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=st(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:rt(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}),Ts=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:nt(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}),Ds=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=Rt();successResponse(t,200,HubsSuccessSchema,{hubs:ne.getHubs(S).map(e=>({docName:e.docName,title:rt(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}),Os=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=>Tt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ne.getDeadLinks(Rt(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:nt(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}),ks=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=Tt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Kr(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}=Jr(J);recordContributor(j,F,L,B,void 0,qr({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),Xr(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 Mt(j);if(me?.kind===`failure`){Ft(w,me.failure,`agent-patch`);return}if(me?.kind===`divergence`){It(w,`agent-patch`);return}jt(j,`agent-patch`),se?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),ue?.();let ge=Et(j),_e=Dt();_e===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=Jr(J),ye=Lt(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`}),As=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=Tt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Kr(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,qr({clientName:k,clientVersion:j,label:F}))}finally{ce?.touchMode(E,`idle`)}if(q){let e=await Mt(w);if(e?.kind===`failure`){Ft(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){It(g,`agent-undo`);return}jt(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`}),Ns=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}),Ps=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=Tt(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}),Is=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=Tt(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}),Rs=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}),$s=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!k){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}k(),oe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),ec=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Kr(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`}),tc=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=Ml(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 nc(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 rc=withValidation(EmptyRequestSchema,async(e,s)=>{let g=F?.current;if(!g){errorResponse(s,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`diff`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),w=S.searchParams.get(`docName`)??``,E=S.searchParams.get(`from`)??``,D=S.searchParams.get(`to`)??``;if(!D||!/^[0-9a-f]{40}$/i.test(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`'to' must be a valid 40-char commit SHA.`,{handler:`diff`});return}let O=te??`.`,k=safeDocPath(w,O);if(`error`in k){errorResponse(s,400,`urn:ok:error:invalid-request`,k.error,{handler:`diff`});return}let j=shadowGit(g),L=J?.()??`main`,B=getOrLoadRenameLogIndex(g.gitDir),H=createAncestorShaSetCache(),q=e=>{let t=safeDocPath(e,O);return`error`in t?`${e}.md`:t.path};try{let e=await resolveDocPathAtCommit(g,w,D,L,B,q,H);if(e===null){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document did not exist at the target version.`,{handler:`diff`});return}let S=await j.raw(`show`,`${D}:${e}`),O;if(E&&/^[0-9a-f]{40}$/i.test(E)){let e=await resolveDocPathAtCommit(g,w,E,L,B,q,H);if(e===null){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document did not exist at the source version.`,{handler:`diff`});return}O=await j.raw(`show`,`${E}:${e}`)}else{let e=t.documents.get(w);if(!e){errorResponse(s,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`diff`});return}O=e.getText(`source`).toString()}let k=stripFrontmatter(O).body,F=stripFrontmatter(S).body,ee=diffLines(k,F),J=[],Y=0,te=0;for(let e of ee){let t=e.value.replace(/\n$/,``).split(`
|
|
1710
|
+
`),s=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)J.push({type:s,text:e});e.added&&(Y+=t.length),e.removed&&(te+=t.length)}successResponse(s,200,DiffSuccessSchema,{lines:J,additions:Y,deletions:te},{handler:`diff`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`diff`,cause:e})}},{handler:`diff`,method:`GET`,skipBodyParse:!0}),ic=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=Jr(s);te=t||!g.response?g.response:Yr(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),Xr(s,!t);break}case`principal`:{let e=Jr(w.summary);te=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),Xr(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 Mt(O);if(ne?.kind===`failure`){Ft(g,ne.failure,`rollback`);return}if(ne?.kind===`divergence`){It(g,`rollback`);return}jt(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`}),ac=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}),oc=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}),sc=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 cc(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 lc(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 uc(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 dc(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 fc=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}),pc=1048576,mc=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>pc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${pc}-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}),hc=1440*60*1e3,gc=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>hc){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});async function _c(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`rescue-get`,extraHeaders:{Allow:`GET`}});return}if(!F?.current){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`rescue-get`});return}let g=resolve(F.current.gitDir,`rescue`),S=resolve(g,`${s}${getDocExtension(s)}`);if(!S.startsWith(`${g}/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid document name.`,{handler:`rescue-get`});return}if(existsSync(S)){let e=statSync(S);if(Date.now()-e.mtimeMs>hc)try{unlinkSync(S)}catch{}else{let e=readFileSync(S,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=J?.()??`main`,g=(await listRescueCheckpoints(F.current,e)).filter(e=>e.docName===s).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(g){let e=shadowGit(F.current),s=((await e.raw(`ls-tree`,`-r`,g.sha)).trim().split(`
|
|
1711
|
+
`)[0]??``).split(/\s+/)[2];if(s){let g=await e.raw(`cat-file`,`-p`,s);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(g);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`rescue-get`})}let 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}),Ve(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]:Hr(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))Ve(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=$e(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 Wr(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Ht(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=Zr(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)]:Hr(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 Gr(E,D,w,F?{actor:F}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Vt(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&&Ke();let H;if(L.renamed.length>0&&(H=Zr(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}=Ht(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Cc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Kr(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`?Vr(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]:Hr(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 Ut(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}),Ue(E)),Ke();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`){Ke(),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(Ke(),j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Ut(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`&&Ue(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}=Kr(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/open`,Ac=`/api/local-op/ok-init`,jc=600*1e3,Mc=45e3,Nc=`local-op-clone`,Pc=withValidation(LocalOpCloneRequestSchema,Fc,{handler:Nc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Nc})});async function Fc(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:Nc,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:Nc,cause:Error(`dir=${S}`)});return}if(!Pe.tryAcquire(Oc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Nc,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,Nc),D=null,O=runCloneSubprocess({cliArgs:fe,url:g,dir:S,branch:w,timeoutMs:jc,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 Ic(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:Nc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Pe.release(Oc)}})(),t.on(`close`,()=>{O.cancel()})}async function Ic(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=fe,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$4.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$4.error({cwd:s,cliCmd:e,err:t.message},`[local-op/open] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Lc=`local-op-open`,Rc=withValidation(LocalOpOpenRequestSchema,async(e,t,s)=>{let{dir:g,port:S}=s;if(!isSafeLocalPath(g)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:Lc,cause:Error(`dir=${g}`)});return}if(!Pe.tryAcquire(kc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:Lc,extraHeaders:{"Retry-After":`5`}});return}try{let e=await Ic(g,S);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:Lc}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:Lc,cause:Error(e.error)})}finally{Pe.release(kc)}},{handler:Lc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Lc})}),zc=`local-op-ok-init`,Bc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:zc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:zc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:zc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:zc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:zc});return}if(!Pe.tryAcquire(Ac)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:zc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:zc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:zc})}finally{Pe.release(Ac)}},{handler:zc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:zc})}),Vc=`/api/local-op/auth/login`,Hc=`/api/local-op/auth/status`,Uc=`/api/local-op/auth/repos`,Wc=`/api/local-op/auth/signout`,Gc=`/api/local-op/auth/pat`,Kc=null,qc=`local-op-auth-login`,Jc=withValidation(LocalOpAuthHostRequestSchema,Yc,{handler:qc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:qc})});async function Yc(e,t,s){let g=s.host??`github.com`;if(!Pe.tryAcquire(Vc)){let e=Kc;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:qc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Kc=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,qc),w=runDeviceFlowSubprocess({cliArgs:fe,host:g,timeoutMs:jc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Kc=w;let E=()=>{w.cancel(),Kc===w&&(Kc=null,Pe.release(Vc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Kc===w&&(Kc=null,Pe.release(Vc))})}let Xc=`local-op-auth-status`,Zc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Pe.tryAcquire(Hc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Xc,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(`
|
|
1712
|
+
`).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:Xc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:Xc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Xc,cause:e})}finally{Pe.release(Hc)}},{handler:Xc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Xc})}),Qc=`local-op-auth-repos`,$c=withValidation(LocalOpAuthHostRequestSchema,nl,{handler:Qc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Qc})});async function nl(e,t,s){let g=s.host??`github.com`;if(!Pe.tryAcquire(Uc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Qc,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,Qc),[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`)},jc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
|
|
1713
|
+
`);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(),Pe.release(Uc))}),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()),Pe.release(Uc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Pe.release(Uc))})}let il=`local-op-auth-signout`,al=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Pe.tryAcquire(Wc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:il,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:il})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:il,cause:e})}finally{Pe.release(Wc)}},{handler:il,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:il})}),cl=`local-op-auth-pat`,ll=withValidation(LocalOpAuthPatRequestSchema,async(e,t,s)=>{let{pat:g,host:S}=s,w=S??`github.com`;if(!Pe.tryAcquire(Gc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:cl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=fe,S=[...s,`auth`,`pat`,`--json`,`--host`,w],E=(await new Promise((t,s)=>{let w=spawn(e,S,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),E=setTimeout(()=>{w.kill(`SIGTERM`)},3e4);w.stdin.write(`${g}\n`),w.stdin.end();let D=[];w.stdout.on(`data`,e=>D.push(e)),w.on(`close`,e=>{clearTimeout(E),e===0?t(Buffer.concat(D).toString(`utf-8`)):s(Error(`auth pat exited with code ${e}`))}),w.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
|
|
1714
|
+
`).map(e=>e.trim()).filter(Boolean),D=null;for(let e=E.length-1;e>=0;e--)try{D=JSON.parse(E[e]);break}catch{}D===null?successResponse(t,200,LocalOpAuthPatSuccessSchema,{},{handler:cl}):successResponse(t,200,LocalOpAuthPatSuccessSchema,D,{handler:cl})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:cl,cause:e})}finally{Pe.release(Gc)}},{handler:cl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:cl})}),ul=`local-op-auth-identity`;async function dl(e,t){if(checkLocalOpSecurity(e,t,{handler:ul})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:ul,extraHeaders:{Allow:`GET`}});return}if(!me){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:ul});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(me)},{handler:ul})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:ul,cause:e})}}}let fl=`/api/local-op/auth/set-identity`,pl=`local-op-auth-set-identity`,ml=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:pl});return}if(!Pe.tryAcquire(fl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:pl,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(me,g,S),de?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:pl})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:pl,cause:e})}finally{Pe.release(fl)}},{handler:pl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:pl})});async function hl(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 gl=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 _l(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 vl=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 yl(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 xl(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 Cl=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 Tl(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 El=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 Dl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Xe.probeAll)}catch(e){t.headersSent||(log$4.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}async function Ol(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-abort-merge`}))return;if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-abort-merge`,extraHeaders:{Allow:`POST`}});return}let s=de?.();if(!s){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-abort-merge`});return}try{await s.abortMerge(),successResponse(t,200,SyncAbortMergeSuccessSchema,{},{handler:`sync-abort-merge`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to abort merge.`,{handler:`sync-abort-merge`,cause:e})}}let kl=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 jl(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:nt(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 Ml(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 Pl=/^[A-Za-z0-9_-]+$/;function Fl(e,t,s=`template`){return!e||!Pl.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 Il(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 Ll(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 Rl(e,t){if(e.method===`GET`)return zl(e,t);if(e.method===`PUT`)return Bl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Ml(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}),Bl=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(Me){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=Ml(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`&&(ji(e,Qr(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Hi(`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 Vl(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 Hl=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 Ul(e,t){if(e.method===`GET`)return Kl(e,t);if(e.method===`PUT`)return ql(e,t);if(e.method===`POST`)return Yl(e,t);if(e.method===`DELETE`)return Jl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Wl=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Gl=e=>{let t=e.match(Wl),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}},Kl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Fl(g,t,`template-get`))return;let S=Ml(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Il(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}=Gl(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}),ql=withValidation(TemplatePutRequestSchema,async(e,t,s)=>{try{if(Me){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(!Fl(g,t,`template-put`))return;let S=Ml(s.folder,t,`folder`,`template-put`);if(!S||Vl(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:Ll(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}ji(e,Qr(`template`,S.folderRel,g),`${w.created?`template-create`:`template-edit`}: ${w.path}`),await Hi(`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`}),Jl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Fl(g,t,`template-delete`))return;let S=Ml(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(Vl(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&&(ji(E,Qr(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Hi(`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}),Yl=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(!Fl(s.fromName,t,`template-move`)||!Fl(s.toName,t,`template-move`))return;let g=Ml(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Ml(s.toFolder,t,`folder`,`template-move`);if(!S||Vl(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=Il(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=Gl(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:Ll(s.frontmatter)});t.ok||(E=t.error)}}if(ji(e,Qr(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Hi(`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 Xl(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 Zl(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 Ql(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function $l(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 eu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}async function tu(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);E=performance.now()-t,s&&s.size>0&&(w={scores:s})}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 nu(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`?Zl(e.document.content,t):void 0}}async function ru(e){let t=performance.now(),s=await ou(),g=await tu(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=>nu(t,e.query)),w;if(g.status){let e=S.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),t=e>0;w={...g.status,applied:t},recordSemanticQuery({outcome:g.capable?t?`applied`:g.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,capable:g.capable,embedded:g.status.coverage.embedded,total:g.pageTotal,queryEmbedMs:g.queryEmbedMs,vectorContributors:e})}return{query:e.query,intent:e.intent,results:S,elapsedMs:Math.max(0,performance.now()-t),...w?{semantic:w}:{}}}async function iu(){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,...Xl(e)]}function au(){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 ou(){let e=`${g}${me??``}`,t=au(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return s.corpus;if(s?.fingerprint===t&&s.pending)return s.pending;let S=iu().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 su(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{ou().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}su();async function cu(e,t){if(e.method===`GET`)return lu(e,t);if(e.method===`POST`)return uu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let lu=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Ql(s.searchParams.get(`intent`)),E=$l(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),D=eu(s.searchParams.get(`semantic`)),O=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 ru({query:S,intent:w,scopes:E,limit:O,semanticParam:D}),{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}),uu=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Ql(s.intent),w=$l(s.scopes??s.scope),E=typeof s.limit==`number`?s.limit:void 0,D=eu(s.semantic);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 ru({query:g,intent:S,scopes:w,limit:E,semanticParam:D}),{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`}),du=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 fu(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 pu(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 mu=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})}),hu=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}),gu=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 _u(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 vu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Pe.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 _u([`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{Pe.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})}),yu=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(!Pe.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 _u([`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{Pe.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})}),bu=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(!Pe.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 _u(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{Pe.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),xu=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`})}),Su=me?getLocalDir(me):null;async function Cu(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}Su&&clearArmedPaneTarget(Su),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:Su?readServerLock(Su)?.port??0:0,paneTarget:Su?readArmedPaneTarget(Su):null,singleFile:Me};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 wu=`local-op-embeddings-set-key`,Tu=`local-op-embeddings-clear-key`,Eu=`/api/local-op/embeddings`,Du=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Pe.tryAcquire(Eu)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:wu,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(je).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:wu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:wu,cause:e})}finally{Pe.release(Eu)}},{handler:wu,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:wu})}),Ou=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Pe.tryAcquire(Eu)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Tu,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(je),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:Tu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Tu,cause:e})}finally{Pe.release(Eu)}},{handler:Tu,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Tu})}),ku=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(je).get()?`file`:process.env.OK_EMBEDDINGS_API_KEY?`env`:null,D=E!==null,O=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(O+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:D,keySource:E,ready:s,capable:g,embedded:S,total:O},{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}),Au={"/api/config":Cu,"/api/asset":fc,"/api/asset-text":mc,"/api/document":Xi,"/api/documents":Zi,"/api/backlinks":ka,"/api/backlink-counts":_s,"/api/forward-links":xs,"/api/link-graph":Cs,"/api/dead-links":Os,"/api/orphans":Ts,"/api/hubs":Ds,"/api/tags":kl,"/api/pages":Tc,"/api/folder-config":Rl,"/api/template":Ul,"/api/templates":Hl,"/api/search":cu,"/api/semantic-status":ku,"/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":Ui,"/api/agent-write-md":Gi,"/api/frontmatter-patch":Ki,"/api/agent-patch":ks,"/api/agent-undo":As,"/api/agent-activity":Ns,"/api/agent-burst-diff":Ps,"/api/save-version":ec,"/api/history":tc,"/api/diff":rc,"/api/rollback":ic,"/api/metrics/reconciliation":ac,"/api/metrics/parse-health":oc,"/api/metrics/agent-presence":lc,"/api/__embed-detect":uc,"/api/server-info":sc,"/api/share/construct-url":mu,"/api/git/branch-info":hu,"/api/git/checkout":gu,"/api/share/publish/owners":vu,"/api/share/publish/name-check":yu,"/api/share/publish":bu,"/api/principal":cc,"/api/rescue":gc,"/api/workspace":dc,"/api/sync/status":hl,"/api/sync/trigger":gl,"/api/sync/conflicts":_l,"/api/sync/conflict-content":yl,"/api/sync/resolve-conflict":vl,"/api/sync/abort-merge":Ol,"/api/local-op/clone":Pc,"/api/local-op/open":Rc,"/api/local-op/ok-init":Bc,"/api/local-op/auth/login":Jc,"/api/local-op/auth/status":Zc,"/api/local-op/auth/repos":$c,"/api/local-op/auth/signout":al,"/api/local-op/auth/pat":ll,"/api/local-op/auth/identity":dl,"/api/local-op/auth/set-identity":ml,"/api/local-op/embeddings/set-key":Du,"/api/local-op/embeddings/clear-key":Ou,"/api/installed-agents":Dl,"/api/spawn-cursor":pu,"/api/handoff":fu,"/api/install-skill":El,"/api/skill/install-state":du,"/api/seed/plan":xl,"/api/seed/apply":Cl,"/api/seed/packs":Tl,"/api/client-logs":xu};j&&(Au[`/api/test-reset`]=Is,Au[`/api/test-rescan-backlinks`]=Rs,Au[`/api/test-rescan-files`]=$s);let ju=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/sync/abort-merge./api/git/checkout./api/test-reset./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/seed/apply./api/client-logs`.split(`.`)),Mu=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),s.startsWith(`/api/`)){let s=e.headers.origin;if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(ju.has(s)||Mu.some(e=>s.startsWith(e))){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(Me&&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/rescue/`)?E=`/api/rescue/:docName`:s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Au[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=Au[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/rescue/`)){let g=decodeURIComponent(s.slice(12));g&&(E=!0,await _c(e,t,g))}else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await nc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await jl(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)}function seedBasenameIndex(e){let t=e.contentDir,s=new Set;function g(S){let w;try{w=readdirSync(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=relative(t,w);if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=lstatSync(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=realpathSync(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=statSync(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?g(S):E.isFile()&&isSupportedAssetFile(w,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),g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}g(t)}const HocuspocusAuthTokenSchema=object$1({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional(),clientProtocolVersion:number().optional(),clientRuntimeVersion:string().optional(),clientKind:string().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),s=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(s))return{kind:null,payload:void 0};if(t===-1)return{kind:s,payload:void 0};let g=e.slice(t+1);return{kind:s,payload:g.length>0?g:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,s){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof s==`string`&&s.length>0?s:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let s=HocuspocusAuthTokenSchema.safeParse(t);return s.success?s.data:void 0}const log$3=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$3.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$3.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$3.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-CvT4CaVU-HAzuhDq0.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(`
|
|
1714
1715
|
`).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(`
|
|
1715
1716
|
`)}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(`
|
|
1716
1717
|
`)}function compareSemver(e,t){let s=e.split(`.`).map(e=>Number.parseInt(e,10)||0),g=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=s[e]??0,S=g[e]??0;if(t!==S)return t-S}return 0}const GIT_PREFLIGHT_FAIL_SPAN_NAME=`ok.preflight.git.fail`;function emitPreflightFailureSpan(e){let t=e instanceof GitTooOldError?`too_old`:`not_available`,s=e instanceof GitTooOldError?e.detected:``;withSpanSync(GIT_PREFLIGHT_FAIL_SPAN_NAME,{attributes:{"ok.platform":e.platform,"ok.preflight.git.reason":t,"ok.preflight.git.detected_version":s}},()=>{})}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,s=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,g=0,S=null,w=null,E=!1,D=!1;function O(){S!==null&&(t.clearTimeout(S),S=null),w!==null&&(t.clearTimeout(w),w=null)}function k(){O(),!(D||E)&&g===0&&(s>0&&s<e.thresholdMs&&(w=t.setTimeout(()=>{w=null,g===0&&!E&&e.log?.warn({msUntilShutdown:s,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-s)),S=t.setTimeout(()=>{if(S=null,!(D||E)&&g===0){E=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let j=(e,t)=>{e.url?.startsWith(`/collab`)&&(g++,O(),t.once(`close`,()=>{g--,g<0&&(g=0),g===0&&k()}))};return e.httpServer.on(`upgrade`,j),k(),{detach:()=>{D||(D=!0,e.httpServer.off(`upgrade`,j),O())}}}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function readRawSinkBlock(e){if(!existsSync(e))return{};let t;try{t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!isObject(t))return{};let s=t.telemetry;if(!isObject(s))return{};let g=s.localSink;return isObject(g)?g:{}}function readBoolean(e){return typeof e==`boolean`?e:void 0}function readPositiveNumber(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function readStringArray(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function readMaxBytes(e){if(isObject(e))return readPositiveNumber(e.maxBytes)}function resolveLocalSinkConfig(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=readRawSinkBlock(resolveConfigPath(`project`,e.projectDir)),s=readRawSinkBlock(resolveConfigPath(`project-local`,e.projectDir));if((readBoolean(s.enabled)??readBoolean(t.enabled)??!0)===!1)return null;let g=readMaxBytes(s.spans)??readMaxBytes(t.spans)??52428800,S=readMaxBytes(s.logs)??readMaxBytes(t.logs)??26214400,w=readStringArray(s.attributeDenylist)??readStringArray(t.attributeDenylist)??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:g,attributeDenylist:w},logs:{projectDir:e.projectDir,maxBytes:S}}}const MCP_SERVER_NAME=`open-knowledge`,MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let s=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return s?s.slice(0,128):t}function buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `exec("ls -A <dir>")`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut`) and returns raw stdout plus enriched metadata per file. One command or a pipe (`|`) per call — it is NOT a shell, so `&&` / `;` / redirects are rejected; list several dirs with `ls -A a b c` or make separate calls.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment.\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir, the folder\'s own `title`/`description`/`tags` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, or to land them on a finished deliverable (see below) — not to re-check your own edits.\n\n**End a turn on the deliverable, not your scratch space.** Keep the preview steady *during* a multi-doc task — don\'t yank it around to re-check your own edits. But when a turn created or substantially changed user-facing docs, navigate the preview to the primary deliverable before you hand back: the hub / overview / index page when you created several docs, or the changed doc when you changed one. Don\'t step the user through every supporting source card — the user is watching, so leave them on the result.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session. If a tool can navigate to a URL, it counts as an in-app browser — match on the capability, not on what your host is called.\n\n- **You have `preview_*` tools** (e.g. `preview_start` + `preview_eval`) → **First open of the session:** to land directly on a doc, arm it first with `preview_url({ armPaneTarget: true, document })` (or `folder`), then `preview_start("open-knowledge-ui")` — `ok ui` redirects the base-open straight to the armed route, so the pane opens on the doc, not root. Plain `preview_start` (no arm) opens at root. **Moving between docs once the pane is open: do it in one `preview_eval` step — set `window.location.hash` to the target\'s route fragment from the response `previewUrl`, the part from `#` on (e.g. `window.location.hash = \'#/specs/foo/SPEC\'`).** That drives the SPA router directly. Arm + `preview_start` only redirects a *fresh* open; it can\'t move an already-open pane (`preview_start` reuses the live process without reloading), so use `preview_eval` there. Don\'t read or edit `.claude/launch.json` — host-managed; the OK lock-collision proxy handles the UI-already-running case. If `preview_start` fails, report it; don\'t "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** — Codex\'s built-in browser, or any host tool that navigates to a URL (`browser`, `view_url`, `open_url`, `web.browse`, etc.) → call `preview_url` once for the **exact** target (`document` for a doc, `folder` for a folder) and navigate your **in-app browser** straight to the returned `url`. Open that deep URL directly — never the root then navigate. Omit both args only for the root.\n- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all, e.g. the Claude Code CLI) → for an "open `<doc>`/`<folder>`" request, run **`ok open <doc>`** (`--folder` for a folder) — opens the doc in OK Desktop via deep link (folders in the browser), with browser fallback; an action, not a URL to print. No `ok` on PATH or no shell → `preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly. The system browser is the fallback, never the default.\n- **Honor `autoOpen`** (on `preview_url`, or on `warning` for write tools). If `false`, do not open or refresh any preview UI; surface the URL only if asked.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `preview_url` → in-app browser).\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the two attach-warning tools: `write` / `edit`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete` / `move` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed. (Navigating the pane with `preview_eval` by setting `window.location.hash` is fine — that drives the view, it is not a read-back verification loop.)\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `config({ key: \'content.dir\' })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. A folder\'s own metadata + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If substantial folders have no frontmatter of their own and no `templates_available`, the project isn\'t onboarded — invoke `workflow({ kind: \'discover\' })` before writing.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let s=t.validateToolInput;if(typeof s!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,g){if(!e.inputSchema||!isZodSchema(e.inputSchema))return s.call(this,e,t,g);let S=await e.inputSchema.safeParseAsync(t);if(S.success)return S.data;let w=prettifyError(S.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${g}:\n${w}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,s={}){let g=t?{error:t instanceof Error?t.message:String(t),...s}:s;this.emit(`error`,e,g)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,s){let g={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...s},S=`${JSON.stringify(g)}\n`;process.stderr.write(S);let w=process.env.OK_LOG_FILE;if(w)try{appendFileSync(w,S)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
|
|
1717
1718
|
`).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(`
|
|
1718
|
-
`);function register$16(e,t){e.registerTool(`checkpoint`,{description:DESCRIPTION$16,inputSchema:{summary:summaryArgSchema.describe(`Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({version:string().describe(VERSION_FIELD_DESCRIBE),previewUrl:previewUrlOutputField.describe(`Always null — a checkpoint is project-wide, not scoped to one doc.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=t.identityRef?.current,w=await httpPost(g,`/api/save-version`,{...e.summary===void 0?{}:{summary:e.summary},...S?{writers:[{id:`agent-${S.connectionId}`,name:S.displayName,email:`agent-${S.connectionId}@openknowledge.local`}]}:{}});if(!w.ok)return textResult(`Error: ${w.error}`,!0);let E=typeof w.checkpointRef==`string`?w.checkpointRef:``,D=E.split(`/`).pop()??``;return/^[0-9a-f]{40}$/i.test(D)?textPlusStructured(`Checkpoint saved. Version: ${D}`,{version:D,previewUrl:null}):textResult(`Error: checkpoint committed but the server returned no usable version ref ("${E}"). Find the latest checkpoint via \`history\`.`,!0)})}const DESCRIPTION$15=[`[Operates on disk; no running OK server required] Read the effective merged Open Knowledge config (defaults → user → project).`,``,`Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.`,``,"Read returns the FULL merged config or a sub-tree when `key` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, and `github.*` config sub-trees, plus `preview.baseUrl`, were removed; their values are now built-in constants in `@inkeep/open-knowledge-core
|
|
1719
|
+
`);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(`
|
|
1719
1720
|
`),InputSchema$3={key:string().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$5=outputSchemaWithText({value:unknown().describe(`Resolved config value at the requested path (or full config).`),exists:boolean().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:string().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)});function readConfigPath(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s)return;s=s[e]}return s}function register$15(e,t){e.registerTool(`config`,{description:DESCRIPTION$15,inputSchema:InputSchema$3,outputSchema:OutputSchema$5,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=e.key?e.key.split(`.`).filter(e=>e.length>0):[],S=g.length>0?readConfigPath(s.config,g):s.config;return g.length>0&&S===void 0?textPlusStructured(`(no value at ${e.key})`,{value:null,exists:!1,...e.key?{key:e.key}:{}}):textPlusStructured(JSON.stringify(S,null,2),{value:S,exists:!0,...e.key?{key:e.key}:{}})})}const DESCRIPTION$14=["[Requires: Hocuspocus server] Read GitHub-sync merge conflicts. Dispatches on `kind`:",``,'- `kind: "list"` — enumerate every doc currently tracked in a merge-conflict state. Returns `{ list: [{ file, detectedAt, ... }] }` (empty when none). The entry point to the resolve flow.','- `kind: "content"` — fetch the three merge stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, lifecycleStatus } }`. `ours` reflects the live Y.Text (what the human sees) when the doc is loaded server-side.',``,`**Parameters:**`,"- `kind` — `list` | `content`.",'- `file` — Required for `kind: "content"`. Relative path WITH the `.md`/`.mdx` extension (e.g. `notes/sso.md`) — git stages key on the exact path, so do NOT strip the extension.',``,"The `shape` field discriminates the conflict: `both-modified` (both sides edited), `delete-modify` (you deleted, they edited — `ours` empty), or `modify-delete` (you edited, they deleted — `theirs` empty). Use it to pick the `resolve_conflict` strategy."].join(`
|
|
1720
1721
|
`);function register$14(e,t){e.registerTool(`conflicts`,{description:DESCRIPTION$14,inputSchema:{kind:_enum([`list`,`content`]).describe("`list` enumerates tracked conflicts; `content` fetches one file's stages."),file:string().min(1).optional().describe('Required when `kind: "content"`. Conflicted file WITH extension (e.g. `notes/sso.md`) — git stages key on the exact path, so keep the extension (DD2).'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({list:looseObjectArray.optional().describe('`kind: "list"` — every tracked conflict (`{ file, detectedAt, ... }`).'),content:object$1({file:string().describe(`The conflicted file.`),base:string().describe(`Merge-base stage content.`),ours:string().describe(`Our stage (live Y.Text when loaded server-side).`),theirs:string().describe(`Their stage content.`),shape:_enum([`both-modified`,`delete-modify`,`modify-delete`]).describe("Conflict shape — pick the `resolve_conflict` strategy from it."),lifecycleStatus:string().nullable().describe(`The doc's lifecycle status, or null.`)}).optional().describe('`kind: "content"` — the three merge stages + shape + lifecycle.')}),annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.kind===`content`){if(!e.file)return textResult('Error: `kind: "content"` requires `file` — the conflicted file WITH extension, e.g. conflicts({ kind: "content", file: "notes/sso.md" }).',!0);let t=await httpGet(g,`/api/sync/conflict-content${`?file=${encodeURIComponent(e.file)}&source=ytext`}`);if(!t.ok){let e=t.error,s=typeof t.detail==`string`?t.detail:void 0;return textResult(`Error: ${s?`${e} — ${s}`:e}`,!0)}let s=t,S=typeof s.file==`string`?s.file:e.file,w=typeof s.base==`string`?s.base:``,E=typeof s.ours==`string`?s.ours:``,D=typeof s.theirs==`string`?s.theirs:``,O=s.kind===`delete-modify`||s.kind===`modify-delete`?s.kind:`both-modified`,k=typeof s.lifecycleStatus==`string`?s.lifecycleStatus:null;return textPlusStructured(`Conflict stages for ${S} (shape: ${O})${k?` (lifecycle: ${k})`:``}:\n--- base ---\n${w}\n--- ours ---\n${E}\n--- theirs ---\n${D}`,{content:{file:S,base:w,ours:E,theirs:D,shape:O,lifecycleStatus:k}})}let S=await httpGet(g,`/api/sync/conflicts`);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let w=S.conflicts,E=Array.isArray(w)?w:[];return textPlusStructured(E.length===0?`No conflicts tracked.`:`Tracked conflicts (${E.length}):\n${E.map(e=>`- ${e&&typeof e==`object`&&`file`in e?String(e.file??``):``}`).join(`
|
|
1721
1722
|
`)}`,{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(`
|
|
@@ -1737,7 +1738,7 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
|
|
|
1737
1738
|
`);function register$9(e,t){e.registerTool(`history`,{description:DESCRIPTION$9,inputSchema:{document:string().optional().describe("Document name to query history for. Mutually exclusive with `folder`."),folder:string().optional().describe('Folder path to query the FOLDER timeline for — attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter): created / edited / renamed / moved / deleted, by whom, when. Mutually exclusive with `document`. Use `""` for the project root.'),branch:string().optional().describe(`Branch name (default: current branch)`),limit:number().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:number().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),kind:_enum([`checkpoint`,`upstream`,`wip`]).optional().describe("Filter by entry type (`checkpoint` / `upstream` / `wip`)."),author:string().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:string().optional().describe(`Exclude entries by this author name or email`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({entries:array(HistoryEntryOutputSchema).describe("Timeline entries, newest first. Each carries a `version` for `restore_version`."),total:number().int().optional().describe(`Total entries available (pre-pagination).`),truncated:boolean().optional().describe(`Whether more entries exist beyond this returned page (the result was limit-capped).`),previewUrl:previewUrlOutputField,previewUrlSource:previewUrlSourceField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=e.folder!==void 0;if(w===(e.document!==void 0))return textResult("Error: pass EXACTLY ONE of `document` or `folder`.",!0);let E=new URLSearchParams,D=null;if(w)E.set(`folder`,e.folder??``);else{let t=normalizeDocName(e.document);if(!t.ok)return textResult(t.error,!0);E.set(`docName`,t.docName),D=t.docName}e.branch&&E.set(`branch`,e.branch),e.limit!=null&&E.set(`limit`,String(e.limit)),e.offset!=null&&E.set(`offset`,String(e.offset)),e.kind&&E.set(`type`,e.kind),e.author&&E.set(`author`,e.author),e.excludeAuthor&&E.set(`excludeAuthor`,e.excludeAuthor);let O=await httpGet(S,`/api/history?${E.toString()}`);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let{ok:k,...j}=O,F=(Array.isArray(j.entries)?j.entries:[]).map(e=>{let t=e;return{version:t.sha,timestamp:t.timestamp,author:t.author,authorEmail:t.authorEmail,kind:t.type,message:t.message,contributors:t.contributors,checkpoint:t.checkpoint??null}}),L=j.total,B=j.hasMore,H=D?await resolvePreviewUrlForTool(D,{config:t.config,resolveCwd:t.resolveCwd},g):null,q={entries:F,...typeof L==`number`?{total:L}:{},...typeof B==`boolean`?{truncated:B}:{}};return textPlusStructured(JSON.stringify(q,null,2),{...q,previewUrl:H?.url??null,...H?{previewUrlSource:H.source}:{}})})}const LINK_KINDS=[`backlinks`,`forward`,`dead`,`orphans`,`hubs`,`suggest`],DESCRIPTION$8=["[Requires: Hocuspocus server] Read the wiki-link graph. `kind` takes one value, or an array for a one-call audit — results merge into a single payload; any per-kind failure lands in an `errors` map.",``,'- `backlinks` / `forward` / `suggest` — operate on one page; require `document`. `suggest` finds prose mentions of the page not yet wrapped in link syntax. Each mention returns an `excerpt` (a normalized, `…`-trimmed snippet for context — NOT an edit-ready literal) plus an `offset`. To wrap one: re-read the doc (`exec("cat …")`), find the real mention text, and `edit` it into a `[[wiki-link]]`.',"- `dead` — missing internal link targets corpus-wide; optional `sourceDocuments` filter (OR semantics).","- `orphans` — disconnected pages; optional `mode`: `incoming` | `outgoing` | `both`.","- `hubs` — most-linked pages; optional `limit` (default 20)."].join(`
|
|
1738
1739
|
`);function register$8(e,t){e.registerTool(`links`,{description:DESCRIPTION$8,inputSchema:{kind:union([_enum(LINK_KINDS),array(_enum(LINK_KINDS)).min(1)]).describe(`Link-graph view(s) to return — one kind, or an array to fetch several in one call (e.g. ["dead","orphans","hubs"] for a graph audit).`),document:string().optional().describe(`Target page (path, extension-less). Required for kind=backlinks|forward|suggest.`),sourceDocuments:array(string()).optional().describe(`Referring source docs to narrow the audit with OR semantics. Used by kind=dead.`),mode:_enum(ORPHAN_MODES).optional().describe(`Filter which type of graph disconnection to surface. Used by kind=orphans.`),limit:number().int().positive().max(100).optional().describe(`Maximum number of hubs to return (default 20, max 100). Used by kind=hubs.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({backlinks:looseObjectArray.optional().describe(`kind=backlinks: pages that link TO the target.`),forwardLinks:looseObjectArray.optional().describe(`kind=forward: links FROM the target (doc + external).`),deadLinks:looseObjectArray.optional().describe(`kind=dead: internal links whose target does not exist.`),orphans:looseObjectArray.optional().describe(`kind=orphans: disconnected pages.`),hubs:looseObjectArray.optional().describe(`kind=hubs: the most-linked pages.`),suggest:record(string(),unknown()).optional().describe("kind=suggest: `{ mentions: [{ source, excerpt, offset }], previewUrl }` — `excerpt` is a `…`-trimmed context snippet (re-read the doc for the real text before `edit`)."),errors:record(string(),string()).optional().describe("Per-kind failures on a multi-kind call: `{ kind: message }`."),cwd:string().describe(`Absolute directory the read ran against.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=Array.isArray(e.kind)?[...new Set(e.kind)]:[e.kind],{resolve:E}=await buildListResolver(t,g),D=await Promise.all(w.map(s=>runKind(s,e,S,g,t,E))),O={},k={};if(w.forEach((e,t)=>{let s=D[t];s.ok?Object.assign(O,s.data):k[e]=s.error}),Object.keys(O).length===0){let e=w.length===1?k[w[0]]:`All requested link kinds failed: ${JSON.stringify(k)}`;return textResult(e.startsWith(`Error`)?e:`Error: ${e}`,!0)}let j={...O,...Object.keys(k).length>0?{errors:k}:{},cwd:g};return textPlusStructured(JSON.stringify(j,null,2),j)})}function runKind(e,t,s,g,S,w){switch(e){case`backlinks`:return runBacklinks(t,s,w);case`forward`:return runForwardLinks(t,s,w);case`dead`:return runDeadLinks(t,s,w);case`orphans`:return runOrphans(t,s,w);case`hubs`:return runHubs(t,s,w);case`suggest`:return runSuggest(t,s,g,S)}}async function runBacklinks(e,t,s){if(!e.document)return{ok:!1,error:"kind=backlinks requires `document`."};let g=normalizeDocName(e.document);if(!g.ok)return{ok:!1,error:g.error};let S=await httpGet(t,`/api/backlinks?docName=${encodeURIComponent(g.docName)}`);if(!S.ok)return{ok:!1,error:String(S.error)};let{ok:w,...E}=S;return{ok:!0,data:{backlinks:(E.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runForwardLinks(e,t,s){if(!e.document)return{ok:!1,error:"kind=forward requires `document`."};let g=normalizeDocName(e.document);if(!g.ok)return{ok:!1,error:g.error};let S=await httpGet(t,`/api/forward-links?docName=${encodeURIComponent(g.docName)}`);if(!S.ok)return{ok:!1,error:String(S.error)};let{ok:w,...E}=S;return{ok:!0,data:{forwardLinks:(E.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runDeadLinks(e,t,s){let g=new URLSearchParams;for(let t of e.sourceDocuments??[]){let e=normalizeDocName(t);if(!e.ok)return{ok:!1,error:e.error};g.append(`sourceDocName`,e.docName)}let S=g.toString(),w=await httpGet(t,`/api/dead-links${S?`?${S}`:``}`);if(!w.ok)return{ok:!1,error:String(w.error)};let{ok:E,...D}=w;return{ok:!0,data:{deadLinks:(D.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,g=t?s(t):null,S=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}});return{...e,sources:S,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runOrphans(e,t,s){let g=await httpGet(t,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!g.ok)return{ok:!1,error:String(g.error)};let{ok:S,...w}=g;return{ok:!0,data:{orphans:(w.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runHubs(e,t,s){let g=await httpGet(t,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!g.ok)return{ok:!1,error:String(g.error)};let{ok:S,...w}=g;return{ok:!0,data:{hubs:(w.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,g=t?s(t):null;return{...e,previewUrl:g?.url??null,...g?{previewUrlSource:g.source}:{}}})}}}async function runSuggest(e,t,s,g){if(!e.document)return{ok:!1,error:"kind=suggest requires `document`."};let S=normalizeDocName(e.document);if(!S.ok)return{ok:!1,error:S.error};let w=await httpGet(t,`/api/suggest-links?docName=${encodeURIComponent(S.docName)}`);if(!w.ok)return{ok:!1,error:String(w.error)};let{ok:E,...D}=w,O=await resolvePreviewUrlForTool(S.docName,{config:g.config,resolveCwd:g.resolveCwd},s);return{ok:!0,data:{suggest:{...D,previewUrl:O?.url??null,...O?{previewUrlSource:O.source}:{}}}}}const DESCRIPTION$7=["[Requires: Hocuspocus server] Move or rename a document, folder, or asset through the managed flow at `POST /api/rename-path`. Works for all three — the tool probes the content directory to decide. Inbound wiki-links plus supported inline Markdown links are rewritten across affected docs; renamed assets are reported.",``,`**Parameters:**`,"- `from` — Current path. Doc: docName (trailing `.md`/`.mdx` stripped). Folder: relative path, no leading/trailing slash. Asset: the file path incl. extension.","- `to` — New path. Same shape as `from`.",'- `template` — Move/rename a TEMPLATE instead of a doc/folder/asset: `{ from: "<folder>/<name>", to: "<folder>/<name>" }` (nested — a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc). Mutually exclusive with flat `from`/`to`. Inherited templates are not moved (move the local copy / the owning folder); templates carry no inbound links, so nothing is rewritten.','- `summary` — Optional one-line user-outcome (≤80 chars). If omitted, defaults to "Renamed X → Y". Avoid secrets or PII — persisted to git history.',``,"**Errors:** 400 — invalid path / excluded by `.gitignore`/`.okignore`; 404 — source does not exist; 409 — destination already exists (`colliding[]` returned)."].join(`
|
|
1739
1740
|
`);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(`
|
|
1740
|
-
`),{ok:!0,kind:D,renamed:F,rewrittenDocs:L,...B.length>0?{renamedAssets:B}:{},...Object.keys(q).length>0?{previewUrls:q}:{},...ee?{previewUrlSource:ee}:{},...J?{previousPreviewUrl:J}:{},...Y?{summary:Y}:{}})})}const DESCRIPTION$6=[`[Operates on registry data; no running OK server required] Return the OK authoring palette so a generated document reads as one coherent, themed artifact.`,``,`Three sections:`,"- `components` — the **markdown-native forms** OK auto-promotes into themed canonical components at parse time. Write `> [!NOTE]` (not `<Callout>`), `<details>` (not `<Accordion>`), ` ```mermaid `, `$x$`. Each entry carries a copy-ready `example` + `guidance`.","- `embedPatterns` — copy-ready ` ```html preview ` starters (chart, stat cards, custom SVG, interactive control) already wired to the theme tokens, so an embed tracks light/dark with no hand-picked colors.","- `tokens` — the CSS custom properties injected into every preview iframe; reference them as `var(--chart-1)`, `var(--foreground)`, … inside an `html preview` embed.",``,'Pass `components: [ids]` to ALSO get the full JSX-form prop schema for specific canonicals (e.g. `palette({ components: ["Callout", "Tabs"] })`) — merged from the former `get_components`.',``,`**Parameters:**`,"- `components` (optional) — Canonical ids to expand to full JSX-form detail (max 32). Case-sensitive (`Callout` not `callout`). Returns `componentDetails` + `notFound`.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
1741
|
+
`),{ok:!0,kind:D,renamed:F,rewrittenDocs:L,...B.length>0?{renamedAssets:B}:{},...Object.keys(q).length>0?{previewUrls:q}:{},...ee?{previewUrlSource:ee}:{},...J?{previousPreviewUrl:J}:{},...Y?{summary:Y}:{}})})}const DESCRIPTION$6=[`[Operates on registry data; no running OK server required] Return the OK authoring palette so a generated document reads as one coherent, themed artifact.`,``,`Three sections:`,"- `components` — the **markdown-native forms** OK auto-promotes into themed canonical components at parse time. Write `> [!NOTE]` (not `<Callout>`), `<details>` (not `<Accordion>`), ` ```mermaid `, `$x$`. Each entry carries a copy-ready `example` + `guidance`.","- `embedPatterns` — copy-ready ` ```html preview ` starters (chart, stat cards, custom SVG, interactive control) already wired to the theme tokens, so an embed tracks light/dark with no hand-picked colors.","- `tokens` — the CSS custom properties injected into every preview iframe; reference them as `var(--chart-1)`, `var(--foreground)`, … inside an `html preview` embed.",``,"External resources load directly: the preview iframe has open network access, so an embed can load external stylesheets, `fetch` live data, or pull map tiles / remote images / web fonts over `https:`. The iframe is a sandboxed null-origin frame — an embed can reach the network but never the knowledge base, cookies, or auth.",``,'Pass `components: [ids]` to ALSO get the full JSX-form prop schema for specific canonicals (e.g. `palette({ components: ["Callout", "Tabs"] })`) — merged from the former `get_components`.',``,`**Parameters:**`,"- `components` (optional) — Canonical ids to expand to full JSX-form detail (max 32). Case-sensitive (`Callout` not `callout`). Returns `componentDetails` + `notFound`.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
1741
1742
|
`),InputSchema$1={components:array(string().min(1)).max(32).optional().describe("Canonical ids to expand to full JSX-form detail (max 32, case-sensitive). Returns `componentDetails` + `notFound`."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$3=outputSchemaWithText({version:literal(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:array(object$1({id:string(),displayName:string(),description:string(),authoring:_enum([`markdown`,`jsx`]).describe("`markdown` — write the markdown-native form OK auto-promotes; `jsx` — write the JSX tag directly (no markdown-native form exists)."),example:string().describe(`Copy-ready source for the authoring form.`),guidance:string().describe(`One line on when / how to use this construct.`)})).describe(`Canonical authoring constructs, keyed by the form an agent should write.`),embedPatterns:array(object$1({id:string(),title:string(),description:string(),snippet:string().describe("A complete, theme-wired ```html preview fenced block.")})).describe("Copy-ready themed `html preview` starters."),tokens:array(object$1({name:string().describe("CSS custom-property name, e.g. `--chart-1`."),light:string(),dark:string()})).describe("Theme tokens injected into every preview iframe — reference with `var(--name)`."),componentDetails:array(record(string(),unknown())).optional().describe("Full JSX-form prop schema for the requested `components` ids (when provided)."),notFound:array(string()).optional().describe("Requested `components` ids that did not match any canonical.")}),AUTHORING_FORMS=[{id:`Callout`,registryName:`Callout`,fallbackDisplayName:`Callout`,description:`Alert / admonition box in one of 15 themed type variants.`,authoring:`markdown`,example:`> [!NOTE]
|
|
1742
1743
|
> Body text. Swap NOTE for TIP, IMPORTANT, WARNING, CAUTION, …`,guidance:"Write the GFM alert form — OK auto-promotes it to a themed Callout. 15 types; append `+` / `-` (e.g. `> [!NOTE]+`) to make it foldable."},{id:`Accordion`,registryName:`Accordion`,fallbackDisplayName:`Accordion`,description:`Collapsible section with a clickable summary.`,authoring:`markdown`,example:`<details>
|
|
1743
1744
|
<summary>Section title</summary>
|
|
@@ -1758,9 +1759,9 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
|
|
|
1758
1759
|
</Tabs>`,guidance:`Tabs is the one canonical with no markdown-native form — write the JSX directly.`}];function buildComponents(){let e=new Map(getAgentCanonicalDescriptors().map(e=>[e.name,e]));return AUTHORING_FORMS.map(t=>{let s=t.registryName?e.get(t.registryName):void 0;return{id:t.id,displayName:s?.displayName??s?.name??t.fallbackDisplayName,description:t.description,authoring:t.authoring,example:t.example,guidance:t.guidance}})}function register$6(e,t){e.registerTool(`palette`,{description:DESCRIPTION$6,inputSchema:InputSchema$1,outputSchema:OutputSchema$3,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{e.cwd;let t={version:1,components:buildComponents(),embedPatterns:PREVIEW_EMBED_STARTERS.map(e=>({id:e.id,title:e.title,description:e.description,snippet:previewEmbedFence(e)})),tokens:PREVIEW_THEME_TOKENS.map(e=>({name:e.name,light:e.light,dark:e.dark}))};if(e.components&&e.components.length>0){let s=new Map(getAgentCanonicalDescriptors().map(e=>[e.name,e])),g=[],S=[],w=new Set;for(let t of e.components){if(w.has(t))continue;w.add(t);let e=s.get(t);if(e===void 0){S.push(t);continue}g.push(projectFull(e))}t.componentDetails=g,t.notFound=S}return textPlusStructured(JSON.stringify(t,null,2),t)})}const DESCRIPTION$5=[`[Requires: Hocuspocus server] Resolve a tracked merge conflict by writing the chosen content to disk and committing.`,``,`Strategy:`,"- `mine` — runs `git checkout --ours -- <file>` then `git add` (your committed ours stage, stage 2). Fails on delete-modify (DU) conflicts where stage 2 is missing — use `delete` instead.","- `theirs` — runs `git checkout --theirs -- <file>` then `git add` (their committed stage 3). Fails on modify-delete (UD) conflicts where stage 3 is missing — use `delete` instead.",'- `content` — writes the provided `content` argument (e.g. a per-hunk merged result, or the live Y.Text bytes the user sees in the DiffView). The provided string must be non-empty — use `delete` to remove the file entirely (an agent constructing a per-hunk merge that happens to land on `""` gets a 400 at the Zod boundary rather than a misleading 500).','- `delete` — runs `git rm <file>` then commits the deletion. Honors deletion intent for delete-modify (DU: "keep deletion") and modify-delete (UD: "accept their deletion") shapes. Inspect the `shape` field on `conflicts({ kind: "content" })` to pick the right strategy for the conflict shape.',``,'Returns 200 on success; 500 indicates commit failure (re-call `conflicts({ kind: "list" })` to confirm post-state — the resolve API is best-effort, non-atomic, and the file may have been resolved by another session).',``,`**DESTRUCTIVE:** this modifies the working tree and creates a git commit.`,``,`**Parameters:**`,"- `file` — Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`).","- `strategy` — One of `mine` | `theirs` | `content` | `delete`.",'- `content` — Required (non-empty) when `strategy === "content"`; ignored otherwise.'].join(`
|
|
1759
1760
|
`),OutputSchema$2=outputSchemaWithText({ok:boolean(),file:string()});function register$5(e,t){e.registerTool(`resolve_conflict`,{description:DESCRIPTION$5,inputSchema:{file:string().min(1).describe("Relative-to-projectDir path WITH .md extension (e.g. `notes/sso.md`)."),strategy:_enum([`mine`,`theirs`,`content`,`delete`]).describe("Resolution strategy. `content` requires the `content` arg. `delete` runs `git rm` — use for delete-vs-modify (DU/UD) shapes where one stage is missing."),content:string().optional().describe('Exact bytes to write. Required when `strategy === "content"`; ignored otherwise.'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema$2,annotations:{readOnlyHint:!1,idempotentHint:!1,destructiveHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S={file:e.file,strategy:e.strategy};e.content!==void 0&&(S.content=e.content);let w=await httpPost(g,`/api/sync/resolve-conflict`,S);if(!w.ok){let t=w.error,s=typeof w.detail==`string`?w.detail:void 0;return textPlusStructured(`Error: ${s?`${t} — ${s}`:t}`,{ok:!1,file:e.file},!0)}return textPlusStructured(`Resolved conflict on ${e.file} (strategy: ${e.strategy}).`,{ok:!0,file:e.file})})}const DESCRIPTION$4=[`[Requires: Hocuspocus server] Restore a single document to a historical version via the CRDT layer — append-only (creates a new version with the old content; all connected editors see the change live).`,``,`**Parameters:**`,"- `document` — The document to restore (path, no extension; trailing `.md`/`.mdx` is stripped).","- `version` — The 40-character commit SHA to restore to. Copy it from the `history` tool (same field name there).",'- `summary` — Optional one-line summary (≤80 chars). Defaults to "Restored to <sha-short>". Avoid secrets or PII — persisted to git history.',``,'A response may include `structuredContent.contentDivergence` when the restored `Y.Text` does not byte-match the target-version bytes. The restore still landed; re-read the doc with `exec("cat <document>")` to see what converged.'].join(`
|
|
1760
1761
|
`);function register$4(e,t){e.registerTool(`restore_version`,{description:DESCRIPTION$4,inputSchema:{document:string().describe(`Document to restore (path, no extension).`),version:versionInputSchema.describe("The 40-character commit SHA to restore to — copy it straight from a `history` entry's `version` field (same name there)."),summary:summaryArgSchema.describe(`Optional one-line summary (≤80 chars). Defaults to "Restored to <sha-short>". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:string().describe(`The document that was restored (echo of the input).`),version:string().describe(`The version the document was restored to (echo of the input).`),previewUrl:previewUrlOutputField,previewUrlSource:previewUrlSourceField,summary:summaryOutputSchema.optional(),contentDivergence:WriteWarningSchema.optional().describe(`Present only when the restored Y.Text did not byte-match the target version.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=normalizeDocName(e.document);if(!w.ok)return textResult(w.error,!0);let E=w.docName,D=await httpGet(S,`/api/history/${e.version}?docName=${encodeURIComponent(E)}`);if(!D.ok)return textResult(`Error: ${D.error??`Version not found`}`,!0);let O=t.identityRef?.current,k=await httpPost(S,`/api/rollback`,{docName:E,commitSha:e.version,...e.summary===void 0?{}:{summary:e.summary},...agentIdentityFields(O)});if(!k.ok)return textResult(`Error: ${k.error}`,!0);let j=k.summary&&typeof k.summary==`object`?k.summary:void 0,F=typeof j?.hint==`string`?j.hint:void 0,L=parseContentDivergence(k.warning),B=typeof D.author==`string`?D.author:void 0,H=typeof D.timestamp==`string`?D.timestamp:void 0,q=B&&H?` (${B}, ${H})`:``,ee=[`Restored "${E}" to version ${e.version.slice(0,8)}${q}. The change has been applied to all connected editors.`];F&&ee.push(F),L&&ee.push(formatContentDivergenceLine(L));let J=await resolvePreviewUrlForTool(E,{config:t.config,resolveCwd:t.resolveCwd},g);return textPlusStructured(ee.join(`
|
|
1761
|
-
`),{document:E,version:e.version,previewUrl:J?.url??null,...J?{previewUrlSource:J.source}:{},...j?{summary:j}:{},...L?{contentDivergence:L}:{}})})}const DESCRIPTION$3=["[Requires: Hocuspocus server] Ranked page retrieval for a query (title boost + body BM25 + recency — the cmd-K engine). For literal search across every line, use `exec` (`grep`) instead.",``,"Returns scored page (and folder, with `omnibar` intent) hits, each with a body snippet. `exec`-grep covers every occurrence and needs no server.",``,`**Parameters:**`,"- `query` — Free-form; tokenized across title, name, path segments, and (with `full_text`) body.","- `intent` (optional) — `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.","- `scopes` (optional) — Result scope: `page` | `folder` | `content`. Defaults derive from `intent`.","- `limit` (optional) — Max rows; default 20, max 100.",``,'If the server is down, the tool returns a recovery hint — use `exec("grep ...")` as the server-free fallback.'].join(`
|
|
1762
|
-
`),InputSchema={query:string().describe(`Search query — title, path, or body terms.`),intent:_enum([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),scopes:array(_enum([`page`,`folder`,`content`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'content'. Defaults derive from intent.`),limit:number().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},SearchResultRowSchema=object$1({kind:_enum([`page`,`folder`]),path:string(),docName:string(),title:string().nullable(),score:number(),signals:object$1({lexical:number(),fullText:number(),recency:number()}),snippet:string().optional(),previewUrl:string().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),OutputSchema$1=outputSchemaWithText({cwd:string(),query:string(),intent:string(),resultCount:number().int(),results:array(SearchResultRowSchema),elapsedMs:number().nullable()});function isSearchKind(e){return e===`page`||e===`folder`}function normalizeSignals(e){return{lexical:typeof e?.lexical==`number`?e.lexical:0,fullText:typeof e?.fullText==`number`?e.fullText:0,recency:typeof e?.recency==`number`?e.recency:0}}function formatResultsBlock(e){if(e.length===0)return``;let t=[];for(let s of e){let e=s.title?.trim()||s.path;t.push(`### ${e} (${s.path})`),t.push(`Score ${s.score.toFixed(2)} — kind: ${s.kind}`),s.snippet&&t.push(s.snippet),t.push(``)}return t.join(`
|
|
1763
|
-
`)}function register$3(e,t){e.registerTool(`search`,{description:DESCRIPTION$3,inputSchema:InputSchema,outputSchema:OutputSchema$1,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(`${HOCUSPOCUS_NOT_RUNNING_ERROR}\nFor server-free literal-string search, use \`exec("grep ...")\` instead — it walks the filesystem and does not need Hocuspocus.`,!0);let E=e.intent??`full_text`,D=e.limit??20,O={query:e.query,intent:E,limit:D};e.scopes&&(O.scopes=e.scopes);let k=await httpPost(w,`/api/search`,O);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let{resolve:j}=await buildListResolver({config:S,resolveCwd:async()=>g},g),F=(k.results??[]).flatMap(e=>{if(!isSearchKind(e.kind)||typeof e.path!=`string`)return[];let t=docNameFromPath(e.path),s=j(t);return[{kind:e.kind,path:e.path,docName:t,title:e.title??null,score:typeof e.score==`number`?e.score:0,signals:normalizeSignals(e.signals),...e.snippet?{snippet:e.snippet}:{},previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}]}),L={cwd:g,query:e.query,intent:E,resultCount:F.length,results:F,elapsedMs:typeof k.elapsedMs==`number`?k.elapsedMs:null},
|
|
1762
|
+
`),{document:E,version:e.version,previewUrl:J?.url??null,...J?{previewUrlSource:J.source}:{},...j?{summary:j}:{},...L?{contentDivergence:L}:{}})})}const DESCRIPTION$3=["[Requires: Hocuspocus server] Ranked page retrieval for a query (title boost + body BM25 + recency — the cmd-K engine). For literal search across every line, use `exec` (`grep`) instead.",``,"When semantic search is enabled for the workspace (an opt-in setting with an API key), an embeddings signal is additionally fused into `full_text` ranking, surfacing conceptually-related pages that share no keywords. This tool opts in by default; the `semantic` block in the response reports coverage. Note: with semantic enabled, the query and matching page content are sent to the configured embeddings provider (content egress). Set `semantic: false` to force pure-lexical ranking for a call.",``,"Returns scored page (and folder, with `omnibar` intent) hits, each with a body snippet and a `signals` breakdown (lexical / fullText / recency / vector). `exec`-grep covers every occurrence and needs no server.",``,`**Parameters:**`,"- `query` — Free-form; tokenized across title, name, path segments, and (with `full_text`) body.","- `intent` (optional) — `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.","- `scopes` (optional) — Result scope: `page` | `folder` | `content`. Defaults derive from `intent`.","- `limit` (optional) — Max rows; default 20, max 100.","- `semantic` (optional) — Set `false` to force pure-lexical ranking even when semantic search is enabled. Omit to use semantic when available.",``,'If the server is down, the tool returns a recovery hint — use `exec("grep ...")` as the server-free fallback.'].join(`
|
|
1763
|
+
`),InputSchema={query:string().describe(`Search query — title, path, or body terms.`),intent:_enum([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),scopes:array(_enum([`page`,`folder`,`content`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'content'. Defaults derive from intent.`),limit:number().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),semantic:boolean().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},SearchResultRowSchema=object$1({kind:_enum([`page`,`folder`]),path:string(),docName:string(),title:string().nullable(),score:number(),signals:object$1({lexical:number(),fullText:number(),recency:number(),vector:number().optional()}),snippet:string().optional(),previewUrl:string().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),SearchSemanticStatusSchema=object$1({capable:boolean(),applied:boolean(),coverage:object$1({embedded:number().int(),total:number().int()})}),OutputSchema$1=outputSchemaWithText({cwd:string(),query:string(),intent:string(),resultCount:number().int(),results:array(SearchResultRowSchema),elapsedMs:number().nullable(),semantic:SearchSemanticStatusSchema.optional()});function isSearchKind(e){return e===`page`||e===`folder`}function normalizeSignals(e){return{lexical:typeof e?.lexical==`number`?e.lexical:0,fullText:typeof e?.fullText==`number`?e.fullText:0,recency:typeof e?.recency==`number`?e.recency:0,...typeof e?.vector==`number`?{vector:e.vector}:{}}}function normalizeSemanticStatus(e){if(!(!e||typeof e.capable!=`boolean`))return{capable:e.capable,applied:e.applied===!0,coverage:{embedded:typeof e.coverage?.embedded==`number`?e.coverage.embedded:0,total:typeof e.coverage?.total==`number`?e.coverage.total:0}}}function formatSemanticNote(e){if(!e)return``;if(!e.capable)return`> Semantic: enabled but not ready (no API key, or warming up) — lexical ranking only.`;let{embedded:t,total:s}=e.coverage;return e.applied?`> Semantic: on — vector signal contributed (${t}/${s} pages embedded).`:t<s?`> Semantic: on — indexing ${t}/${s} pages; vectors are still filling in, re-run for fuller coverage.`:`> Semantic: on — no page cleared the similarity threshold for this query.`}function formatResultsBlock(e){if(e.length===0)return``;let t=[];for(let s of e){let e=s.title?.trim()||s.path;t.push(`### ${e} (${s.path})`),t.push(`Score ${s.score.toFixed(2)} — kind: ${s.kind}`),s.snippet&&t.push(s.snippet),t.push(``)}return t.join(`
|
|
1764
|
+
`)}function register$3(e,t){e.registerTool(`search`,{description:DESCRIPTION$3,inputSchema:InputSchema,outputSchema:OutputSchema$1,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(`${HOCUSPOCUS_NOT_RUNNING_ERROR}\nFor server-free literal-string search, use \`exec("grep ...")\` instead — it walks the filesystem and does not need Hocuspocus.`,!0);let E=e.intent??`full_text`,D=e.limit??20,O={query:e.query,intent:E,limit:D,semantic:e.semantic??!0};e.scopes&&(O.scopes=e.scopes);let k=await httpPost(w,`/api/search`,O);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let{resolve:j}=await buildListResolver({config:S,resolveCwd:async()=>g},g),F=(k.results??[]).flatMap(e=>{if(!isSearchKind(e.kind)||typeof e.path!=`string`)return[];let t=docNameFromPath(e.path),s=j(t);return[{kind:e.kind,path:e.path,docName:t,title:e.title??null,score:typeof e.score==`number`?e.score:0,signals:normalizeSignals(e.signals),...e.snippet?{snippet:e.snippet}:{},previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}]}),L=normalizeSemanticStatus(k.semantic),B={cwd:g,query:e.query,intent:E,resultCount:F.length,results:F,elapsedMs:typeof k.elapsedMs==`number`?k.elapsedMs:null,...L?{semantic:L}:{}},H=`## Search results for "${e.query}" (${F.length} hit${F.length===1?``:`s`}, intent: ${E})`,q=formatSemanticNote(L),ee=F.length===0?`No matches for "${e.query}".`:`${H}\n\n${formatResultsBlock(F)}`;return textPlusStructured(q?`${ee}\n${q}`:ee,B)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const DESCRIPTION$2=["[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",``,`Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own Open Knowledge install.`,``,"**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.",``,`**Parameters:**`,'- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.","- `cwd` (optional) — Project root (see `cwd` description below).",``,"**Preconditions:** project on a named branch (not detached HEAD); origin set to a `github.com` remote; the branch already pushed to origin."].join(`
|
|
1764
1765
|
`);function messageForShareError(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is not a `github.com` remote. Share links are GitHub-only in v1.";case`invalid-path`:return"The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.";default:return`Unknown share-construct-url error: ${String(e)}`}}function isExistingDirectory(e){try{return statSync(e).isDirectory()}catch{return!1}}function resolveExistingDocPath(e,t){for(let s of[`.mdx`,`.md`]){let g=`${t}${s}`;if(existsSync(g)){let t=resolveWithinRoot(e,g);return t.ok?t.rel:null}}return null}function resolveShareTarget(e,t,s,g){if(s===``)return g===`folder`?{ok:!0,kind:`folder`,sharePath:``}:{ok:!1,code:`invalid-path`};let S=resolveWithinRoot(t,s);if(!S.ok)return{ok:!1,code:`target-not-found`};let w=resolveExistingDocPath(e,S.abs.replace(/\.(mdx|md)$/i,``)),E=isExistingDirectory(S.abs);if(g===`doc`)return w===null?E?{ok:!1,code:`kind-mismatch`}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:w};if(g===`folder`){if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return w===null?{ok:!1,code:`target-not-found`}:{ok:!1,code:`kind-mismatch`}}if(w!==null)return{ok:!0,kind:`doc`,sharePath:w};if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return{ok:!1,code:`target-not-found`}}const OutputSchema=outputSchemaWithText({ok:boolean().describe(`Success discriminator.`),shareUrl:string().optional().describe(`Marketing share URL (success only).`),sharedUrl:string().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:string().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:_enum([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),error:_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:string().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:string().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:string().optional().describe(`Internal: preview-URL provenance.`)});function register$2(e,t){e.registerTool(`share_link`,{description:DESCRIPTION$2,inputSchema:{path:string().describe('Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).'),kind:_enum([`doc`,`folder`]).optional().describe("Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveShareTarget(g,join(g,S.content.dir),e.path,e.kind);if(!E.ok){let t;if(E.code===`kind-mismatch`){let s=e.kind===`folder`?`folder`:`doc`;t=`\`${e.path}\` exists, but not as a ${s}. Pass \`kind: '${s===`doc`?`folder`:`doc`}'\` to share it as the other kind.`}else t=E.code===`invalid-path`?'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.':`Target \`${e.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;let s={ok:!1,error:E.code,message:t};return textPlusStructured(`Error: ${t}`,s,!0)}let D=E.kind===`doc`?{kind:`doc`,docPath:E.sharePath}:{kind:`folder`,folderPath:E.sharePath},O;try{O=await fetch(`${w}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(D),signal:AbortSignal.timeout(3e4)})}catch(e){let t=`Server unreachable: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let k;try{k=await O.json()}catch(e){let t=`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!O.ok){let e;if(k&&typeof k==`object`){let t=k,s=typeof t.title==`string`?t.title:void 0,g=typeof t.detail==`string`?t.detail:void 0;e=s&&g?`${s}: ${g}`:s||g||`HTTP ${O.status}`}else e=`HTTP ${O.status}`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let j=ShareConstructUrlResponseSchema.safeParse(k);if(!j.success){let e=`Server returned an unexpected share-construct-url response shape.`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let F=j.data;if(!F.ok){let e=messageForShareError(F.error,F.branch),t={ok:!1,error:F.error,message:e,...F.branch?{branch:F.branch}:{}};return textPlusStructured(`Error: ${e}`,t,!0)}let{shareUrl:L,sharedUrl:B,branch:H}=F,q={ok:!0,shareUrl:L,sharedUrl:B,branch:H,resolvedKind:E.kind},ee={config:t.config,resolveCwd:t.resolveCwd},J=await resolvePreviewUrlForTool(E.sharePath.replace(/\.(mdx|md)$/i,``),ee,g);if(J&&E.kind===`folder`){let e=E.sharePath.replace(/^\/+|\/+$/g,``),t=e===``?`/#/`:`/#/${encodeDocName(e)}/`;J={...J,url:t}}let Y=e.path===``?`(content root)`:e.path;return textPlusStructured(`Share link for ${E.kind} \`${Y}\` on branch \`${H}\`:\n${L}`,{...q,previewUrl:J?.url??null,...J?{previewUrlSource:J.source}:{}})})}function buildConsolidateBody(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
|
|
1765
1766
|
|
|
1766
1767
|
Topic: ${e}
|
|
@@ -2813,8 +2814,8 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
2813
2814
|
`),{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: `].join(`
|
|
2814
2815
|
`),{asset:{ok:!0,...B?{src:B}:{},...H?{path:H}:{},...q?{deduped:q}:{}}})}async function handleBatch(e,t,s,g,S,w,E){let D=[];for(let w of e)D.push(await writeOneDoc(w,t,s,g,S));let O=D.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=resolvePreviewUrl(e.docName,{lockDir:w}),s=parseContentDivergence(e.raw.warning);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...s?{contentDivergence:s}:{}}}),k=O.filter(e=>e.ok).length,j=k===O.length,F=e.map((e,t)=>{let s=D[t];if(!s?.ok)return`Failed ${e.path}: ${s?.error??`unknown error`}`;if(emptyAppendNoOpNote(s.position,e.content))return`No change to ${e.path} — empty ${s.position}, document unchanged.`;let g=O[t],S=`Wrote ${e.path} (${s.position}).`;return g?.ok&&g.contentDivergence?`${S} ${formatContentDivergenceBrief(g.contentDivergence)}`:S}),L=e.flatMap((e,t)=>{let s=D[t];if(!s?.ok)return[];let g=frontmatterIgnoredNote(s.position,e.content);return[...g?[g]:[],...s.extensionNote?[s.extensionNote]:[]].map(t=>`${e.path} — ${t}`)}),B=[`${k}/${O.length} written.`,...F,...L].join(`
|
|
2815
2816
|
`),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(`
|
|
2816
|
-
`);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}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))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)?!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(`
|
|
2817
|
-
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){return e.startsWith(`!`)?`!${t}/${e.slice(1)}`:`${t}/${e}`}function loadNestedIgnoreFiles(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let w=0;for(let E of S){if(!E.isDirectory()||BUILTIN_SKIP_DIRS.has(E.name))continue;let S=join(e,E.name),D=relative(t,S);if(!D.startsWith(`..`)&&!(s.ignores(D)||s.ignores(`${D}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(S,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);g.value+=e.length;let S=parseIgnorePatterns(e).map(e=>prefixPattern(e,D));s.add(S),w++}catch(s){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,s)}}w+=loadNestedIgnoreFiles(S,t,s,g)}}return w}async function initContentDirStateAsync(e,t,s,g,S,w,E){let D;try{D=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let O of D){let D=t?`${t}/${O.name}`:O.name;if(O.isDirectory()){if(BUILTIN_SKIP_DIRS.has(O.name))continue;let t=join(e,O.name);if(!w){let e=relative(s,t);if(e.startsWith(`..`)||g.ignores(e)||g.ignores(`${e}/`))continue;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${s} at ${S}:`,e)}}}await initContentDirStateAsync(t,D,s,g,S,w,E)}else if(O.isFile()&&isSupportedDocFile(O.name)){if(!w){let e=S?`${S}/${D}`:D;if(g.ignores(e))continue}E.set(t,(E.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,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))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)?!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}}}})}}}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(`
|
|
2817
|
+
`);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(`
|
|
2818
|
+
`).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}}}})}}}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(`
|
|
2818
2819
|
`).find(e=>e.endsWith(` ${g}`));if(S)return S.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}async function startHeadWatcher(e,t,s){let g=resolveGitDir(e);if(!g)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let S=g,w=!1,E=null,D=null,O=null,k=null;async function j(e){if(L&&await L,!w)return;E&&=(clearTimeout(E),null),D&&=(clearTimeout(D),null);let t=readHeadSha(S),g=O!==t,j=readBranchFromHead(S),F;F=j?.startsWith(`detached-`)?`detached-head`:k===j?`within-branch`:`cross-branch`;let B=k;try{await s({headMoved:g,oldHead:O,newHead:t,timeout:e,batchKind:F,oldBranch:B,newBranch:j})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{w=!1,O=t,k=j}}function F(){E&&clearTimeout(E),E=setTimeout(()=>{E=null,j(!1)},QUIET_WINDOW_MS)}let L=null;async function B(e){if(!w){w=!0,O=readHeadSha(S);let s=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();L=s,await s,L=null,D=setTimeout(()=>{D=null,j(!0)},BATCH_TIMEOUT_MS)}F()}let H,q;try{q=await import(`@parcel/watcher`)}catch(e){throw Error(`@parcel/watcher unavailable for HEAD watching: ${e instanceof Error?e.message:e}`)}try{let e=await q.subscribe(S,(e,t)=>{if(e){console.error(`[head-watcher]`,e);return}for(let e of t){let t=e.path.split(`/`).pop()??``;if(WATCHED_FILES.has(t)){B(t);break}}});H=()=>e.unsubscribe()}catch(e){throw Error(`@parcel/watcher subscribe failed for HEAD watching: ${e instanceof Error?e.message:e}`)}return O=readHeadSha(S),k=readBranchFromHead(S),getLogger(`head-watcher`).info({gitDir:S},`watching for HEAD changes`),{unsubscribe:async()=>{w&&await j(!1),E&&clearTimeout(E),D&&clearTimeout(D),await H()},getLastKnownBranch:()=>k}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:s,signalChannel:g,debounceMs:S=100}=e,w=new Map;function E(e){let t=w.get(e);t&&(clearTimeout(t),w.delete(e))}function D(e,D){E(e),w.set(e,setTimeout(()=>{w.delete(e);try{let S=serializeLiveDocument(D);t.updateDocumentFromMarkdown(e,S),g?.(`backlinks`),g?.(`graph`),s&&(s.updateDocumentFromMarkdown(e,S),g?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},S))}return{async onChange({documentName:e,document:t,transactionOrigin:s}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(s)&&s.context?.origin===`file-watcher`||D(e,t)},async beforeUnloadDocument({documentName:e}){E(e)},async onDestroy(){for(let e of w.values())clearTimeout(e);w.clear()}}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function loadPrincipal(e){let t=getLocalDir(e),s=resolve(t,PRINCIPAL_FILE),{name:g,email:S}=await readGitConfig(e);if(existsSync(s)){let e;try{e=JSON.parse(readFileSync(s,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,w=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),E=t.slice(10,18),D={id:t,display_name:g?sanitizeGitIdentity(g):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:S?sanitizeGitIdentity(S):typeof e.display_email==`string`?e.display_email:`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:w};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}mkdirSync(t,{recursive:!0});let w=`principal-${randomUUID()}`,E=w.slice(10,18),D={id:w,display_name:g?sanitizeGitIdentity(g):`Local User`,display_email:S?sanitizeGitIdentity(S):`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}const DEFAULT_CAPACITY=1e4;var RecentlyRemovedDocs=class{map=new Map;capacity;onEviction;onSizeChange;now;constructor(e=DEFAULT_CAPACITY,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&this.onSizeChange?.(this.map.size)}get size(){return this.map.size}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size)}};function fileExistsForDocName(e,t){let s=e.resolveFilePath(t);return s!==null&&e.fileExists(s)}async function runRemovalRedirectGuard(e,t){try{if(isSystemDoc(e)||isConfigDoc(e))return;let s=t.recentlyRemovedDocs.get(e);if(s===void 0)return;if(s.kind===`deleted`){if(fileExistsForDocName(t,e)){t.recentlyRemovedDocs.delete(e);return}throw incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let g=new Set([e]),S=s.newDocName;for(;;){if(g.has(S)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:S}));return}g.add(S);let s=t.recentlyRemovedDocs.get(S);if(s===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S);if(s.kind===`deleted`)throw fileExistsForDocName(t,S)?(t.recentlyRemovedDocs.delete(S),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));S=s.newDocName}}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthRemovalGuardError(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}function createServerObserverExtension(e){let t=new Map,s=new Map;return{async afterLoadDocument({documentName:g,document:S}){if(isSystemDoc(g)||isConfigDoc(g)||t.has(g))return;let w=S,E=w.getXmlFragment(`default`),D=w.getText(`source`),O=()=>{try{let s=setupServerObservers({doc:w,xmlFragment:E,ytext:D,mdManager:e.mdManager,schema:e.schema,docName:g,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(g,s),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${g}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!O()){let e=setTimeout(()=>{s.delete(g),!t.has(g)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${g}'`),O())},5e3);s.set(g,e)}},async afterUnloadDocument({documentName:e}){let g=s.get(e);g&&(clearTimeout(g),s.delete(e));let S=t.get(e);S&&(S(),t.delete(e))},async onDestroy(){for(let e of s.values())clearTimeout(e);s.clear();for(let[e,s]of t.entries())try{s()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let s=t.createdBy;return!(typeof s.runtimeVersion!=`string`||s.protocolVersion!==void 0&&typeof s.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let s;try{s=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let g;try{g=JSON.parse(s)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(g))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:g}}function writeStateManifest(e,t){let s=manifestPath(e);mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),s=e.currentStateSchemaVersion??1,g=e.currentRuntimeVersion??RUNTIME_VERSION,S=e.currentProtocolVersion??1,w=(e.now??(()=>new Date))().toISOString(),E=manifestPath(e.lockDir),D=readStateManifest(e.lockDir);if(D.status===`present`){let O=D.manifest;if(!isCompatibleSchema(O.stateSchemaVersion,s))throw new StateManifestError({kind:`incompatible`,path:E,message:`State manifest at ${E} declares stateSchemaVersion=${O.stateSchemaVersion} but this binary supports ${s}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${O.createdBy.runtimeVersion}, protocol ${O.createdBy.protocolVersion}.)`});try{let t={...O,lastWriteBy:{runtimeVersion:g,protocolVersion:S,at:w}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),O}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let D={stateSchemaVersion:s,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S}};return writeStateManifest(e.lockDir,D),t.info({path:E,stateSchemaVersion:s},`[state-manifest] fresh project — wrote manifest`),D}let O={stateSchemaVersion:0,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S,adoptedAt:w}};return writeStateManifest(e.lockDir,O),t.warn({path:E,runtimeVersion:g},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),O}function deriveUserFacingCode(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_PATTERNS=[/\b(401|403)\b/,/authentication failed/i,/authorization failed/i,/invalid credentials/i,/credential helper/i,/bad credentials/i,/token.*expired/i,/expired.*token/i,/permission denied.*\(publickey\)/i,/host key verification failed/i,/fatal:.*repository.*not found/i],SCOPE_MISMATCH_PATTERNS=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],NON_FAST_FORWARD_PATTERNS=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],PROTECTED_BRANCH_PATTERNS=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],MERGE_CONFLICT_PATTERNS=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],LFS_PATTERNS=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],LARGE_FILE_PATTERNS=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PRE_RECEIVE_PATTERNS=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],SECRET_DETECTED_PATTERNS=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],INDEX_LOCK_PATTERNS=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],DIRTY_TREE_PATTERNS=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],DISK_FULL_PATTERNS=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],NETWORK_PATTERNS=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],HTTP_5XX_PATTERNS=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],HTTP_429_PATTERNS=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function classifyGitError(e){let t=classifyGitErrorBase(e);return{...t,userFacingCode:deriveUserFacingCode(t.class,t.subclass)}}function classifyGitErrorBase(e){let t=e instanceof Error?e:Error(String(e)),s=extractStderr(t),g=`${t.message}\n${s}`.toLowerCase();return matchesAny(g,INDEX_LOCK_PATTERNS)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:s}:matchesAny(g,DIRTY_TREE_PATTERNS)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:s}:matchesAny(g,DISK_FULL_PATTERNS)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:s}:matchesAny(g,SCOPE_MISMATCH_PATTERNS)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:s}:matchesAny(g,AUTH_PATTERNS)?/\b401\b/.test(g)||/token.*expired/i.test(g)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:s}:/\b403\b/.test(g)?matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:s}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:s}:matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:matchesAny(g,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:s}:matchesAny(g,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:s}:matchesAny(g,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:s}:matchesAny(g,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:s}:matchesAny(g,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:s}:matchesAny(g,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:s}:matchesAny(g,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:s}:matchesAny(g,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:s}:matchesAny(g,NETWORK_PATTERNS)?/timed? out/i.test(g)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:s}:/refused/i.test(g)||/econnrefused/i.test(g)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:s}:/resolve.*host/i.test(g)||/enotfound/i.test(g)||/getaddrinfo/i.test(g)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:s}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:s}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:s}}const log$2=getLogger(`github-permissions`),PROBE_TIMEOUT_MS=5e3;function githubApiBase(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function buildHeaders(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function readPushFlag(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let s=t.push;return typeof s==`boolean`?s:null}async function classify(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return log$2.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let s=readPushFlag(t);return s===null?(log$2.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):s?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return log$2.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function resolveProbeTokenWithSource(e,t,s){let g=t(e);if(g.available&&g.token)return{token:g.token,source:`gh`};if(s)try{let t=await s.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){log$2.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function runProbe(e){let{owner:t,repo:s,host:g=`github.com`,detectGh:S=()=>({available:!1}),tokenStore:w,_fetchFn:E=fetch,_timeoutMs:D=PROBE_TIMEOUT_MS}=e,{token:O,source:k}=await resolveProbeTokenWithSource(g,S,w),j=`${githubApiBase(g)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(s)}`;log$2.info({host:g,tokenSource:k,tokenLen:O===void 0?0:O.length},`[permissions] probe starting`);let F=new AbortController,L=setTimeout(()=>F.abort(),D);try{let e=await E(j,{signal:F.signal,headers:buildHeaders(O)}),t=await classify(e,O!==void 0);return log$2.info({host:g,tokenSource:k,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return F.signal.aborted?(log$2.warn({host:g,timeoutMs:D},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(log$2.warn({err:e,host:g},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(L)}}async function checkPushPermission(e){let t=performance.now(),s=await runProbe(e);return recordProbeTelemetry(s,performance.now()-t),s}function outcomeAttributes(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let _outcomeCounter=null;function outcomeCounter(){return _outcomeCounter||=getMeter().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.`}),_outcomeCounter}let _durationHist=null;function durationHist(){return _durationHist||=getMeter().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),_durationHist}function recordProbeTelemetry(e,t){let s=outcomeAttributes(e);outcomeCounter().add(1,s),durationHist().record(t,{outcome:s.outcome})}function computeRemainingMs(e,t,s=Date.now()){if(!e)return 0;let g=new Date(e).getTime();if(Number.isNaN(g))return 0;let S=g+t*1e3;return Math.max(0,S-s)}const log$1=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i;function pushPermissionStatusFrom(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function pushPermissionStatusEqual(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function jitteredMs(e){let t=e*1e3,s=t*.15*(2*Math.random()-1);return Math.round(t+s)}function isUnbornHead(e){try{let t=join(e,`.git`,`HEAD`);if(!existsSync(t))return!1;let s=readFileSync(t,`utf-8`).trim(),g=/^ref:\s+(refs\/.+)$/.exec(s);if(!g)return!1;let S=g[1];if(existsSync(join(e,`.git`,S)))return!1;let w=join(e,`.git`,`packed-refs`);if(existsSync(w)){let e=readFileSync(w,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${S}$`,`m`).test(e))return!1}return!0}catch{return!1}}function backoffMs(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var SyncEngine=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;setBatchInProgress;onAutoDisable;detectGh;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.detectGh=e.detectGh,this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??checkPushPermission,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){log$1.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log$1.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log$1.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null,g=s!==null&&existsSync(s);if(this.conflictCount>0&&!g)log$1.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&g)try{let e=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
|
|
2819
2820
|
`).map(e=>e.trim()).filter(Boolean):[]),s=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<s&&log$1.info({cleared:s-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log$1.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(g&&this.conflictCount===0){log$1.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),log$1.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let S=computeRemainingMs(this.lastFetchUtc,this.pullIntervalSeconds),w=computeRemainingMs(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(S>0?S:void 0),this.schedulePush(w>0?w:void 0),log$1.info({branch:this.currentBranch,pullDelayMs:S,pushDelayMs:w},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=3e4,t=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-t>3e4){log$1.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await setTimeout$1(50)}this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log$1.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):log$1.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?readSyncRemoteInfo(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=readOriginGitHubRepo(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,pushPermissionStatusEqual(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,log$1.info({caller:e,host:`github.com`,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let s;try{s=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:`github.com`,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){log$1.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),s={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let g=pushPermissionStatusFrom(s),S=this.pushPermission;this.pushPermission=g;let w=!1;return g.checkStatus===`denied`&&this.syncEnabled===!0?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),w=!0,log$1.info({reason:g.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):g.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.syncEnabled===!0&&this.transitionTo(`idle`),w=!0,log$1.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!w&&!pushPermissionStatusEqual(S,g)&&this.cc1Broadcaster?.signal(`sync-status`),g}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log$1.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!existsSync(join(this.projectDir,`.git`)))return!1;try{return(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log$1.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null;if(!(s!==null&&existsSync(s)))log$1.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),s=new Set(t?t.split(`
|
|
2820
2821
|
`).map(e=>e.trim()).filter(Boolean):[]);for(let e of this.conflictStore.list())s.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<e&&log$1.info({cleared:e-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){log$1.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}this.conflictCount!==e&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,s){this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,s)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{log$1.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??jitteredMs(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{log$1.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=backoffMs(e);return t>0?t:jitteredMs(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`)){if(this.state===`conflict`){this.schedulePull();return}if(isUnbornHead(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t;try{let s=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!s||s===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,log$1.warn({},`[sync] detached HEAD — pausing sync`);return}t=s,this.currentBranch=t}catch(e){this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`pull`);return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));this.handleError(t,`pull`);return}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let s=await this.prepareForMerge(e,t);if(!s.proceed)return;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{s.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`);return}finally{this.setBatchInProgress?.(!1)}}else this.transitionTo(`idle`);this.scheduleSaveState()}async runPushCycle(){if(!this.pushInFlight&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(isUnbornHead(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),s=join(tmpdir(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),g=null;this.transitionTo(`pushing`);try{await withParentLock(async()=>{let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:s});if(isUnbornHead(this.projectDir)){log$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let S;try{S=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),s=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(s)||/ambiguous argument 'HEAD'/i.test(s)||/does not have any commits yet/i.test(s)){log$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,S]);let w=await this.listHeadContentPaths(e,S);if(t.length>0){let s=100;for(let s=0;s<t.length;s+=100){let g=t.slice(s,s+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...g])}}let E=new Set(t.map(e=>e.projectRelPath)),D=[...w].filter(e=>!E.has(e));await this.removePathsFromIndex(e,D);let O=(await e.git.raw([`write-tree`])).trim(),k=``;try{k=(await e.git.raw([`rev-parse`,`${S}^{tree}`])).trim()}catch{}if(k&&k===O){let s=null;try{s=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(s===S){log$1.info({contentFileCount:t.length,headSha:S},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=S,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}log$1.info({headSha:S,upstreamSha:s},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let w=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),w=!0}catch{}w?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),g=S;return}let j=[],F=[];try{let s=(await e.git.raw([`diff-tree`,`--name-only`,`-r`,S,O])).trim();if(s){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of s.split(`
|
|
@@ -2826,8 +2827,8 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
2826
2827
|
`).map(e=>e.trim()).filter(Boolean):[]}catch(t){log$1.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let s=[],g=[];for(let e of t){let t=join(this.projectDir,e),S=relative(this.contentDir,t);!S.startsWith(`..`)&&isSupportedDocFile(S)&&!this.contentFilter.isExcluded(S)?s.push(e):g.push(e)}let S=[];for(let t of g)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log$1.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log$1.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),S.push({file:t,err:e})}if(S.length>0){let t=S.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let s=t.slice(0,3).join(`, `),g=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${s}${g}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log$1.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(s.length>0){for(let e of s)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(s),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log$1.warn({files:s},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log$1.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log$1.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){log$1.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log$1.info({},`[sync] merge aborted`)}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),log$1.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log$1.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};writeFileSync(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`?void 0:t.pausedReason;let s=t.inflightConflicts??[];if(s.length>0){for(let e of s)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log$1.warn({err:e},`[sync] failed to load sync state`)}}};const MOUNT_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function createSyncHandshakeSpanExtension(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(isSystemDoc(e)||isConfigDoc(e))return;let s=t?.get(`mountId`)??void 0,g={"doc.name":e};s!==void 0&&MOUNT_ID_PATTERN.test(s)&&(g[`mount.id`]=s);try{withSpanSync(`sync.handshake`,{attributes:g},()=>{})}catch(e){console.warn(`[sync-handshake-span] emission failed:`,e instanceof Error?e:String(e))}}}}const TAG_VALUE_RE=createTagInTextRegex();function createEmptyState(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function stripInlineCodeSpans(e){return e.replace(/`[^`]*`/g,``)}function extractInlineTagsFromBody(e){let t=e.replaceAll(`\r
|
|
2827
2828
|
`,`
|
|
2828
2829
|
`).split(`
|
|
2829
|
-
`),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:s}of e)try{let e=readFileSync(s,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let s;try{s=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1,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}initTelemetry();let ne=randomUUID(),ae=getLocalDir(s);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,s)=>{let g=oe.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}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=null,je=new Set,Me=!1,Pe,Ie,Re,ze=new Promise((e,t)=>{Ie=e,Re=t});function Be(e){ye?.signal(e)}let Ve=2e3,Ue=null;function We(){Ue!==null&&clearTimeout(Ue),Ue=setTimeout(()=>{Ue=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let Ge=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ke=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||Ge.setRenamed(e,t)},Xe=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(Ge.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ge.setDeleted(e)}},$e=e=>{isSystemDoc(e)||isConfigDoc(e)||Ge.delete(e)};try{ue=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let{prunedFiles:e,prunedFolders:t}=reconcileFileIndexAfterFilterRebuild(zt),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`)}}}),de=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:F},ge=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:me,ephemeral:J,contentRoot:L,backlinkIndex:de,configHomedirOverride:k,getCurrentBranch:()=>Bt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>De,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t,s,g)=>{ye?.emitDiskAck(e,t),!(isSystemDoc(e)||isConfigDoc(e))&&assetReferencesChanged(g,s)&&(Te?.(),Be(`files`))},onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[ge.extension]});let B=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(je.has(e)||Me&&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)},Pe=async e=>{je.add(e);try{await _e.unloadDocument(e)}finally{je.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let q=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:Be});_e.configuration.extensions.push(q),_e.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!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ne}`);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`&&(De&&s.principalId===De.id?E.principalId=De.id:De?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:De.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),_e.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}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Ge,resolveFilePath:te,fileExists:existsSync})}}),_e.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:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>zt?zt.getFileIndex():new Map,getFolderIndex:()=>zt?zt.getFolderIndex():new Map,getAliasMap:()=>zt?zt.getAliasMap():new Map,rescanFiles:()=>zt?.rescanFromDisk(),enableTestRoutes:j,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),takeStoreFailure:e=>ge.takeStoreFailure(e),takeStoreDivergence:e=>ge.takeStoreDivergence(e),markAgentWriteStore:e=>ge.markAgentWriteStore(e),getCurrentBranch:()=>Bt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:de,tagIndex:fe,signalChannel:Be,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Vt,localOpCliArgs:H,projectDir:s,resolveEmbed:se,getPrincipal:()=>De,forceUnloadDocument:Pe,ready:ze,recentlyRemovedDocs:Ge,serializeDoc:st,ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Te=e}});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:L,getCurrentBranch:()=>Bt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension()),_e.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Vt,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(ae),e}let nt=null,rt=new Map,it=[];function at(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function st(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:s,body:g}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(s,g)}let vt=(e,t)=>applyExternalChange(_e,e,t,se,ce);function Tt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Et=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of _e.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=_e.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,se,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}`)}}},Dt=null,jt=e=>{e&&(Dt===null&&(Dt=new Set,setImmediate(()=>{let e=Dt;if(Dt=null,e)try{for(let t of e)Et(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Dt.add(e))};function Mt(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 Ft(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),We(),fe.updateDocumentFromMarkdown(e.docName,e.content),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),$e(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=_e.documents.get(t);if(!g){de.updateDocumentFromMarkdown(t,s),We(),fe.updateDocumentFromMarkdown(t,s),Be(`backlinks`),Be(`graph`),Be(`tags`);return}let S=getReconciledBase(t)??``,w=st(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`:Tt(g),de.updateDocumentFromMarkdown(t,s),We(),fe.updateDocumentFromMarkdown(t,s),Be(`backlinks`),Be(`graph`),Be(`tags`);break;case`clean`:try{vt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Tt(g),de.updateDocumentFromMarkdown(t,s),We(),fe.updateDocumentFromMarkdown(t,s),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Tt(g)}break;case`merged`:try{vt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Tt(g),de.updateDocumentFromMarkdown(t,s),We(),fe.updateDocumentFromMarkdown(t,s),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Tt(g)}break;case`conflicts`:try{vt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,s),We(),fe.updateDocumentFromMarkdown(t,s),Be(`backlinks`),Be(`graph`),Be(`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=_e.documents.get(t);if(!s){de.deleteDocument(t),We(),fe.deleteDocument(t),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Xe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=st(t)??``,w=S!==g;if(w&&me.current){let e=me.current,s=Bt?.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),de.deleteDocument(t),We(),fe.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),_e.closeConnections(t),await Pe(s),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Xe(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=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),de.renameDocument(t,s,g),We(),fe.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}`),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Ke(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=_e.documents.get(t);if(!s)return;let g=st(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`:oe.add(e.relativePath),Be(`files`),jt(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),Be(`files`),jt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Be(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Mt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let It=[];async function Lt(e){if(isBatchInProgress()){It.push(e);return}await Ft(e)}async function Rt(){let e=It.splice(0,It.length);for(let t of e)await Ft(t)}let zt=null,Bt=null,Vt=null,Ht=null;async function Ut(e){if(_e.documents.size===0)return;let t=!1,s=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.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(_e.documents.keys()),S=[],E=[];if(me.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=st(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=at(me.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:me.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 Wt(){return Ht||(Ht=(async()=>{let e=Date.now(),t=[];Me=!0,Ue!==null&&(clearTimeout(Ue),Ue=null);let g,S=await Promise.race([ze.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=_e.documents.size;try{try{try{Bt&&=(await Bt.unsubscribe(),null),zt&&=(await zt.unsubscribe(),null);for(let{docName:e,cleanup:t}of it)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}it.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{ye?.destroy(),we?.destroy(),nt&&=(await nt.disconnect(),null);for(let[e,t]of rt)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}rt.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 ve.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 Ut(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 ge.flushPendingGitCommit(),await ge.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{Vt&&=(await Vt.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(me.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.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(ae)}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)})}}})(),Ht)}let Kt=[];async function $t(){try{De=await loadPrincipal(s),Y.info({principalId:De.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(s),Y.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Kt.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.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(me.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(me.current)try{await shadowGit(me.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{me.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Kt.includes(`shadow-repo`)||Kt.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.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(me.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`),Kt.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`),Kt.push(`upload-tempfile-sweep`)}try{nt=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Kt.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await _e.openDirectConnection(e);rt.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Kt.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=_e.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,ge.configPersistenceCtx);if(Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=te();Vt?.setEnabled(e).catch(t=>{Y.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});it.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}`),Kt.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(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,ge.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 ue.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`),ye?.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`),ye?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(it.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`),Kt.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),de.switchBranch(E);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.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`)}}zt=await startWatcher(t,Lt,ue),fe.init();let e=0;try{ee===void 0?seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,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:oe,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`),Kt.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Kt.push(`basename-index`)}}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Kt.push(`file-watcher`)}try{Bt=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=st(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(me.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=It.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 Rt(),await ge.flushDeferredStores(`within-branch`),Vt!==null)try{await Vt.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),It.splice(0,It.length),switchReconciledBaseScope(g),Ue!==null&&(clearTimeout(Ue),Ue=null),de.switchBranch(g),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,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`),Kt.includes(`basename-index-partial`)||Kt.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=st(e)??``;if(S!==t&&me.current){let t=me.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`);vt(e,w),setReconciledBase(e,w),Y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){Y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}Y.info({branch:g,docCount:_e.documents.size},`[branch-switch] loaded branch ${g} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(g)){let e=await de.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await de.rebuildFromDisk(g);de.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(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(me.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`:vt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:vt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=_e.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-`)&&me.current)try{let t=shadowGit(me.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
|
|
2830
|
-
`))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 ge.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&me.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(me.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`),Kt.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=_e.documents.get(S);if(!w)continue;let E=st(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{Vt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:ue,contentRoot:L,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:ye,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ge.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 Vt.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Vt=null}Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`)}return $t().then(Ie,Re),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Wt,ready:ze,degraded:Kt,lockDir:ae,get syncEngine(){return Vt}}}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-B4QDNiiR.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,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(`
|
|
2830
|
+
`),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:s}of e)try{let e=readFileSync(s,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let s;try{s=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1,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`)});try{ge.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let{prunedFiles:e,prunedFolders:t}=reconcileFileIndexAfterFilterRebuild(Ut),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});try{ge.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}_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:`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 ne=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,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{je=e}});ye.configuration.extensions.push(ne),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),ge.init();let e=0;try{ee===void 0?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(),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(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(`
|
|
2831
|
+
`))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_shPhcO.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(`
|
|
2831
2832
|
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!1});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let w=``;try{w=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,w);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}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/
|
|
2832
|
-
`,`utf-8`),t}export{
|
|
2833
|
-
//# sourceMappingURL=dist-
|
|
2833
|
+
`,`utf-8`),t}export{STATE_MANIFEST_FILENAME as $,loggerFactory as $n,saveVersion as $r,createServerObserverExtension as $t,LOG_MD_TEMPLATE as A,withSpanSync as Ai,incrementCollabSocketFilteredError as An,resetMetrics as Ar,clearContributors as At,OK_OKIGNORE_TEMPLATE as B,isJSONRPCResultResponse as Bi,isConfigDoc as Bn,restoreLifecycleFromConflictsJson as Br,createApiExtension as Bt,GitNotAvailableError as C,tracedWriteFileSync as Ci,getLogger as Cn,reconcile as Cr,buildInstructions as Ct,HocuspocusAuthTokenSchema as D,validateCloneInputs as Di,getTracer as Dn,registerWrite as Dr,classifyEvents as Dt,HocuspocusAuthRejection as E,validateAgentId as Ei,getMetrics as En,registerAllTools as Er,buildWipTree as Et,MIN_GIT_VERSION as F,McpServer as Fi,installPrettyZodErrors as Fn,resolveLockDir as Fr,commitWipFromTree as Ft,ROOT_GITIGNORE_TEMPLATE as G,writeConfigPatch as Gi,isPathWithinDir as Gn,runCloneSubprocess as Gr,createEphemeralProjectDir as Gt,PinoLogger as H,readConfigSafely as Hi,isKnownPackId as Hn,rewriteWikiLinksForDocumentRename as Hr,createContentFilter as Ht,MISSING_OK_CONFIG_MESSAGE as I,JSONRPCMessageSchema as Ii,installTestLoggers as In,resolvePack as Ir,compareSemver as It,STARTER_FOLDERS as J,resolveGitDirDetailed as Ji,isSystemDoc as Jn,safeContentPath as Jr,createLiveDerivedIndexExtension as Jt,SERVICE_WRITER as K,GitDirAccessError as Ki,isProjectRoot as Kn,runDeviceFlowSubprocess as Kr,createExternalChangeHandler as Kt,McpLogger as L,LATEST_PROTOCOL_VERSION as Li,installUserSkill as Ln,resolvePackageVersion as Lr,containsConflictMarkers as Lt,MAX_AGENT_SESSIONS as M,writeStateManifest as Mi,initContent as Mn,resolveContentDir as Mr,coercePackId as Mt,MCP_CONNECTION_ID_HEADER as N,writeTargetVersion as Ni,initShadowRepo as Nn,resolveCursorBinaryDefault as Nr,commitUpstreamImport as Nt,INSTALLED_AGENTS_SCHEMES as O,validateSkillZip as Oi,handleCollabSocketError as On,releaseUiLock as Or,classifyFsPath as Ot,MCP_SERVER_NAME as P,writeTracker as Pi,initTelemetry as Pn,resolveCursorSpawnInvocation as Pr,commitWip as Pt,STARTER_TEMPLATES as Q,loadPrincipal as Qn,saveInMemoryCheckpoint as Qr,createServer$1 as Qt,MissingOkConfigError as R,isInitializedNotification as Ri,isAllowedApiOrigin as Rn,resolveUiInfo as Rr,contentHash as Rt,GIT_UPSTREAM_WRITER as S,tracedWriteFile as Si,getLogFilePath as Sn,readUiLock as Sr,buildExecResult as St,HOCUSPOCUS_AUTH_REJECTION_REASONS as T,updateUiLockPort as Ti,getMeter as Tn,recordSkillInstallEvent as Tr,buildStarterFolderFrontmatterYaml as Tt,ProjectGitInitError as U,resolveConfigPath as Ui,isLoopbackAddress as Un,runAuthReposSubprocess as Ur,createContentFilterAsync as Ut,PANE_TARGET_TTL_MS as V,atomicWriteFileSync as Vi,isHocuspocusAuthRejectionReason as Vn,rewriteMarkdownLinksForDocumentRename as Vr,createAssetServeMiddleware as Vt,ROLLBACK_ORIGIN as W,withFileLockSync as Wi,isPairedWriteOrigin as Wn,runAuthStatusSubprocess as Wr,createEmbeddingsSecretStore as Wt,STARTER_PACKS as X,listRescueCheckpoints as Xn,safetyCheckpoint as Xr,createOsProbe as Xt,STARTER_FOLDER_FRONTMATTER_FILENAME as Y,resolveShadowDir as Yi,lastKnownHash as Yn,safeSubdir as Yr,createMcpHttpHandler as Yt,STARTER_PACK_IDS as Z,listStarterPacks as Zn,sanitizeClientName as Zr,createPersistenceExtension as Zt,EMBEDDINGS_API_KEY_ENV as _,tracedRename as _i,formatContributors as _n,readServerPackageVersion as _r,assertNeverDiskEvent as _t,AgentPresenceBroadcaster as a,spansCurrentPath as ai,detectProjectShape as an,packageVersionMajorMinor as ar,StateManifestError as at,FileEmbeddingsBackend as b,tracedRmdirSync as bi,getCurrentMcpLogger as bn,readTargetRecordedAt as br,buildAndOpenSkill as bt,BacklinkIndex as c,splitMarkdownBlocks as ci,encodeFolderRoute as cn,parseHocuspocusAuthToken as cr,__getShowAllWalkStatsForTesting as ct,CONFLICT_MARKER_RE as d,swapContributors as di,evictStaleTrackerEntries as dn,planSeed as dr,applyAgentMarkdownWrite as dt,seedBasenameIndex as ei,createStreamingErrorWriter as en,logsCurrentPath as er,SeedPrerequisiteError as et,CURSOR_BUNDLE_PATHS_BY_PLATFORM as f,toBroadcasterKey as fi,extractWikiLinksFromMarkdown as fn,prepareSingleFileOpen as fr,applyExternalChange as ft,DEFAULT_PACK_ID as g,tracedMkdirSync as gi,formatAuthRejectionWire as gn,readProjectLocalSemanticConfig as gr,assertGitAvailable as gt,DEFAULT_EMBEDDINGS_DIMENSIONS as h,tracedMkdir as hi,findEnclosingProjectRoot as hn,readBranchFromHead as hr,assertCompatibleStateManifest as ht,AgentFocusBroadcaster as i,shutdownTelemetry as ii,detectGit as in,normalizeFsPath as ir,SingleFileNotMarkdownError as it,MANAGED_RENAME_ORIGIN as j,writeRootGitignoreForNewRepo as ji,incrementServerObserverFire as jn,resolveBundledSkillDir as jr,clearEmbeddingsKeyFromAllBackends as jt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as k,withSpan as ki,handleSpawnCursor as kn,removeLastKnownHash as kr,clearArmedPaneTarget as kt,CC1Broadcaster as l,startWatcher as li,ensureProjectGit as ln,parseKeepaliveConnectionId as lr,__resetShowAllWalkStatsForTesting as lt,DEFAULT_CHECKPOINT_RETENTION as m,tracedLinkSync as mi,findEnclosingGitRoot as mn,readArmedPaneTarget as mr,armPaneTarget as mt,AGENT_ID_RE as n,setActiveSpanAttributes as ni,describeStoredEmbeddingsKey as nn,makeLazyEmbeddingsKeyStore as nr,SingleFileNotAFileError as nt,AgentSessionCapacityError as o,spansPreviousPath as oi,emitPreflightFailureSpan as on,parseAuthRejectionWire as or,TagIndex as ot,ConfigSchema as p,tracedAppendFileSync as pi,fallbackPaths as pn,readAllTargets as pr,applySeed as pt,SKILL_INSTALL_EVENTS_FILE_REL as q,MalformedGitPointerError as qi,isSelfWrite as qn,runWithMcpLogger as qr,createFileLogger as qt,AGENT_WRITE_ORIGIN as r,shadowGit as ri,detectClaudeDesktopPresence as rn,mountMcpAndApi as rr,SingleFileNotFoundError as rt,AgentSessionManager as s,spawnDetached as si,encodeDocName as sn,parseGitVersion as sr,UiLockCollisionError as st,AGENT_ID_MAX_LEN as t,serializeError as ti,createTestLogger as tn,logsPreviousPath as tr,SeedRootDirError as tt,CONFIG_FILENAME as u,streamingProblemEvent as ui,errorResponse as un,pathToDocName as ur,acquireUiLock as ut,FILE_SYSTEM_WRITER as v,tracedRenameSync as vi,formatContributorsFrom as vn,readSkillInstallStateSnapshot as vr,attachIdleShutdown as vt,GitTooOldError as w,updateLastKnownHash as wi,getLogsDir as wn,recordContributor as wr,buildSkillZip as wt,GIT_PREFLIGHT_FAIL_SPAN_NAME as x,tracedUnlinkSync as xi,getLocalDir as xn,readTargetVersion as xr,buildConfigYmlContent as xt,FILE_WATCHER_ORIGIN as y,tracedRmSync as yi,gcCheckpointRefs as yn,readStateManifest as yr,bootServer as yt,OBSERVER_SYNC_ORIGIN as z,isJSONRPCRequest as zi,isAllowedWorkspaceHostHeader as zn,restoreContributors as zr,contributorCount as zt};
|
|
2834
|
+
//# sourceMappingURL=dist-jSj9zzv0.mjs.map
|