@inkeep/open-knowledge 0.0.0-dev-20260501144307 → 0.0.0-dev-20260501170533
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/cli.mjs +6 -6
- package/dist/constants-B8HpPaWG.mjs +2 -0
- package/dist/{dist-B-uWyCj3.mjs → dist-BVnVlgjQ.mjs} +1 -1
- package/dist/{dist-WQbZIrx7.mjs → dist-CDuTCUx1.mjs} +7 -8
- package/dist/{dist-CUghvkAf.mjs → dist-oDoSs1Bl.mjs} +7 -7
- package/dist/index.mjs +1 -1
- package/dist/{init-qoXDcT6N.mjs → init-Bf7LOYAr.mjs} +2 -2
- package/dist/init-BhfL8UL0.mjs +1 -0
- package/dist/{init-DpiVQYhQ.mjs → init-CPq6B11A.mjs} +3 -3
- package/dist/init-DkzHwyzJ.mjs +1 -0
- package/dist/loader-5abUX3Eq.mjs +1 -0
- package/dist/{loader-BEUtMT2_.mjs → loader-C79dNoU-.mjs} +2 -2
- package/dist/paths-BIsyTDX6.mjs +1 -0
- package/dist/paths-Drz5vBVF.mjs +2 -0
- package/dist/{preview-BIrbsSSc.mjs → preview-AXEdeZ4w.mjs} +2 -2
- package/dist/preview-DUYE2XxR.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-C3KENqJ7.js → ActivityModeContent-CCJOMAyp.js} +1 -1
- package/dist/public/assets/DocumentContext-BHFNw5NZ.js +37 -0
- package/dist/public/assets/{GraphPanel-YIuSwj1X.js → GraphPanel-BuZEMdl-.js} +2 -2
- package/dist/public/assets/{McpConsentDialogBody-Dx67JoKA.js → McpConsentDialogBody-CI9rAMX9.js} +1 -1
- package/dist/public/assets/OutlinePanel-CnKUM65X.js +2 -0
- package/dist/public/assets/SettingsPane-B3rEEyMP.js +6 -0
- package/dist/public/assets/{SourceEditor-DGIgtF_h.js → SourceEditor-CE_X9auW.js} +2 -2
- package/dist/public/assets/{config-validation-events-Dlj9dOCp.js → config-validation-events-DqfR4UtM.js} +1 -1
- package/dist/public/assets/{index-DiLfeu2w.css → index-CKzUuzYV.css} +1 -1
- package/dist/public/assets/index-NVu982rh.js +1850 -0
- package/dist/public/assets/{target-navigation-intent-BeUCdVKa.js → target-navigation-intent-1238Z_HW.js} +1 -1
- package/dist/public/assets/{toggle-group-CyBGhndP.js → toggle-group-C5MXNna8.js} +3 -3
- package/dist/public/assets/{tooltip-FdwzzIbl.js → tooltip-BMlqVI54.js} +1 -1
- package/dist/public/index.html +9 -9
- package/dist/{server-Bc0tGxRk.mjs → server-Cb1yd7Zc.mjs} +2 -2
- package/dist/src-CPe0c6hz.mjs +1 -0
- package/dist/start-COO3npTl.mjs +1 -0
- package/dist/{start-BSqokDQs.mjs → start-Dl1pApAn.mjs} +2 -2
- package/package.json +2 -2
- package/dist/constants-D4b3yFb4.mjs +0 -2
- package/dist/init-CleqrmS6.mjs +0 -1
- package/dist/init-D1vMwuMO.mjs +0 -1
- package/dist/loader-CwvZAVlq.mjs +0 -1
- package/dist/paths-B1biT3Kh.mjs +0 -2
- package/dist/paths-BQoQfIvS.mjs +0 -1
- package/dist/preview-BNMytxTe.mjs +0 -1
- package/dist/public/assets/DocumentContext-gM6_1mHt.js +0 -34
- package/dist/public/assets/SettingsPane-tlYUoGwR.js +0 -6
- package/dist/public/assets/clipboard-CW1hOwDY.js +0 -5
- package/dist/public/assets/index-n9oW9uU-.js +0 -1848
- package/dist/src-CGZcpVS_.mjs +0 -1
- package/dist/start-C7hQj_dW.mjs +0 -1
- /package/dist/public/assets/{mcp-consent-store-BBTXqzE6.js → mcp-consent-store-B9QLSyUV.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{$ as addConfigSpanEvent,A as defaultScheduler,B as normalizeBridge,C as applyFastDiff,D as colorFromSeed,E as classifyWikiLinkTarget,F as humanFormat,G as stripFrontmatter,H as readFmMap,I as iconFromClientName,J as PluginKey,K as toWikiLinkSlug,L as isKnownConfigError,Lt as require_dist$1,N as getParseHealth,O as createBasenameIndex,P as getWikiLinkText,R as isOrphanMode,S as SYSTEM_DOC_NAME,T as classifyMarkdownHref,U as resolveInternalHref,V as prependFrontmatter,W as sharedExtensions,Y as Fragment,Z as ConfigSchema,_ as DEFAULT_DEDUP_MODE,a as CC1ConfigValidationRejectedPayloadSchema,b as MarkdownManager,bt as string,c as CC1ServerInfoPayloadSchema,d as CC1_CHANNEL_DISK_ACK,f as CC1_CHANNEL_SERVER_INFO,gt as object,h as CONFIG_DOC_NAME_USER,i as CC1BranchSwitchedPayloadSchema,it as withConfigSpanSync,j as getHeadingSlug,k as createCodeFenceTracker,l as CC1_CHANNEL_BRANCH_SWITCHED,m as CONFIG_DOC_NAME_PROJECT,n as ASSET_EXTENSIONS,o as CC1DerivedViewPayloadSchema,p as CONFIG_DOC_NAMES,q as getSchema,r as BridgeMergeContentLossError,rt as withConfigSpan,s as CC1DiskAckPayloadSchema,t as AGENT_ICON_COLORS,u as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,w as applyIncrementalDiff,z as mergeThreeWay}from"./dist-
|
|
1
|
+
import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{$ as addConfigSpanEvent,A as defaultScheduler,B as normalizeBridge,C as applyFastDiff,D as colorFromSeed,E as classifyWikiLinkTarget,F as humanFormat,G as stripFrontmatter,H as readFmMap,I as iconFromClientName,J as PluginKey,K as toWikiLinkSlug,L as isKnownConfigError,Lt as require_dist$1,N as getParseHealth,O as createBasenameIndex,P as getWikiLinkText,R as isOrphanMode,S as SYSTEM_DOC_NAME,T as classifyMarkdownHref,U as resolveInternalHref,V as prependFrontmatter,W as sharedExtensions,Y as Fragment,Z as ConfigSchema,_ as DEFAULT_DEDUP_MODE,a as CC1ConfigValidationRejectedPayloadSchema,b as MarkdownManager,bt as string,c as CC1ServerInfoPayloadSchema,d as CC1_CHANNEL_DISK_ACK,f as CC1_CHANNEL_SERVER_INFO,gt as object,h as CONFIG_DOC_NAME_USER,i as CC1BranchSwitchedPayloadSchema,it as withConfigSpanSync,j as getHeadingSlug,k as createCodeFenceTracker,l as CC1_CHANNEL_BRANCH_SWITCHED,m as CONFIG_DOC_NAME_PROJECT,n as ASSET_EXTENSIONS,o as CC1DerivedViewPayloadSchema,p as CONFIG_DOC_NAMES,q as getSchema,r as BridgeMergeContentLossError,rt as withConfigSpan,s as CC1DiskAckPayloadSchema,t as AGENT_ICON_COLORS,u as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,w as applyIncrementalDiff,z as mergeThreeWay}from"./dist-oDoSs1Bl.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 acquireServerLock,c as readProcessLock,d as releaseServerLock,i as acquireProcessLock,l as readServerLock,n as RUNTIME_VERSION,o as isProcessAlive,p as updateProcessLockPort,t as ProcessLockCollisionError,u as releaseProcessLock}from"./server-lock-BAi_a4NX-CRPhQdIH.mjs";import{a as require_src$15,i as esm_default,r as withParentLock,t as createGitInstance}from"./git-handle-BhGnmvTB-BMB_49Sb.mjs";import{r as diffLines,t as createPatch}from"./libesm-CE3v6NRY.mjs";import{i as resolveConfigPath,t as applyFolderRulesUpsert}from"./server-Cb1yd7Zc.mjs";import{n as mimes}from"./mrmime-DXdnqyHu.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import{basename,dirname,extname,join,posix,relative,resolve,sep}from"node:path";import{closeSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{homedir,hostname,platform,tmpdir}from"node:os";import{promisify}from"node:util";import{Readable}from"stream";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{Transform}from"node:stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import*as zlib$1 from"zlib";import{mkdir,readFile,readdir,realpath,rename,stat as stat$1,writeFile}from"node:fs/promises";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{createServer}from"node:http";var require_err_helpers=__commonJSMin$1(((e,t)=>{let n=e=>e&&typeof e.message==`string`,r=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return n(t)?t:void 0}else return n(t)?t:void 0},i=(e,t)=>{if(!n(e))return``;let a=e.stack||``;if(t.has(e))return a+`
|
|
2
2
|
causes have become circular...`;let o=r(e);return o?(t.add(e),a+`
|
|
3
3
|
caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?``:e.message||``;if(t.has(e))return a+`: ...`;let s=r(e);if(s){t.add(e);let n=typeof e.cause==`function`;return a+(n?``:`: `)+o(s,t,n)}else return a};t.exports={isErrorLike:n,getErrorCause:r,stackWithCauses:a,messageWithCauses:e=>o(e,new Set)}})),require_err_proto=__commonJSMin$1(((e,t)=>{let n=Symbol(`circular-ref-tag`),r=Symbol(`pino-raw-err-ref`),i=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[r]},set:function(e){this[r]=e}}});Object.defineProperty(i,r,{writable:!0,value:{}}),t.exports={pinoErrProto:i,pinoErrorSymbols:{seen:n,rawSymbol:r}}})),require_err=__commonJSMin$1(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=require_err_helpers(),{pinoErrProto:a,pinoErrorSymbols:o}=require_err_proto(),{seen:s}=o,{toString:c}=Object.prototype;function l(e){if(!i(e))return e;e[s]=void 0;let t=Object.create(a);t.type=c.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=n(e),t.stack=r(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>l(e)));for(let n in e)if(t[n]===void 0){let r=e[n];i(r)?n!==`cause`&&!Object.prototype.hasOwnProperty.call(r,s)&&(t[n]=l(r)):t[n]=r}return delete e[s],t.raw=e,t}})),require_err_with_cause=__commonJSMin$1(((e,t)=>{t.exports=s;let{isErrorLike:n}=require_err_helpers(),{pinoErrProto:r,pinoErrorSymbols:i}=require_err_proto(),{seen:a}=i,{toString:o}=Object.prototype;function s(e){if(!n(e))return e;e[a]=void 0;let t=Object.create(r);t.type=o.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>s(e))),n(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,a)&&(t.cause=s(e.cause));for(let r in e)if(t[r]===void 0){let i=e[r];n(i)?Object.prototype.hasOwnProperty.call(i,a)||(t[r]=s(i)):t[r]=i}return delete e[a],t.raw=e,t}})),require_req=__commonJSMin$1(((e,t)=>{t.exports={mapHttpRequest:a,reqSerializer:i};let n=Symbol(`pino-raw-req-ref`),r=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=e.info||e.socket,n=Object.create(r);if(n.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),n.method=e.method,e.originalUrl)n.url=e.originalUrl;else{let t=e.path;n.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(n.query=e.query),e.params&&(n.params=e.params),n.headers=e.headers,n.remoteAddress=t&&t.remoteAddress,n.remotePort=t&&t.remotePort,n.raw=e.raw||e,n}function a(e){return{req:i(e)}}})),require_res=__commonJSMin$1(((e,t)=>{t.exports={mapHttpResponse:a,resSerializer:i};let n=Symbol(`pino-raw-res-ref`),r=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=Object.create(r);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function a(e){return{res:i(e)}}})),require_pino_std_serializers=__commonJSMin$1(((e,t)=>{let n=require_err(),r=require_err_with_cause(),i=require_req(),a=require_res();t.exports={err:n,errWithCause:r,mapHttpRequest:i.mapHttpRequest,mapHttpResponse:a.mapHttpResponse,req:i.reqSerializer,res:a.resSerializer,wrapErrorSerializer:function(e){return e===n?e:function(t){return e(n(t))}},wrapRequestSerializer:function(e){return e===i.reqSerializer?e:function(t){return e(i.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===a.resSerializer?e:function(t){return e(a.resSerializer(t))}}}})),require_caller=__commonJSMin$1(((e,t)=>{function n(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=n;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),i=[];for(let e of r)e&&i.push(e.getFileName());return i}})),require_redact=__commonJSMin$1(((e,t)=>{function n(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let r=0;r<e.length;r++)t[r]=n(e[r]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=n(e[r]));return t}return e}function r(e){let t=[],n=``,r=!1,i=!1,a=``;for(let o=0;o<e.length;o++){let s=e[o];!r&&s===`.`?n&&=(t.push(n),``):s===`[`?(n&&=(t.push(n),``),r=!0):s===`]`&&r?(t.push(n),n=``,r=!1,i=!1):(s===`"`||s===`'`)&&r?i?s===a?(i=!1,a=``):n+=s:(i=!0,a=s):n+=s}return n&&t.push(n),t}function i(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(typeof r!=`object`||!r||!(n in r)||typeof r[n]!=`object`||r[n]===null)return!1;r=r[n]}let i=t[t.length-1];if(i===`*`){if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=n;else if(typeof r==`object`&&r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=n)}else typeof r==`object`&&r&&i in r&&Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n);return!0}function a(e,t){let n=e;for(let e=0;e<t.length-1;e++){let r=t[e];if(typeof n!=`object`||!n||!(r in n)||typeof n[r]!=`object`||n[r]===null)return!1;n=n[r]}let r=t[t.length-1];if(r===`*`){if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=void 0;else if(typeof n==`object`&&n)for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&delete n[e]}else typeof n==`object`&&n&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}let o=Symbol(`PATH_NOT_FOUND`);function s(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n||!(e in n))return o;n=n[e]}return n}function c(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n)return;n=n[e]}return n}function l(e,t,n,c=!1){for(let l of t){let t=r(l);if(t.includes(`*`))u(e,t,n,l,c);else if(c)a(e,t);else{let r=s(e,t);if(r===o)continue;i(e,t,typeof n==`function`?n(r,t):n)}}}function u(e,t,n,r,i=!1){let a=t.indexOf(`*`);if(a===t.length-1){let r=t.slice(0,-1),a=e;for(let e of r){if(typeof a!=`object`||!a||!a)return;a=a[e]}if(Array.isArray(a))if(i)for(let e=0;e<a.length;e++)a[e]=void 0;else for(let e=0;e<a.length;e++){let t=[...r,e.toString()],i=typeof n==`function`?n(a[e],t):n;a[e]=i}else if(typeof a==`object`&&a)if(i){let e=[];for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&e.push(t);for(let t of e)delete a[t]}else for(let e in a){let t=[...r,e],i=typeof n==`function`?n(a[e],t):n;a[e]=i}}else d(e,t,n,a,r,i)}function d(e,t,n,r,o,s=!1){let l=t.slice(0,r),d=t.slice(r+1),f=[];function p(e,t){if(t===l.length){if(Array.isArray(e))for(let n=0;n<e.length;n++)f[t]=n.toString(),p(e[n],t+1);else if(typeof e==`object`&&e)for(let n in e)f[t]=n,p(e[n],t+1)}else if(t<l.length){let n=l[t];e&&typeof e==`object`&&e&&n in e&&(f[t]=n,p(e[n],t+1))}else d.includes(`*`)?u(e,d,typeof n==`function`?(e,r)=>n(e,[...f.slice(0,t),...r]):n,o,s):s?a(e,d):i(e,d,typeof n==`function`?n(c(e,d),[...f.slice(0,t),...d]):n)}if(l.length===0)p(e,0);else{let t=e;for(let e=0;e<l.length;e++){let n=l[e];if(typeof t!=`object`||!t||!t)return;t=t[n],f[e]=n}t!=null&&p(t,l.length)}}function f(e){if(e.length===0)return null;let t=new Map;for(let n of e){let e=r(n),i=t;for(let t=0;t<e.length;t++){let n=e[t];i.has(n)||i.set(n,new Map),i=i.get(n)}}return t}function p(e,t){if(!t)return e;function n(e,t,r=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let r=[];for(let i=0;i<e.length;i++){let a=i.toString();t.has(a)||t.has(`*`)?r[i]=n(e[i],t.get(a)||t.get(`*`)):r[i]=e[i]}return r}let i=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t.has(r)||t.has(`*`)?i[r]=n(e[r],t.get(r)||t.get(`*`)):i[r]=e[r]);return i}return n(e,t)}function m(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,n=!1,r=``;for(let i=0;i<e.length;i++){let a=e[i];if((a===`"`||a===`'`)&&t>0)n?a===r&&(n=!1,r=``):(n=!0,r=a);else if(a===`[`&&!n)t++;else if(a===`]`&&!n&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function h(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)m(t)}function g(e={}){let{paths:t=[],censor:r=`[REDACTED]`,serialize:i=JSON.stringify,strict:a=!0,remove:o=!1}=e;h(t);let s=f(t);return function(e){if(a&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return i?i(e):e;let c=p(e,s),u=e,d=r;return typeof r==`function`&&(d=r),l(c,t,d,o),i===!1?(c.restore=function(){return n(u)},c):typeof i==`function`?i(c):JSON.stringify(c)}}t.exports=g})),require_symbols=__commonJSMin$1(((e,t)=>{let n=Symbol(`pino.setLevel`),r=Symbol(`pino.getLevel`),i=Symbol(`pino.levelVal`),a=Symbol(`pino.levelComp`),o=Symbol(`pino.useLevelLabels`),s=Symbol(`pino.useOnlyCustomLevels`),c=Symbol(`pino.mixin`),l=Symbol(`pino.lsCache`),u=Symbol(`pino.chindings`),d=Symbol(`pino.asJson`),f=Symbol(`pino.write`),p=Symbol(`pino.redactFmt`),m=Symbol(`pino.time`),h=Symbol(`pino.timeSliceIndex`),g=Symbol(`pino.stream`),_=Symbol(`pino.stringify`),v=Symbol(`pino.stringifySafe`),y=Symbol(`pino.stringifiers`),b=Symbol(`pino.end`),x=Symbol(`pino.formatOpts`),S=Symbol(`pino.messageKey`),C=Symbol(`pino.errorKey`),w=Symbol(`pino.nestedKey`),T=Symbol(`pino.nestedKeyStr`),E=Symbol(`pino.mixinMergeStrategy`),D=Symbol(`pino.msgPrefix`),O=Symbol(`pino.wildcardFirst`),k=Symbol.for(`pino.serializers`),A=Symbol.for(`pino.formatters`),j=Symbol.for(`pino.hooks`);t.exports={setLevelSym:n,getLevelSym:r,levelValSym:i,levelCompSym:a,useLevelLabelsSym:o,mixinSym:c,lsCacheSym:l,chindingsSym:u,asJsonSym:d,writeSym:f,serializersSym:k,redactFmtSym:p,timeSym:m,timeSliceIndexSym:h,streamSym:g,stringifySym:_,stringifySafeSym:v,stringifiersSym:y,endSym:b,formatOptsSym:x,messageKeySym:S,errorKeySym:C,nestedKeySym:w,wildcardFirstSym:O,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:s,formattersSym:A,hooksSym:j,nestedKeyStrSym:T,mixinMergeStrategySym:E,msgPrefixSym:D}})),require_redaction=__commonJSMin$1(((e,t)=>{let n=require_redact(),{redactFmtSym:r,wildcardFirstSym:i}=require_symbols(),a=/[^.[\]]+|\[([^[\]]*?)\]/g,o=`[Redacted]`,s=!1;function c(e,t){let{paths:o,censor:s,remove:c}=l(e),u=o.reduce((e,t)=>{a.lastIndex=0;let n=a.exec(t),r=a.exec(t),o=n[1]===void 0?n[0]:n[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(o===`*`&&(o=i),r===null)return e[o]=null,e;if(e[o]===null)return e;let{index:s}=r,c=`${t.substr(s,t.length-1)}`;return e[o]=e[o]||[],o!==i&&e[o].length===0&&e[o].push(...e[i]||[]),o===i&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(c)}),e[o].push(c),e},{}),d={[r]:n({paths:o,censor:s,serialize:t,strict:!1,remove:c})},f=(...e)=>t(typeof s==`function`?s(...e):s);return[...Object.keys(u),...Object.getOwnPropertySymbols(u)].reduce((e,r)=>{if(u[r]===null)e[r]=e=>f(e,[r]);else{let i=typeof s==`function`?(e,t)=>s(e,[r,...t]):s;e[r]=n({paths:u[r],censor:i,serialize:t,strict:!1,remove:c})}return e},d)}function l(e){if(Array.isArray(e))return e={paths:e,censor:o},e;let{paths:t,censor:n=o,remove:r}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return r===!0&&(n=void 0),{paths:t,censor:n,remove:r}}t.exports=c})),require_time$4=__commonJSMin$1(((e,t)=>{let n=()=>``,r=()=>`,"time":${Date.now()}`,i=()=>`,"time":${Math.round(Date.now()/1e3)}`,a=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,o=1000000n,s=1000000000n,c=BigInt(Date.now())*1000000n,l=process.hrtime.bigint();t.exports={nullTime:n,epochTime:r,unixTime:i,isoTime:a,isoTimeNano:()=>{let e=c+(process.hrtime.bigint()-l),t=e/s,n=e%s,r=Number(t*1000n+n/1000000n),i=new Date(r);return`,"time":"${i.getUTCFullYear()}-${(i.getUTCMonth()+1).toString().padStart(2,`0`)}-${i.getUTCDate().toString().padStart(2,`0`)}T${i.getUTCHours().toString().padStart(2,`0`)}:${i.getUTCMinutes().toString().padStart(2,`0`)}:${i.getUTCSeconds().toString().padStart(2,`0`)}.${n.toString().padStart(9,`0`)}Z"`}}})),require_quick_format_unescaped=__commonJSMin$1(((e,t)=>{function n(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=r;function r(e,t,r){var i=r&&r.stringify||n,a=1;if(typeof e==`object`&&e){var o=t.length+a;if(o===1)return e;var s=Array(o);s[0]=i(e);for(var c=1;c<o;c++)s[c]=i(t[c]);return s.join(` `)}if(typeof e!=`string`)return e;var l=t.length;if(l===0)return e;for(var u=``,d=1-a,f=-1,p=e&&e.length||0,m=0;m<p;){if(e.charCodeAt(m)===37&&m+1<p){switch(f=f>-1?f:0,e.charCodeAt(m+1)){case 100:case 102:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Number(t[d]),f=m+2,m++;break;case 105:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Math.floor(Number(t[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||t[d]===void 0)break;f<m&&(u+=e.slice(f,m));var h=typeof t[d];if(h===`string`){u+=`'`+t[d]+`'`,f=m+2,m++;break}if(h===`function`){u+=t[d].name||`<anonymous>`,f=m+2,m++;break}u+=i(t[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=e.slice(f,m)),u+=String(t[d]),f=m+2,m++;break;case 37:f<m&&(u+=e.slice(f,m)),u+=`%`,f=m+2,m++,d--;break}++d}++m}return f===-1?e:(f<p&&(u+=e.slice(f)),u)}})),require_atomic_sleep=__commonJSMin$1(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function n(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=n}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),require_sonic_boom=__commonJSMin$1(((e,t)=>{let n=__require$1(`fs`),r=__require$1(`events`),i=__require$1(`util`).inherits,a=__require$1(`path`),o=require_atomic_sleep(),s=__require$1(`assert`),c=100,l=Buffer.allocUnsafe(0),u=16*1024,d=`buffer`,f=`utf8`,[p,m]=(process.versions.node||`0.0`).split(`.`).map(Number),h=p>=22&&m>=7;function g(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(n,r){if(n){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,n)}):t.emit(`error`,n);return}let i=t._reopening;t.fd=r,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():i&&process.nextTick(()=>t.emit(`drain`)))}let i=t.append?`a`:`w`,o=t.mode;if(t.sync)try{t.mkdir&&n.mkdirSync(a.dirname(e),{recursive:!0}),r(null,n.openSync(e,i,o))}catch(e){throw r(e),e}else t.mkdir?n.mkdir(a.dirname(e),{recursive:!0},t=>{if(t)return r(t);n.open(e,i,o,r)}):n.open(e,i,o,r)}function _(e){if(!(this instanceof _))return new _(e);let{fd:t,dest:r,minLength:i,maxLength:a,maxWrite:s,periodicFlush:c,sync:u,append:p=!0,mkdir:m,retryEAGAIN:h,fsync:b,contentMode:C,mode:j}=e||{};t||=r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=a||0,this.maxWrite=s||16384,this._periodicFlush=c||0,this._periodicFlushTimer=void 0,this.sync=u||!1,this.writable=!0,this._fsync=b||!1,this.append=p||!1,this.mode=j,this.retryEAGAIN=h||(()=>!0),this.mkdir=m||!1;let M,N;if(C===d)this._writingBuf=l,this.write=S,this.flush=T,this.flushSync=D,this._actualWrite=k,M=()=>n.writeSync(this.fd,this._writingBuf),N=()=>n.write(this.fd,this._writingBuf,this.release);else if(C===void 0||C===f)this._writingBuf=``,this.write=x,this.flush=w,this.flushSync=E,this._actualWrite=O,M=()=>Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`),N=()=>Buffer.isBuffer(this._writingBuf)?n.write(this.fd,this._writingBuf,this.release):n.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${f}" and "${d}", but passed ${C}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)g(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{o(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(N,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let r=v(this._writingBuf,this._len,t);if(this._len=r.len,this._writingBuf=r.writingBuf,this._writingBuf.length){if(!this.sync){N();return}try{do{let e=M(),t=v(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&n.fsyncSync(this.fd);let i=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):i>this.minLength?this._actualWrite():this._ending?i>0?this._actualWrite():(this._writing=!1,A(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(y,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function v(e,t,n){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-n,0),e=e.subarray(n),{writingBuf:e,len:t}}function y(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}i(_,r);function b(e,t){return e.length===0?l:e.length===1?e[0]:Buffer.concat(e,t)}function x(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),n=this._len+t,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+t>this.maxWrite?r.push(e):r[r.length-1]+=e,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function S(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,n=this._bufs,r=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(n.length===0||r[r.length-1]+e.length>this.maxWrite?(n.push([e]),r.push(e.length)):(n[n.length-1].push(e),r[r.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function C(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{n.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,r)},r=n=>{this._flushPending=!1,e(n),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,r)}function w(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&C.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function T(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&C.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}_.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&n.close(t,e=>{if(e)return this.emit(`error`,e)})}),g(this.file,this)},_.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():A(this)))};function E(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?n.writeSync(this.fd,e):n.writeSync(this.fd,e,`utf8`),r=v(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}try{n.fsyncSync(this.fd)}catch{}}function D(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=l);let e=l;for(;this._bufs.length||e.length;){e.length<=0&&(e=b(this._bufs[0],this._lens[0]));try{let t=n.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;o(100)}}}_.prototype.destroy=function(){this.destroyed||A(this)};function O(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?n.writeSync(this.fd,this._writingBuf):n.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else n.write(this.fd,this._writingBuf,e)}function k(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:b(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,n.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else h&&(this._writingBuf=Buffer.from(this._writingBuf)),n.write(this.fd,this._writingBuf,e)}function A(e){if(e.fd===-1){e.once(`ready`,A.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],s(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{n.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?n.close(e.fd,r):r()}function r(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}_.SonicBoom=_,_.default=_,t.exports=_})),require_on_exit_leak_free=__commonJSMin$1(((e,t)=>{let n={exit:[],beforeExit:[]},r={exit:c,beforeExit:l},i;function a(){i===void 0&&(i=new FinalizationRegistry(d))}function o(e){n[e].length>0||process.on(e,r[e])}function s(e){n[e].length>0||(process.removeListener(e,r[e]),n.exit.length===0&&n.beforeExit.length===0&&(i=void 0))}function c(){u(`exit`)}function l(){u(`beforeExit`)}function u(e){for(let t of n[e]){let n=t.deref(),r=t.fn;n!==void 0&&r(n,e)}n[e]=[]}function d(e){for(let t of[`exit`,`beforeExit`]){let r=n[t].indexOf(e);n[t].splice(r,r+1),s(t)}}function f(e,t,r){if(t===void 0)throw Error(`the object can't be undefined`);o(e);let s=new WeakRef(t);s.fn=r,a(),i.register(t,s),n[e].push(s)}function p(e,t){f(`exit`,e,t)}function m(e,t){f(`beforeExit`,e,t)}function h(e){if(i!==void 0){i.unregister(e);for(let t of[`exit`,`beforeExit`])n[t]=n[t].filter(t=>{let n=t.deref();return n&&n!==e}),s(t)}}t.exports={register:p,registerBeforeExit:m,unregister:h}})),require_package=__commonJSMin$1(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),require_wait=__commonJSMin$1(((e,t)=>{let n=1e4;function r(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{let i=Atomics.load(e,t);if(i===r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let c=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),l=Atomics.waitAsync(e,t,i,c);l.async?l.value.then(s):setImmediate(s)};s()}function i(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{if(Atomics.load(e,t)!==r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let i=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),c=Atomics.waitAsync(e,t,r,i);c.async?c.value.then(s):setImmediate(s)};s()}t.exports={wait:r,waitDiff:i}})),require_indexes=__commonJSMin$1(((e,t)=>{let n=4,r=8;t.exports={WRITE_INDEX:4,READ_INDEX:8}})),require_thread_stream=__commonJSMin$1(((e,t)=>{let{version:n}=require_package(),{EventEmitter:r}=__require$1(`events`),{Worker:i}=__require$1(`worker_threads`),{join:a}=__require$1(`path`),{pathToFileURL:o}=__require$1(`url`),{wait:s}=require_wait(),{WRITE_INDEX:c,READ_INDEX:l}=require_indexes(),u=__require$1(`buffer`),d=__require$1(`assert`),f=Symbol(`kImpl`),p=u.constants.MAX_STRING_LENGTH;var m=class{constructor(e){this._value=e}deref(){return this._value}},h=class{register(){}unregister(){}};let g=process.env.NODE_V8_COVERAGE?h:global.FinalizationRegistry||h,_=process.env.NODE_V8_COVERAGE?m:global.WeakRef||m,v=new g(e=>{e.exited||e.terminate()});function y(e,t){let{filename:r,workerData:s}=t,c=new i((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||a(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf(`file://`)===0?r:o(r).href,dataBuf:e[f].dataBuf,stateBuf:e[f].stateBuf,workerData:{$context:{threadStreamVersion:n},...s}}});return c.stream=new m(e),c.on(`message`,S),c.on(`exit`,C),v.register(e,c),c}function b(e){d(!e[f].sync),e[f].needDrain&&(e[f].needDrain=!1,e.emit(`drain`))}function x(e){let t=Atomics.load(e[f].state,c),n=e[f].data.length-t;if(n>0){if(e[f].buf.length===0){e[f].flushing=!1,e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e);return}let t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);r<=n?(e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);r>e[f].data.length;)n/=2,t=e[f].buf.slice(0,n),r=Buffer.byteLength(t);e[f].buf=e[f].buf.slice(n),D(e,t,x.bind(null,e))}})}else if(n===0){if(t===0&&e[f].buf.length===0)return;e.flush(()=>{Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l),x(e)})}else E(e,Error(`overwritten`))}function S(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new _(t),t.flush(()=>{t[f].ready=!0,t.emit(`ready`)});break;case`ERROR`:E(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:E(t,Error(`this should not happen: `+e.code))}}function C(e){let t=this.stream.deref();t!==void 0&&(v.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,C),E(t,e===0?null:Error(`the worker thread exited`)))}var w=class extends r{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[f]={},this[f].stateBuf=new SharedArrayBuffer(128),this[f].state=new Int32Array(this[f].stateBuf),this[f].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[f].data=Buffer.from(this[f].dataBuf),this[f].sync=e.sync||!1,this[f].ending=!1,this[f].ended=!1,this[f].needDrain=!1,this[f].destroyed=!1,this[f].flushing=!1,this[f].ready=!1,this[f].finished=!1,this[f].errored=null,this[f].closed=!1,this[f].buf=``,this.worker=y(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[f].destroyed)return T(this,Error(`the worker has exited`)),!1;if(this[f].ending)return T(this,Error(`the worker is ending`)),!1;if(this[f].flushing&&this[f].buf.length+e.length>=p)try{k(this),this[f].flushing=!0}catch(e){return E(this,e),!1}if(this[f].buf+=e,this[f].sync)try{return k(this),!0}catch(e){return E(this,e),!1}return this[f].flushing||(this[f].flushing=!0,setImmediate(x,this)),this[f].needDrain=this[f].data.length-this[f].buf.length-Atomics.load(this[f].state,c)<=0,!this[f].needDrain}end(){this[f].destroyed||(this[f].ending=!0,O(this))}flush(e){if(this[f].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[f].state,c);s(this[f].state,l,t,1/0,(t,n)=>{if(t){E(this,t),process.nextTick(e,t);return}if(n===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[f].destroyed||(k(this),A(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[f].ready}get destroyed(){return this[f].destroyed}get closed(){return this[f].closed}get writable(){return!this[f].destroyed&&!this[f].ending}get writableEnded(){return this[f].ending}get writableFinished(){return this[f].finished}get writableNeedDrain(){return this[f].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[f].errored}};function T(e,t){setImmediate(()=>{e.emit(`error`,t)})}function E(e,t){e[f].destroyed||(e[f].destroyed=!0,t&&(e[f].errored=t,T(e,t)),e.worker.exited?setImmediate(()=>{e[f].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[f].closed=!0,e.emit(`close`)}))}function D(e,t,n){let r=Atomics.load(e[f].state,c),i=Buffer.byteLength(t);return e[f].data.write(t,r),Atomics.store(e[f].state,c,r+i),Atomics.notify(e[f].state,c),n(),!0}function O(e){if(!(e[f].ended||!e[f].ending||e[f].flushing)){e[f].ended=!0;try{e.flushSync();let t=Atomics.load(e[f].state,l);Atomics.store(e[f].state,c,-1),Atomics.notify(e[f].state,c);let n=0;for(;t!==-1;){if(Atomics.wait(e[f].state,l,t,1e3),t=Atomics.load(e[f].state,l),t===-2){E(e,Error(`end() failed`));return}if(++n===10){E(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[f].finished=!0,e.emit(`finish`)})}catch(t){E(e,t)}}}function k(e){let t=()=>{e[f].ending?O(e):e[f].needDrain&&process.nextTick(b,e)};for(e[f].flushing=!1;e[f].buf.length!==0;){let n=Atomics.load(e[f].state,c),r=e[f].data.length-n;if(r===0){A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);continue}else if(r<0)throw Error(`overwritten`);let i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);if(a<=r)e[f].buf=e[f].buf.slice(r),D(e,i,t);else{for(A(e),Atomics.store(e[f].state,l,0),Atomics.store(e[f].state,c,0),Atomics.notify(e[f].state,l);a>e[f].buf.length;)r/=2,i=e[f].buf.slice(0,r),a=Buffer.byteLength(i);e[f].buf=e[f].buf.slice(r),D(e,i,t)}}}function A(e){if(e[f].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[f].state,c),n=0;for(;;){let r=Atomics.load(e[f].state,l);if(r===-2)throw Error(`_flushSync failed`);if(r!==t)Atomics.wait(e[f].state,l,r,1e3);else break;if(++n===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=w})),require_transport=__commonJSMin$1(((e,t)=>{let{createRequire:n}=__require$1(`module`),{existsSync:r}=__require$1(`node:fs`),i=require_caller(),{join:a,isAbsolute:o,sep:s}=__require$1(`node:path`),{fileURLToPath:c}=__require$1(`node:url`),l=require_atomic_sleep(),u=require_on_exit_leak_free(),d=require_thread_stream();function f(e){u.register(e,v),u.registerBeforeExit(e,y),e.on(`close`,function(){u.unregister(e)})}function p(){let e=process.execArgv;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--import`||n===`--require`||n===`-r`||n.startsWith(`--import=`)||n.startsWith(`--require=`)||n.startsWith(`-r=`))return!0}return!1}function m(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let n=[],r=!1;for(let e=0;e<t.length;e++){let i=t[e];if(i===`--require`||i===`-r`||i===`--import`){let a=t[e+1];if(a&&h(a)){r=!0,e++;continue}n.push(i),a&&(n.push(a),e++);continue}if((i.startsWith(`--require=`)||i.startsWith(`-r=`)||i.startsWith(`--import=`))&&h(i.slice(i.indexOf(`=`)+1))){r=!0;continue}n.push(i)}return r?n.join(` `):e}function h(e){let t=g(e);if(!t)return!1;let n=t;if(n.startsWith(`file://`))try{n=c(n)}catch{return!1}return o(n)&&!r(n)}function g(e){let t=e[0],n=e[e.length-1];return t===`"`&&n===`"`||t===`'`&&n===`'`?e.slice(1,-1):e}function _(e,t,n,r,i){if(!n.execArgv&&p()&&__require$1.main===void 0&&(n={...n,execArgv:[]}),!n.env&&process.env.NODE_OPTIONS){let e=m(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(n={...n,env:{...process.env,NODE_OPTIONS:e}})}n={...n,name:i};let a=new d({filename:e,workerData:t,workerOpts:n,sync:r});a.on(`ready`,o),a.on(`close`,function(){process.removeListener(`exit`,s)}),process.on(`exit`,s);function o(){process.removeListener(`exit`,s),a.unref(),n.autoEnd!==!1&&f(a)}function s(){a.closed||(a.flushSync(),l(100),a.end())}return a}function v(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function y(e){e.flushSync()}function b(e){let{pipeline:t,targets:r,levels:c,dedupe:l,worker:u={},caller:d=i(),sync:f=!1}=e,p={...e.options},m=typeof d==`string`?[d]:d,h=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),g=e.target;if(g&&r)throw Error(`only one of target or targets can be specified`);r?(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.targets=r.filter(e=>e.target).map(e=>({...e,target:y(e.target)})),p.pipelines=r.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:y(t.target)})))):t&&(g=h[`pino-worker`]||a(__dirname,`worker.js`),p.pipelines=[t.map(e=>({...e,target:y(e.target)}))]),c&&(p.levels=c),l&&(p.dedupe=l),p.pinoWillSendConfig=!0;let v=r||t?`pino.transport`:g;return _(y(g),p,u,f,v);function y(e){if(e=h[e]||e,o(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return a(__dirname,`..`,`file.js`);let t;for(let r of m)try{t=n(r===`node:repl`?process.cwd()+s:r).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=b})),require_tools=__commonJSMin$1(((e,t)=>{let n=__require$1(`node:diagnostics_channel`),r=require_quick_format_unescaped(),{mapHttpRequest:i,mapHttpResponse:a}=require_pino_std_serializers(),o=require_sonic_boom(),s=require_on_exit_leak_free(),{lsCacheSym:c,chindingsSym:l,writeSym:u,serializersSym:d,formatOptsSym:f,endSym:p,stringifiersSym:m,stringifySym:h,stringifySafeSym:g,wildcardFirstSym:_,nestedKeySym:v,formattersSym:y,messageKeySym:b,errorKeySym:x,nestedKeyStrSym:S,msgPrefixSym:C}=require_symbols(),{isMainThread:w}=__require$1(`worker_threads`),T=require_transport(),[E]=process.versions.node.split(`.`).map(e=>Number(e)),D=n.tracingChannel(`pino_asJson`),O=E>=25?e=>JSON.stringify(e):j;function k(){}function A(e,t){if(!t)return n;return function(...r){t.call(this,r,n,e)};function n(t,...n){if(typeof t==`object`){let o=t;t!==null&&(t.method&&t.headers&&t.socket?t=i(t):typeof t.setHeader==`function`&&(t=a(t)));let s;o===null&&n.length===0?s=[null]:(o=n.shift(),s=n),typeof this[C]==`string`&&o!=null&&(o=this[C]+o),this[u](t,r(o,s,this[f]),e)}else{let i=t===void 0?n.shift():t;typeof this[C]==`string`&&i!=null&&(i=this[C]+i),this[u](null,r(i,n,this[f]),e)}}}function j(e){let t=``,n=0,r=!1,i=255,a=e.length;if(a>100)return JSON.stringify(e);for(var o=0;o<a&&i>=32;o++)i=e.charCodeAt(o),(i===34||i===92)&&(t+=e.slice(n,o)+`\\`,n=o,r=!0);return r?t+=e.slice(n):t=e,i<32?JSON.stringify(e):`"`+t+`"`}function M(e,t,n,r){if(D.hasSubscribers===!1)return N.call(this,e,t,n,r);let i={instance:this,arguments};return D.traceSync(N,i,this,e,t,n,r)}function N(e,t,n,r){let i=this[h],a=this[g],o=this[m],s=this[p],u=this[l],f=this[d],C=this[y],w=this[b],T=this[x],E=this[c][n]+r;E+=u;let D;C.log&&(e=C.log(e));let k=o[_],A=``;for(let t in e)if(D=e[t],Object.prototype.hasOwnProperty.call(e,t)&&D!==void 0){f[t]?D=f[t](D):t===T&&f.err&&(D=f.err(D));let e=o[t]||k;switch(typeof D){case`undefined`:case`function`:continue;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D));break;case`string`:D=(e||O)(D);break;default:D=(e||i)(D,a)}if(D===void 0)continue;let n=O(t);A+=`,`+n+`:`+D}let j=``;if(t!==void 0){D=f[w]?f[w](t):t;let e=o[w]||k;switch(typeof D){case`function`:break;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D)),j=`,"`+w+`":`+D;break;case`string`:D=(e||O)(D),j=`,"`+w+`":`+D;break;default:D=(e||i)(D,a),j=`,"`+w+`":`+D}}return this[v]&&A?E+this[S]+A.slice(1)+`}`+j+s:E+A+j+s}function P(e,t){let n,r=e[l],i=e[h],a=e[g],o=e[m],s=o[_],c=e[d],u=e[y].bindings;t=u(t);for(let e in t)if(n=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&n!==void 0)===!0){if(n=c[e]?c[e](n):n,n=(o[e]||s||i)(n,a),n===void 0)continue;r+=`,"`+e+`":`+n}return r}function F(e){return e.write!==e.constructor.prototype.write}function I(e){let t=new o(e);return t.on(`error`,n),!e.sync&&w&&(s.register(t,L),t.on(`close`,function(){s.unregister(t)})),t;function n(e){if(e.code===`EPIPE`){t.write=k,t.end=k,t.flushSync=k,t.destroy=k;return}t.removeListener(`error`,n),t.emit(`error`,e)}}function L(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function R(e){return function(t,n,r={},i){if(typeof r==`string`)i=I({dest:r}),r={};else if(typeof i==`string`){if(r&&r.transport)throw Error(`only one of option.transport or stream can be specified`);i=I({dest:i})}else if(r instanceof o||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof o||r.transport.writable||r.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;r.customLevels&&(e=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=T({caller:n,...r.transport,levels:e})}if(r=Object.assign({},e,r),r.serializers=Object.assign({},e.serializers,r.serializers),r.formatters=Object.assign({},e.formatters,r.formatters),r.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:a,onChild:s}=r;return a===!1&&(r.level=`silent`),s||(r.onChild=k),i||=F(process.stdout)?process.stdout:I({fd:process.stdout.fd||1}),{opts:r,stream:i}}}function z(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[g])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function B(e,t,n){return{level:e,bindings:t,log:n}}function V(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:k,buildSafeSonicBoom:I,asChindings:P,asJson:M,genLog:A,createArgsNormalizer:R,stringify:z,buildFormatters:B,normalizeDestFileDescriptor:V}})),require_constants$6=__commonJSMin$1(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),require_levels=__commonJSMin$1(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=require_symbols(),{noop:l,genLog:u}=require_tools(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=require_constants$6(),p={fatal:e=>{let t=u(d.fatal,e);return function(...e){let n=this[a];if(t.call(this,...e),typeof n.flushSync==`function`)try{n.flushSync()}catch{}}},error:e=>u(d.error,e),warn:e=>u(d.warn,e),info:e=>u(d.info,e),debug:e=>u(d.debug,e),trace:e=>u(d.trace,e)},m=Object.keys(d).reduce((e,t)=>(e[d[t]]=t,e),{}),h=Object.keys(m).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function g(e){let t=e[o].level,{labels:r}=e.levels,i={};for(let e in r){let n=t(r[e],Number(e));i[e]=JSON.stringify(n).slice(0,-1)}return e[n]=i,e}function _(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function v(e){let{labels:t,values:n}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(n[e]===void 0)throw Error(`unknown level `+e);let a=this[r],o=this[r]=n[e],d=this[i],f=this[c],m=this[s].logMethod;for(let e in n){if(f(n[e],o)===!1){this[e]=l;continue}this[e]=_(e,d)?p[e](m):u(n[e],m)}this.emit(`level-change`,e,o,t[a],a,this)}function y(e){let{levels:t,levelVal:n}=this;return t&&t.labels?t.labels[n]:``}function b(e){let{values:t}=this.levels,n=t[e];return n!==void 0&&this[c](n,this[r])}function x(e,t,n){return e===f.DESC?t<=n:t>=n}function S(e){return typeof e==`string`?x.bind(null,e):e}function C(e=null,t=!1){let n=e?Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:m,n),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:d,e)}}function w(e,t,n){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),n?[]:Object.keys(m).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:d,t)))throw Error(`default level:${e} must be included in custom levels`)}function T(e,t){let{labels:n,values:r}=e;for(let e in t){if(e in r)throw Error(`levels cannot be overridden`);if(t[e]in n)throw Error(`pre-existing level values cannot be used for new levels`)}}function E(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(f).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:h,genLsCache:g,levelMethods:p,getLevel:y,setLevel:v,isLevelEnabled:b,mappings:C,assertNoLevelCollisions:T,assertDefaultLevelFound:w,genLevelComparison:S,assertLevelComparison:E}})),require_meta=__commonJSMin$1(((e,t)=>{t.exports={version:`10.3.1`}})),require_proto=__commonJSMin$1(((e,t)=>{let{EventEmitter:n}=__require$1(`node:events`),{lsCacheSym:r,levelValSym:i,setLevelSym:a,getLevelSym:o,chindingsSym:s,mixinSym:c,asJsonSym:l,writeSym:u,mixinMergeStrategySym:d,timeSym:f,timeSliceIndexSym:p,streamSym:m,serializersSym:h,formattersSym:g,errorKeySym:_,messageKeySym:v,useOnlyCustomLevelsSym:y,needsMetadataGsym:b,redactFmtSym:x,stringifySym:S,formatOptsSym:C,stringifiersSym:w,msgPrefixSym:T,hooksSym:E}=require_symbols(),{getLevel:D,setLevel:O,isLevelEnabled:k,mappings:A,initialLsCache:j,genLsCache:M,assertNoLevelCollisions:N}=require_levels(),{asChindings:P,asJson:F,buildFormatters:I,stringify:L,noop:R}=require_tools(),{version:z}=require_meta(),B=require_redaction(),V={constructor:class{},child:U,bindings:W,setBindings:G,flush:ee,isLevelEnabled:k,version:z,get level(){return this[o]()},set level(e){this[a](e)},get levelVal(){return this[i]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[T]},get[Symbol.toStringTag](){return`Pino`},[r]:j,[u]:q,[l]:F,[o]:D,[a]:O};Object.setPrototypeOf(V,n.prototype),t.exports=function(){return Object.create(V)};let H=e=>e;function U(e,t){if(!e)throw Error(`missing bindings for child Pino`);let n=this[h],r=this[g],i=Object.create(this);if(t==null)return i[g].bindings!==H&&(i[g]=I(r.level,H,r.log)),i[s]=P(i,e),this.onChild!==R&&this.onChild(i),i;if(t.hasOwnProperty(`serializers`)===!0){i[h]=Object.create(null);for(let e in n)i[h][e]=n[e];let e=Object.getOwnPropertySymbols(n);for(var o=0;o<e.length;o++){let t=e[o];i[h][t]=n[t]}for(let e in t.serializers)i[h][e]=t.serializers[e];let r=Object.getOwnPropertySymbols(t.serializers);for(var c=0;c<r.length;c++){let e=r[c];i[h][e]=t.serializers[e]}}else i[h]=n;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:n,log:a}=t.formatters;i[g]=I(e||r.level,n||H,a||r.log)}else i[g]=I(r.level,H,r.log);if(t.hasOwnProperty(`customLevels`)===!0&&(N(this.levels,t.customLevels),i.levels=A(t.customLevels,i[y]),M(i)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){i.redact=t.redact;let e=B(i.redact,L),n={stringify:e[x]};i[S]=L,i[w]=e,i[C]=n}if(typeof t.msgPrefix==`string`&&(i[T]=(this[T]||``)+t.msgPrefix),i[s]=P(i,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;i[a](e)}return this.onChild(i),i}function W(){let e=`{${this[s].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function G(e){this[s]=P(this,e)}function K(e,t){return Object.assign(t,e)}function q(e,t,n){let r=this[f](),i=this[c],a=this[_],o=this[v],s=this[d]||K,u,h=this[E].streamWrite;e==null?u={}:e instanceof Error?(u={[a]:e},t===void 0&&(t=e.message)):(u=e,t===void 0&&e[o]===void 0&&e[a]&&(t=e[a].message)),i&&(u=s(u,i(u,n,this)));let g=this[l](u,t,n,r),y=this[m];y[b]===!0&&(y.lastLevel=n,y.lastObj=u,y.lastMsg=t,y.lastTime=r.slice(this[p]),y.lastLogger=this),y.write(h?h(g):g)}function ee(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[m];typeof t.flush==`function`?t.flush(e||R):e&&e()}})),require_safe_stable_stringify=__commonJSMin$1(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=_();r.configure=_,r.stringify=r,r.default=r,e.stringify=r,e.configure=_,t.exports=r;let i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function a(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let n=e[t],r=t;for(;r!==0&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}let s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return s.call(e)!==void 0&&e.length!==0}function l(e,t,n){e.length<n&&(n=e.length);let r=t===`,`?``:` `,i=`"0":${r}${e[0]}`;for(let a=1;a<n;a++)i+=`${t}"${a}":${r}${e[a]}`;return i}function u(e){if(n.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function d(e){let t;if(n.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function f(e,t){let r;if(n.call(e,t)&&(r=e[t],typeof r!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return r===void 0?!0:r}function p(e,t){let r;if(n.call(e,t)){if(r=e[t],typeof r!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw TypeError(`The "${t}" argument must be an integer`);if(r<1)throw RangeError(`The "${t}" argument must be >= 1`)}return r===void 0?1/0:r}function m(e){return e===1?`1 item`:`${e} items`}function h(e){let t=new Set;for(let n of e)(typeof n==`string`||typeof n==`number`)&&t.add(String(n));return t}function g(e){if(n.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function _(e){e={...e};let t=g(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let n=u(e),r=f(e,`bigint`),i=d(e),s=typeof i==`function`?i:void 0,_=p(e,`maximumDepth`),v=p(e,`maximumBreadth`);function y(e,l,u,d,f,p){let h=l[e];switch(typeof h==`object`&&h&&typeof h.toJSON==`function`&&(h=h.toJSON(e)),h=d.call(l,e,h),typeof h){case`string`:return a(h);case`object`:{if(h===null)return`null`;if(u.indexOf(h)!==-1)return n;let e=``,t=`,`,r=p;if(Array.isArray(h)){if(h.length===0)return`[]`;if(_<u.length+1)return`"[Array]"`;u.push(h),f!==``&&(p+=f,e+=`\n${p}`,t=`,\n${p}`);let n=Math.min(h.length,v),i=0;for(;i<n-1;i++){let n=y(String(i),h,u,d,f,p);e+=n===void 0?`null`:n,e+=t}let a=y(String(i),h,u,d,f,p);if(e+=a===void 0?`null`:a,h.length-1>v){let n=h.length-v-1;e+=`${t}"... ${m(n)} not stringified"`}return f!==``&&(e+=`\n${r}`),u.pop(),`[${e}]`}let l=Object.keys(h),g=l.length;if(g===0)return`{}`;if(_<u.length+1)return`"[Object]"`;let b=``,x=``;f!==``&&(p+=f,t=`,\n${p}`,b=` `);let S=Math.min(g,v);i&&!c(h)&&(l=o(l,s)),u.push(h);for(let n=0;n<S;n++){let r=l[n],i=y(r,h,u,d,f,p);i!==void 0&&(e+=`${x}${a(r)}:${b}${i}`,x=t)}if(g>v){let n=g-v;e+=`${x}"...":${b}"${m(n)} not stringified"`,x=t}return f!==``&&x.length>1&&(e=`\n${p}${e}\n${r}`),u.pop(),`{${e}}`}case`number`:return isFinite(h)?String(h):t?t(h):`null`;case`boolean`:return h===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(h);default:return t?t(h):void 0}}function b(e,i,o,s,c,l){switch(typeof i==`object`&&i&&typeof i.toJSON==`function`&&(i=i.toJSON(e)),typeof i){case`string`:return a(i);case`object`:{if(i===null)return`null`;if(o.indexOf(i)!==-1)return n;let e=l,t=``,r=`,`;if(Array.isArray(i)){if(i.length===0)return`[]`;if(_<o.length+1)return`"[Array]"`;o.push(i),c!==``&&(l+=c,t+=`\n${l}`,r=`,\n${l}`);let n=Math.min(i.length,v),a=0;for(;a<n-1;a++){let e=b(String(a),i[a],o,s,c,l);t+=e===void 0?`null`:e,t+=r}let u=b(String(a),i[a],o,s,c,l);if(t+=u===void 0?`null`:u,i.length-1>v){let e=i.length-v-1;t+=`${r}"... ${m(e)} not stringified"`}return c!==``&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(i);let u=``;c!==``&&(l+=c,r=`,\n${l}`,u=` `);let d=``;for(let e of s){let n=b(e,i[e],o,s,c,l);n!==void 0&&(t+=`${d}${a(e)}:${u}${n}`,d=r)}return c!==``&&d.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case`number`:return isFinite(i)?String(i):t?t(i):`null`;case`boolean`:return i===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(i);default:return t?t(i):void 0}}function x(e,u,d,f,p){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return x(e,u,d,f,p);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=p;if(Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u),p+=f;let e=`\n${p}`,n=`,\n${p}`,r=Math.min(u.length,v),i=0;for(;i<r-1;i++){let t=x(String(i),u[i],d,f,p);e+=t===void 0?`null`:t,e+=n}let a=x(String(i),u[i],d,f,p);if(e+=a===void 0?`null`:a,u.length-1>v){let t=u.length-v-1;e+=`${n}"... ${m(t)} not stringified"`}return e+=`\n${t}`,d.pop(),`[${e}]`}let r=Object.keys(u),h=r.length;if(h===0)return`{}`;if(_<d.length+1)return`"[Object]"`;p+=f;let g=`,\n${p}`,y=``,b=``,S=Math.min(h,v);c(u)&&(y+=l(u,g,v),r=r.slice(u.length),S-=u.length,b=g),i&&(r=o(r,s)),d.push(u);for(let e=0;e<S;e++){let t=r[e],n=x(t,u[t],d,f,p);n!==void 0&&(y+=`${b}${a(t)}: ${n}`,b=g)}if(h>v){let e=h-v;y+=`${b}"...": "${m(e)} not stringified"`,b=g}return b!==``&&(y=`\n${p}${y}\n${t}`),d.pop(),`{${y}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function S(e,u,d){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return S(e,u,d);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=``,r=u.length!==void 0;if(r&&Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u);let e=Math.min(u.length,v),n=0;for(;n<e-1;n++){let e=S(String(n),u[n],d);t+=e===void 0?`null`:e,t+=`,`}let r=S(String(n),u[n],d);if(t+=r===void 0?`null`:r,u.length-1>v){let e=u.length-v-1;t+=`,"... ${m(e)} not stringified"`}return d.pop(),`[${t}]`}let f=Object.keys(u),p=f.length;if(p===0)return`{}`;if(_<d.length+1)return`"[Object]"`;let h=``,g=Math.min(p,v);r&&c(u)&&(t+=l(u,`,`,v),f=f.slice(u.length),g-=u.length,h=`,`),i&&(f=o(f,s)),d.push(u);for(let e=0;e<g;e++){let n=f[e],r=S(n,u[n],d);r!==void 0&&(t+=`${h}${a(n)}:${r}`,h=`,`)}if(p>v){let e=p-v;t+=`${h}"...":"${m(e)} not stringified"`}return d.pop(),`{${t}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function C(e,t,n){if(arguments.length>1){let r=``;if(typeof n==`number`?r=` `.repeat(Math.min(n,10)):typeof n==`string`&&(r=n.slice(0,10)),t!=null){if(typeof t==`function`)return y(``,{"":e},[],t,r,``);if(Array.isArray(t))return b(``,e,[],h(t),r,``)}if(r.length!==0)return x(``,e,[],r,``)}return S(``,e,[])}return C}})),require_multistream=__commonJSMin$1(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=require_constants$6(),i=r.info;function a(e,t){e||=[],t||={dedupe:!1};let a=Object.create(r);a.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{a[e]=t.levels[e]});let u={write:d,add:m,remove:h,emit:f,flushSync:p,end:g,minLevel:0,lastId:0,streams:[],clone:_,[n]:!0,streamLevels:a};return Array.isArray(e)?e.forEach(m,u):m.call(u,e),e=null,u;function d(e){let r,i=this.lastLevel,{streams:a}=this,o=0,u;for(let d=s(a.length,t.dedupe);l(d,a.length,t.dedupe);d=c(d,t.dedupe))if(r=a[d],r.level<=i){if(o!==0&&o!==r.level)break;if(u=r.stream,u[n]){let{lastTime:e,lastMsg:t,lastObj:n,lastLogger:r}=this;u.lastLevel=i,u.lastTime=e,u.lastMsg=t,u.lastObj=n,u.lastLogger=r}u.write(e),t.dedupe&&(o=r.level)}else if(!t.dedupe)break}function f(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function p(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function m(e){if(!e)return u;let t=typeof e.write==`function`||e.stream,n=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:r,streamLevels:a}=this,s;s=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?a[e.level]:typeof e.level==`number`?e.level:i;let c={stream:n,level:s,levelVal:void 0,id:++u.lastId};return r.unshift(c),r.sort(o),this.minLevel=r[0].level,u}function h(e){let{streams:t}=this,n=t.findIndex(t=>t.id===e);return n>=0&&(t.splice(n,1),t.sort(o),this.minLevel=t.length>0?t[0].level:-1),u}function g(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function _(e){let t=Array(this.streams.length);for(let n=0;n<t.length;n++)t[n]={level:e,stream:this.streams[n].stream};return{write:d,add:m,remove:h,minLevel:e,streams:t,clone:_,emit:f,flushSync:p,[n]:!0}}}function o(e,t){return e.level-t.level}function s(e,t){return t?e-1:0}function c(e,t){return t?e-1:e+1}function l(e,t,n){return n?e>=0:e<t}t.exports=a})),require_pino=__commonJSMin$1(((e,t)=>{let n=__require$1(`node:os`),r=require_pino_std_serializers(),i=require_caller(),a=require_redaction(),o=require_time$4(),s=require_proto(),c=require_symbols(),{configure:l}=require_safe_stable_stringify(),{assertDefaultLevelFound:u,mappings:d,genLsCache:f,genLevelComparison:p,assertLevelComparison:m}=require_levels(),{DEFAULT_LEVELS:h,SORTING_ORDER:g}=require_constants$6(),{createArgsNormalizer:_,asChindings:v,buildSafeSonicBoom:y,buildFormatters:b,stringify:x,normalizeDestFileDescriptor:S,noop:C}=require_tools(),{version:w}=require_meta(),{chindingsSym:T,redactFmtSym:E,serializersSym:D,timeSym:O,timeSliceIndexSym:k,streamSym:A,stringifySym:j,stringifySafeSym:M,stringifiersSym:N,setLevelSym:P,endSym:F,formatOptsSym:I,messageKeySym:L,errorKeySym:R,nestedKeySym:z,mixinSym:B,levelCompSym:V,useOnlyCustomLevelsSym:H,formattersSym:U,hooksSym:W,nestedKeyStrSym:G,mixinMergeStrategySym:K,msgPrefixSym:q}=c,{epochTime:ee,nullTime:J}=o,{pid:Y}=process,X=n.hostname(),Z=r.err,te=_({level:`info`,levelComparison:g.ASC,levels:h,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:Y,hostname:X},serializers:Object.assign(Object.create(null),{err:Z}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ee,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),ne=Object.assign(Object.create(null),r);function Q(...e){let t={},{opts:n,stream:r}=te(t,i(),...e);n.level&&typeof n.level==`string`&&h[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:o,crlf:c,serializers:g,timestamp:_,messageKey:y,errorKey:S,nestedKey:w,base:Y,name:X,level:Z,customLevels:ne,levelComparison:Q,mixin:re,mixinMergeStrategy:ie,useOnlyCustomLevels:ae,formatters:oe,hooks:se,depthLimit:ce,edgeLimit:le,onChild:ue,msgPrefix:de}=n,fe=l({maximumDepth:ce,maximumBreadth:le}),pe=b(oe.level,oe.bindings,oe.log),me=x.bind({[M]:fe}),he=o?a(o,me):{},ge=o?{stringify:he[E]}:{stringify:me},_e=`}`+(c?`\r
|
|
4
4
|
`:`
|
|
@@ -50,7 +50,7 @@ To resolve the conflict:`,(0,r.getConflictResolutionRecipe)(i,e))),a=o):n.diag.w
|
|
|
50
50
|
`+n)}function x(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,x),e.emit(`wsClientError`,r,n,t)}else b(n,r,i,a)}}));require_stream(),require_receiver(),require_sender(),require_websocket();var import_websocket_server=__toESM(require_websocket_server(),1),require_ignore=__commonJSMin$1(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}let r=``,i=` `,a=`\\`,o=/^\s+$/,s=/(?:[^\\]|^)\\$/,c=/^\\!/,l=/^\\#/,u=/\r?\n/g,d=/^\.*\/|^\.+$/,f=`/`,p=`node-ignore`;typeof Symbol<`u`&&(p=Symbol.for(`node-ignore`));let m=p,h=(e,t,n)=>Object.defineProperty(e,t,{value:n}),g=/([0-z])-([0-z])/g,_=()=>!1,v=e=>e.replace(g,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:``),y=e=>{let{length:t}=e;return e.slice(0,t-t%2)},b=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===`\\`?`\\[${n}${y(r)}${i}`:i===`]`&&r.length%2==0?`[${v(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],x=Object.create(null),S=(e,t)=>{let n=x[e];return n||(n=b.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),x[e]=n),t?new RegExp(n,`i`):new RegExp(n)},C=e=>typeof e==`string`,w=e=>e&&C(e)&&!o.test(e)&&!s.test(e)&&e.indexOf(`#`)!==0,T=e=>e.split(u);var E=class{constructor(e,t,n,r){this.origin=e,this.pattern=t,this.negative=n,this.regex=r}};let D=(e,t)=>{let n=e,r=!1;e.indexOf(`!`)===0&&(r=!0,e=e.substr(1)),e=e.replace(c,`!`).replace(l,`#`);let i=S(e,t);return new E(n,e,r,i)},O=(e,t)=>{throw new t(e)},k=(e,t,n)=>C(e)?e?k.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),A=e=>d.test(e);k.isNotRelative=A,k.convert=e=>e;var j=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){h(this,m,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[m]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(w(e)){let t=D(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(C(e)?T(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,r=!1;return this._rules.forEach(i=>{let{negative:a}=i;r===a&&n!==r||a&&!n&&!r&&!t||i.regex.test(e)&&(n=!a,r=a)}),{ignored:n,unignored:r}}_test(e,t,n,r){let i=e&&k.convert(e);return k(i,e,this._allowRelativePaths?_:O),this._t(i,t,n,r)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(`/`),r.pop(),!r.length)return t[e]=this._testOne(e,n);let i=this._t(r.join(`/`)+`/`,t,n,r);return t[e]=i.ignored?i:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let M=e=>new j(e);if(M.isPathValid=e=>k(e&&k.convert(e),e,_),M.default=M,t.exports=M,typeof process<`u`&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform===`win32`)){k.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;k.isNotRelative=t=>e.test(t)||A(t)}}));init_esm$2();var import_pino=__toESM$1(require_pino(),1),import_pino_pretty=__toESM$1(require_pino_pretty(),1),import_src=require_src$14(),import_src$1=require_src$13(),import_src$2=require_src$4(),import_src$3=require_src$3(),import_src$4=require_src$2(),import_src$5=require_src$1(),import_src$6=require_src();init_esm$1();var import_lib=__toESM$1(require_lib(),1),import_yazl=__toESM$1(require_yazl(),1),import_dist=require_dist$1(),import_ignore=__toESM$1(require_ignore(),1);const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const AGENT_ID_RE=/^[a-zA-Z0-9_-]+$/;function validateAgentId(e){return typeof e!=`string`||e.length===0||!AGENT_ID_RE.test(e)?null:e}function toBroadcasterKey(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function isPresenceEligibleAgentId(e){return!e.startsWith(`principal-`)}function resolveAgentType(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function parseAgentBodyFields(e){let t=typeof e.agentId==`string`&&e.agentId.length>0&&AGENT_ID_RE.test(e.agentId)?e.agentId:void 0;return{rawAgentId:t,writerId:t===void 0?void 0:toBroadcasterKey(t),displayName:typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?sanitizeGitIdentity(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?sanitizeGitIdentity(e.clientVersion):void 0,label:typeof e.label==`string`?sanitizeGitIdentity(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}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=[];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),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return(0,import_pino.default)(this.options,import_pino.default.transport({targets:this.transportConfigs}));try{let e=(0,import_pino_pretty.default)({colorize:shouldColorize(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return(0,import_pino.default)(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),(0,import_pino.default)(this.options)}}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}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 n;return n=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new PinoLogger(e,this.config.pinoConfig),this.loggers.set(e,n),n}reset(){this.config={},this.loggers.clear()}};const loggerFactory=new LoggerFactory;function getLogger(e){return loggerFactory.getLogger(e)}var AgentFocusBroadcaster=class{hocuspocus;log=getLogger(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){isPresenceEligibleAgentId(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}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={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,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0};function incrementReconcile(){counters.reconcileCount++}function incrementConflict(){counters.conflictCount++}function incrementBatch(){counters.batchCount++}function incrementUpstreamImport(){counters.upstreamImportCount++}function incrementRescueBuffer(){counters.rescueBufferCount++}function incrementBranchSwitch(){counters.branchSwitchCount++}function incrementPark(){counters.parkCount++}function incrementGitAutoSaveFailure(){counters.gitAutoSaveFailureCount++}function incrementGitWriterCommitFailure(){counters.gitWriterCommitFailureCount++}function incrementCC1Broadcast(){counters.cc1BroadcastCount++}function incrementCC1BroadcastDrop(){counters.cc1BroadcastDropCount++}function setCC1SubscriberCount(e){counters.cc1SubscriberCount=e}function incrementServerObserverFire(e){e===`a`?counters.serverObserverFiresA++:counters.serverObserverFiresB++}function incrementPersistenceDiskWrite(){counters.persistenceDiskWrites++}function incrementServerObserverError(e){e===`a`?counters.serverObserverErrorsA++:counters.serverObserverErrorsB++}function incrementBridgeMergeContentLoss(){counters.bridgeMergeContentLoss++}function incrementAgentWriteCalls(){counters.agentWriteCalls++}function incrementSummariesProvided(){counters.summariesProvided++}function incrementSummariesTruncated(){counters.summariesTruncated++}function incrementBridgeMergeCheckpointCreated(){counters.bridgeMergeCheckpointCreated++}function incrementCollabSocketFilteredError(e){e===`EPIPE`?counters.collabSocketEpipeCount++:counters.collabSocketEconnresetCount++}function incrementShadowMigrationLegacyRefsDeleted(e){counters.shadowMigrationLegacyRefsDeleted+=e}function incrementEffectDiffCaptureFailures(){counters.effectDiffCaptureFailures++}function incrementAgentPresenceMutationError(){counters.agentPresenceMutationErrors++}function handleCollabSocketError(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(incrementCollabSocketFilteredError(e.code),!0):!1}function setCC1LastSeq(e,t){counters.cc1LastSeq[e]=t}function getMetrics(){return{...counters,cc1LastSeq:{...counters.cc1LastSeq}}}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 n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:BROADCASTER_EVICTION_MS},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!isPresenceEligibleAgentId(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!isPresenceEligibleAgentId(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||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(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),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 n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!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 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 n=(this.seqs.get(e)??0)+1;this.seqs.set(e,n);let r=CC1DerivedViewPayloadSchema.parse({v:1,ch:e,seq:n});t.broadcastStateless(JSON.stringify(r)),incrementCC1Broadcast(),setCC1LastSeq(e,n),setCC1SubscriberCount(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}emitServerInfo(e,t){try{let n=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!n){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitServerInfo — dropped`),!0),incrementCC1BroadcastDrop();return}let r=CC1ServerInfoPayloadSchema.parse({v:1,ch:CC1_CHANNEL_SERVER_INFO,seq:0,serverInstanceId:e,...t===void 0?{}:{currentBranch:t}});n.broadcastStateless(JSON.stringify(r)),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 n=(this.seqs.get(`branch-switched`)??0)+1;this.seqs.set(CC1_CHANNEL_BRANCH_SWITCHED,n);let r=CC1BranchSwitchedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_BRANCH_SWITCHED,seq:n,branch:e});t.broadcastStateless(JSON.stringify(r)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_BRANCH_SWITCHED,n)}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 n=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!n){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitDiskAck — dropped`),!0),incrementCC1BroadcastDrop();return}let r=(this.seqs.get(`disk-ack`)??0)+1;this.seqs.set(CC1_CHANNEL_DISK_ACK,r);let i=CC1DiskAckPayloadSchema.parse({v:1,ch:CC1_CHANNEL_DISK_ACK,seq:r,docName:e,sv:Buffer.from(t).toString(`base64`)});n.broadcastStateless(JSON.stringify(i)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_DISK_ACK,r)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitDiskAck failed`)}}getLatestDiskAckSVsAsBase64(){let e={};for(let[t,n]of this.latestDiskAckSVs)e[t]=Buffer.from(n).toString(`base64`);return e}emitConfigValidationRejected(e,t){try{let n=this.hocuspocus.documents.get(SYSTEM_DOC_NAME);if(!n){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found at emitConfigValidationRejected — dropped`),!0),incrementCC1BroadcastDrop();return}let r=(this.seqs.get(`config-validation-rejected`)??0)+1;this.seqs.set(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,r);let i=CC1ConfigValidationRejectedPayloadSchema.parse({v:1,ch:CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,seq:r,docName:e,error:t});n.broadcastStateless(JSON.stringify(i)),incrementCC1Broadcast(),setCC1LastSeq(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,r)}catch(t){this.log.error({err:t,docName:e},`[cc1] emitConfigValidationRejected 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 TRACER_NAME=`open-knowledge-server`;let tracerProvider=null,meterProvider=null;function noopResult(){return{tracer:trace.getTracer(TRACER_NAME),meter:metrics.getMeter(TRACER_NAME)}}function initTelemetry(){if(process.env.OTEL_SDK_DISABLED!==`false`||tracerProvider)return noopResult();try{let e=(0,import_src$4.resourceFromAttributes)({[ATTR_SERVICE_NAME]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[ATTR_SERVICE_VERSION]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),t=new import_src.AsyncLocalStorageContextManager;context.setGlobalContextManager(t);let n=new import_src$6.BasicTracerProvider({resource:e,spanProcessors:[new import_src$6.BatchSpanProcessor(new import_src$3.OTLPTraceExporter)]});trace.setGlobalTracerProvider(n),propagation.setGlobalPropagator(new import_src$1.W3CTraceContextPropagator);let r=new import_src$5.MeterProvider({resource:e,readers:[new import_src$5.PeriodicExportingMetricReader({exporter:new import_src$2.OTLPMetricExporter})]});metrics.setGlobalMeterProvider(r),tracerProvider=n,meterProvider=r,getLogger(`telemetry`).info({otlp_endpoint:process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`,service_name:e.attributes[ATTR_SERVICE_NAME]},`OpenTelemetry initialized — traces + metrics exporting via OTLP/HTTP`)}catch(e){getLogger(`telemetry`).error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),tracerProvider=null,meterProvider=null}return noopResult()}const SHUTDOWN_TIMEOUT_MS=5e3;async function shutdownTelemetry(){if(!tracerProvider&&!meterProvider)return;let e=getLogger(`telemetry`),t=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`)})]);await Promise.race([t.then(()=>!1),new Promise(e=>setTimeout(()=>e(!0),SHUTDOWN_TIMEOUT_MS))])&&e.warn({},`telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms — data may be lost`),tracerProvider=null,meterProvider=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,n){return getTracer().startActiveSpan(e,t??{},async e=>{try{let t=await n(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,n){return getTracer().startActiveSpan(e,t??{},e=>{try{return n(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)}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 mdManager=new MarkdownManager({extensions:sharedExtensions}),schema=getSchema(sharedExtensions),log$6=getLogger(`agent-sessions`);function applyAgentMarkdownWrite(e,t,n,r){withSpanSync(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":n,"agent.markdown.bytes":t.length}},()=>applyAgentMarkdownWriteInner(e,t,n,r))}function applyAgentMarkdownWriteInner(e,t,n,r){try{let i=e.getXmlFragment(`default`),a=e.getText(`source`),o=yXmlFragmentToProseMirrorRootNode(i,schema).toJSON(),s=mdManager.serialize(o),{frontmatter:c}=stripFrontmatter(a.toString()),{frontmatter:l,body:u}=stripFrontmatter(t),d,f;switch(n){case`replace`:d=l||c,f=u.trim();break;case`prepend`:d=c,f=`${u.trim()}\n\n${s}`;break;case`append`:d=c,f=s.trim()?`${s}\n\n${u.trim()}\n`:`${u.trim()}\n`;break}let p=mdManager.parseWithFallback(f,r);updateYFragment(e,i,schema.nodeFromJSON(p),{mapping:new Map,isOMark:new Map}),d!==c&&recordFrontmatterEditSurface(`mcp-write`);let m=mdManager.serialize(yXmlFragmentToProseMirrorRootNode(i,schema).toJSON()),h=prependFrontmatter(d,m);applyFastDiff(a,a.toString(),h)}catch(r){throw log$6.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function applyAgentUndo(e,t,n){return withSpanSync(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let r=applyAgentUndoInner(e,t,n);return setActiveSpanAttributes({"agent.undo_effective":r}),r})}function applyAgentUndoInner(e,t,n){let{dc:r,um:i,undoOrigin:a}=e,o=r.document,s=o.getXmlFragment(`default`),c=o.getText(`source`),l=!1;return o.transact(()=>{if(t===`last`){if(i.undoStack.length===0)return;i.undo(),l=!0}else for(;i.undoStack.length>0;)i.undo(),l=!0;let{body:e,frontmatter:r}=stripFrontmatter(c.toString()),a=mdManager.parseWithFallback(e,n);updateYFragment(o,s,schema.nodeFromJSON(a),{mapping:new Map,isOMark:new Map});let u=prependFrontmatter(r,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(s,schema).toJSON()));applyFastDiff(c,c.toString(),u)},a),l}function createSessionOrigin(e,t,n,r,i){let a={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(a.agent_type=t),n!==void 0&&(a.principal=n),r!==void 0&&(a.display_name=r),i!==void 0&&(a.color_seed=i),Object.freeze(a);let o={source:`local`,skipStoreHooks:!1,context:a};return Object.freeze(o),o}function createUndoOrigin(e,t){let n={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(n.agent_type=t),Object.freeze(n);let r={source:`local`,skipStoreHooks:!1,context:n};return Object.freeze(r),r}var AgentSessionManager=class{sessions=new Map;pendingSessions=new Map;hocuspocus;constructor(e){this.hocuspocus=e}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,n]of this.sessions)e.endsWith(t)&&(yield n)}getLiveSession(e,t){return this.sessions.get(this.sessionKey(e,t))}async getSession(e,t=`claude-1`,n){if(isSystemDoc(e)||isConfigDoc(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let r=this.sessionKey(e,t),i=this.sessions.get(r);if(i)return i;let a=this.pendingSessions.get(r);if(a)return a;let o=this._createSession(e,t,n);this.pendingSessions.set(r,o);try{let e=await o;return this.sessions.set(r,e),e}finally{this.pendingSessions.delete(r)}}async _createSession(e,t,n){let r=n?.clientName,i=t.startsWith(`agent-`)?t.slice(6):t,a=createSessionOrigin(i,r,n?.principalId,n?.displayName,n?.colorSeed),o=createUndoOrigin(i,r),s={session_id:i,...r===void 0?{}:{agent_type:r},...n?.clientName===void 0?{}:{client_name:n.clientName},...n?.principalId===void 0?{}:{principalId:n.principalId}},c=await this.hocuspocus.openDirectConnection(e,s),l=new UndoManager([c.document.getText(`source`),c.document.getMap(`agent-flash`)],{trackedOrigins:new Set([a]),captureTimeout:500,captureTransaction:e=>e.origin!==o,ignoreRemoteMapChanges:!0}),u=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return l.on(`stack-item-added`,u),l.on(`stack-item-updated`,u),log$6.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:c,origin:a,undoOrigin:o,um:l,agentId:t,docName:e}}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async closeSession(e,t=`claude-1`){let n=this.sessionKey(e,t),r=this.sessions.get(n);r&&(r.um.destroy(),await r.dc.disconnect(),this.sessions.delete(n),log$6.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,n=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));n.length>0&&await Promise.allSettled(n.map(e=>this.pendingSessions.get(e)));let r=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of r){let n=this.sessions.get(t);if(n)try{n.um.destroy(),await n.dc.disconnect(),this.sessions.delete(t)}catch(t){log$6.error({err:t,agentId:e},`[agent-session] Failed to close session for agent ${e}`)}}}async closeAllForDoc(e){let t=`${e}\0`,n=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of n){let n=this.sessions.get(t);if(n)try{n.um.destroy(),await n.dc.disconnect(),this.sessions.delete(t)}catch(t){log$6.error({err:t,docName:e},`[agent-session] Failed to close session for doc ${e}`)}}}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);if(t)try{t.um.destroy(),await t.dc.disconnect(),this.sessions.delete(e)}catch(t){log$6.error({err:t,key:e},`[agent-session] Failed to close session: ${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,n,r){let i=e.doc;if(!i)return;let a=++_effectCounter,o=i.getMap(`agent-effects`),s=l=>{e.unobserve(s),i.off(`destroy`,c);let u=`${t}:${a}`,d={sessionId:t,timestamp:Date.now(),delta:l.delta,agent_type:r??`agent`,color_seed:n??t};try{i.transact(()=>{if(o.set(u,d),o.size>RING_BUFFER_LIMIT){let e=[...o.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,o.size-RING_BUFFER_LIMIT))o.delete(t)}},EFFECT_CAPTURE_ORIGIN)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),incrementEffectDiffCaptureFailures(),process.env.NODE_ENV!==`production`)throw e}},c=()=>{e.unobserve(s)};e.observe(s),i.once(`destroy`,c)}function collectItemsInDeleteSet(e,t,n){iterateDeletedStructs(e,t,e=>{e instanceof Item&&n.add(e)})}function*walkYTextItems(e){let t=e._start;for(;t!==null;)yield t,t=t.right}function synthesizeStackItemDiff(e,t){let n=[],r=[],i=t.doc,a=new Set,o=new Set;i&&i.transact(t=>{collectItemsInDeleteSet(t,e.insertions,a),collectItemsInDeleteSet(t,e.deletions,o)});let s=``,c=``,l=0,u=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str,i=t.length,d=a.has(e),f=o.has(e);e.deleted?f&&(r.push({position:l,content:t,length:i}),s+=t,l+=i):(c+=t,d?n.push({position:u,content:t,length:i}):(s+=t,l+=i),u+=i)}return{insertions:n,deletions:r,before:s,after:c}}function synthesizeStackItemDiffText(e,t,n){let{before:r,after:i}=synthesizeStackItemDiff(e,t);return r===i?``:createPatch(n,r,i,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 n=t.doc,r=new Set,i=new Set;n&&n.transact(t=>{collectItemsInDeleteSet(t,e.insertions,r),collectItemsInDeleteSet(t,e.deletions,i)});let a=0,o=0;for(let e of walkYTextItems(t)){if(!(e.content instanceof ContentString))continue;let t=e.content.str.length;!e.deleted&&r.has(e)&&(a+=t),i.has(e)&&(o+=t)}return{additions:a,deletions:o}}function listAgentActivity(e,t){let n=[],r=null,i=!1;for(let a of e.sessionsForConnection(t)){if(i=!0,!r){let e=a.origin.context,n=typeof e?.agent_type==`string`?e.agent_type:void 0,i=typeof e?.color_seed==`string`?e.color_seed:t,o=iconFromClientName(n),s=AGENT_ICON_COLORS[o]??colorFromSeed(i);r={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:s,icon:o,connectionId:t}}let e=a.docName,o=a.um,s=a.dc.document.getText(`source`),c=[];for(let e=0;e<o.undoStack.length;e++){let t=o.undoStack[e],n=getBurstTs(t),{additions:r,deletions:i}=countStackItemChanges(t,s);c.push({stackIndex:e,ts:n,additions:r,deletions:i})}if(c.length===0)continue;c.sort((e,t)=>t.stackIndex-e.stackIndex);let l=c.reduce((e,t)=>e+t.additions,0),u=c.reduce((e,t)=>e+t.deletions,0),d=Math.max(...c.map(e=>e.ts));n.push({docName:e,additionsTotal:l,deletionsTotal:u,lastTs:d,bursts:c})}return i?(n.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:r,files:n}):{sessionAlive:!1,agent:null,files:[]}}const ELLIPSIS=`…`;function normalizeSummary(e){return e===void 0?{kind:`absent`}:typeof e==`string`?e.length===0||e.trim().length===0?{kind:`absent`}:e.length<=80?{kind:`value`,value:e}:{kind:`value`,value:e.slice(0,79)+ELLIPSIS,truncatedFrom:e.length}:{kind:`invalid`}}let pendingContributors=new Map;function recordContributor(e,t,n,r,i,a,o){let s=pendingContributors.get(t);if(s||(s={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[]},pendingContributors.set(t,s)),s.docs.add(e),i!==void 0&&(s.subjectOverride=i),a!==void 0){let e=s.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),s.actor=e}typeof o==`string`&&o.length>0&&s.summaries.push(o)}function swapContributors(){let e=pendingContributors;return pendingContributors=new Map,e}function restoreContributors(e){for(let[t,n]of e){let e=pendingContributors.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[]},pendingContributors.set(t,e));for(let t of n.docs)e.docs.add(t);n.summaries.length>0&&(e.summaries=[...n.summaries,...e.summaries])}}function restoreContributorEntry(e,t){let n=pendingContributors.get(e);n||(n={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[]},pendingContributors.set(e,n));for(let e of t.docs)n.docs.add(e);t.summaries.length>0&&(n.summaries=[...t.summaries,...n.summaries])}function contributorCount(){return pendingContributors.size}function hasContributor(e){return pendingContributors.has(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,n=e.now??Date.now,r=e.ttlMs??6e4;async function i(i){let a=t.get(i);if(a?.status===`resolved`&&a.expiresAt>n())return a.installed;if(a?.status===`inflight`)return a.promise;let o=(async()=>{try{let a=await e.probe(i);return t.set(i,{status:`resolved`,installed:a,expiresAt:n()+r}),a}catch{return t.set(i,{status:`resolved`,installed:!1,expiresAt:n()+r}),!1}})();return t.set(i,{status:`inflight`,promise:o}),o}async function a(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await i(e)]));return Object.fromEntries(e)}return{probeAll:a,probeWithCache:i}}async function handleInstalledAgents(e,t,n){if(e.method!==`GET`){writeJson(t,405,{error:`Method not allowed`});return}try{writeJson(t,200,await n())}catch(e){console.error(`[installed-agents]`,e),writeJson(t,500,{error:`Internal server error`})}}function writeJson(e,t,n){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify(n))}function createOsProbe(e,t=execFile){return n=>e===`darwin`?probeMacOs(n,t):e===`win32`?probeWindows(n,t):probeLinux(n,t)}function probeMacOs(e,t){let n=MACOS_APP_NAMES[e];function r(e){return new Promise(n=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}return(async()=>{for(let e of n)if(await r(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(n=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{n(!e)})})}function probeLinux(e,t){return new Promise(n=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let n=[],r=new Set,i=t=>{!t||r.has(t)||t!==e&&(r.add(t),n.push(t))},a=buildLowerDocNameIndex(t),o=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(i(lookup(t,a,joinDocName(o,e))),n.length>=MAX_CANDIDATES)return n;let e=o===``?null:basename$1(o);if(e&&(i(lookup(t,a,joinDocName(o,e))),n.length>=MAX_CANDIDATES))return n;if(o===``)break;o=parentFolder(o)}return n}function lookup(e,t,n){return e.has(n)?n:t.get(n.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let n of e.keys()){let e=n.toLowerCase();t.has(e)||t.set(e,n)}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 n=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(n))return normalizeFrontmatterScalar(t.slice(n.length))||null;return null}function parseInlineAliases(e){let t=[],n=``,r=null;for(let i of e){if(r){n+=i,i===r&&(r=null);continue}if(i===`"`||i===`'`){r=i,n+=i;continue}if(i===`,`){let e=normalizeFrontmatterScalar(n);e&&t.push(e),n=``;continue}n+=i}let i=normalizeFrontmatterScalar(n);return i&&t.push(i),t}function dedupeExact(e){let t=[],n=new Set;for(let r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let n=splitFrontmatterLines(t);for(let e=0;e<n.length;e+=1){let t=n[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let r=t[1]?.trim()??``;if(r){if(r.startsWith(`[`)&&r.endsWith(`]`))return dedupeExact(parseInlineAliases(r.slice(1,-1)));let e=normalizeFrontmatterScalar(r);return e?[e]:[]}let i=[];for(let t=e+1;t<n.length;t+=1){let e=n[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&i.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(i)}return[]}function extractPageTitle(e,t){let{frontmatter:n,body:r}=stripFrontmatter(e),i=extractFrontmatterScalar(n,`title`);if(i)return i;let a=r.match(/^# (.+)$/m);return a?a[1].trim():t}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 n=`${t}:`,r=splitFrontmatterLines(e);for(let e=0;e<r.length;e+=1){let t=r[e];if(!t?.startsWith(n))continue;let i=t.slice(n.length).trim();if(i){if(i.startsWith(`[`)&&i.endsWith(`]`)){let e=parseInlineAliases(i.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(i);return e?[e]:void 0}let a=[];for(let t=e+1;t<r.length;t+=1){let e=r[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&a.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return a.length>0?a:void 0}}function extractPageIdentity(e,t){let n=extractPageTitle(e,t),r=extractPageAliases(e),i=dedupeExact([n,...r]),a=[],o=new Set;for(let e of i){let t=toWikiLinkSlug(e);!t||o.has(t)||(o.add(t),a.push(t))}return{docName:t,title:n,aliases:r,matchLabels:i,normalizedMatchLabels:a}}const MAX_ZIP_BYTES=102400;function resolveBundledSkillDir(){let e=[`../assets/skills/open-knowledge`,`./assets/skills/open-knowledge`],t=[];for(let n of e){let e=fileURLToPath(new URL(n,import.meta.url));if(existsSync(e))return e;t.push(e)}throw Error(`Bundled skill asset directory not found. Tried: ${t.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 readCliVersion(){for(let e of[`../../cli/package.json`,`../package.json`]){let t=fileURLToPath(new URL(e,import.meta.url));if(!existsSync(t))continue;let n=await readFile(t,`utf-8`),r=JSON.parse(n);if(r.name===`@inkeep/open-knowledge`&&typeof r.version==`string`)return r.version}throw Error(`Could not resolve @inkeep/open-knowledge CLI version — no package.json with matching name found in candidate paths.`)}async function*walkFiles(e,t=e){let n=await readdir(e,{withFileTypes:!0});for(let r of n){let n=join(e,r.name);r.isDirectory()?yield*walkFiles(n,t):r.isFile()&&(yield relative(t,n))}}async function zipDirectory(e,t){let n=e.split(`/`).pop()??`open-knowledge`,r=new import_yazl.ZipFile;r.addEmptyDirectory(`${n}/`);let i=[];for await(let t of walkFiles(e))i.push(t);i.sort();for(let t of i){let i=join(e,t),a=`${n}/${t}`;r.addFile(i,a)}r.end(),await new Promise((e,n)=>{let i=createWriteStream(t);r.outputStream.pipe(i),i.on(`close`,()=>e()),i.on(`error`,n),r.outputStream.on(`error`,n)})}async function sha256OfFile(e){return new Promise((t,n)=>{let r=createHash(`sha256`),i=createReadStream(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>t(r.digest(`hex`))),i.on(`error`,n)})}function extractMetadataVersion(e){let t=e.indexOf(`
|
|
51
51
|
---`,4);if(!e.startsWith(`---
|
|
52
52
|
`)||t<0)return;let n=e.slice(4,t),r=n.search(/^metadata:/m);if(r<0)return;let i=n.slice(r).split(`
|
|
53
|
-
`).slice(1);for(let e of i){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,n={}){let r=statSync(e).size;if(r>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${r} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let i=await sha256OfFile(e),a=await readFile(join(resolveBundledSkillDir(),`SKILL.md`),`utf-8`);if(!/^name:\s+open-knowledge$/m.test(a.slice(0,1e3)))throw Error("SKILL.md frontmatter `name:` does not match 'open-knowledge'. Check packages/server/assets/skills/open-knowledge/SKILL.md frontmatter.");let o=extractMetadataVersion(a);if(!n.skipVersionCheck){if(!o)throw Error("SKILL.md metadata.version missing. Add it to packages/server/assets/skills/open-knowledge/SKILL.md or run `bash scripts/sync-skill-version.sh`.");if(o!==t)throw Error(`SKILL.md metadata.version (${o}) does not match CLI version (${t}). Run \`bash scripts/sync-skill-version.sh\` after bumping package versions.`)}return{size:r,sha256:i,skillVersion:o}}async function buildSkillZip(e={}){let t=e.sourceDir??resolveBundledSkillDir(),n=e.outputPath??join(process.cwd(),`openknowledge.skill`),r=await readCliVersion();await zipDirectory(t,n);let{size:i,sha256:a,skillVersion:o}=await validateSkillZip(n,r,{skipVersionCheck:e.skipVersionCheck});return{outputPath:n,size:i,sha256:a,cliVersion:r,skillVersion:o}}const SIDECAR_FILENAME=`skill-installed-version`,CENTRAL_SKILL_DIR_REL=[`.agents`,`skills`,`open-knowledge`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS=6e4,VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/;async function readServerPackageVersion(){let e=await readFile(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}function sidecarPath(e){return join(e,`.ok`,SIDECAR_FILENAME)}async function readSidecarVersion(e){try{let t=(await readFile(sidecarPath(e),`utf-8`)).trim();return t.length===0||!VERSION_RE.test(t)?null:t}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function writeSidecarVersion(e,t){let n=sidecarPath(e);await mkdir(dirname(n),{recursive:!0}),await writeFile(n,`${t}\n`,`utf-8`)}function centralSkillDir(e){return join(e,...CENTRAL_SKILL_DIR_REL)}async function centralSkillExists(e){try{return(await stat$1(centralSkillDir(e))).isDirectory()}catch{return!1}}function runSpawn(e,t,n,r,i){return new Promise(a=>{let o;try{o=e(t,n,{env:r,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){a({kind:`spawn-error`,stderr:``,error:e});return}let s=``,c=!1,l=e=>{c||(c=!0,clearTimeout(u),a(e))};o.stderr?.on(`data`,e=>{s+=typeof e==`string`?e:e.toString(`utf-8`)}),o.on(`error`,e=>{l({kind:`spawn-error`,stderr:s,error:e})}),o.on(`exit`,e=>{l(e===0?{kind:`ok`,exitCode:e,stderr:s}:{kind:`nonzero`,exitCode:e,stderr:s})});let u=setTimeout(()=>{try{o.kill(`SIGTERM`)}catch{}l({kind:`timeout`,stderr:s})},i)})}async function installUserSkill(e={}){let t=e.home??homedir(),n=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},r=e.spawn??spawn,i=e.timeoutMs??DEFAULT_TIMEOUT_MS,a;try{a=await readServerPackageVersion()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),`failed`}let o=await readSidecarVersion(t).catch(()=>null);if(o!==null&&o===a){if(await centralSkillExists(t))return n.info?.({event:`skill-install.skip-current`,version:a},`Open Knowledge skill already installed at current version; skipping.`),`skip-current`;n.info?.({event:`skill-install.reinstall-missing`,version:a,path:centralSkillDir(t)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let s;try{s=resolveBundledSkillDir()}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),`failed`}let c=await runSpawn(r,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,s,`--agent`,`*`,`-g`,`-y`,`--copy`],{...process.env,HOME:t},i);if(c.kind===`ok`){try{await writeSidecarVersion(t,a)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),`failed`}return n.info?.({event:`skill-install.installed`,version:a},`Open Knowledge skill installed to detected agent hosts.`),`installed`}return c.kind===`timeout`?(n.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:i,stderr:c.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):c.kind===`spawn-error`?(n.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(c.error),stderr:c.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):(n.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:c.exitCode,stderr:c.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,n){let r={detached:!0,stdio:`ignore`};try{return t===`darwin`?(n(`open`,[e],r).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],r).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],r).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.homeDir??homedir(),n=resolve(e.out??defaultDownloadsPath(t)),r=e.platformName??platform(),i=e.spawnFn??spawn;try{await mkdir(dirname(n),{recursive:!0})}catch(e){return{status:`failed`,buildError:`could not create output directory: ${e instanceof Error?e.message:String(e)}`}}let a;try{a=await buildSkillZip({outputPath:n,skipVersionCheck:!0})}catch(e){return{status:`failed`,buildError:e instanceof Error?e.message:String(e)}}let o={status:`built`,outputPath:a.outputPath,size:a.size,sha256:a.sha256,cliVersion:a.cliVersion,skillVersion:a.skillVersion};if(e.noOpen)return o;let s=invokeFileAssociation(a.outputPath,r,i);return s.ok?{...o,status:`installed`}:{...o,handoffError:{reason:s.reason,message:s.message}}}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}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}conflict`)?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,n){let r={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return n&&Object.assign(r,n),r}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,n){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,n)})}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,n){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,n)})}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 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)})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};const log$5=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,n){this.hash.update(e),this.bytes+=e.length,n(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(e,`.ok`,`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,n){let r=extname(n),i=n.slice(0,n.length-r.length),a=[n,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let n of a){let r=resolve(t,n);try{tracedLinkSync(e,r);try{tracedUnlinkSync(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new UploadWriteError(`storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new UploadWriteError(`storage-readonly`,t):new UploadWriteError(`storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let n=tmpUploadDir(e),r={scanned:0,deleted:0,errors:0};if(!existsSync(n))return r;let i;try{i=readdirSync(n)}catch(e){return log$5.warn({err:e,dir:n},`[upload-tempfile-sweep] readdir failed`),r.errors++,r}let a=Date.now()-t;for(let e of i){if(!e.startsWith(`upload-`))continue;r.scanned++;let t=resolve(n,e);try{if(statSync(t).mtimeMs>=a)continue;tracedUnlinkSync(t),r.deleted++}catch(e){log$5.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&log$5.info({dir:n,scanned:r.scanned,deleted:r.deleted,errors:r.errors},`[upload-tempfile-sweep] swept ${r.deleted}/${r.scanned} (errors: ${r.errors})`),r}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n;for(;r<e.length;){if(e[r]!=="`"){r++;continue}let t=0;for(;e[r+t]==="`";)t++;if(t===n)return{nextIndex:r+n};r+=t}return null}function readWikiLink$2(e,t){let n=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function readMarkdownLink$2(e,t){let n=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!n)return null;let r=n[2]??``;return{text:n[1]??``,hrefRaw:r,href:r.startsWith(`<`)&&r.endsWith(`>`)?r.slice(1,-1):r,titleSuffix:n[3]??``,nextIndex:t+n[0].length}}function readImageRef(e,t){let n=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!n)return null;let r=n[2]??``;return{alt:n[1]??``,hrefRaw:r,href:r.startsWith(`<`)&&r.endsWith(`>`)?r.slice(1,-1):r,titleSuffix:n[3]??``,nextIndex:t+n[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),n=[];for(let e=0;e<t.length;e+=2)n.push({line:t[e]??``,ending:t[e+1]??``});return n}function rewriteWikiLinksInLine(e,t,n){let r=``,i=0,a=0,o=leadingMarkdownPrefixLength$2(e);for(o>0&&(r+=e.slice(0,o),a=o);a<e.length;){if(e[a]===`\\`&&a+1<e.length){r+=e.slice(a,a+2),a+=2;continue}if(e[a]==="`"){let t=readInlineCode$2(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let o=readWikiLink$2(e,a);if(o){o.target===t?(r+=`[[${n}${o.anchor?`#${o.anchor}`:``}${o.alias?`|${o.alias}`:``}]]`,i++):r+=e.slice(a,o.nextIndex),a=o.nextIndex;continue}}r+=e[a],a++}return{markdown:r,rewrites:i}}function recomputeRelativeImageHref(e,t,n){let r=e.indexOf(`#`),i=r>=0?e.slice(r):``,a=r>=0?e.slice(0,r):e,o=a.indexOf(`?`),s=o>=0?a.slice(o):``,c=o>=0?a.slice(0,o):a;if(c.startsWith(`/`)||c.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(c))return null;let l=posix.dirname(t),u=posix.dirname(n);if(l===u)return null;let d=l===`.`?`/`:`/${l}/`,f=posix.resolve(d,c).slice(1),p=posix.relative(u===`.`?``:u,f);return p||=posix.basename(f),c.startsWith(`./`)&&!p.startsWith(`./`)&&!p.startsWith(`../`)&&(p=`./${p}`),`${p}${s}${i}`}function recomputeRelativeMarkdownHref(e,t,n){let r=e.indexOf(`#`),i=r>=0?e.slice(r):``,a=r>=0?e.slice(0,r):e,o=a.indexOf(`?`),s=o>=0?a.slice(o):``,c=o>=0?a.slice(0,o):a,l=posix.dirname(t),u=posix.relative(l===`.`?``:l,n);return u||=posix.basename(n),c.endsWith(`.mdx`)?u+=`.mdx`:c.endsWith(`.md`)&&(u+=`.md`),c.startsWith(`./`)&&!u.startsWith(`./`)&&!u.startsWith(`../`)&&(u=`./${u}`),`${u}${s}${i}`}function rewriteMarkdownLinksInLine(e,t,n,r){let i=``,a=0,o=0,s=leadingMarkdownPrefixLength$2(e);for(s>0&&(i+=e.slice(0,s),o=s);o<e.length;){if(e[o]===`\\`&&o+1<e.length){i+=e.slice(o,o+2),o+=2;continue}if(e[o]==="`"){let t=readInlineCode$2(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o+1]===`[`){let t=readWikiLink$2(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`!`&&e[o+1]===`[`){let s=readImageRef(e,o);if(s){let c=t===n&&n!==r?recomputeRelativeImageHref(s.href,n,r):null;if(c!==null){let e=s.hrefRaw.startsWith(`<`)&&s.hrefRaw.endsWith(`>`)?`<${c}>`:c;i+=``,a++}else i+=e.slice(o,s.nextIndex);o=s.nextIndex;continue}}if(e[o]===`[`){let s=readMarkdownLink$2(e,o);if(s){if(resolveInternalHref(s.href,t)?.docName===n){let e=recomputeRelativeMarkdownHref(s.href,t,r),n=s.hrefRaw.startsWith(`<`)&&s.hrefRaw.endsWith(`>`)?`<${e}>`:e;i+=`[${s.text}](${n}${s.titleSuffix})`,a++}else i+=e.slice(o,s.nextIndex);o=s.nextIndex;continue}}i+=e[o],o++}return{markdown:i,rewrites:a}}function rewriteWikiLinksForDocumentRename(e,t,n){let r=null,i=0;return{markdown:splitLines(e).map(({line:e,ending:a})=>{if(r)return isFenceClose$2(e,r)&&(r=null),`${e}${a}`;let o=matchFence$2(e);if(o)return r=o,`${e}${a}`;let s=rewriteWikiLinksInLine(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}function rewriteMarkdownLinksForDocumentRename(e,t,n,r){let i=null,a=0;return{markdown:splitLines(e).map(({line:e,ending:o})=>{if(i)return isFenceClose$2(e,i)&&(i=null),`${e}${o}`;let s=matchFence$2(e);if(s)return i=s,`${e}${o}`;let c=rewriteMarkdownLinksInLine(e,t,n,r);return a+=c.rewrites,`${c.markdown}${o}`}).join(``),rewrites:a}}function rewriteOutboundMarkdownLinksInLine(e,t,n){let r=``,i=0,a=0,o=leadingMarkdownPrefixLength$2(e);for(o>0&&(r+=e.slice(0,o),a=o);a<e.length;){if(e[a]===`\\`&&a+1<e.length){r+=e.slice(a,a+2),a+=2;continue}if(e[a]==="`"){let t=readInlineCode$2(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let t=readWikiLink$2(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`!`&&e[a+1]===`[`){let t=readImageRef(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`){let o=readMarkdownLink$2(e,a);if(o){let s=resolveInternalHref(o.href,t);if(s!==null){let t=recomputeRelativeMarkdownHref(o.href,n,s.docName);if(t!==o.href){let e=o.hrefRaw.startsWith(`<`)&&o.hrefRaw.endsWith(`>`)?`<${t}>`:t;r+=`[${o.text}](${e}${o.titleSuffix})`,i++}else r+=e.slice(a,o.nextIndex)}else r+=e.slice(a,o.nextIndex);a=o.nextIndex;continue}}r+=e[a],a++}return{markdown:r,rewrites:i}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,n){if(posix.dirname(t)===posix.dirname(n))return{markdown:e,rewrites:0};let r=null,i=0;return{markdown:splitLines(e).map(({line:e,ending:a})=>{if(r)return isFenceClose$2(e,r)&&(r=null),`${e}${a}`;let o=matchFence$2(e);if(o)return r=o,`${e}${a}`;let s=rewriteOutboundMarkdownLinksInLine(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e){super(`${e} does not exist`),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e){super(`Source path is not a ${e}`),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}};function buildRenameMap(e){let t=new Map,n=[];for(let{from:r,to:i}of e){for(let[e,a]of t)e!==r&&a===i&&n.push({existing:e,incoming:r,to:i});t.set(r,i)}if(n.length>0)throw new ManagedRenameCollisionError(n);return t}function rewriteSupportedLinksForRename(e,t,n,r){let{frontmatter:i,body:a}=stripFrontmatter(e),o=rewriteWikiLinksForDocumentRename(a,n,r),s=rewriteMarkdownLinksForDocumentRename(o.markdown,t,n,r);return{markdown:prependFrontmatter(i,s.markdown),rewrites:o.rewrites+s.rewrites}}function applyRenameMap(e,t,n){let r=e,i=0,a,o=[];for(let[e,r]of n)e!==r&&(e===t?a=r:o.push([e,r]));if(a!==void 0){let e=rewriteSupportedLinksForRename(r,t,t,a);r=e.markdown,i+=e.rewrites;let{frontmatter:n,body:o}=stripFrontmatter(r),s=rewriteOutboundMarkdownLinksForSourceMove(o,t,a);r=prependFrontmatter(n,s.markdown),i+=s.rewrites}let s=a??t,c=new Map;for(let[e,t]of o){let n=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,a=rewriteSupportedLinksForRename(r,s,e,n);a.rewrites>0&&(r=a.markdown,i+=a.rewrites,c.set(n,t))}for(let[e,t]of c)r=rewriteSupportedLinksForRename(r,s,e,t).markdown;return{markdown:r,rewrites:i}}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 n=extname(e).slice(1).toLowerCase();return n.length>0&&t.has(n)}function stripDocExtension(e){let t=e.toLowerCase();for(let n of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(n))return e.slice(0,-n.length);return e}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let n=docExtensionByName.get(e);return n?n===t?{effective:n,changed:!1,shadowed:null}:rank(t)<rank(n)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:n}):{effective:n,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,n){if(!normalizeSnippet$1(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
53
|
+
`).slice(1);for(let e of i){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,n={}){let r=statSync(e).size;if(r>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${r} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let i=await sha256OfFile(e),a=await readFile(join(resolveBundledSkillDir(),`SKILL.md`),`utf-8`);if(!/^name:\s+open-knowledge$/m.test(a.slice(0,1e3)))throw Error("SKILL.md frontmatter `name:` does not match 'open-knowledge'. Check packages/server/assets/skills/open-knowledge/SKILL.md frontmatter.");let o=extractMetadataVersion(a);if(!n.skipVersionCheck){if(!o)throw Error("SKILL.md metadata.version missing. Add it to packages/server/assets/skills/open-knowledge/SKILL.md or run `bash scripts/sync-skill-version.sh`.");if(o!==t)throw Error(`SKILL.md metadata.version (${o}) does not match CLI version (${t}). Run \`bash scripts/sync-skill-version.sh\` after bumping package versions.`)}return{size:r,sha256:i,skillVersion:o}}async function buildSkillZip(e={}){let t=e.sourceDir??resolveBundledSkillDir(),n=e.outputPath??join(process.cwd(),`openknowledge.skill`),r=await readCliVersion();await zipDirectory(t,n);let{size:i,sha256:a,skillVersion:o}=await validateSkillZip(n,r,{skipVersionCheck:e.skipVersionCheck});return{outputPath:n,size:i,sha256:a,cliVersion:r,skillVersion:o}}const SIDECAR_FILENAME=`skill-installed-version`,CENTRAL_SKILL_DIR_REL=[`.agents`,`skills`,`open-knowledge`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$3=6e4,VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/;async function readServerPackageVersion(){let e=await readFile(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}function sidecarPath(e){return join(e,`.ok`,SIDECAR_FILENAME)}async function readSidecarVersion(e){try{let t=(await readFile(sidecarPath(e),`utf-8`)).trim();return t.length===0||!VERSION_RE.test(t)?null:t}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function writeSidecarVersion(e,t){let n=sidecarPath(e);await mkdir(dirname(n),{recursive:!0}),await writeFile(n,`${t}\n`,`utf-8`)}function centralSkillDir(e){return join(e,...CENTRAL_SKILL_DIR_REL)}async function centralSkillExists(e){try{return(await stat$1(centralSkillDir(e))).isDirectory()}catch{return!1}}function runSpawn(e,t,n,r,i){return new Promise(a=>{let o;try{o=e(t,n,{env:r,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){a({kind:`spawn-error`,stderr:``,error:e});return}let s=``,c=!1,l=e=>{c||(c=!0,clearTimeout(u),a(e))};o.stderr?.on(`data`,e=>{s+=typeof e==`string`?e:e.toString(`utf-8`)}),o.on(`error`,e=>{l({kind:`spawn-error`,stderr:s,error:e})}),o.on(`exit`,e=>{l(e===0?{kind:`ok`,exitCode:e,stderr:s}:{kind:`nonzero`,exitCode:e,stderr:s})});let u=setTimeout(()=>{try{o.kill(`SIGTERM`)}catch{}l({kind:`timeout`,stderr:s})},i)})}async function installUserSkill(e={}){let t=e.home??homedir(),n=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},r=e.spawn??spawn,i=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,a;try{a=await readServerPackageVersion()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),`failed`}let o=await readSidecarVersion(t).catch(()=>null);if(o!==null&&o===a){if(await centralSkillExists(t))return n.info?.({event:`skill-install.skip-current`,version:a},`Open Knowledge skill already installed at current version; skipping.`),`skip-current`;n.info?.({event:`skill-install.reinstall-missing`,version:a,path:centralSkillDir(t)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let s;try{s=resolveBundledSkillDir()}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),`failed`}let c=await runSpawn(r,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,s,`--agent`,`*`,`-g`,`-y`,`--copy`],{...process.env,HOME:t},i);if(c.kind===`ok`){try{await writeSidecarVersion(t,a)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),`failed`}return n.info?.({event:`skill-install.installed`,version:a},`Open Knowledge skill installed to detected agent hosts.`),`installed`}return c.kind===`timeout`?(n.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:i,stderr:c.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):c.kind===`spawn-error`?(n.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(c.error),stderr:c.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):(n.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:c.exitCode,stderr:c.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,n){let r={detached:!0,stdio:`ignore`};try{return t===`darwin`?(n(`open`,[e],r).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],r).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],r).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.homeDir??homedir(),n=resolve(e.out??defaultDownloadsPath(t)),r=e.platformName??platform(),i=e.spawnFn??spawn;try{await mkdir(dirname(n),{recursive:!0})}catch(e){return{status:`failed`,buildError:`could not create output directory: ${e instanceof Error?e.message:String(e)}`}}let a;try{a=await buildSkillZip({outputPath:n,skipVersionCheck:!0})}catch(e){return{status:`failed`,buildError:e instanceof Error?e.message:String(e)}}let o={status:`built`,outputPath:a.outputPath,size:a.size,sha256:a.sha256,cliVersion:a.cliVersion,skillVersion:a.skillVersion};if(e.noOpen)return o;let s=invokeFileAssociation(a.outputPath,r,i);return s.ok?{...o,status:`installed`}:{...o,handoffError:{reason:s.reason,message:s.message}}}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}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}conflict`)?`conflict`:e.includes(`${sep}.ok${sep}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function buildAttrs(e,t,n){let r={"fs.operation":e,"fs.path":normalizeFsPath(t),"fs.path.role":classifyFsPath(t)};return n&&Object.assign(r,n),r}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,n){return withSpan(`fs.writeFile`,{attributes:buildAttrs(`writeFile`,e,{"fs.bytes":byteLength(t)})},async()=>{await writeFile(e,t,n)})}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,n){withSpanSync(`fs.writeFileSync`,{attributes:buildAttrs(`writeFileSync`,e,{"fs.bytes":byteLength(t)})},()=>{writeFileSync(e,t,n)})}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 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)})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};const log$5=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,n){this.hash.update(e),this.bytes+=e.length,n(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(e,`.ok`,`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,n){let r=extname(n),i=n.slice(0,n.length-r.length),a=[n,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let n of a){let r=resolve(t,n);try{tracedLinkSync(e,r);try{tracedUnlinkSync(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new UploadWriteError(`storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new UploadWriteError(`storage-readonly`,t):new UploadWriteError(`storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let n=tmpUploadDir(e),r={scanned:0,deleted:0,errors:0};if(!existsSync(n))return r;let i;try{i=readdirSync(n)}catch(e){return log$5.warn({err:e,dir:n},`[upload-tempfile-sweep] readdir failed`),r.errors++,r}let a=Date.now()-t;for(let e of i){if(!e.startsWith(`upload-`))continue;r.scanned++;let t=resolve(n,e);try{if(statSync(t).mtimeMs>=a)continue;tracedUnlinkSync(t),r.deleted++}catch(e){log$5.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&log$5.info({dir:n,scanned:r.scanned,deleted:r.deleted,errors:r.errors},`[upload-tempfile-sweep] swept ${r.deleted}/${r.scanned} (errors: ${r.errors})`),r}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n;for(;r<e.length;){if(e[r]!=="`"){r++;continue}let t=0;for(;e[r+t]==="`";)t++;if(t===n)return{nextIndex:r+n};r+=t}return null}function readWikiLink$2(e,t){let n=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function readMarkdownLink$2(e,t){let n=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!n)return null;let r=n[2]??``;return{text:n[1]??``,hrefRaw:r,href:r.startsWith(`<`)&&r.endsWith(`>`)?r.slice(1,-1):r,titleSuffix:n[3]??``,nextIndex:t+n[0].length}}function readImageRef(e,t){let n=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!n)return null;let r=n[2]??``;return{alt:n[1]??``,hrefRaw:r,href:r.startsWith(`<`)&&r.endsWith(`>`)?r.slice(1,-1):r,titleSuffix:n[3]??``,nextIndex:t+n[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),n=[];for(let e=0;e<t.length;e+=2)n.push({line:t[e]??``,ending:t[e+1]??``});return n}function rewriteWikiLinksInLine(e,t,n){let r=``,i=0,a=0,o=leadingMarkdownPrefixLength$2(e);for(o>0&&(r+=e.slice(0,o),a=o);a<e.length;){if(e[a]===`\\`&&a+1<e.length){r+=e.slice(a,a+2),a+=2;continue}if(e[a]==="`"){let t=readInlineCode$2(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let o=readWikiLink$2(e,a);if(o){o.target===t?(r+=`[[${n}${o.anchor?`#${o.anchor}`:``}${o.alias?`|${o.alias}`:``}]]`,i++):r+=e.slice(a,o.nextIndex),a=o.nextIndex;continue}}r+=e[a],a++}return{markdown:r,rewrites:i}}function recomputeRelativeImageHref(e,t,n){let r=e.indexOf(`#`),i=r>=0?e.slice(r):``,a=r>=0?e.slice(0,r):e,o=a.indexOf(`?`),s=o>=0?a.slice(o):``,c=o>=0?a.slice(0,o):a;if(c.startsWith(`/`)||c.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(c))return null;let l=posix.dirname(t),u=posix.dirname(n);if(l===u)return null;let d=l===`.`?`/`:`/${l}/`,f=posix.resolve(d,c).slice(1),p=posix.relative(u===`.`?``:u,f);return p||=posix.basename(f),c.startsWith(`./`)&&!p.startsWith(`./`)&&!p.startsWith(`../`)&&(p=`./${p}`),`${p}${s}${i}`}function recomputeRelativeMarkdownHref(e,t,n){let r=e.indexOf(`#`),i=r>=0?e.slice(r):``,a=r>=0?e.slice(0,r):e,o=a.indexOf(`?`),s=o>=0?a.slice(o):``,c=o>=0?a.slice(0,o):a,l=posix.dirname(t),u=posix.relative(l===`.`?``:l,n);return u||=posix.basename(n),c.endsWith(`.mdx`)?u+=`.mdx`:c.endsWith(`.md`)&&(u+=`.md`),c.startsWith(`./`)&&!u.startsWith(`./`)&&!u.startsWith(`../`)&&(u=`./${u}`),`${u}${s}${i}`}function rewriteMarkdownLinksInLine(e,t,n,r){let i=``,a=0,o=0,s=leadingMarkdownPrefixLength$2(e);for(s>0&&(i+=e.slice(0,s),o=s);o<e.length;){if(e[o]===`\\`&&o+1<e.length){i+=e.slice(o,o+2),o+=2;continue}if(e[o]==="`"){let t=readInlineCode$2(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o+1]===`[`){let t=readWikiLink$2(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`!`&&e[o+1]===`[`){let s=readImageRef(e,o);if(s){let c=t===n&&n!==r?recomputeRelativeImageHref(s.href,n,r):null;if(c!==null){let e=s.hrefRaw.startsWith(`<`)&&s.hrefRaw.endsWith(`>`)?`<${c}>`:c;i+=``,a++}else i+=e.slice(o,s.nextIndex);o=s.nextIndex;continue}}if(e[o]===`[`){let s=readMarkdownLink$2(e,o);if(s){if(resolveInternalHref(s.href,t)?.docName===n){let e=recomputeRelativeMarkdownHref(s.href,t,r),n=s.hrefRaw.startsWith(`<`)&&s.hrefRaw.endsWith(`>`)?`<${e}>`:e;i+=`[${s.text}](${n}${s.titleSuffix})`,a++}else i+=e.slice(o,s.nextIndex);o=s.nextIndex;continue}}i+=e[o],o++}return{markdown:i,rewrites:a}}function rewriteWikiLinksForDocumentRename(e,t,n){let r=null,i=0;return{markdown:splitLines(e).map(({line:e,ending:a})=>{if(r)return isFenceClose$2(e,r)&&(r=null),`${e}${a}`;let o=matchFence$2(e);if(o)return r=o,`${e}${a}`;let s=rewriteWikiLinksInLine(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}function rewriteMarkdownLinksForDocumentRename(e,t,n,r){let i=null,a=0;return{markdown:splitLines(e).map(({line:e,ending:o})=>{if(i)return isFenceClose$2(e,i)&&(i=null),`${e}${o}`;let s=matchFence$2(e);if(s)return i=s,`${e}${o}`;let c=rewriteMarkdownLinksInLine(e,t,n,r);return a+=c.rewrites,`${c.markdown}${o}`}).join(``),rewrites:a}}function rewriteOutboundMarkdownLinksInLine(e,t,n){let r=``,i=0,a=0,o=leadingMarkdownPrefixLength$2(e);for(o>0&&(r+=e.slice(0,o),a=o);a<e.length;){if(e[a]===`\\`&&a+1<e.length){r+=e.slice(a,a+2),a+=2;continue}if(e[a]==="`"){let t=readInlineCode$2(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let t=readWikiLink$2(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`!`&&e[a+1]===`[`){let t=readImageRef(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`){let o=readMarkdownLink$2(e,a);if(o){let s=resolveInternalHref(o.href,t);if(s!==null){let t=recomputeRelativeMarkdownHref(o.href,n,s.docName);if(t!==o.href){let e=o.hrefRaw.startsWith(`<`)&&o.hrefRaw.endsWith(`>`)?`<${t}>`:t;r+=`[${o.text}](${e}${o.titleSuffix})`,i++}else r+=e.slice(a,o.nextIndex)}else r+=e.slice(a,o.nextIndex);a=o.nextIndex;continue}}r+=e[a],a++}return{markdown:r,rewrites:i}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,n){if(posix.dirname(t)===posix.dirname(n))return{markdown:e,rewrites:0};let r=null,i=0;return{markdown:splitLines(e).map(({line:e,ending:a})=>{if(r)return isFenceClose$2(e,r)&&(r=null),`${e}${a}`;let o=matchFence$2(e);if(o)return r=o,`${e}${a}`;let s=rewriteOutboundMarkdownLinksInLine(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e){super(`${e} does not exist`),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e){super(`Source path is not a ${e}`),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}};function buildRenameMap(e){let t=new Map,n=[];for(let{from:r,to:i}of e){for(let[e,a]of t)e!==r&&a===i&&n.push({existing:e,incoming:r,to:i});t.set(r,i)}if(n.length>0)throw new ManagedRenameCollisionError(n);return t}function rewriteSupportedLinksForRename(e,t,n,r){let{frontmatter:i,body:a}=stripFrontmatter(e),o=rewriteWikiLinksForDocumentRename(a,n,r),s=rewriteMarkdownLinksForDocumentRename(o.markdown,t,n,r);return{markdown:prependFrontmatter(i,s.markdown),rewrites:o.rewrites+s.rewrites}}function applyRenameMap(e,t,n){let r=e,i=0,a,o=[];for(let[e,r]of n)e!==r&&(e===t?a=r:o.push([e,r]));if(a!==void 0){let e=rewriteSupportedLinksForRename(r,t,t,a);r=e.markdown,i+=e.rewrites;let{frontmatter:n,body:o}=stripFrontmatter(r),s=rewriteOutboundMarkdownLinksForSourceMove(o,t,a);r=prependFrontmatter(n,s.markdown),i+=s.rewrites}let s=a??t,c=new Map;for(let[e,t]of o){let n=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,a=rewriteSupportedLinksForRename(r,s,e,n);a.rewrites>0&&(r=a.markdown,i+=a.rewrites,c.set(n,t))}for(let[e,t]of c)r=rewriteSupportedLinksForRename(r,s,e,t).markdown;return{markdown:r,rewrites:i}}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 n=extname(e).slice(1).toLowerCase();return n.length>0&&t.has(n)}function stripDocExtension(e){let t=e.toLowerCase();for(let n of SUPPORTED_DOC_EXTENSIONS)if(t.endsWith(n))return e.slice(0,-n.length);return e}function rank(e){return SUPPORTED_DOC_EXTENSIONS.indexOf(e)}const docExtensionByName=new Map;function registerDocExtension(e,t){let n=docExtensionByName.get(e);return n?n===t?{effective:n,changed:!1,shadowed:null}:rank(t)<rank(n)?(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:n}):{effective:n,changed:!1,shadowed:t}:(docExtensionByName.set(e,t),{effective:t,changed:!0,shadowed:null})}function getDocExtension(e){return docExtensionByName.get(e)??DEFAULT_EXTENSION}function forgetDocExtension(e){docExtensionByName.delete(e)}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,n){if(!normalizeSnippet$1(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
54
54
|
`,t-1)),i=[e.indexOf(`.`,n),e.indexOf(`?`,n),e.indexOf(`!`,n),e.indexOf(`
|
|
55
55
|
`,n)].filter(e=>e>=0),a=r>=0?r+1:Math.max(0,t-60),o=i.length>0?Math.min(...i)+1:Math.min(e.length,n+60),s=a>0?`…`:``,c=o<e.length?`…`:``,l=normalizeSnippet$1(e.slice(a,o));return l?`${s}${l}${c}`:null}function matchFence$1(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function isFenceClose$1(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$1(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$1(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n,i=r;for(;i<e.length;){if(e[i]!=="`"){i++;continue}let t=0;for(;e[i+t]==="`";)t++;if(t===n)return{text:e.slice(r,i),nextIndex:i+n};i+=t}return null}function readWikiLink$1(e,t){WIKI_LINK_RE$1.lastIndex=t;let n=WIKI_LINK_RE$1.exec(e);if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function extractWikiLinksFromLine(e){let t=``,n=[],r=leadingMarkdownPrefixLength$1(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=readInlineCode$1(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=readWikiLink$1(e,r);if(i){let e=getWikiLinkText(i),a=t.length;t+=e;let o=classifyWikiLinkTarget(i.target,i.anchor);o?.kind===`doc`&&n.push({target:o.docName,anchor:o.anchor,start:a,end:a+e.length}),r=i.nextIndex;continue}}t+=e[r],r++}return{text:t,occurrences:n}}function extractExternalWikiLinksFromLine(e){let t=``,n=[],r=leadingMarkdownPrefixLength$1(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=readInlineCode$1(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=readWikiLink$1(e,r);if(i){let e=getWikiLinkText(i),a=t.length;t+=e;let o=classifyWikiLinkTarget(i.target,i.anchor);o?.kind===`external`&&n.push({url:o.url,label:e,start:a,end:a+e.length}),r=i.nextIndex;continue}}t+=e[r],r++}return{text:t,occurrences:n}}function normalizeMarkdownHref$1(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function readMarkdownLink$1(e,t){MD_LINK_RE$1.lastIndex=t;let n=MD_LINK_RE$1.exec(e);return n?{text:n[1]??``,href:normalizeMarkdownHref$1(n[2]??``),nextIndex:t+n[0].length}:null}function extractMarkdownLinksFromLine(e,t){let n=``,r=[],i=leadingMarkdownPrefixLength$1(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=readInlineCode$1(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=readWikiLink$1(e,i);if(t){n+=getWikiLinkText(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=readMarkdownLink$1(e,i);if(a){let e=classifyMarkdownHref(a.href,t);if(e?.kind===`doc`){let t=n.length;n+=a.text,r.push({target:e.docName,anchor:e.anchor,start:t,end:t+a.text.length})}else n+=a.text;i=a.nextIndex;continue}}n+=e[i],i++}return{text:n,occurrences:r}}function extractExternalMarkdownLinksFromLine(e,t){let n=``,r=[],i=leadingMarkdownPrefixLength$1(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=readInlineCode$1(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=readWikiLink$1(e,i);if(t){n+=getWikiLinkText(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=readMarkdownLink$1(e,i);if(a){let e=classifyMarkdownHref(a.href,t);if(n+=a.text,e?.kind===`external`){let t=n.length-a.text.length;r.push({url:e.url,label:a.text||null,start:t,end:t+a.text.length})}i=a.nextIndex;continue}}n+=e[i],i++}return{text:n,occurrences:r}}function extractMarkdownLinksFromMarkdown(e,t){let n=e.replaceAll(`\r
|
|
56
56
|
`,`
|
|
@@ -78,7 +78,8 @@ To resolve the conflict:`,(0,r.getConflictResolutionRecipe)(i,e))),a=o):n.diag.w
|
|
|
78
78
|
`).trim()),i=[]):i.push(e)}if(i.length>0){let e=i.join(`
|
|
79
79
|
`).trim();e&&r.push(e)}return r}function reconcile(e){if(isSystemDoc(e.docName)||isConfigDoc(e.docName))return{kind:`noop`};let{base:t,ours:n,theirs:r}=e;return containsConflictMarkers(r)?{kind:`refused`,reason:`conflict-markers`}:r===t?{kind:`noop`}:n===t?{kind:`clean`,newContent:r}:mergeBlocks(splitMarkdownBlocks(t),splitMarkdownBlocks(n),splitMarkdownBlocks(r))}function mergeBlocks(e,t,n){let r=computeEditOps(e,t),i=computeEditOps(e,n),a=[],o=[];for(let t=0;t<e.length;t++){let n=e[t],s=r.get(t),c=i.get(t),l=s?.insertsBefore??[],u=c?.insertsBefore??[];a.push(...l,...u);let d=s?.action??`keep`,f=c?.action??`keep`;if(d===`keep`&&f===`keep`)a.push(n);else if(d===`keep`&&f!==`keep`)f===`modify`&&c?.newContent!==void 0&&a.push(c.newContent);else if(d!==`keep`&&f===`keep`)d===`modify`&&s?.newContent!==void 0&&a.push(s.newContent);else{let e=d===`modify`?s?.newContent:null,r=f===`modify`?c?.newContent:null;e===r||o.push({blockIndex:t,base:n,ours:e??``,theirs:r??``}),e!=null&&a.push(e)}}let s=r.get(e.length),c=i.get(e.length);s?.insertsBefore&&a.push(...s.insertsBefore),c?.insertsBefore&&a.push(...c.insertsBefore);let l=a.length>0?`${a.join(`
|
|
80
80
|
|
|
81
|
-
`)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function computeEditOps(e,t){let n=new Map,r=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function longestCommonSubsequence(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let a=1;a<=n;a++)for(let n=1;n<=r;n++)e[a-1]===t[n-1]?i[a][n]=i[a-1][n-1]+1:i[a][n]=Math.max(i[a-1][n],i[a][n-1]);let a=[],o=n,s=r;for(;o>0&&s>0;)e[o-1]===t[s-1]?(a.push([o-1,s-1]),o--,s--):i[o-1][s]>=i[o][s-1]?o--:s--;return a.reverse()}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let n=writeTracker.get(e)??[];n.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,n)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,n]of writeTracker){let r=n.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);r.length===0?writeTracker.delete(t):r.length!==n.length&&writeTracker.set(t,r)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function extractDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(isSupportedDocFile(r.path)){if(n){let e=relative(t,r.path);if(n.isExcluded(e))continue}switch(r.type){case`delete`:i.push(r);break;case`create`:lastKnownHash.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of o)try{c.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function l(e){let n=pathToDocName(e,t);if(!r)return n;let i=null;try{i=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=realpathSync(e)}catch(t){let i=t.code;return i!==`ENOENT`&&i!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),r.delete(n),n}if(!isWithinContentDir(a,t))return r.delete(n),n;let o=pathToDocName(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=removeLastKnownHash(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(r===void 0)continue;let i=contentHash(r);if(i===t){d.add(n.path),f.add(e.path),updateLastKnownHash(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||(removeLastKnownHash(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(t===void 0)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(t===void 0)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function isSelfWrite(e,t){let n=writeTracker.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,n,r,i,a){let o=a??new Set;try{let a=readdirSync(e,{withFileTypes:!0});for(let s of a){let a=join(e,s.name),c;try{c=lstatSync(a)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${a}, skipping:`,e);continue}if(c.isSymbolicLink()){let e;try{e=realpathSync(a)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${a}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${a}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${a} → ${e}, skipping`);continue}try{let c=statSync(e);if(o.has(c.ino)){if(c.isFile()&&isSupportedDocFile(s.name)){let n=pathToDocName(a,t),o=pathToDocName(e,t);i.set(n,o);let s=r.get(o);s&&!s.aliases.includes(n)&&s.aliases.push(n)}continue}if(o.add(c.ino),c.isDirectory()){if(n){let r=relative(t,e);if(n.isDirExcluded(r))continue}seedLastKnownHashes(e,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(n){let r=relative(t,e);if(n.isExcluded(r))continue}let o=pathToDocName(a,t),s=pathToDocName(e,t);i.set(o,s);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let n=extractDocExtension(e);if(n){let e=registerDocExtension(s,n);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(s,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:e,inode:c.ino,aliases:[o]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(c.isDirectory()){if(n){let e=relative(t,a);if(n.isDirExcluded(e))continue}seedLastKnownHashes(a,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(o.has(c.ino))continue;if(o.add(c.ino),n){let e=relative(t,a);if(n.isExcluded(e))continue}try{let e=readFileSync(a,`utf-8`);lastKnownHash.set(a,contentHash(e));let n=pathToDocName(a,t),i=extractDocExtension(a);if(i){let e=registerDocExtension(n,i);if(e.shadowed&&(console.warn(`[file-watcher] docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:a,inode:c.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${a}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${a}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(e.kind===`asset-create`||e.kind===`asset-delete`)return;let n=e.kind===`rename`?e.newDocName:e.docName;if(!(isSystemDoc(n)||isConfigDoc(n)))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=extractDocExtension(e.path);i&®isterDocExtension(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let r=extractDocExtension(e.newPath);r&®isterDocExtension(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[]});break}}}async function handleRawEvents(e,t,n,r,i,a){let o=e.filter(e=>isSupportedDocFile(e.path)),s=e.filter(e=>isSupportedAssetFile(e.path,ASSET_EXTENSIONS));if(o.length===0&&s.length===0)return;let c=o.length>0?await classifyEvents(o,t,n,a):[];for(let e of c){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=contentHash(e.content),r=e.path;try{r=realpathSync(e.path)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${n})`)}t=isSelfWrite(r,n)}else if(e.kind===`rename`){let n=contentHash(e.content),r=e.newPath;try{r=realpathSync(e.newPath)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=isSelfWrite(r,n)}if(updateFileIndex(e,r),n&&!t)switch(e.kind){case`create`:n.incrementMdDir(dirname(e.docName));break;case`delete`:n.decrementMdDir(dirname(e.docName));break;case`rename`:n.decrementMdDir(dirname(e.oldDocName)),n.incrementMdDir(dirname(e.newDocName));break}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let a=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(a),"disk.path.role":classifyFsPath(a)}},async()=>i(e))}for(let e of s){if(n){let r=relative(t,e.path);if(n.isExcluded(r))continue}let r=relative(t,e.path);await i(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:r}:{kind:`asset-create`,path:e.path,relativePath:r})}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,n,r,i){let a;try{a=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let o=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await a.subscribe(e,async(a,o)=>{if(a){console.error(`[file-watcher]`,a);return}try{await handleRawEvents(o.map(e=>({type:e.type,path:e.path})),e,t,n,r,i)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},o)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,n,r,i){let{watch:a}=await import(`./chokidar-DjlCoHHX.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let o=a(e,{ignoreInitial:!0,ignored:t?(n,r)=>{let i=relative(e,n);return i===``||i===`.`?!1:r?.isDirectory()?t.isDirExcluded(i):t.isExcluded(i)}:void 0});o.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let s=50,c=[],l=null;function u(a,o){c.push({type:a,path:o}),l||=setTimeout(()=>{let a=c;c=[],l=null,handleRawEvents(a,e,t,n,r,i).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return o.on(`add`,e=>u(`create`,e)),o.on(`change`,e=>u(`update`,e)),o.on(`unlink`,e=>u(`delete`,e)),{unsubscribe:()=>(l&&(clearTimeout(l),l=null,c=[]),o.close())}}async function startWatcher(e,t,n){let r;try{r=realpathSync(e)}catch{r=e}let i=new Map,a=new Map;seedLastKnownHashes(r,r,n,i,a);let o=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),s,c;try{let e=await startParcelWatcher(r,n,i,t,a);e?(s=e,c=`parcel`):(s=await startChokidarWatcher(r,n,i,t,a),c=`chokidar`)}catch(e){throw clearInterval(o),e}let l=s.unsubscribe.bind(s);return console.log(`[file-watcher] Watching ${r} for external .md changes (backend: ${c})`),{async unsubscribe(){return clearInterval(o),writeTracker.clear(),lastKnownHash.clear(),l()},getFileIndex(){return i},getAliasMap(){return a}}}const defaultGitConfigReader=(e,t,n)=>{let r=spawnSync(`git`,[`config`,n===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return r.status!==0||!r.stdout?null:r.stdout.trim()||null};async function resolveGitIdentity(e,t,n,r=defaultGitConfigReader){let i=r(e,`user.name`,`local`),a=r(e,`user.email`,`local`);if(i&&a)return{name:i,email:a};let o=r(e,`user.name`,`global`),s=r(e,`user.email`,`global`);if(o&&s)return{name:o,email:s};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function writeGitIdentity(e,t,n){let r=(t,n)=>{let r=spawnSync(`git`,[`config`,`--local`,t,n],{cwd:e,encoding:`utf-8`,timeout:5e3});if(r.status!==0){let e=r.stderr?.trim()??``;throw Error(`git config --local ${t} failed: ${e}`)}};r(`user.name`,t),r(`user.email`,n)}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function isSafeLocalPath(e){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let t=homedir(),n=resolve(expandTilde(e));return n===t||n.startsWith(`${t}/`)}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,n){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(n(t,403,{ok:!1,error:`Forbidden: invalid origin for local-op endpoint`}),!1):(n(t,403,{ok:!1,error:`Forbidden: local-op endpoints require loopback connection`}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function isLoopbackAddress(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function isAllowedWorkspaceHostHeader(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}const MANAGED_RENAME_JOURNAL_FILENAME=`managed-rename.json`;function journalDir(e){return resolve(e,`.ok`)}function managedRenameJournalPath(e){return resolve(journalDir(e),MANAGED_RENAME_JOURNAL_FILENAME)}function createManagedRenameRecoveryJournal(e){return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:e.affectedDocs,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots}}function isManagedRenameSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function isManagedRenameAffectedDoc(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.from==`string`&&typeof t.to==`string`}function parseV2(e){if(typeof e.fromPath!=`string`||e.fromPath.length===0)throw Error(`Managed rename journal v2 is missing fromPath`);if(typeof e.toPath!=`string`||e.toPath.length===0)throw Error(`Managed rename journal v2 is missing toPath`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v2 is missing createdAt`);if(!Array.isArray(e.affectedDocs)||e.affectedDocs.length===0||!e.affectedDocs.every(isManagedRenameAffectedDoc))throw Error(`Managed rename journal v2 has invalid affectedDocs`);if(!Array.isArray(e.snapshots)||e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v2 has invalid snapshots`);for(let t of e.affectedDocs)if(!e.snapshots.some(e=>e.docName===t.from))throw Error(`Managed rename journal v2 is missing snapshot for affected doc: ${t.from}`);return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:e.affectedDocs,createdAt:e.createdAt,snapshots:e.snapshots}}function parseV1(e){if(typeof e.sourceDocName!=`string`||e.sourceDocName.length===0)throw Error(`Managed rename journal v1 is missing sourceDocName`);if(typeof e.destinationDocName!=`string`||e.destinationDocName.length===0)throw Error(`Managed rename journal v1 is missing destinationDocName`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v1 is missing createdAt`);if(!Array.isArray(e.snapshots)||e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v1 has invalid snapshots`);if(!e.snapshots.some(t=>t.docName===e.sourceDocName))throw Error(`Managed rename journal v1 must include the source document snapshot`);return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt,snapshots:e.snapshots}}function parseManagedRenameRecoveryJournal(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version===2)return parseV2(t);if(t.version===1)return parseV1(t);throw Error(`Unsupported managed rename journal version: ${String(t.version)}`)}function readManagedRenameJournal(e){let t=managedRenameJournalPath(e);if(!existsSync(t))return null;try{let e=readFileSync(t,`utf-8`);return parseManagedRenameRecoveryJournal(JSON.parse(e))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function writeManagedRenameJournal(e,t){let n=managedRenameJournalPath(e);tracedMkdirSync(dirname(n),{recursive:!0});let r=`${n}.tmp`;tracedWriteFileSync(r,JSON.stringify(t,null,2),`utf-8`),tracedRenameSync(r,n)}function clearManagedRenameJournal(e){tracedRmSync(managedRenameJournalPath(e),{force:!0})}async function withManagedRenameRecovery(e,t,n){writeManagedRenameJournal(e,t);let r=await n();return clearManagedRenameJournal(e),r}function destinationsToCleanV1(e){return[e.destinationDocName]}function destinationsToCleanV2(e){return e.affectedDocs.map(e=>e.to)}function pruneEmptyAncestors(e,t){let n=resolve(t),r=`${n}${sep}`,i=dirname(e);for(;i.startsWith(r)&&i!==n;){let e;try{e=readdirSync(i)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot read ${i}:`,e);return}if(e.length>0)return;try{tracedRmdirSync(i)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot rmdir ${i}:`,e);return}i=dirname(i)}}function recoverPendingManagedRename(e){let t=readManagedRenameJournal(e);if(!t)return{recovered:!1,journal:null,restoredDocNames:[]};let n=new Set,r=[];for(let i of t.snapshots)try{let t=safeContentPath(i.docName,e);tracedMkdirSync(dirname(t),{recursive:!0}),tracedWriteFileSync(t,i.content,`utf-8`),n.add(i.docName)}catch(e){r.push({docName:i.docName,cause:e}),console.warn(`[managed-rename] Failed to restore ${i.docName}:`,e)}if(r.length>0){let e=r.map(e=>e.docName).join(`, `);console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${e})`);let t=r.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to restore: ${e}`)}let i=t.version===2?destinationsToCleanV2(t):destinationsToCleanV1(t),a=[];for(let t of i){if(n.has(t))continue;let r=safeContentPath(t,e);try{tracedRmSync(r,{force:!0}),pruneEmptyAncestors(r,e)}catch(e){existsSync(r)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t}:`,e),a.push({destination:t,cause:e})}}if(a.length>0){let e=a.map(e=>e.destination).join(`, `),t=a.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to clean destinations: ${e}`)}return clearManagedRenameJournal(e),{recovered:!0,journal:t,restoredDocNames:[...n].sort((e,t)=>e.localeCompare(t))}}const STARTER_FOLDERS=[{path:`external-sources`,match:`external-sources/**`,title:`External Sources`,description:"Raw sources SAVED verbatim — not just cited. The actual fetched text of URLs, extracted text of PDFs, and copies of any referenced files live as .md files here, each with frontmatter carrying the original URL, access date, and any publisher / author metadata. Produced by `ingest` — applies whether the user shared the URL OR the agent fetched it itself to ground a knowledge-base claim. The KB is closed-loop: downstream docs cite local paths in this folder, never bare web URLs. Immutable after capture (update only to refresh a stale fetch). No analysis in these files — that belongs in `research/`. Downstream articles cite specific docs here by path so every claim is traceable to preserved evidence rather than a dead link.",tags:[`source`,`immutable`,`layer-ingest`]},{path:`research`,match:`research/**`,title:`Research`,description:"Provisional analysis synthesizing external sources. Produced by the `research` tool. Every factual claim cites a specific doc in `external-sources/` (or an inline URL if ingest was skipped) — no unsourced assertions. Each article has `status: provisional` and a `sources:` frontmatter list of cited paths. Promoted to `articles/` via `consolidate` once the team decides the findings are stable.",tags:[`research`,`provisional`,`layer-research`]},{path:`articles`,match:`articles/**`,title:`Articles`,description:"Canonical knowledge committed after a team decision. Produced by `consolidate`. Carries `status: canonical` plus a `supersedes:` chain tying back to the `research/` docs it replaces, which in turn cite `external-sources/` — the full evidence chain is traceable without leaving the repo. Source-of-truth for the domain; update only when a new decision supersedes it.",tags:[`article`,`canonical`,`layer-consolidate`]}],LOG_MD_TEMPLATE=`---
|
|
81
|
+
`)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function computeEditOps(e,t){let n=new Map,r=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function longestCommonSubsequence(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let a=1;a<=n;a++)for(let n=1;n<=r;n++)e[a-1]===t[n-1]?i[a][n]=i[a-1][n-1]+1:i[a][n]=Math.max(i[a-1][n],i[a][n-1]);let a=[],o=n,s=r;for(;o>0&&s>0;)e[o-1]===t[s-1]?(a.push([o-1,s-1]),o--,s--):i[o-1][s]>=i[o][s-1]?o--:s--;return a.reverse()}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let n=writeTracker.get(e)??[];n.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,n)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,n]of writeTracker){let r=n.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);r.length===0?writeTracker.delete(t):r.length!==n.length&&writeTracker.set(t,r)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function extractDocExtension(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(isSupportedDocFile(r.path)){if(n){let e=relative(t,r.path);if(n.isExcluded(e))continue}switch(r.type){case`delete`:i.push(r);break;case`create`:lastKnownHash.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of o)try{c.set(e.path,await readFile(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function l(e){let n=pathToDocName(e,t);if(!r)return n;let i=null;try{i=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=realpathSync(e)}catch(t){let i=t.code;return i!==`ENOENT`&&i!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),r.delete(n),n}if(!isWithinContentDir(a,t))return r.delete(n),n;let o=pathToDocName(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=removeLastKnownHash(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(r===void 0)continue;let i=contentHash(r);if(i===t){d.add(n.path),f.add(e.path),updateLastKnownHash(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||(removeLastKnownHash(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(t===void 0)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(t===void 0)continue;let n=contentHash(t);updateLastKnownHash(e.path,n),containsConflictMarkers(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function isSelfWrite(e,t){let n=writeTracker.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,n,r,i,a){let o=a??new Set;try{let a=readdirSync(e,{withFileTypes:!0});for(let s of a){let a=join(e,s.name),c;try{c=lstatSync(a)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${a}, skipping:`,e);continue}if(c.isSymbolicLink()){let e;try{e=realpathSync(a)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${a}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${a}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${a} → ${e}, skipping`);continue}try{let c=statSync(e);if(o.has(c.ino)){if(c.isFile()&&isSupportedDocFile(s.name)){let n=pathToDocName(a,t),o=pathToDocName(e,t);i.set(n,o);let s=r.get(o);s&&!s.aliases.includes(n)&&s.aliases.push(n)}continue}if(o.add(c.ino),c.isDirectory()){if(n){let r=relative(t,e);if(n.isDirExcluded(r))continue}seedLastKnownHashes(e,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(n){let r=relative(t,e);if(n.isExcluded(r))continue}let o=pathToDocName(a,t),s=pathToDocName(e,t);i.set(o,s);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let n=extractDocExtension(e);if(n){let e=registerDocExtension(s,n);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(s,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:e,inode:c.ino,aliases:[o]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(c.isDirectory()){if(n){let e=relative(t,a);if(n.isDirExcluded(e))continue}seedLastKnownHashes(a,t,n,r,i,o)}else if(c.isFile()&&isSupportedDocFile(s.name)){if(o.has(c.ino))continue;if(o.add(c.ino),n){let e=relative(t,a);if(n.isExcluded(e))continue}try{let e=readFileSync(a,`utf-8`);lastKnownHash.set(a,contentHash(e));let n=pathToDocName(a,t),i=extractDocExtension(a);if(i){let e=registerDocExtension(n,i);if(e.shadowed&&(console.warn(`[file-watcher] docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:a,inode:c.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${a}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${a}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(e.kind===`asset-create`||e.kind===`asset-delete`)return;let n=e.kind===`rename`?e.newDocName:e.docName;if(!(isSystemDoc(n)||isConfigDoc(n)))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=extractDocExtension(e.path);i&®isterDocExtension(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let r=extractDocExtension(e.newPath);r&®isterDocExtension(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[]});break}}}async function handleRawEvents(e,t,n,r,i,a){let o=e.filter(e=>isSupportedDocFile(e.path)),s=e.filter(e=>isSupportedAssetFile(e.path,ASSET_EXTENSIONS));if(o.length===0&&s.length===0)return;let c=o.length>0?await classifyEvents(o,t,n,a):[];for(let e of c){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=contentHash(e.content),r=e.path;try{r=realpathSync(e.path)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${n})`)}t=isSelfWrite(r,n)}else if(e.kind===`rename`){let n=contentHash(e.content),r=e.newPath;try{r=realpathSync(e.newPath)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=isSelfWrite(r,n)}if(updateFileIndex(e,r),n&&!t)switch(e.kind){case`create`:n.incrementMdDir(dirname(e.docName));break;case`delete`:n.decrementMdDir(dirname(e.docName));break;case`rename`:n.decrementMdDir(dirname(e.oldDocName)),n.incrementMdDir(dirname(e.newDocName));break}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let a=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(a),"disk.path.role":classifyFsPath(a)}},async()=>i(e))}for(let e of s){if(n){let r=relative(t,e.path);if(n.isExcluded(r))continue}let r=relative(t,e.path);await i(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:r}:{kind:`asset-create`,path:e.path,relativePath:r})}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,n,r,i){let a;try{a=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let o=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await a.subscribe(e,async(a,o)=>{if(a){console.error(`[file-watcher]`,a);return}try{await handleRawEvents(o.map(e=>({type:e.type,path:e.path})),e,t,n,r,i)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},o)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,n,r,i){let{watch:a}=await import(`./chokidar-DjlCoHHX.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let o=a(e,{ignoreInitial:!0,ignored:t?(n,r)=>{let i=relative(e,n);return i===``||i===`.`?!1:r?.isDirectory()?t.isDirExcluded(i):t.isExcluded(i)}:void 0});o.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let s=50,c=[],l=null;function u(a,o){c.push({type:a,path:o}),l||=setTimeout(()=>{let a=c;c=[],l=null,handleRawEvents(a,e,t,n,r,i).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return o.on(`add`,e=>u(`create`,e)),o.on(`change`,e=>u(`update`,e)),o.on(`unlink`,e=>u(`delete`,e)),{unsubscribe:()=>(l&&(clearTimeout(l),l=null,c=[]),o.close())}}async function startWatcher(e,t,n){let r;try{r=realpathSync(e)}catch{r=e}let i=new Map,a=new Map;seedLastKnownHashes(r,r,n,i,a);let o=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),s,c;try{let e=await startParcelWatcher(r,n,i,t,a);e?(s=e,c=`parcel`):(s=await startChokidarWatcher(r,n,i,t,a),c=`chokidar`)}catch(e){throw clearInterval(o),e}let l=s.unsubscribe.bind(s);return console.log(`[file-watcher] Watching ${r} for external .md changes (backend: ${c})`),{async unsubscribe(){return clearInterval(o),writeTracker.clear(),lastKnownHash.clear(),l()},getFileIndex(){return i},getAliasMap(){return a}}}const defaultGitConfigReader=(e,t,n)=>{let r=spawnSync(`git`,[`config`,n===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return r.status!==0||!r.stdout?null:r.stdout.trim()||null};async function resolveGitIdentity(e,t,n,r=defaultGitConfigReader){let i=r(e,`user.name`,`local`),a=r(e,`user.email`,`local`);if(i&&a)return{name:i,email:a};let o=r(e,`user.name`,`global`),s=r(e,`user.email`,`global`);if(o&&s)return{name:o,email:s};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function writeGitIdentity(e,t,n){let r=(t,n)=>{let r=spawnSync(`git`,[`config`,`--local`,t,n],{cwd:e,encoding:`utf-8`,timeout:5e3});if(r.status!==0){let e=r.stderr?.trim()??``;throw Error(`git config --local ${t} failed: ${e}`)}};r(`user.name`,t),r(`user.email`,n)}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function isSafeLocalPath(e){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let t=homedir(),n=resolve(expandTilde(e));return n===t||n.startsWith(`${t}/`)}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,n){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(n(t,403,{ok:!1,error:`Forbidden: invalid origin for local-op endpoint`}),!1):(n(t,403,{ok:!1,error:`Forbidden: local-op endpoints require loopback connection`}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function runSubprocess(e){let[t,...n]=e.cliArgs;if(!t)return{done:Promise.resolve({code:-1,stderr:`no command provided`,timedOut:!1,cancelled:!1}),cancel:()=>{}};let r=[...n,...e.trailingArgs],i=!1,a=!1,o=``,s=[],c=spawn(t,r,{cwd:e.cwd,stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),l=setTimeout(()=>{i=!0,c.kill(`SIGTERM`)},e.timeoutMs),u=t=>{if(!t.trim())return;let n=null;try{let e=JSON.parse(t);n=e&&typeof e==`object`?e:null}catch{n=null}e.onLine({raw:t,parsed:n})};return c.stdout.on(`data`,e=>{o+=e.toString(`utf-8`);let t=o.split(`
|
|
82
|
+
`);o=t.pop()??``;for(let e of t)u(e)}),c.stderr.on(`data`,t=>{s.push(t),e.onStderr?.(t)}),{done:new Promise(e=>{c.on(`close`,t=>{clearTimeout(l),o.trim()&&u(o),o=``,e({code:t,stderr:Buffer.concat(s).toString(`utf-8`).trim(),timedOut:i,cancelled:a})}),c.on(`error`,t=>{clearTimeout(l),s.push(Buffer.from(t.message,`utf-8`)),e({code:-1,stderr:Buffer.concat(s).toString(`utf-8`).trim(),timedOut:i,cancelled:a})})}),cancel:()=>{if(!a&&(a=!0,!c.killed))try{c.kill(`SIGTERM`)}catch{}}}}const DEFAULT_TIMEOUT_MS$2=600*1e3;function asAuthEvent(e){let t=e.type;return t===`verification`?typeof e.user_code==`string`&&typeof e.verification_uri==`string`&&typeof e.expires_in==`number`?{type:`verification`,user_code:e.user_code,verification_uri:e.verification_uri,expires_in:e.expires_in}:null:t===`complete`?{type:`complete`,host:typeof e.host==`string`?e.host:``,login:typeof e.login==`string`?e.login:``,name:typeof e.name==`string`?e.name:void 0,email:typeof e.email==`string`?e.email:void 0,avatarUrl:typeof e.avatarUrl==`string`?e.avatarUrl:void 0}:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function runDeviceFlowSubprocess(e){let t=e.host??`github.com`,n=e.timeoutMs??DEFAULT_TIMEOUT_MS$2,r=!1,i=runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`login`,`--json`,`--host`,t],timeoutMs:n,onLine:({parsed:t})=>{if(!t)return;let n=asAuthEvent(t);n&&((n.type===`complete`||n.type===`error`)&&(r=!0),e.onEvent(n))}});return{done:i.done.then(n=>{r||(n.code===0?e.onEvent({type:`complete`,host:t,login:``}):e.onEvent({type:`error`,message:n.timedOut?`Sign-in timed out`:`auth login exited with code ${n.code??-1}`}))}),cancel:i.cancel}}const DEFAULT_TIMEOUT_MS=600*1e3;function asRawCloneEvent(e){let t=e.type;return t===`progress`?typeof e.phase==`string`&&typeof e.pct==`number`?{type:`progress`,phase:e.phase,pct:e.pct}:null:t===`complete`?typeof e.dir==`string`?{type:`complete`,dir:e.dir}:null:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function runCloneSubprocess(e){let t=expandTilde(e.dir),n=e.timeoutMs??DEFAULT_TIMEOUT_MS,r=!1,i=runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`clone`,`--json`,e.url,t],timeoutMs:n,onLine:({parsed:t})=>{if(!t)return;let n=asRawCloneEvent(t);n&&((n.type===`complete`||n.type===`error`)&&(r=!0),e.onEvent(n))}});return{done:i.done.then(n=>{if(!r){if(n.timedOut){e.onEvent({type:`error`,message:`Clone timed out after 10 minutes`});return}if(n.code!==0){let t=n.stderr?` — ${n.stderr}`:``;e.onEvent({type:`error`,message:`Clone process exited with code ${n.code??-1}${t}`});return}e.onEvent({type:`complete`,dir:t})}}),cancel:i.cancel}}function isLoopbackAddress(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function isAllowedWorkspaceHostHeader(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}const MANAGED_RENAME_JOURNAL_FILENAME=`managed-rename.json`;function journalDir(e){return resolve(e,`.ok`)}function managedRenameJournalPath(e){return resolve(journalDir(e),MANAGED_RENAME_JOURNAL_FILENAME)}function createManagedRenameRecoveryJournal(e){return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:e.affectedDocs,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots}}function isManagedRenameSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function isManagedRenameAffectedDoc(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.from==`string`&&typeof t.to==`string`}function parseV2(e){if(typeof e.fromPath!=`string`||e.fromPath.length===0)throw Error(`Managed rename journal v2 is missing fromPath`);if(typeof e.toPath!=`string`||e.toPath.length===0)throw Error(`Managed rename journal v2 is missing toPath`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v2 is missing createdAt`);if(!Array.isArray(e.affectedDocs)||e.affectedDocs.length===0||!e.affectedDocs.every(isManagedRenameAffectedDoc))throw Error(`Managed rename journal v2 has invalid affectedDocs`);if(!Array.isArray(e.snapshots)||e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v2 has invalid snapshots`);for(let t of e.affectedDocs)if(!e.snapshots.some(e=>e.docName===t.from))throw Error(`Managed rename journal v2 is missing snapshot for affected doc: ${t.from}`);return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:e.affectedDocs,createdAt:e.createdAt,snapshots:e.snapshots}}function parseV1(e){if(typeof e.sourceDocName!=`string`||e.sourceDocName.length===0)throw Error(`Managed rename journal v1 is missing sourceDocName`);if(typeof e.destinationDocName!=`string`||e.destinationDocName.length===0)throw Error(`Managed rename journal v1 is missing destinationDocName`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v1 is missing createdAt`);if(!Array.isArray(e.snapshots)||e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v1 has invalid snapshots`);if(!e.snapshots.some(t=>t.docName===e.sourceDocName))throw Error(`Managed rename journal v1 must include the source document snapshot`);return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt,snapshots:e.snapshots}}function parseManagedRenameRecoveryJournal(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version===2)return parseV2(t);if(t.version===1)return parseV1(t);throw Error(`Unsupported managed rename journal version: ${String(t.version)}`)}function readManagedRenameJournal(e){let t=managedRenameJournalPath(e);if(!existsSync(t))return null;try{let e=readFileSync(t,`utf-8`);return parseManagedRenameRecoveryJournal(JSON.parse(e))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function writeManagedRenameJournal(e,t){let n=managedRenameJournalPath(e);tracedMkdirSync(dirname(n),{recursive:!0});let r=`${n}.tmp`;tracedWriteFileSync(r,JSON.stringify(t,null,2),`utf-8`),tracedRenameSync(r,n)}function clearManagedRenameJournal(e){tracedRmSync(managedRenameJournalPath(e),{force:!0})}async function withManagedRenameRecovery(e,t,n){writeManagedRenameJournal(e,t);let r=await n();return clearManagedRenameJournal(e),r}function destinationsToCleanV1(e){return[e.destinationDocName]}function destinationsToCleanV2(e){return e.affectedDocs.map(e=>e.to)}function pruneEmptyAncestors(e,t){let n=resolve(t),r=`${n}${sep}`,i=dirname(e);for(;i.startsWith(r)&&i!==n;){let e;try{e=readdirSync(i)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot read ${i}:`,e);return}if(e.length>0)return;try{tracedRmdirSync(i)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot rmdir ${i}:`,e);return}i=dirname(i)}}function recoverPendingManagedRename(e){let t=readManagedRenameJournal(e);if(!t)return{recovered:!1,journal:null,restoredDocNames:[]};let n=new Set,r=[];for(let i of t.snapshots)try{let t=safeContentPath(i.docName,e);tracedMkdirSync(dirname(t),{recursive:!0}),tracedWriteFileSync(t,i.content,`utf-8`),n.add(i.docName)}catch(e){r.push({docName:i.docName,cause:e}),console.warn(`[managed-rename] Failed to restore ${i.docName}:`,e)}if(r.length>0){let e=r.map(e=>e.docName).join(`, `);console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${e})`);let t=r.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to restore: ${e}`)}let i=t.version===2?destinationsToCleanV2(t):destinationsToCleanV1(t),a=[];for(let t of i){if(n.has(t))continue;let r=safeContentPath(t,e);try{tracedRmSync(r,{force:!0}),pruneEmptyAncestors(r,e)}catch(e){existsSync(r)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t}:`,e),a.push({destination:t,cause:e})}}if(a.length>0){let e=a.map(e=>e.destination).join(`, `),t=a.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to clean destinations: ${e}`)}return clearManagedRenameJournal(e),{recovered:!0,journal:t,restoredDocNames:[...n].sort((e,t)=>e.localeCompare(t))}}const STARTER_FOLDERS=[{path:`external-sources`,match:`external-sources/**`,title:`External Sources`,description:"Raw sources SAVED verbatim — not just cited. The actual fetched text of URLs, extracted text of PDFs, and copies of any referenced files live as .md files here, each with frontmatter carrying the original URL, access date, and any publisher / author metadata. Produced by `ingest` — applies whether the user shared the URL OR the agent fetched it itself to ground a knowledge-base claim. The KB is closed-loop: downstream docs cite local paths in this folder, never bare web URLs. Immutable after capture (update only to refresh a stale fetch). No analysis in these files — that belongs in `research/`. Downstream articles cite specific docs here by path so every claim is traceable to preserved evidence rather than a dead link.",tags:[`source`,`immutable`,`layer-ingest`]},{path:`research`,match:`research/**`,title:`Research`,description:"Provisional analysis synthesizing external sources. Produced by the `research` tool. Every factual claim cites a specific doc in `external-sources/` (or an inline URL if ingest was skipped) — no unsourced assertions. Each article has `status: provisional` and a `sources:` frontmatter list of cited paths. Promoted to `articles/` via `consolidate` once the team decides the findings are stable.",tags:[`research`,`provisional`,`layer-research`]},{path:`articles`,match:`articles/**`,title:`Articles`,description:"Canonical knowledge committed after a team decision. Produced by `consolidate`. Carries `status: canonical` plus a `supersedes:` chain tying back to the `research/` docs it replaces, which in turn cite `external-sources/` — the full evidence chain is traceable without leaving the repo. Source-of-truth for the domain; update only when a new decision supersedes it.",tags:[`article`,`canonical`,`layer-consolidate`]}],LOG_MD_TEMPLATE=`---
|
|
82
83
|
title: Work Log
|
|
83
84
|
description: Append-only audit trail. After each turn that creates, edits, or restructures content in the knowledge base, append one dated entry here (one per turn, not per file). Silent edits break the audit trail.
|
|
84
85
|
---
|
|
@@ -124,9 +125,7 @@ What to log:
|
|
|
124
125
|
`)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=getHeadingSlug(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}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}}function createApiExtension(e){let{hocuspocus:t,sessionManager:n,contentDir:r,serverInstanceId:i,getFileIndex:a,getAliasMap:o,enableTestRoutes:s=!1,shadowRef:c,flushGitCommit:l,getCurrentBranch:u,getDiskAckSVs:d,contentRoot:f,backlinkIndex:p,signalChannel:m,agentFocusBroadcaster:h,agentPresenceBroadcaster:g,onAgentWrite:_,getSyncEngine:v,localOpCliArgs:y=[`open-knowledge`],projectDir:b,getPrincipal:x,contentFilter:S,installedAgentsProbe:C,forceUnloadDocument:w}=e,T=createConcurrencyGuard(),E=createInstalledAgentsProbe({probe:C??createOsProbe(process.platform)});function D(e){if(!isSafeDocName(e))return null;let t=resolve(r),n=resolve(t,`${e}${getDocExtension(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function O(e){let t=D(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}let k={cluster:void 0,category:void 0,tags:void 0};function A(e){try{let n=t.documents.get(e);if(n){let e=readFmMap(n.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,n=typeof e.category==`string`?e.category:void 0,r;return Array.isArray(e.tags)?r=e.tags.length>0?e.tags:void 0:typeof e.tags==`string`&&e.tags&&(r=[e.tags]),{cluster:t,category:n,tags:r}}}}catch{}try{let t=D(e);if(!t||!existsSync(t))return k;let{frontmatter:n}=stripFrontmatter(readFileSync(t,`utf-8`));return n?parseFrontmatterMetadata(n):k}catch{return k}}function j(e){if(p)try{if(p.getBacklinks(e).length>0)return;let t=performance.now(),n=findHubCandidates(e,a()),r=performance.now()-t;return r>5&&log$2.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,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): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function M(e){return o?.().get(e)??e}function N(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function P(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function F(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>l?.()).catch(e=>{log$2.warn({err:e},`[${n}] post-write flush failed`)})}function I(){let e=new Set;for(let[t,n]of a()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function L(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let R=L();function z(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,error:e.message}:e instanceof ManagedRenameDestinationExistsError?{status:409,error:e.message}:e instanceof ManagedRenameSourceTypeMismatchError?{status:400,error:e.message}:e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`Cannot snapshot missing document:`)?{status:404,error:e.message}:e.message.startsWith(`symlink-escape:`)?{status:400,error:e.message}:e.message===`Managed rename requires backlink index support`?{status:503,error:e.message}:{status:500,error:`Failed to rename document`}:{status:500,error:`Failed to rename document`}}async function B(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);deleteReconciledBase(n),e&&(t.closeConnections(n),await(w??t.unloadDocument.bind(t))(e))}return r}function V(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=safeContentPath(i,r),a=t.get(n);typeof a==`string`&&tracedWriteFileSync(e,a,`utf-8`);let o=typeof a==`string`?a:existsSync(e)?readFileSync(e,`utf-8`):null;typeof o==`string`&®isterWrite(e,contentHash(o))}}function H(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=safeContentPath(e,r);if(!existsSync(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:readFileSync(i,`utf-8`)}})}function U(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=resolveContentEntryPath(r,`file`,e);return existsSync(i)?readFileSync(i,`utf-8`):null}function W(e,t){let n=resolveContentEntryPath(r,`file`,e);tracedMkdirSync(dirname(n),{recursive:!0}),tracedWriteFileSync(n,t,`utf-8`),registerWrite(n,contentHash(t)),setReconciledBase(e,t);let i=a();i instanceof Map&&updateFileIndex({kind:`update`,path:n,docName:e,content:t},i)}function G(n,r){let i=t.documents.get(n);if(!i)throw Error(`Document is not loaded: ${n}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=applyRenameMap(s,n,r),a.rewrites===0)return;let{body:c}=stripFrontmatter(a.markdown),l=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:n}:void 0,u=mdManager.parseWithFallback(c,l);updateYFragment(i,t,schema.nodeFromJSON(u),{mapping:new Map,isOMark:new Map}),applyFastDiff(o,s,a.markdown)},MANAGED_RENAME_ORIGIN),a}async function K(e,n,i){return R(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":i}},async o=>{if(!p)throw Error(`Managed rename requires backlink index support`);let s=resolveContentEntryPath(r,i,e),c=resolveContentEntryPath(r,i,n);if(s===c)return{renamed:[],rewrittenDocs:[]};if(!existsSync(s))throw new ManagedRenameSourceNotFoundError(i);if(existsSync(c))throw new ManagedRenameDestinationExistsError;let l=statSync(s);if(i===`file`&&!l.isFile()||i===`folder`&&!l.isDirectory())throw new ManagedRenameSourceTypeMismatchError(i);let u=(i===`file`?[stripDocExtension(e)]:listAffectedDocNames(a(),i,e)).map(t=>({from:t,to:i===`file`?stripDocExtension(n):remapDocNameForRename(t,i,e,n)}));if(o.setAttribute(`rename.affected_docs`,u.length),u.length===0)return{renamed:[],rewrittenDocs:[]};let d=buildRenameMap(u),f=u.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),h=new Set;for(let{from:e}of u)for(let t of p.getBacklinks(e))d.has(t.source)||h.add(t.source);let g=[...h].sort((e,t)=>e.localeCompare(t)),_=new Map,v=[],y=[];for(let e of[...d.keys(),...g]){if(_.has(e))continue;if(!d.has(e)&&!existsSync(resolveContentEntryPath(r,`file`,e))){y.push(e);continue}let t=U(e);typeof t==`string`?(_.set(e,t),d.has(e)||v.push(e)):d.has(e)||y.push(e)}for(let{from:e}of u)if(typeof _.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let x=createManagedRenameRecoveryJournal({fromPath:e,toPath:n,affectedDocs:[...u],snapshots:H([..._.keys()],_)}),S=[];return await withManagedRenameRecovery(r,x,async()=>{for(let e of y)p.deleteDocument(e);for(let e of v){let n=t.documents.get(e)?G(e,d):applyRenameMap(_.get(e)??``,e,d);n.rewrites>0&&(W(e,n.markdown),S.push({docName:e,rewrites:n.rewrites})),p.updateDocumentFromMarkdown(e,n.markdown)}let o=await B([...d.keys()]),s=resolveContentEntryPath(r,i,e),c=resolveContentEntryPath(r,i,n);await renameTrackedPathInGit(b,s,c)||(tracedMkdirSync(dirname(c),{recursive:!0}),tracedRenameSync(s,c));let l=i===`file`&&isSupportedDocFile(n)?extname(n).toLowerCase():null;for(let{from:e,to:t}of u){let n=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,l??n)}let f=[...u].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of f){let n=resolveContentEntryPath(r,`file`,e),i=resolveContentEntryPath(r,`file`,t),s=applyRenameMap(o.get(e)??_.get(e)??readFileSync(i,`utf-8`),e,d);V([{fromDocName:e,toDocName:t}],new Map([[e,s.markdown]])),setReconciledBase(t,s.markdown);let c=a();c instanceof Map&&updateFileIndex({kind:`rename`,oldPath:n,newPath:i,oldDocName:e,newDocName:t,content:s.markdown},c),p.renameDocument(e,t,s.markdown),s.rewrites>0&&S.push({docName:t,rewrites:s.rewrites})}}),p.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),m?.(`files`),m?.(`backlinks`),m?.(`graph`),S.sort((e,t)=>e.docName.localeCompare(t.docName)),o.setAttribute(`rename.rewrite_count`,S.length),{renamed:f,rewrittenDocs:S}}))}function q(e){let t=parseAgentBodyFields(e),n=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:n,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??n,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function ee(e){return{principalId:x?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function J(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 Y(e){return{value:e.value}}function X(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}async function Z(t,r){if(t.method!==`POST`){r.writeHead(405),r.end(`Method not allowed`);return}try{let i;try{i=await readBody(t)}catch{json(r,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{json(r,400,{ok:!1,error:`Invalid JSON`});return}let o=typeof a.docName==`string`&&a.docName.length>0?a.docName:`test-doc`;if(!isSafeDocName(o)){json(r,400,{ok:!1,error:`Invalid docName`});return}let s=M(o);if(isSystemDoc(s)||isConfigDoc(s)){json(r,400,{ok:!1,error:`'${s}' is a reserved document name`});return}let{agentId:c,agentName:l,colorSeed:u,clientName:d,clientVersion:f,label:p}=q(a),m=normalizeSummary(a.summary);if(m.kind===`invalid`){json(r,400,{ok:!1,error:`summary must be a string`});return}let h=await n.getSession(s,c,{displayName:l,colorSeed:u,clientName:d}),v=new Date().toISOString(),y=typeof a.content==`string`?a.content:`Hello from the agent! ${v}`,{response:b,stored:x}=J(m);try{let t=iconFromClientName(d),n=AGENT_ICON_COLORS[t]??colorFromSeed(u??c);g?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:s,mode:`writing`,ts:Date.now()}),captureEffect(h.dc.document.getText(`source`),c,u,d),h.dc.document.transact(()=>{applyAgentMarkdownWrite(h.dc.document,`${y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:s}:void 0),h.dc.document.getMap(`agent-flash`).set(c,{agentId:c,timestamp:Date.now(),type:`insert`,description:`Added (${l}): ${y.slice(0,50)}`})},h.origin),recordContributor(s,c,l,u,void 0,ee({clientName:d,clientVersion:f,label:p}),x),incrementAgentWriteCalls(),X(m)}finally{g?.touchMode(c,`idle`)}F(s,`agent-write`),_?.(),json(r,200,{ok:!0,timestamp:v,...b?{summary:b}:{}})}catch(e){log$2.error({err:e},`[agent-write] handler failed`),json(r,500,{ok:!1,error:`Internal server error`})}}async function te(t,r){if(t.method!==`POST`){r.writeHead(405),r.end(`Method not allowed`);return}try{let i;try{i=await readBody(t)}catch{json(r,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(i.toString())}catch{json(r,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(r,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:o,position:s}=a;if(!o||typeof o!=`string`){json(r,400,{ok:!1,error:`markdown field required`});return}let c=s===`prepend`?`prepend`:s===`replace`?`replace`:`append`,l=a.docName,u=typeof l==`string`&&l.length>0?l:`test-doc`;if(!isSafeDocName(u)){json(r,400,{ok:!1,error:`Invalid docName`});return}let d=M(u);if(isSystemDoc(d)||isConfigDoc(d)){json(r,400,{ok:!1,error:`'${d}' is a reserved document name`});return}let{agentId:f,agentName:p,colorSeed:m,clientName:v,clientVersion:y,label:b}=q(a),x=normalizeSummary(a.summary);if(x.kind===`invalid`){json(r,400,{ok:!1,error:`summary must be a string`});return}let{response:S,stored:C}=J(x),w=await n.getSession(d,f,{displayName:p,colorSeed:m,clientName:v}),T=new Date().toISOString();try{let t=iconFromClientName(v),n=AGENT_ICON_COLORS[t]??colorFromSeed(m??f);g?.setPresence(f,{displayName:p,icon:t,color:n,currentDoc:d,mode:`writing`,ts:Date.now()}),captureEffect(w.dc.document.getText(`source`),f,m,v),w.dc.document.transact(()=>{applyAgentMarkdownWrite(w.dc.document,o,c,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0),w.dc.document.getMap(`agent-flash`).set(f,{agentId:f,timestamp:Date.now(),type:`insert`,description:`Added (${p}): ${o.trim().slice(0,50)}`})},w.origin),recordContributor(d,f,p,m,void 0,ee({clientName:v,clientVersion:y,label:b}),C),incrementAgentWriteCalls(),X(x)}finally{g?.touchMode(f,`idle`)}F(d,`agent-write-md`),h?.setFocus(f,{agentName:p,currentDoc:d,writeKind:`write`,ts:Date.now()}),_?.();let E=j(d),D=N(d),O=P();O===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(v)}),json(r,200,{ok:!0,timestamp:T,subscriberCount:D,systemSubscriberCount:O,...E?{hints:E}:{},...S?{summary:S}:{}})}catch(e){log$2.error({err:e},`[agent-write-md] handler failed`),json(r,500,{ok:!1,error:`Internal server error`})}}async function ne(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}try{let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(i)){json(n,400,{ok:!1,error:`Invalid docName`});return}let a=M(i);if(isSystemDoc(a)||isConfigDoc(a)){json(n,400,{ok:!1,error:`'${a}' is a reserved document name`});return}let o=t.documents.get(a);if(o){json(n,200,{ok:!0,docName:a,content:o.getText(`source`).toString()});return}if(!existsSync(resolveContentEntryPath(r,`file`,a))){json(n,404,{ok:!1,error:`Document not found: ${a}`});return}let s=await t.openDirectConnection(a);try{let e=s.document;if(!e){json(n,500,{ok:!1,error:`Document not available`});return}json(n,200,{ok:!0,docName:a,content:e.getText(`source`).toString()})}finally{await s.disconnect()}}catch(e){console.error(`[document-read]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function Q(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{safeSubdir(r,n)}catch{json(t,400,{ok:!1,error:`Invalid directory parameter`});return}let i=a(),o=[];for(let[e,t]of i){if(n&&!e.startsWith(`${n}/`)&&e!==n)continue;let i=getDocExtension(e);o.push({docName:e,docExt:i,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let a of t.aliases){if(n&&!a.startsWith(`${n}/`)&&a!==n)continue;let s=relative(r,t.canonicalPath);o.push({docName:a,docExt:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:s})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function re(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,backlinks:p.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:O(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),json(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function ie(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){json(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(r[t]=p.getBacklinkCount(t))}json(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),json(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function ae(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,forwardLinks:p.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:O(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),json(t,500,{ok:!1,error:`Failed to read forward links`})}}async function oe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!isSafeDocName(r)){json(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){json(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){json(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=p.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=p.getLinkGraph());json(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=A(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:O(e.docName),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:o})}catch(e){console.error(`[link-graph]`,e),json(t,500,{ok:!1,error:`Failed to read link graph`})}}async function se(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(n)){json(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}json(t,200,{ok:!0,orphans:p.getOrphans([...a().keys()],n).map(e=>({docName:e,title:O(e)}))})}catch(e){console.error(`[orphans]`,e),json(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function ce(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;json(t,200,{ok:!0,hubs:p.getHubs(i).map(e=>({docName:e.docName,title:O(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),json(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function le(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!isSafeDocName(e))){json(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>M(e)))]:void 0;json(t,200,{ok:!0,deadLinks:p.getDeadLinks(I(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:O(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),json(t,500,{ok:!1,error:`Failed to read dead links`})}}async function ue(t,r){if(t.method!==`POST`){r.writeHead(405),r.end(`Method not allowed`);return}try{let i;try{i=await readBody(t)}catch{json(r,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(i.toString())}catch{json(r,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(r,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:o,replace:s,docName:c,offset:l}=a;if(typeof o!=`string`||o.length===0){json(r,400,{ok:!1,error:`find field required`});return}if(typeof s!=`string`){json(r,400,{ok:!1,error:`replace field required`});return}if(findLooksLikeFrontmatter(o)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),json(r,400,{ok:!1,error:`Frontmatter edits are not supported via edit_document. Frontmatter editing through MCP is currently unavailable; use write_document with position:"replace" to rewrite the document including its YAML block.`});return}let u=Object.hasOwn(a,`offset`),d;if(u){if(typeof l!=`number`||!Number.isInteger(l)||l<0){json(r,400,{ok:!1,error:`offset must be a non-negative integer`});return}d=l}let f=typeof c==`string`&&c.length>0?c:`test-doc`;if(!isSafeDocName(f)){json(r,400,{ok:!1,error:`Invalid docName`});return}let p=M(f);if(isSystemDoc(p)||isConfigDoc(p)){json(r,400,{ok:!1,error:`'${p}' is a reserved document name`});return}let{agentId:m,agentName:v,colorSeed:y,clientName:b,clientVersion:x,label:S}=q(a),C=normalizeSummary(a.summary);if(C.kind===`invalid`){json(r,400,{ok:!1,error:`summary must be a string`});return}let w=await n.getSession(p,m,{displayName:v,colorSeed:y,clientName:b}),T=new Date().toISOString(),E=!1,D=!1,O=!1;try{let t=iconFromClientName(b),n=AGENT_ICON_COLORS[t]??colorFromSeed(y??m);if(g?.setPresence(m,{displayName:v,icon:t,color:n,currentDoc:p,mode:`writing`,ts:Date.now()}),captureEffect(w.dc.document.getText(`source`),m,y,b),w.dc.document.transact(()=>{let t=w.dc.document.getXmlFragment(`default`),n=stripFrontmatter(w.dc.document.getText(`source`).toString()).frontmatter,r=prependFrontmatter(n,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(t,schema).toJSON())),i=d==null?r.indexOf(o):r.slice(d,d+o.length)===o?d:-1;if(i===-1){d==null?E=!0:D=!0;return}if(i<n.length){O=!0;return}let{body:a}=stripFrontmatter(r.slice(0,i)+s+r.slice(i+o.length));applyAgentMarkdownWrite(w.dc.document,a,`replace`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:p}:void 0),w.dc.document.getMap(`agent-flash`).set(m,{agentId:m,timestamp:Date.now(),type:`insert`,description:`Patched (${v}): ${o.slice(0,50)}`})},w.origin),!E&&!D&&!O){let{stored:e}=J(C);recordContributor(p,m,v,y,void 0,ee({clientName:b,clientVersion:x,label:S}),e),incrementAgentWriteCalls(),X(C)}}finally{g?.touchMode(m,`idle`)}if(D){json(r,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(E){json(r,404,{ok:!1,error:`Text not found in document`});return}if(O){agentPatchFmTouchCounter().add(1,{result:`rejected`}),json(r,400,{ok:!1,error:`Frontmatter edits are not supported via edit_document. Frontmatter editing through MCP is currently unavailable; use write_document with position:"replace" to rewrite the document including its YAML block.`});return}F(p,`agent-patch`),h?.setFocus(m,{agentName:v,currentDoc:p,writeKind:`edit`,ts:Date.now()}),_?.();let k=N(p),A=P();A===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(b)});let{response:j}=J(C);json(r,200,{ok:!0,timestamp:T,subscriberCount:k,systemSubscriberCount:A,...j?{summary:j}:{}})}catch(e){log$2.error({err:e},`[agent-patch] handler failed`),json(r,500,{ok:!1,error:`Internal server error`})}}async function de(t,r){if(t.method!==`POST`){r.writeHead(405),r.end(`Method not allowed`);return}try{let i;try{i=await readBody(t)}catch{json(r,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{json(r,400,{ok:!1,error:`Invalid JSON`});return}let{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=q(a),f=typeof a.docName==`string`&&a.docName.length>0?a.docName:`test-doc`;if(!isSafeDocName(f)){json(r,400,{ok:!1,error:`Invalid docName`});return}let p=M(f);if(isSystemDoc(p)||isConfigDoc(p)){json(r,400,{ok:!1,error:`'${p}' is a reserved document name`});return}let m=typeof a.connectionId==`string`?a.connectionId:void 0;if(!m){json(r,400,{ok:!1,error:`connectionId required`});return}let _=a.scope,v=_===`session`||_===`file`?`session`:`last`;if(!n.hasSession(p,m)){json(r,404,{ok:!1,error:`No active session for this connectionId and docName`});return}let y=await n.getSession(p,m),b=!1;try{let t=iconFromClientName(l),n=AGENT_ICON_COLORS[t]??colorFromSeed(c??o);g?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:p,mode:`writing`,ts:Date.now()}),b=applyAgentUndo(y,v,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:p}:void 0),b&&recordContributor(p,m,s,c,void 0,ee({clientName:l,clientVersion:u,label:d}))}finally{g?.touchMode(o,`idle`)}b&&F(p,`agent-undo`),h?.setFocus(m,{agentName:m,currentDoc:p,writeKind:`undo`,ts:Date.now()}),json(r,200,{ok:!0,docName:p,scope:v,undone:b})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),json(r,500,{ok:!1,error:`Internal server error`})}}async function fe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(r===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}json(t,200,{ok:!0,...listAgentActivity(n,r)})}catch(e){log$2.error({err:e},`[agent-activity] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function pe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=validateAgentId(r.searchParams.get(`agentId`)),a=r.searchParams.get(`docName`),o=r.searchParams.get(`stackIndex`);if(i===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}if(!a||a.trim()===``){json(t,400,{ok:!1,error:`docName required`});return}if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let s=M(a);if(isSystemDoc(s)||isConfigDoc(s)){json(t,400,{ok:!1,error:`'${s}' is a reserved document name`});return}if(!o||Number.isNaN(Number(o))){json(t,400,{ok:!1,error:`stackIndex must be a number`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`stackIndex must be a non-negative integer`});return}let l=n.getLiveSession(s,i);if(!l){json(t,404,{ok:!1,error:`No active session for this agentId and docName`});return}let u=l.um;if(c>=u.undoStack.length){json(t,404,{ok:!1,error:`stackIndex ${c} out of range (stack has ${u.undoStack.length} items)`});return}let d=u.undoStack[c];json(t,200,{ok:!0,diff:synthesizeStackItemDiffText(d,l.dc.document.getText(`source`),s),generatedAt:Date.now()})}catch(e){log$2.error({err:e},`[agent-burst-diff] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function me(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=M(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=safeContentPath(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),json(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await(w??t.unloadDocument.bind(t))(c),writeFileSync(o,``,`utf-8`),p&&(p.deleteDocument(a),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),json(i,500,{ok:!1,error:`Internal server error`})}}async function he(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}p.rebuildFromDisk(),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),m?.(`backlinks`),m?.(`graph`),json(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function ge(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o,s={},c,l;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}s=e,typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.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,``)}}));let n=e.principal;if(n&&typeof n==`object`&&!Array.isArray(n)){let e=n;typeof e.name==`string`&&e.name.trim()&&(c=sanitizeGitIdentity(e.name.trim())),typeof e.email==`string`&&e.email.trim()&&(l=sanitizeGitIdentity(e.email.trim()))}}let{rawAgentId:u,agentId:d,agentName:p,clientName:m}=q(s);a.length===0&&(a=u===void 0?[SERVICE_WRITER]:[{id:d,name:m?`${p} (${m})`:p,email:`${d}@openknowledge.local`}]);let h=f??`.`,g=await saveVersion(n,h,a);console.log(`[history] checkpoint ${g.checkpointRef}`);let _=swapContributors(),v;if(b){let e=!1;try{await esm_default({baseDir:b,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{v=await withParentLock(async()=>{let e=esm_default({baseDir:b,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=`openknowledge`,i=`noreply@openknowledge.local`;if(c&&l)r=c,i=l;else try{let e=await resolveGitIdentity(b);e&&(r=e.name,i=e.email)}catch{}let a=[];for(let e of _.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;a.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let s=formatCheckpointSubject(o??`Checkpoint v${t}`),u=a.length>0?`${s}\n\n${a.join(`
|
|
125
126
|
`)}`:s,d=h||`.`;return await e.add(d),await e.env({GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i}).commit(u,[`--allow-empty`]),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}}json(t,200,{ok:!0,checkpointRef:g.checkpointRef,...v?{versionTag:v}:{}})}catch(e){console.error(`[save-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function _e(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??u?.()??`main`;if(!i){json(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){json(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),s=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),d=Number.isFinite(s)?s:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await getDocumentHistory(n,{docName:i,branch:a,limit:l,offset:d,type:p,author:m,excludeAuthor:h},f??`.`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),json(t,200,{ok:!0,...e})}catch(e){console.error(`[shadow]`,e),json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ve(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=c?.current;if(!r){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=safeDocPath(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,f??`.`);if(`error`in i){json(t,400,{ok:!1,error:i.error});return}let a=i.path,o=shadowGit(r);if(!/^[0-9a-f]{40}$/i.test(n)){json(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{json(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);json(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[shadow-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function ye(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,s=i.searchParams.get(`to`)??``;if(!s||!/^[0-9a-f]{40}$/i.test(s)){json(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=safeDocPath(a,f??`.`);if(`error`in l){json(n,400,{ok:!1,error:l.error});return}let u=l.path,d=shadowGit(r);try{let e;try{e=await d.raw(`show`,`${s}:${u}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await d.raw(`show`,`${o}:${u}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=stripFrontmatter(r).body,c=stripFrontmatter(e).body,l=diffLines(i,c),f=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
|
|
126
127
|
`),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)f.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}json(n,200,{ok:!0,lines:f,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function be(n,r){if(n.method!==`POST`){r.writeHead(405),r.end(`Method not allowed`);return}let i=c?.current;if(!i){json(r,400,{ok:!1,error:`Shadow repo not configured`});return}let a;try{a=await readBody(n)}catch{json(r,413,{ok:!1,error:`Payload too large`});return}let o;try{o=a.length>0?JSON.parse(a.toString()):{}}catch{json(r,400,{ok:!1,error:`Invalid JSON`});return}if(!o||typeof o!=`object`||Array.isArray(o)){json(r,400,{ok:!1,error:`Body must be a JSON object`});return}let s=o,l=extractActorIdentity(s,x);if(l.kind===`invalid-summary`){json(r,400,{ok:!1,error:`summary must be a string`});return}let{docName:u,commitSha:d,versionTag:p}=s,m=typeof u==`string`?u:``,g=typeof d==`string`?d:``,_=typeof p==`string`?p:void 0;if(!m){json(r,400,{ok:!1,error:`docName required`});return}if(!g||!/^[0-9a-f]{40}$/i.test(g)){json(r,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let v=f??`.`,y=safeDocPath(m,v);if(`error`in y){json(r,400,{ok:!1,error:y.error});return}let S=y.path,C=shadowGit(i),w=Date.now();try{try{await C.raw(`cat-file`,`-e`,`${g}:${S}`)}catch{json(r,404,{ok:!1,error:`Document did not exist at this version`});return}let n=await C.raw(`show`,`${g}:${S}`),a=new Date().toISOString();await safetyCheckpoint(i,v,{action:`rollback`,context:{docName:m,targetSha:g}});let o=t.documents.get(m);if(!o){json(r,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{body:s}=stripFrontmatter(n),c=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:m}:void 0,u=mdManager.parseWithFallback(s,c),d=schema.nodeFromJSON(u),p=o.getXmlFragment(`default`);o.transact(()=>{updateYFragment(o,p,d,{mapping:new Map,isOMark:new Map});let e=o.getText(`source`),t=e.toString();t!==n&&(e.delete(0,t.length),e.insert(0,n))},ROLLBACK_ORIGIN);let y;switch(l.kind){case`agent`:{let e=g.slice(0,8),t=l.summary.kind===`value`,n=t?l.summary:normalizeSummary(`Restored to ${e}`),r=J(n);y=t||!r.response?r.response:Y(r.response),recordContributor(m,l.writerId,l.displayName,l.colorSeed,formatRollbackSubject(m,g),l.actor,r.stored),incrementAgentWriteCalls(),X(n,!t);break}case`principal`:{let e=J(l.summary);y=e.response,recordContributor(m,l.writerId,l.displayName,l.colorSeed,formatRollbackSubject(m,g),l.actor,e.stored),X(l.summary,!1);break}case`anonymous`:log$2.debug({docName:m,commitSha:g.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(l.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:l.kind}),F(m,`rollback`);let x=Date.now()-w;if(console.log(`[rollback] docName=${m} from=${g.slice(0,8)} duration=${x}ms`),b){let e=`Restored to ${_??g.slice(0,8)}: ${m}`,t=f??`.`;withParentLock(async()=>{let n=esm_default({baseDir:b,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}l.kind===`agent`&&h?.setFocus(l.writerId,{agentName:l.displayName,currentDoc:m,writeKind:`rollback-apply`,ts:Date.now()}),json(r,200,{ok:!0,restoredFrom:g,timestamp:a,...y?{summary:y}:{}})}catch(e){console.error(`[rollback]`,e),json(r,500,{ok:!1,error:e instanceof Error?e.message:`Failed to roll back document`})}}async function xe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getMetrics())}async function Se(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getParseHealth())}async function Ce(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=getActiveBranch(),r=d?.();json(t,200,{ok:!0,serverInstanceId:i,currentBranch:n,...r===void 0?{}:{currentDiskAckSVs:r}},{"Cache-Control":`no-store`})}async function we(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=x?.()??null;if(!n){json(t,404,{error:`Principal not available`});return}json(t,200,n)}async function Te(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=g?.getPresenceMap()??{},r=Date.now(),i={};for(let[e,t]of Object.entries(n))r-t.ts<2e4&&(i[e]=t);json(t,200,{presence:i})}async function Ee(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=resolve(r),i=n,a=!0;try{i=realpathSync(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),json(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}json(t,200,{ok:!0,contentDir:i,pathSeparator:sep,symlinkResolved:a})}let De=1440*60*1e3;async function Oe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){json(t,200,[]);return}let n=Date.now(),r=[],i=resolve(c.current.gitDir,`rescue`);if(existsSync(i))try{let e=readdirSync(i).filter(e=>isSupportedDocFile(e));for(let t of e){let e=resolve(i,t),a=statSync(e);if(n-a.mtimeMs>De){try{unlinkSync(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:stripDocExtension(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=u?.()??`main`,t=await listRescueCheckpoints(c.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}json(t,200,r)}async function ke(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){t.writeHead(404),t.end(`Not found`);return}let r=resolve(c.current.gitDir,`rescue`),i=resolve(r,`${n}${getDocExtension(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(existsSync(i)){let e=statSync(i);if(Date.now()-e.mtimeMs>De)try{unlinkSync(i)}catch{}else{let e=readFileSync(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=u?.()??`main`,r=(await listRescueCheckpoints(c.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=shadowGit(c.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
|
|
127
|
-
`)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function Ae(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let o=extractActorIdentity(i,x);if(o.kind===`invalid-summary`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{path:s}=i;if(!s||typeof s!=`string`||s.length===0){json(t,400,{ok:!1,error:`path is required`});return}if(!isSupportedDocFile(s)){json(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(s.includes(`..`)||s.startsWith(`/`)||s.includes(`\0`)||s.includes(`\\`)){json(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let c=resolve(r),l=resolve(c,s);if(!l.startsWith(`${c}/`)&&l!==c){json(t,400,{ok:!1,error:`path must not escape content directory`});return}let u=stripDocExtension(s);if(isSystemDoc(u)||isConfigDoc(u)){json(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}mkdirSync(dirname(l),{recursive:!0});let d=``;try{writeFileSync(l,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){json(t,409,{ok:!1,error:`File already exists`});return}throw e}let f=stripDocExtension(s);switch(S&&S.incrementMdDir(dirname(f)),registerWrite(l,contentHash(``)),o.kind){case`agent`:case`principal`:recordContributor(f,o.writerId,o.displayName,o.colorSeed,void 0,o.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(o.kind)}`)}let h=typeof a==`function`?a():null;h instanceof Map&&updateFileIndex({kind:`create`,path:l,docName:f,content:``},h),p&&(p.updateDocumentFromMarkdown(f,``),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${f}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(t,200,{ok:!0,docName:f})}catch(e){console.error(`[create-page]`,e),json(t,500,{ok:!1,error:`Failed to create page`})}}async function je(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}let r=D(n);if(!r){json(t,400,{ok:!1,error:`Invalid docName`});return}if(!existsSync(r)){json(t,404,{ok:!1,error:`Page not found`});return}json(t,200,{ok:!0,docName:n,headings:extractHeadings(readFileSync(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),json(t,500,{ok:!1,error:`Failed to read headings`})}}async function Me(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let a=i,o=extractActorIdentity(a,x);if(o.kind===`invalid-summary`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{kind:s,fromPath:c,toPath:l}=a;if(s!==`file`&&s!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof c!=`string`||typeof l!=`string`){json(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!isValidRelativeContentPath(c)||!isValidRelativeContentPath(l)){json(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===`file`&&(isSystemDoc(c)||isSystemDoc(l)||isConfigDoc(c)||isConfigDoc(l))){json(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(c===`.ok`||c.startsWith(`.ok/`)||l===`.ok`||l.startsWith(`.ok/`)){json(t,400,{ok:!1,error:`.ok is a reserved directory`});return}if(c===l){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(c.toLowerCase()===l.toLowerCase()){json(t,400,{ok:!1,error:`Case-only renames are not supported`});return}if(s===`file`&&probeAndRegisterSourceFileExtension(r,c),S&&(s===`file`?S.isExcluded(isSupportedDocFile(l)?l:`${l}${getDocExtension(c)}`):S.isDirExcluded(l))){json(t,400,{ok:!1,error:`Destination ${s===`file`?`document`:`folder`} is excluded by the workspace content config`});return}let u;try{u=await K(c,l,s)}catch(e){if(e instanceof ManagedRenameCollisionError){json(t,409,{ok:!1,error:e.message,colliding:e.colliding});return}throw e}if(u.renamed.length===0){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}let d;switch(o.kind){case`agent`:{let e=o.summary.kind===`value`,t=e?o.summary:normalizeSummary(`Renamed ${c} → ${l}`),n=J(t);d=e||!n.response?n.response:Y(n.response);for(let{fromDocName:e,toDocName:t}of u.renamed)recordContributor(t,o.writerId,o.displayName,o.colorSeed,formatRenameSubject(e,t),o.actor,n.stored);incrementAgentWriteCalls(),X(t,!e);for(let{toDocName:e}of u.renamed)F(e,`rename-path`);break}case`principal`:{let e=J(o.summary);d=e.response;for(let{fromDocName:t,toDocName:n}of u.renamed)recordContributor(n,o.writerId,o.displayName,o.colorSeed,formatRenameSubject(t,n),o.actor,e.stored);X(o.summary,!1);for(let{toDocName:e}of u.renamed)F(e,`rename-path`);break}case`anonymous`:log$2.debug({kind:s,fromPath:c,toPath:l,affectedDocs:u.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRenamePath: ${String(o.kind)}`)}renameAttributionCounter().add(1,{kind:`rename-${s}`,attribution_kind:o.kind}),json(t,200,{ok:!0,renamed:u.renamed,rewrittenDocs:u.rewrittenDocs,...d?{summary:d}:{}})}catch(e){console.error(`[rename-path]`,e);let{status:n,error:r}=z(e);json(t,n,{ok:!1,error:r})}}async function Ne(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}q(i);let{kind:o,path:s}=i;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!isValidRelativeContentPath(s)){json(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=resolveContentEntryPath(r,o,s);if(!existsSync(c)){json(t,404,{ok:!1,error:`${o} does not exist`});return}let l=statSync(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){json(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:listAffectedDocNames(a(),o,s);await B(u),o===`file`?unlinkSync(c):rmSync(c,{recursive:!0,force:!1}),json(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),json(t,500,{ok:!1,error:`Failed to delete path`})}}async function Pe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=a(),n=[];for(let[t,i]of e){let e=t,a=getDocExtension(t);try{e=extractPageTitle(readFileSync(resolve(r,`${t}${a}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,docExt:a,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),json(t,500,{ok:!1,error:`Failed to list pages`})}}async function Fe(e,n){if(e.method!==`GET`){json(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){json(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}if(isSystemDoc(r)||isConfigDoc(r)){json(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}json(n,200,{ok:!0,...await suggestLinks({hocuspocus:t,fileIndex:a(),docName:r})})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){json(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),json(n,500,{ok:!1,error:`Failed to suggest links`})}}async function Ie(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{n=await readUploadBody(e,r)}catch(e){if(e instanceof UploadWriteError){if(e.reason===`malformed-upload`){json(t,400,{ok:!1,error:`malformed-upload`});return}if(e.reason===`storage-full`){json(t,507,{ok:!1,error:`storage-full`});return}if(e.reason===`storage-readonly`){json(t,500,{ok:!1,error:`storage-readonly`});return}json(t,500,{ok:!1,error:`storage-error`});return}json(t,400,{ok:!1,error:`Failed to parse upload: ${e instanceof Error?e.message:String(e)}`});return}let{filename:i,tempPath:a,sha:o,byteLength:s,parentDocName:c}=n,{agentId:l,agentName:u}=q(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),d=()=>{if(existsSync(a))try{unlinkSync(a)}catch{}};if(s===0){d(),json(t,400,{ok:!1,error:`No file received`});return}if(!c){d(),json(t,400,{ok:!1,error:`parentDocName is required`});return}if(c.includes(`\0`)||c.includes(`..`)||c.startsWith(`/`)){d(),json(t,400,{ok:!1,error:`path-escape`});return}let f=resolve(r),p=resolveUploadDestDir(c,`./`,f);if(!isWithinContentDir(p,f)){d(),json(t,400,{ok:!1,error:`path-escape`});return}try{mkdirSync(p,{recursive:!0})}catch(e){if(e.code!==`EEXIST`){d(),log$2.error({err:e,destDir:p},`[upload] failed to create attachment directory`),json(t,500,{ok:!1,error:`storage-error`});return}}try{let e=realpathSync(p),n;try{n=realpathSync(f)}catch{n=f}if(!isWithinContentDir(e,n)){d(),json(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){d(),json(t,400,{ok:!1,error:`path-escape`});return}}let m=await fileTypeFromFile(a),h=m?.mime,g=m?.ext;if(!h){let e=readTempFileHead(a,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(h=`image/svg+xml`,g=`svg`)}{let n=await findDuplicateAsset(p,o,s);if(n){d();let i=relative(r,resolve(p,n));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:l,agentName:u,dedup:!0,mime:h??null,size:s,destPath:i,httpStatus:200},`[upload] dedup hit`),json(t,200,{ok:!0,src:n,path:i,deduped:!0});return}}let _;if(!i||i===`upload`||GENERIC_PASTE_NAMES.test(i)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=i?extname(i).slice(1):``,n=g??t??``;_=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else _=sanitizeFilename(i);try{let n=linkTempToFinalWithCollisionRetry(a,p,_),i=relative(r,resolve(p,n));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:l,agentName:u,dedup:!1,mime:h??null,size:s,destPath:i,httpStatus:200},`[upload] write ok`),json(t,200,{ok:!0,src:n,path:i,deduped:!1})}catch(n){let r=n instanceof Error?n.message:String(n),i=n instanceof UploadWriteError?n.reason:`unknown`;if(log$2.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:l,agentName:u,filename:_,size:s,reason:i,message:r,httpStatus:n instanceof UploadWriteError&&n.reason===`storage-full`?507:500},`[upload] write failed`),n instanceof UploadWriteError){if(n.reason===`storage-full`){json(t,507,{ok:!1,error:`storage-full`});return}if(n.reason===`storage-readonly`){json(t,500,{ok:!1,error:`storage-readonly`});return}if(n.reason===`collision-exhaustion`){json(t,500,{ok:!1,error:`collision-exhaustion`});return}json(t,500,{ok:!1,error:`storage-error`});return}json(t,500,{ok:!1,error:`storage-error`})}}let Le=`/api/local-op/clone`,Re=`/api/local-op/open`,ze=600*1e3,Be=45e3;async function Ve(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){json(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isAllowedGitUrl(n)){json(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!isSafeLocalPath(r)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!T.tryAcquire(Le)){json(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=expandTilde(r),[a,...o]=y,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=spawn(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},ze);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
|
|
128
|
-
`);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){T.release(Le);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&log$2.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await He(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),T.release(Le)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),T.release(Le)})}async function He(e){let t=resolve(expandTilde(e)),n=resolve(t,`.ok`),r=readUiLock(n);if(r&&r.port>0)return{port:r.port};let i=readServerLock(n),[a,...o]=y,s=i&&i.port>0?`ui`:`start`,c=spawn(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`,OK_PARENT_PID:String(process.pid)}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),log$2.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await setTimeout$1(500);let e=readUiLock(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function Ue(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isSafeLocalPath(n)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!T.tryAcquire(Re)){json(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await He(n);`port`in e?json(t,200,{port:e.port}):json(t,504,{ok:!1,error:e.error})}finally{T.release(Re)}}let We=`/api/local-op/auth/login`,Ge=`/api/local-op/auth/status`,Ke=`/api/local-op/auth/repos`,qe=`/api/local-op/auth/signout`,Je=`/api/local-op/auth/pat`;async function Ye(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!T.tryAcquire(We)){json(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=y,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},ze),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
|
|
129
|
-
`);c=n.pop()??``;for(let e of n)if(e.trim())try{let t=JSON.parse(e);(t.type===`complete`||t.type===`error`)&&(s=!0)}catch{}}),l.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/login] stderr`)}),l.on(`close`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(e===0&&!s?t.write(`${JSON.stringify({type:`complete`,host:n,login:``})}\n`):e!==0&&t.write(`${JSON.stringify({type:`error`,message:`auth login exited with code ${e}`})}\n`)),t.end()),T.release(We)}),l.on(`error`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),T.release(We)})}async function Xe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!T.tryAcquire(Ge)){json(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=y,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=spawn(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
|
|
128
|
+
`)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function Ae(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let o=extractActorIdentity(i,x);if(o.kind===`invalid-summary`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{path:s}=i;if(!s||typeof s!=`string`||s.length===0){json(t,400,{ok:!1,error:`path is required`});return}if(!isSupportedDocFile(s)){json(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(s.includes(`..`)||s.startsWith(`/`)||s.includes(`\0`)||s.includes(`\\`)){json(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let c=resolve(r),l=resolve(c,s);if(!l.startsWith(`${c}/`)&&l!==c){json(t,400,{ok:!1,error:`path must not escape content directory`});return}let u=stripDocExtension(s);if(isSystemDoc(u)||isConfigDoc(u)){json(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}mkdirSync(dirname(l),{recursive:!0});let d=``;try{writeFileSync(l,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){json(t,409,{ok:!1,error:`File already exists`});return}throw e}let f=stripDocExtension(s);switch(S&&S.incrementMdDir(dirname(f)),registerWrite(l,contentHash(``)),o.kind){case`agent`:case`principal`:recordContributor(f,o.writerId,o.displayName,o.colorSeed,void 0,o.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(o.kind)}`)}let h=typeof a==`function`?a():null;h instanceof Map&&updateFileIndex({kind:`create`,path:l,docName:f,content:``},h),p&&(p.updateDocumentFromMarkdown(f,``),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${f}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(t,200,{ok:!0,docName:f})}catch(e){console.error(`[create-page]`,e),json(t,500,{ok:!1,error:`Failed to create page`})}}async function je(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}let r=D(n);if(!r){json(t,400,{ok:!1,error:`Invalid docName`});return}if(!existsSync(r)){json(t,404,{ok:!1,error:`Page not found`});return}json(t,200,{ok:!0,docName:n,headings:extractHeadings(readFileSync(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),json(t,500,{ok:!1,error:`Failed to read headings`})}}async function Me(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let a=i,o=extractActorIdentity(a,x);if(o.kind===`invalid-summary`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{kind:s,fromPath:c,toPath:l}=a;if(s!==`file`&&s!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof c!=`string`||typeof l!=`string`){json(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!isValidRelativeContentPath(c)||!isValidRelativeContentPath(l)){json(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===`file`&&(isSystemDoc(c)||isSystemDoc(l)||isConfigDoc(c)||isConfigDoc(l))){json(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(c===`.ok`||c.startsWith(`.ok/`)||l===`.ok`||l.startsWith(`.ok/`)){json(t,400,{ok:!1,error:`.ok is a reserved directory`});return}if(c===l){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(c.toLowerCase()===l.toLowerCase()){json(t,400,{ok:!1,error:`Case-only renames are not supported`});return}if(s===`file`&&probeAndRegisterSourceFileExtension(r,c),S&&(s===`file`?S.isExcluded(isSupportedDocFile(l)?l:`${l}${getDocExtension(c)}`):S.isDirExcluded(l))){json(t,400,{ok:!1,error:`Destination ${s===`file`?`document`:`folder`} is excluded by the workspace content config`});return}let u;try{u=await K(c,l,s)}catch(e){if(e instanceof ManagedRenameCollisionError){json(t,409,{ok:!1,error:e.message,colliding:e.colliding});return}throw e}if(u.renamed.length===0){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}let d;switch(o.kind){case`agent`:{let e=o.summary.kind===`value`,t=e?o.summary:normalizeSummary(`Renamed ${c} → ${l}`),n=J(t);d=e||!n.response?n.response:Y(n.response);for(let{fromDocName:e,toDocName:t}of u.renamed)recordContributor(t,o.writerId,o.displayName,o.colorSeed,formatRenameSubject(e,t),o.actor,n.stored);incrementAgentWriteCalls(),X(t,!e);for(let{toDocName:e}of u.renamed)F(e,`rename-path`);break}case`principal`:{let e=J(o.summary);d=e.response;for(let{fromDocName:t,toDocName:n}of u.renamed)recordContributor(n,o.writerId,o.displayName,o.colorSeed,formatRenameSubject(t,n),o.actor,e.stored);X(o.summary,!1);for(let{toDocName:e}of u.renamed)F(e,`rename-path`);break}case`anonymous`:log$2.debug({kind:s,fromPath:c,toPath:l,affectedDocs:u.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRenamePath: ${String(o.kind)}`)}renameAttributionCounter().add(1,{kind:`rename-${s}`,attribution_kind:o.kind}),json(t,200,{ok:!0,renamed:u.renamed,rewrittenDocs:u.rewrittenDocs,...d?{summary:d}:{}})}catch(e){console.error(`[rename-path]`,e);let{status:n,error:r}=z(e);json(t,n,{ok:!1,error:r})}}async function Ne(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}q(i);let{kind:o,path:s}=i;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!isValidRelativeContentPath(s)){json(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=resolveContentEntryPath(r,o,s);if(!existsSync(c)){json(t,404,{ok:!1,error:`${o} does not exist`});return}let l=statSync(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){json(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:listAffectedDocNames(a(),o,s);await B(u),o===`file`?unlinkSync(c):rmSync(c,{recursive:!0,force:!1}),json(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),json(t,500,{ok:!1,error:`Failed to delete path`})}}async function Pe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=a(),n=[];for(let[t,i]of e){let e=t,a=getDocExtension(t);try{e=extractPageTitle(readFileSync(resolve(r,`${t}${a}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,docExt:a,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),json(t,500,{ok:!1,error:`Failed to list pages`})}}async function Fe(e,n){if(e.method!==`GET`){json(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){json(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}if(isSystemDoc(r)||isConfigDoc(r)){json(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}json(n,200,{ok:!0,...await suggestLinks({hocuspocus:t,fileIndex:a(),docName:r})})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){json(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),json(n,500,{ok:!1,error:`Failed to suggest links`})}}async function Ie(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{n=await readUploadBody(e,r)}catch(e){if(e instanceof UploadWriteError){if(e.reason===`malformed-upload`){json(t,400,{ok:!1,error:`malformed-upload`});return}if(e.reason===`storage-full`){json(t,507,{ok:!1,error:`storage-full`});return}if(e.reason===`storage-readonly`){json(t,500,{ok:!1,error:`storage-readonly`});return}json(t,500,{ok:!1,error:`storage-error`});return}json(t,400,{ok:!1,error:`Failed to parse upload: ${e instanceof Error?e.message:String(e)}`});return}let{filename:i,tempPath:a,sha:o,byteLength:s,parentDocName:c}=n,{agentId:l,agentName:u}=q(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),d=()=>{if(existsSync(a))try{unlinkSync(a)}catch{}};if(s===0){d(),json(t,400,{ok:!1,error:`No file received`});return}if(!c){d(),json(t,400,{ok:!1,error:`parentDocName is required`});return}if(c.includes(`\0`)||c.includes(`..`)||c.startsWith(`/`)){d(),json(t,400,{ok:!1,error:`path-escape`});return}let f=resolve(r),p=resolveUploadDestDir(c,`./`,f);if(!isWithinContentDir(p,f)){d(),json(t,400,{ok:!1,error:`path-escape`});return}try{mkdirSync(p,{recursive:!0})}catch(e){if(e.code!==`EEXIST`){d(),log$2.error({err:e,destDir:p},`[upload] failed to create attachment directory`),json(t,500,{ok:!1,error:`storage-error`});return}}try{let e=realpathSync(p),n;try{n=realpathSync(f)}catch{n=f}if(!isWithinContentDir(e,n)){d(),json(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){d(),json(t,400,{ok:!1,error:`path-escape`});return}}let m=await fileTypeFromFile(a),h=m?.mime,g=m?.ext;if(!h){let e=readTempFileHead(a,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(h=`image/svg+xml`,g=`svg`)}{let n=await findDuplicateAsset(p,o,s);if(n){d();let i=relative(r,resolve(p,n));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:l,agentName:u,dedup:!0,mime:h??null,size:s,destPath:i,httpStatus:200},`[upload] dedup hit`),json(t,200,{ok:!0,src:n,path:i,deduped:!0});return}}let _;if(!i||i===`upload`||GENERIC_PASTE_NAMES.test(i)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=i?extname(i).slice(1):``,n=g??t??``;_=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else _=sanitizeFilename(i);try{let n=linkTempToFinalWithCollisionRetry(a,p,_),i=relative(r,resolve(p,n));log$2.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:l,agentName:u,dedup:!1,mime:h??null,size:s,destPath:i,httpStatus:200},`[upload] write ok`),json(t,200,{ok:!0,src:n,path:i,deduped:!1})}catch(n){let r=n instanceof Error?n.message:String(n),i=n instanceof UploadWriteError?n.reason:`unknown`;if(log$2.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:l,agentName:u,filename:_,size:s,reason:i,message:r,httpStatus:n instanceof UploadWriteError&&n.reason===`storage-full`?507:500},`[upload] write failed`),n instanceof UploadWriteError){if(n.reason===`storage-full`){json(t,507,{ok:!1,error:`storage-full`});return}if(n.reason===`storage-readonly`){json(t,500,{ok:!1,error:`storage-readonly`});return}if(n.reason===`collision-exhaustion`){json(t,500,{ok:!1,error:`collision-exhaustion`});return}json(t,500,{ok:!1,error:`storage-error`});return}json(t,500,{ok:!1,error:`storage-error`})}}let Le=`/api/local-op/clone`,Re=`/api/local-op/open`,ze=600*1e3,Be=45e3;async function Ve(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){json(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isAllowedGitUrl(n)){json(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!isSafeLocalPath(r)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!T.tryAcquire(Le)){json(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=null,a=runCloneSubprocess({cliArgs:y,url:n,dir:r,timeoutMs:ze,onEvent:e=>{if(e.type===`complete`){i=e.dir;return}e.type===`error`&&e.message&&log$2.warn({stderr:e.message,url:n,dir:r},`[local-op/clone] clone failed`),t.writableEnded||t.write(`${JSON.stringify(e)}\n`)}});(async()=>{try{if(await a.done,i&&!t.writableEnded){let e=await He(i);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:i})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),T.release(Le)}})(),t.on(`close`,()=>{a.cancel()})}async function He(e){let t=resolve(expandTilde(e)),n=resolve(t,`.ok`),r=readUiLock(n);if(r&&r.port>0)return{port:r.port};let i=readServerLock(n),[a,...o]=y,s=i&&i.port>0?`ui`:`start`,c=spawn(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`,OK_PARENT_PID:String(process.pid)}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),log$2.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await setTimeout$1(500);let e=readUiLock(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function Ue(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isSafeLocalPath(n)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!T.tryAcquire(Re)){json(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await He(n);`port`in e?json(t,200,{port:e.port}):json(t,504,{ok:!1,error:e.error})}finally{T.release(Re)}}let We=`/api/local-op/auth/login`,Ge=`/api/local-op/auth/status`,Ke=`/api/local-op/auth/repos`,qe=`/api/local-op/auth/signout`,Je=`/api/local-op/auth/pat`;async function Ye(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!T.tryAcquire(We)){json(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let r=runDeviceFlowSubprocess({cliArgs:y,host:n,timeoutMs:ze,onEvent:e=>{t.writableEnded||t.write(`${JSON.stringify(e)}\n`)}}),i=()=>{r.cancel()};t.on(`close`,i),r.done.finally(()=>{t.off(`close`,i),t.writableEnded||t.end(),T.release(We)})}async function Xe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!T.tryAcquire(Ge)){json(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=y,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=spawn(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
|
|
130
129
|
`).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}o===null?json(t,200,{authenticated:!1}):json(t,200,o)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{T.release(Ge)}}async function Ze(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!T.tryAcquire(Ke)){json(t,429,{ok:!1,error:`An auth repos operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=y,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},ze);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),s.on(`close`,e=>{clearTimeout(c),o||(o=!0,e!==0&&!t.writableEnded&&t.write(`${JSON.stringify({type:`error`,message:`auth repos exited with code ${e}`})}\n`),t.end()),T.release(Ke)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),T.release(Ke)})}async function Qe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!T.tryAcquire(qe)){json(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=y,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=spawn(e,i,{stdio:`ignore`,env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{T.release(qe)}}async function $e(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){json(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!T.tryAcquire(Je)){json(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=y,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=spawn(e,a,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),o=setTimeout(()=>{i.kill(`SIGTERM`)},3e4);i.stdin.write(`${r}\n`),i.stdin.end();let s=[];i.stdout.on(`data`,e=>s.push(e)),i.on(`close`,e=>{clearTimeout(o),e===0?t(Buffer.concat(s).toString(`utf-8`)):n(Error(`auth pat exited with code ${e}`))}),i.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
|
|
131
130
|
`).map(e=>e.trim()).filter(Boolean),s=null;for(let e=o.length-1;e>=0;e--)try{s=JSON.parse(o[e]);break}catch{}s===null?json(t,200,{ok:!0}):json(t,200,s)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{T.release(Je)}}async function et(e,t){if(checkLocalOpSecurity(e,t,json)){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!b){json(t,400,{ok:!1,error:`No project directory configured`});return}try{json(t,200,{ok:!0,identity:await resolveGitIdentity(b)})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let tt=`/api/local-op/auth/set-identity`;async function nt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){json(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){json(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!b){json(t,400,{ok:!1,error:`No project directory configured`});return}if(!T.tryAcquire(tt)){json(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{writeGitIdentity(b,n,r),v?.()?.refreshIdentity().catch(()=>{}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{T.release(tt)}}async function rt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,200,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1});return}json(t,200,n.getStatus())}async function it(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await readBody(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}json(t,202,{ok:!0,op:r}),n.trigger(r)}async function at(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await readBody(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){json(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),json(t,200,{ok:!0,status:n.getStatus()})}async function ot(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();json(t,200,{conflicts:n?n.getConflicts():[]})}async function st(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await readBody(e);r=JSON.parse(t.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){json(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){json(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ct(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!b){json(t,503,{ok:!1,error:`Project repo not configured`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!n){json(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){json(t,400,{ok:!1,error:`Invalid file path`});return}let r=esm_default({baseDir:b,timeout:{block:15e3}});async function i(e){try{return await r.raw([`show`,`:${e}:${n}`])}catch{return``}}try{let[e,r,a]=await Promise.all([i(1),i(2),i(3)]);json(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function lt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=new URL(e.url??`/`,`http://localhost`).searchParams.get(`rootDir`)??void 0;try{json(t,200,{ok:!0,plan:await planSeed({projectDir:r,rootDir:n})})}catch(e){if(e instanceof SeedPrerequisiteError){json(t,200,{ok:!1,error:{kind:`prerequisite-missing`,message:e.message}});return}if(e instanceof SeedRootDirError){json(t,200,{ok:!1,error:{kind:`invalid-root`,message:e.message}});return}json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function ut(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(!i.plan||typeof i.plan!=`object`){json(t,400,{ok:!1,error:`Missing or invalid plan`});return}n=i.plan}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}try{json(t,200,{ok:!0,result:await applySeed(n,{projectDir:r})})}catch(e){json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function dt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n={};try{let r=await readBody(e);if(r.length>0){let e=JSON.parse(r.toString());if(typeof e.noOpen==`boolean`&&(n.noOpen=e.noOpen),typeof e.out==`string`){if(!isSafeLocalPath(e.out)){json(t,400,{ok:!1,error:`Output path must be within home directory`});return}n.out=e.out}}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}try{json(t,200,await buildAndOpenSkill(n))}catch(e){json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function ft(e,t){if(checkLocalOpSecurity(e,t,json))return handleInstalledAgents(e,t,E.probeAll)}async function pt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let mt={"/api/document":ne,"/api/documents":Q,"/api/backlinks":re,"/api/backlink-counts":ie,"/api/forward-links":ae,"/api/link-graph":oe,"/api/dead-links":le,"/api/orphans":se,"/api/hubs":ce,"/api/pages":Pe,"/api/suggest-links":Fe,"/api/page-headings":je,"/api/create-page":Ae,"/api/rename-path":Me,"/api/delete-path":Ne,"/api/upload":Ie,"/api/agent-write":Z,"/api/agent-write-md":te,"/api/agent-patch":ue,"/api/agent-undo":de,"/api/agent-activity":fe,"/api/agent-burst-diff":pe,"/api/save-version":ge,"/api/history":_e,"/api/diff":ye,"/api/rollback":be,"/api/metrics/reconciliation":xe,"/api/metrics/parse-health":Se,"/api/metrics/agent-presence":Te,"/api/server-info":Ce,"/api/principal":we,"/api/rescue":Oe,"/api/workspace":Ee,"/api/sync/status":rt,"/api/sync/trigger":it,"/api/sync/set-enabled":at,"/api/sync/conflicts":ot,"/api/sync/conflict-content":ct,"/api/sync/resolve-conflict":st,"/api/sync/abort-merge":pt,"/api/local-op/clone":Ve,"/api/local-op/open":Ue,"/api/local-op/auth/login":Ye,"/api/local-op/auth/status":Xe,"/api/local-op/auth/repos":Ze,"/api/local-op/auth/signout":Qe,"/api/local-op/auth/pat":$e,"/api/local-op/auth/identity":et,"/api/local-op/auth/set-identity":nt,"/api/installed-agents":ft,"/api/install-skill":dt,"/api/seed/plan":lt,"/api/seed/apply":ut};s&&(mt[`/api/test-reset`]=me,mt[`/api/test-rescan-backlinks`]=he);let ht=new Set([`/api/upload`,`/api/create-page`,`/api/rename-path`,`/api/delete-path`,`/api/agent-write`,`/api/agent-write-md`,`/api/agent-patch`,`/api/save-version`,`/api/rollback`,`/api/sync/trigger`,`/api/sync/set-enabled`,`/api/sync/resolve-conflict`,`/api/sync/abort-merge`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/install-skill`]),gt=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!isAllowedApiOrigin(n)){typeof t.setHeader==`function`&&t.setHeader(`Content-Type`,`application/json`),t.writeHead(403),t.end(JSON.stringify({ok:!1,error:`origin-not-allowed`}));return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),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`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(ht.has(n)||gt.some(e=>n.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!isLoopbackAddress(n)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}}if(!n.startsWith(`/api/`))return;let r=propagation.extract(context.active(),e.headers),i=e.method??`GET`,a=n;n.startsWith(`/api/rescue/`)?a=`/api/rescue/:docName`:n.startsWith(`/api/history/`)&&(a=`/api/history/:sha`);let o=getTracer(),s=Date.now();await context.with(r,()=>o.startActiveSpan(`HTTP ${i} ${a}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_URL_PATH]:n,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async r=>{try{let i=mt[n];if(i)await i(e,t);else if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await ke(e,t,r)}else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await ve(e,t,r)}let a=t.statusCode;r.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,a),a>=500&&r.setStatus({code:SpanStatusCode.ERROR,message:`status ${a}`})}catch(e){throw r.recordException(e),r.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),e}finally{r.end();let e=(Date.now()-s)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`});function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a}=e;return(e,o,s)=>{let c;try{c=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return s()}if(!c||t.isExcluded(c))return s();o.setHeader(`X-Content-Type-Options`,`nosniff`);let l=extname(c).slice(1).toLowerCase();l===`md`||l===`mdx`||(r.has(l)?o.setHeader(`Content-Disposition`,`inline`):o.setHeader(`Content-Disposition`,`attachment`)),n(e,o,()=>{if(!o.headersSent){if(i.has(l)||a.has(l)){o.statusCode=404,o.end();return}s()}})}}function isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedBasenameIndex(e){let t=e.contentDir,n=new Set;function r(i){let a;try{a=readdirSync(i,{withFileTypes:!0})}catch(t){let n=errnoCode(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=join(i,o.name),s=relative(t,a);if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=lstatSync(a)}catch(t){let n=errnoCode(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=realpathSync(a)}catch(t){let n=errnoCode(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!isWithinDir(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=statSync(i)}catch(t){let n=errnoCode(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(o.ino))continue;n.add(o.ino),o.isDirectory()?r(i):o.isFile()&&isSupportedAssetFile(a,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(c.ino))continue;n.add(c.ino),r(a);continue}c.isFile()&&isSupportedAssetFile(a,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}r(t)}const HocuspocusAuthTokenSchema=object({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional()}).loose();var HocuspocusAuthRejection=class extends Error{reason;constructor(e,t){super(t),this.name=`HocuspocusAuthRejection`,this.reason=e}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=HocuspocusAuthTokenSchema.safeParse(t);return n.success?n.data:void 0}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,n=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!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 u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}async function startConfigFileWatcher(e,t){let n=getLogger(`config-file-watcher`),{watch:r}=await import(`./chokidar-DjlCoHHX.mjs`),i=dirname(e);try{tracedMkdirSync(i,{recursive:!0})}catch(e){e.code!==`EEXIST`&&n.warn({err:e,watchDir:i},`failed to create watch directory; watcher may be inert`)}let a=r(i,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==i&&t!==e});await new Promise(e=>{a.once(`ready`,()=>e())});let o=r=>{if(r!==e)return;let i;try{i=readFileSync(r,`utf-8`)}catch(e){if(e.code===`ENOENT`){n.debug({path:r},`config file disappeared between event and read; dropping`);return}n.warn({err:e,path:r},`config file read failed; dropping event`);return}try{t(i)}catch(e){n.warn({err:e,path:r},`config file change handler threw`)}};a.on(`add`,o),a.on(`change`,o),a.on(`unlink`,t=>{t===e&&n.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),a.on(`error`,t=>{n.warn({err:t,watchDir:i,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let s=!1;return async()=>{s||(s=!0,await a.close())}}const 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`]),IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function createContentFilter(e){let{projectDir:t,contentDir:n}=e,r=(0,import_ignore.default)();r.add(`.git`);let i=[];for(let e of IGNORE_FILE_NAMES){let n=join(t,e);if(existsSync(n))try{let e=parseIgnorePatterns(readFileSync(n,`utf-8`));i.push(...e),r.add(e)}catch(t){console.warn(`[content-filter] Failed to read ${e} at ${n}:`,t)}}let a=relative(t,n),o=a.startsWith(`..`);if(a&&!o)for(let e of IGNORE_FILE_NAMES){let t=join(n,e);if(existsSync(t))try{let e=parseIgnorePatterns(readFileSync(t,`utf-8`)).map(e=>prefixPattern(e,a));r.add(e)}catch(n){console.warn(`[content-filter] Failed to read ${e} at ${t}:`,n)}}loadNestedIgnoreFiles(n,t,r);let s=i.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),c=new Map;function l(e){if(o)return!1;let t=a?`${a}/${e}`:e;return r.ignores(t)}return populateDirCount(n,``,l,c),{isExcluded(e){let t=stripDocExtension(e);if(isSystemDoc(t)||isConfigDoc(t)||!o&&l(e))return!0;if(isSupportedDocFile(e))return!1;let n=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(n)){let t=dirname(e),n=t===`.`?``:t;if((c.get(n)??0)>0)return!1}return!0},isDirExcluded(e){let t=e.split(`/`)[0];if(BUILTIN_SKIP_DIRS.has(t))return!0;if(o)return!1;let n=a?`${a}/${e}`:e;return r.ignores(n)||r.ignores(`${n}/`)},getWatcherIgnoreGlobs(){return s},incrementMdDir(e){let t=e===`.`?``:e;c.set(t,(c.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,n=c.get(t)??0;n<=1?c.delete(t):c.set(t,n-1)},rebuildDirCount(){c.clear(),populateDirCount(n,``,l,c)}}}function populateDirCount(e,t,n,r){let i;try{i=readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of i){let i=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){if(BUILTIN_SKIP_DIRS.has(a.name)||n(i)||n(`${i}/`))continue;populateDirCount(join(e,a.name),i,n,r)}else a.isFile()&&isSupportedDocFile(a.name)&&!n(i)&&r.set(t,(r.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
|
|
132
131
|
`).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,n){let r;try{r=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let i of r){if(!i.isDirectory()||BUILTIN_SKIP_DIRS.has(i.name))continue;let r=join(e,i.name),a=relative(t,r);if(!a.startsWith(`..`)&&!(n.ignores(a)||n.ignores(`${a}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(r,e);if(existsSync(t))try{let e=parseIgnorePatterns(readFileSync(t,`utf-8`)).map(e=>prefixPattern(e,a));n.add(e)}catch(n){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,n)}}loadNestedIgnoreFiles(r,t,n)}}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function resolveGitDir(e){let t=resolve(e,`.git`);try{let n=statSync(t);if(n.isDirectory())return t;if(n.isFile()){let n=readFileSync(t,`utf-8`).trim().match(/^gitdir:\s*(.+)$/);if(n)return resolve(e,n[1])}}catch{}return null}function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let n=resolve(e,t.slice(5));try{return readFileSync(n,`utf-8`).trim()}catch{try{let n=readFileSync(resolve(e,`packed-refs`),`utf-8`),r=t.slice(5),i=n.split(`
|
|
@@ -139,5 +138,5 @@ What to log:
|
|
|
139
138
|
`)){let n=t.trim();if(!n)continue;let r=e.get(n)??relative(this.contentDir,join(this.projectDir,n));r&&!r.startsWith(`..`)&&u.push(r)}}}catch{u=t.map(e=>e.contentRelPath)}let d=this.buildCommitMessage(u),f=await resolveGitIdentity(this.projectDir),p=f===null;this.identityUnresolved!==p&&(this.identityUnresolved=p,this.cc1Broadcaster?.signal(`sync-status`));let m=f?.name??`Open Knowledge`,h=f?.email??`sync@open-knowledge.local`;e.git.env({GIT_AUTHOR_NAME:m,GIT_AUTHOR_EMAIL:h,GIT_COMMITTER_NAME:m,GIT_COMMITTER_EMAIL:h});let g=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,d])).trim();if(!g||!SHA_HEX_40.test(g)){log.warn({raw:g},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}if(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,g,i]),t.length>0){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),n=100;for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}}let _=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),_=!0}catch{}_?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=g}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.error=void 0,this.schedulePull(0)))}catch(t){let n=classifyGitError(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){log.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});this.setBatchInProgress?.(!0);try{if(await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e)){this.setBatchInProgress?.(!1);return}await e.git.merge([`origin/${this.currentBranch}`])}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),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}log.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n)}finally{try{unlinkSync(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync();if(n.length===0)return null;let r=join(tmpdir(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),i=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:r});try{await i.git.raw([`read-tree`,t]);let r=100;for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await i.git.raw([`add`,`--`,...t])}let a=(await i.git.raw([`write-tree`])).trim();if(a===(await i.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let o=await resolveGitIdentity(this.projectDir),s=o?.name??`Open Knowledge`,c=o?.email??`sync@open-knowledge.local`;i.git.env({GIT_AUTHOR_NAME:s,GIT_AUTHOR_EMAIL:c,GIT_COMMITTER_NAME:s,GIT_COMMITTER_EMAIL:c});let l=(await i.git.raw([`commit-tree`,a,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();if(!l||!SHA_HEX_40.test(l))return log.warn({raw:l},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null;await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,l,t]);for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}return l}finally{try{unlinkSync(r)}catch{}}}async pauseIfNonContentDirty(e){let t=``;try{t=(await e.git.raw([`diff-index`,`--name-only`,`HEAD`])).trim()}catch{return!0}if(!t)return!0;let n=t.split(`
|
|
140
139
|
`).map(e=>e.trim()).filter(Boolean);return n.length===0?!0:(this.error=`External changes pending: ${n.slice(0,3).join(`, `)}${n.length>3?`, +${n.length-3} more`:``}`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log.warn({files:n},`[sync] paused — non-content tracked files dirty`),!1)}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=join(n,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`.git`||i.name.startsWith(`.`)&&i.name!==`.ok`)continue;t(r)}else if(i.isFile()){let t=relative(this.contentDir,r);if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=relative(this.projectDir,r);e.push({contentRelPath:t,projectRelPath:n})}}}};return existsSync(this.contentDir)&&t(this.contentDir),e}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t=[];try{let n=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=n?n.split(`
|
|
141
140
|
`).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.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.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=join(this.projectDir,e),i=relative(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log.warn({files:n},`[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.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log.info({},`[sync] merge aborted`)}catch(e){log.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,log.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`):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.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={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};writeFileSync(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){log.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,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)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.warn({err:e},`[sync] failed to load sync state`)}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,configHomedirOverride:l,enableTestRoutes:u=!1,shadowRepo:d,contentRoot:f,destroyTimeoutMs:p=1e4,localOpCliArgs:m,skipStateManifestCheck:h=!1}=e,g=getLogger(`server`);initTelemetry();let _=randomUUID(),v=resolve(t,`.ok`);if(acquireServerLock(v,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,...e.parentPid!==void 0&&{parentPid:e.parentPid},capabilities:[`http`,`ws`]}),!h)try{assertCompatibleStateManifest({lockDir:v,shadowRepoDir:resolveShadowDir(n)})}catch(e){throw releaseServerLock(v),e}let y=createBasenameIndex(),b=(e,t)=>y.resolveEmbed(e,t),x,S,C,w,T,E,D=null,O=null,k=null,A=null,j=new Set,M=!1,N;function P(e){D?.signal(e)}try{x=createContentFilter({projectDir:n,contentDir:t}),S=new BacklinkIndex({projectDir:n,contentDir:t,contentFilter:x}),C={current:d},w=createPersistenceExtension({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:C,contentRoot:f,backlinkIndex:S,configHomedirOverride:l,getCurrentBranch:()=>Y?.getLastKnownBranch()??null,resolveEmbed:b,getPrincipal:()=>A,onAgentCommit:()=>D?.signal(`session-activity`),onDiskFlush:(e,t)=>D?.emitDiskAck(e,t),onConfigRejected:(e,t)=>D?.emitConfigValidationRejected(e,t)}),T=new Hocuspocus({quiet:r,debounce:i,maxDebounce:a,extensions:[w.extension]});let p=T.shouldUnloadDocument.bind(T);T.shouldUnloadDocument=e=>(M||j.has(e))&&p(e),N=async e=>{j.add(e);try{await T.unloadDocument(e)}finally{j.delete(e)}},D=new CC1Broadcaster(T),O=new AgentFocusBroadcaster(T),k=new AgentPresenceBroadcaster(T),E=new AgentSessionManager(T);let h=createLiveDerivedIndexExtension({backlinkIndex:S,signalChannel:P});T.configuration.extensions.push(h),T.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=parseHocuspocusAuthToken(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==_)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${_}`);let i=n?.expectedBranch,a=getActiveBranch();if(typeof i==`string`&&i.length>0&&i!==a)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(A&&n.principalId===A.id?o.principalId=A.id:A?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:A.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),T.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 g=createApiExtension({hocuspocus:T,sessionManager:E,contentDir:t,contentFilter:x,serverInstanceId:_,getFileIndex:()=>J?J.getFileIndex():new Map,getAliasMap:()=>J?J.getAliasMap():new Map,enableTestRoutes:u,shadowRef:C,flushGitCommit:()=>w.flushPendingGitCommit(),getCurrentBranch:()=>Y?.getLastKnownBranch()??null,getDiskAckSVs:()=>D?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,backlinkIndex:S,signalChannel:P,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>X,localOpCliArgs:m,projectDir:n,resolveEmbed:b,getPrincipal:()=>A,forceUnloadDocument:N});T.configuration.extensions.push(g),T.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:C,contentRoot:f,getCurrentBranch:()=>Y?.getLastKnownBranch()??null,resolveEmbed:b}))}catch(e){throw releaseServerLock(v),e}let F=null,I=new Map,L=[];function R(e,t){let n=resolve(e,`rescue`),r=resolve(n,`${t}${getDocExtension(t)}`);return r.startsWith(`${n}/`)?r:null}function z(e){let t=T.documents.get(e);if(!t)return null;let n=yXmlFragmentToProseMirrorRootNode(t.getXmlFragment(`default`),schema).toJSON(),r=mdManager.serialize(n),i=stripFrontmatter(t.getText(`source`).toString()).frontmatter;return prependFrontmatter(i,r)}let B=(e,t)=>applyExternalChange(T,e,t,b),V=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of T.documents){if(isSystemDoc(n)||isConfigDoc(n))continue;let r=T.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{applyDiskContentToDoc(r,i,b,n)}catch(t){g.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},H=null,U=e=>{e&&(H===null&&(H=new Set,setImmediate(()=>{let e=H;if(H=null,e)try{for(let t of e)V(t)}catch(t){g.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),H.add(e))};function W(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:return e.relativePath;default:return e.docName}}async function G(e){try{switch(e.kind){case`create`:g.info({docName:e.docName},`[reconcile] create: ${e.docName}`),S.updateDocumentFromMarkdown(e.docName,e.content),S.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),P(`files`),P(`backlinks`),P(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=T.documents.get(t);if(!r){S.updateDocumentFromMarkdown(t,n),S.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),P(`backlinks`),P(`graph`);return}let i=getReconciledBase(t)??``,a=z(t)??i,o=reconcile({docName:t,base:i,ours:a,theirs:n}),s=contentHash(i).slice(0,6),c=contentHash(a).slice(0,6),l=contentHash(n).slice(0,6);switch(g.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:S.updateDocumentFromMarkdown(t,n),S.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),P(`backlinks`),P(`graph`);break;case`clean`:try{B(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),S.updateDocumentFromMarkdown(t,n),S.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),P(`backlinks`),P(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`merged`:try{B(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),S.updateDocumentFromMarkdown(t,n),S.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),P(`backlinks`),P(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`conflicts`:try{B(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),incrementConflict(),S.updateDocumentFromMarkdown(t,n),S.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),P(`backlinks`),P(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`refused`:{incrementConflict();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=T.documents.get(t);if(!n){S.deleteDocument(t),S.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),P(`files`),P(`backlinks`),P(`graph`);return}let r=getReconciledBase(t)??``,i=z(t)??``,a=i!==r;if(a&&C.current){let e=C.current,n=Y?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),g.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{g.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),S.deleteDocument(t),S.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),g.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),T.closeConnections(t),await N(n),P(`files`),P(`backlinks`),P(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=T.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(n,r),S.renameDocument(t,n,r),S.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}g.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),P(`files`),P(`backlinks`),P(`graph`);break}case`conflict`:{let{docName:t}=e,n=T.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),g.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:y.add(e.relativePath),P(`files`),U(basename(e.relativePath));break;case`asset-delete`:y.remove(e.relativePath),P(`files`),U(basename(e.relativePath));break;default:assertNeverDiskEvent(e)}}catch(t){let n=W(e);g.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let K=[];async function q(e){if(isBatchInProgress()){K.push(e);return}await G(e)}async function ee(){let e=K.splice(0,K.length);for(let t of e)await G(t)}let J=null,Y=null,X=null,Z=null;async function te(e){if(T.documents.size===0)return;let t=!1,n=new Promise(e=>{T.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(T.documents.keys());T.closeConnections(),T.flushPendingStores();for(let e of T.documents.values())e.getConnectionsCount()===0&&T.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 i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(T.documents.keys()),i=[],o=[];if(C.current){for(let e of n)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=z(e);if(t===null){g.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=R(C.current.gitDir,e);if(!n){g.warn({docName:e,gitDir:C.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),incrementRescueBuffer(),i.push(e),g.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),g.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else g.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function ne(){return Z||(Z=(async()=>{let e=Date.now(),t=[];M=!0;let r,i=await Promise.race([ie.then(()=>`completed`,e=>(g.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&g.warn({},`[server] init did not complete within 5s during shutdown`);let a=T.documents.size;try{try{try{Y&&=(await Y.unsubscribe(),null),J&&=(await J.unsubscribe(),null);for(let{docName:e,cleanup:t}of L)try{await t()}catch(t){g.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}L.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{D?.destroy(),k?.destroy(),F&&=(await F.disconnect(),null);for(let[e,t]of I)try{await t.disconnect()}catch(t){g.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}I.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await E.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await te(p)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await w.flushPendingGitCommit(),await w.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),p)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{X&&=(await X.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(C.current){try{let e=(await esm_default({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(C.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(C.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?g.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):g.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(v)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),g.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)})}}})(),Z)}let Q=[];async function re(){try{A=await loadPrincipal(t),g.info({principalId:A.id},`[server] principal loaded`)}catch(e){g.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!C.current)try{C.current=await initShadowRepo(n),g.info({gitDir:C.current.gitDir},`[server] history repo initialized at ${C.current.gitDir}`)}catch(e){g.error({err:e},`[server] history repo init failed`),Q.push(`shadow-repo`)}if(C.current)try{await shadowGit(C.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`)){g.warn({},`[server] history repo appears corrupted — reinitializing`);try{C.current=await initShadowRepo(n)}catch(e){g.error({err:e},`[server] history repo reinit failed`),C.current=void 0,Q.includes(`shadow-repo`)||Q.push(`shadow-repo`)}}else g.error({err:e},`[server] history repo check failed (transient?)`)}if(C.current)try{let e=resolve(C.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await esm_default({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await esm_default({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}g.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await commitUpstreamImport(C.current,f??``,t,r,e),incrementUpstreamImport()}catch(e){g.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else g.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{writeFileSync(e,r,`utf-8`)}catch(e){g.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){g.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;g.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){g.error({err:e},`[server] managed rename recovery failed`),Q.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(t);(e.deleted>0||e.errors>0)&&g.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){g.error({err:e},`[server] upload-tempfile sweep failed`),Q.push(`upload-tempfile-sweep`)}try{F=await T.openDirectConnection(SYSTEM_DOC_NAME),D?.emitServerInfo(_,getActiveBranch())}catch(e){g.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Q.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await T.openDirectConnection(e);I.set(e,t)}catch(t){g.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Q.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,n)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,n,l)]]);for(let t of CONFIG_DOC_NAMES){let n=e.get(t);if(n)try{g.info({docName:t,path:n},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(n,e=>{let n=T.documents.get(t);g.info({docName:t,hasDocument:n!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let r=applyExternalConfigChange(n??null,t,e,w.configPersistenceCtx);g.info({docName:t,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`)});L.push({docName:t,cleanup:e}),g.info({docName:t,path:n},`[config-file-watcher] started`)}catch(e){g.warn({err:e,docName:t,path:n},`[config-file-watcher] failed to start for ${t}`),Q.push(`config-file-watcher:${t}`)}}let r=resolveGitDir(n),i=r?readBranchFromHead(r)??`main`:`main`;switchReconciledBaseScope(i),S.switchBranch(i);try{J=await startWatcher(t,q,x),S.rebuildFromDisk(getActiveBranch()),S.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${getActiveBranch()}:`,e)});let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:x,basenameIndex:y,onSkip:(t,n,r)=>{e++,g.warn({reason:t,code:n,path:r},`[basename-index] skipped entry during seed (${t}${n?` ${n}`:``})`)}}),e>0&&(g.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Q.push(`basename-index-partial`))}catch(e){g.error({err:e},`[basename-index] startup seed failed`),Q.push(`basename-index`)}}catch(e){g.error({err:e},`[server] disk bridge watcher failed to start`),Q.push(`file-watcher`)}try{Y=await startHeadWatcher(n,async({trigger:e})=>{if(g.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),T.flushPendingStores(),await w.flushPendingGitCommit(),setBatchInProgress(!0),C.current){let e=getActiveBranch(),t=resolveGitDir(n),r=t?readBranchFromHead(t)??e:e,i=[];for(let[e,t]of T.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let n=null;if(t.transact(()=>{n=z(e)},PARK_SNAPSHOT_ORIGIN),n===null)continue;let r=getReconciledBase(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await parkBranch(C.current,e,SERVICE_WRITER.id,i,r);t&&(incrementPark(),g.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){g.error({err:e},`[shadow] park failed`)}}},async e=>{let n=K.length,r=e.newBranch??`main`;if(g.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)setBatchInProgress(!1),await ee(),await w.flushDeferredStores(`within-branch`);else{incrementBranchSwitch(),K.splice(0,K.length),switchReconciledBaseScope(r),S.switchBranch(r),x.rebuildDirCount();try{let e=0;y.clear(),seedBasenameIndex({contentDir:t,contentFilter:x,basenameIndex:y,onSkip:(t,n,i)=>{e++,g.warn({reason:t,code:n,path:i,branch:r},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(g.warn({count:e,branch:r},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Q.includes(`basename-index-partial`)||Q.push(`basename-index-partial`))}catch(e){g.error({err:e,branch:r},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of T.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let i=safeContentPath(e,t);if(!existsSync(i)){let t=getReconciledBase(e)??``,i=z(e)??``;if(i!==t&&C.current){let t=C.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,f??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),g.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{g.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),g.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=readFileSync(i,`utf-8`);B(e,a),setReconciledBase(e,a),g.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){g.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(g.info({branch:r,docCount:T.documents.size},`[branch-switch] loaded branch ${r} (${T.documents.size} docs)`),S.rebuildFromDisk(r),S.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),C.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of T.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let n=await readParkedState(C.current,r,SERVICE_WRITER.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=getReconciledBase(t);if(!i)continue;let a=reconcile({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:B(t,a.newContent),setReconciledBase(t,a.newContent),e++;break;case`conflicts`:B(t,a.newContent),setReconciledBase(t,a.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){g.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&g.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&C.current)try{let t=shadowGit(C.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
|
|
142
|
-
`))e&&await t.raw(`update-ref`,`-d`,e);g.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){g.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await w.flushDeferredStores(`discard-stale`),D?.emitBranchSwitched(r)}if(e.headMoved&&e.newHead&&C.current&&n>0){let t=f??`.`;try{let n=await commitUpstreamImport(C.current,t,e.oldHead,e.newHead,r);incrementUpstreamImport(),g.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){g.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){g.error({err:e},`[server] HEAD watcher failed to start`),Q.push(`head-watcher`)}let a=m?.[0]??`open-knowledge`,o=[`-c`,`credential.helper=!${m&&m.length>1?m.join(` `):a} auth git-credential`];try{X=new SyncEngine({projectDir:n,contentDir:t,contentFilter:x,contentRoot:f,credentialArgs:o,cc1Broadcaster:D,setBatchInProgress:e=>{setBatchInProgress(e),e||w.flushDeferredStores(`within-branch`).catch(e=>{g.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{g.info({state:e},`[sync] state → ${e}`)}}),await X.start()}catch(e){g.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),X=null}}let ie=re();return{hocuspocus:T,sessionManager:E,cc1Broadcaster:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,contentFilter:x,basenameIndex:y,serverInstanceId:_,destroy:ne,ready:ie,degraded:Q,lockDir:v,get syncEngine(){return X}}}const DEFAULT_PARENT_DEATH_POLL_MS=5e3,DEFAULT_IDLE_THRESHOLD_MS=1800*1e3;async function bootServer(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??getLogger(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=process.env.OK_PARENT_PID,s=typeof o==`string`&&/^[0-9]+$/.test(o)?Number.parseInt(o,10):void 0,c=e.lockKind??a??`interactive`,l=e.parentPid??s;initTelemetry();let{createServer:u}=await import(`node:http`),{WebSocketServer:d}=await import(`./wrapper-DYxqFKGF.mjs`),{updateServerLockPort:f}=await import(`./server-lock-BAi_a4NX-uRxotxS6.mjs`).then(e=>e.a),p=!1;!t&&e.ensureProjectGitFn&&(p=!!(await e.ensureProjectGitFn()).didInit);let m=!1;if(!t&&e.autoInitFn)try{m=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}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:c,parentPid:l,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:g,destroy:_,ready:v,degraded:y,lockDir:b,agentPresenceBroadcaster:x}=h,S=u((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){g.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),C=new d({noServer:!0});C.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)});let w=e.keepaliveGraceMs??1e4,T=new Map,E=new Set,D=!1;S.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive socket error`)}),C.handleUpgrade(e,t,n,t=>{let n=parseKeepaliveConnectionId(e.url);if(n){let e=T.get(n);e!==void 0&&(clearTimeout(e),T.delete(n),i.info({connectionId:n},`[keepalive] reconnect during grace — timer cancelled`))}let r=setInterval(()=>{try{t.ping()}catch{}},3e4);r.unref?.();let a=n?setInterval(()=>{x?.bumpPresenceTs(toBroadcasterKey(n))},3e3):null;a?.unref?.(),t.on(`close`,()=>{if(clearInterval(r),a!==null&&clearInterval(a),!n)return;let e=setTimeout(()=>{if(T.delete(n),D)return;let e=(async()=>{i.info({connectionId:n},`[keepalive] grace expired — cleaning up sessions`);try{await h.sessionManager.closeAllForAgent(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] closeAllForAgent failed`)}try{h.agentFocusBroadcaster?.clearFocus(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearFocus failed`)}try{x?.clearPresence(toBroadcasterKey(n))}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearPresence failed`)}})();E.add(e),e.finally(()=>E.delete(e))},w);e.unref?.(),T.set(n,e),i.info({connectionId:n,graceMs:w},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`Upgrade socket error`)}),C.handleUpgrade(e,t,n,t=>{let n=g.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let O=null;r!==null&&(O=attachIdleShutdown({httpServer:S,thresholdMs:r??DEFAULT_IDLE_THRESHOLD_MS,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await _()})})),await new Promise((t,n)=>{let r=e=>n(e);S.once(`error`,r),S.listen(e.port,e.host,()=>{S.removeListener(`error`,r),t()})});let k=S.address(),A=typeof k==`object`&&k?k.port:e.port??0;if(f(b,A),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:b,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let j=!1,M=null,N=async()=>{if(!j){j=!0,D=!0,M!==null&&(clearInterval(M),M=null);try{O?.detach()}catch(e){i.warn({err:e},`[bootServer.destroy] idleHandle.detach failed`)}for(let e of T.values())clearTimeout(e);T.clear(),E.size>0&&await Promise.allSettled([...E]);try{try{S.closeAllConnections?.()}catch(e){i.warn({err:e},`[bootServer.destroy] closeAllConnections failed`)}let e;try{await Promise.race([new Promise(e=>S.close(()=>e())),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`httpServer.close timeout after 10s`)),1e4)})]).catch(e=>{i.warn({err:e},`[bootServer.destroy] httpServer.close did not complete within timeout`)})}finally{e!==void 0&&clearTimeout(e)}}finally{await _(),await shutdownTelemetry()}}};if(l!==void 0){let t=e.parentDeathPollMs??DEFAULT_PARENT_DEATH_POLL_MS,n=e.parentAliveCheck??isProcessAlive;M=setInterval(()=>{j||n(l)||(i.warn({parentPid:l,lockKind:c},`[boot] parent process gone — initiating graceful shutdown`),N().catch(e=>{i.error({err:e,parentPid:l},`[boot] parent-death shutdown failed`)}))},t),M.unref?.()}return{httpServer:S,destroy:N,lockDir:b,contentDir:e.contentDir,port:A,ready:v,degraded:y,didAutoInit:m,didGitInit:p,serverInstance:h}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):n===`win32`?existsSync(join(r.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function ensureProjectGit(e){let t=resolve(e),n=resolve(t,`.git`);if(existsSync(n))return{didInit:!1};let r=``;try{r=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let n=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)}`,n,{cause:e})}if(!existsSync(resolve(n,`HEAD`)))throw new ProjectGitInitError(`git init reported success but ${n}/HEAD is missing (partial init detected)`,r);return console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0}}export{detectProjectShape as $,withSpan as $t,applySeed as A,registerWrite as At,commitWip as B,saveVersion as Bt,SeedPrerequisiteError as C,pathToDocName as Ct,acquireUiLock as D,readUiLock as Dt,UiLockCollisionError as E,readStateManifest as Et,buildAndOpenSkill as F,rewriteWikiLinksForDocumentRename as Ft,createApiExtension as G,splitMarkdownBlocks as Gt,containsConflictMarkers as H,setActiveSpanAttributes as Ht,buildSkillZip as I,safeContentPath as It,createLiveDerivedIndexExtension as J,toBroadcasterKey as Jt,createAssetServeMiddleware as K,startWatcher as Kt,buildWipTree as L,safeSubdir as Lt,assertNeverDiskEvent as M,removeLastKnownHash as Mt,attachIdleShutdown as N,resolveBundledSkillDir as Nt,applyAgentMarkdownWrite as O,reconcile as Ot,bootServer as P,rewriteMarkdownLinksForDocumentRename as Pt,detectClaudeDesktopPresence as Q,validateSkillZip as Qt,classifyEvents as R,safetyCheckpoint as Rt,STATE_MANIFEST_FILENAME as S,parseKeepaliveConnectionId as St,StateManifestError as T,readBranchFromHead as Tt,contentHash as U,shadowGit as Ut,commitWipFromTree as V,seedBasenameIndex as Vt,contributorCount as W,shutdownTelemetry as Wt,createServer$1 as X,updateUiLockPort as Xt,createPersistenceExtension as Y,updateLastKnownHash as Yt,createServerObserverExtension as Z,validateAgentId as Zt,ProjectGitInitError as _,lastKnownHash as _t,BacklinkIndex as a,parseWriterId as an,getMetrics as at,SERVICE_WRITER as b,loggerFactory as bt,FILE_SYSTEM_WRITER as c,incrementCollabSocketFilteredError as ct,HocuspocusAuthRejection as d,initTelemetry as dt,withSpanSync as en,ensureProjectGit as et,HocuspocusAuthTokenSchema as f,installUserSkill as ft,PinoLogger as g,isSystemDoc as gt,OBSERVER_SYNC_ORIGIN as h,isSelfWrite as ht,AgentSessionManager as i,getWipRefPattern as in,getMeter as it,assertCompatibleStateManifest as j,releaseUiLock as jt,applyExternalChange as k,recordContributor as kt,FILE_WATCHER_ORIGIN as l,incrementServerObserverFire as lt,MANAGED_RENAME_ORIGIN as m,isPairedWriteOrigin as mt,AgentFocusBroadcaster as n,writeTracker as nn,extractWikiLinksFromMarkdown as nt,CC1Broadcaster as o,readContributors as on,getTracer as ot,LOG_MD_TEMPLATE as p,isConfigDoc as pt,createContentFilter as q,starterFolderRule as qt,AgentPresenceBroadcaster as r,getShadowRepoPath as rn,getLogger as rt,CONFLICT_MARKER_RE as s,handleCollabSocketError as st,AGENT_ID_RE as t,writeStateManifest as tn,evictStaleTrackerEntries as tt,GIT_UPSTREAM_WRITER as u,initShadowRepo as ut,ROLLBACK_ORIGIN as v,listRescueCheckpoints as vt,SeedRootDirError as w,planSeed as wt,STARTER_FOLDERS as x,parseHocuspocusAuthToken as xt,SEED_CONFIG_FILENAME as y,loadPrincipal as yt,commitUpstreamImport as z,saveInMemoryCheckpoint as zt};
|
|
143
|
-
//# sourceMappingURL=dist-
|
|
141
|
+
`))e&&await t.raw(`update-ref`,`-d`,e);g.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){g.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await w.flushDeferredStores(`discard-stale`),D?.emitBranchSwitched(r)}if(e.headMoved&&e.newHead&&C.current&&n>0){let t=f??`.`;try{let n=await commitUpstreamImport(C.current,t,e.oldHead,e.newHead,r);incrementUpstreamImport(),g.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){g.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){g.error({err:e},`[server] HEAD watcher failed to start`),Q.push(`head-watcher`)}let a=m?.[0]??`open-knowledge`,o=[`-c`,`credential.helper=!${m&&m.length>1?m.join(` `):a} auth git-credential`];try{X=new SyncEngine({projectDir:n,contentDir:t,contentFilter:x,contentRoot:f,credentialArgs:o,cc1Broadcaster:D,setBatchInProgress:e=>{setBatchInProgress(e),e||w.flushDeferredStores(`within-branch`).catch(e=>{g.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{g.info({state:e},`[sync] state → ${e}`)}}),await X.start()}catch(e){g.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),X=null}}let ie=re();return{hocuspocus:T,sessionManager:E,cc1Broadcaster:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,contentFilter:x,basenameIndex:y,serverInstanceId:_,destroy:ne,ready:ie,degraded:Q,lockDir:v,get syncEngine(){return X}}}const DEFAULT_PARENT_DEATH_POLL_MS=5e3,DEFAULT_IDLE_THRESHOLD_MS=1800*1e3;async function bootServer(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??getLogger(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=process.env.OK_PARENT_PID,s=typeof o==`string`&&/^[0-9]+$/.test(o)?Number.parseInt(o,10):void 0,c=e.lockKind??a??`interactive`,l=e.parentPid??s;initTelemetry();let{createServer:u}=await import(`node:http`),{WebSocketServer:d}=await import(`./wrapper-DYxqFKGF.mjs`),{updateServerLockPort:f}=await import(`./server-lock-BAi_a4NX-uRxotxS6.mjs`).then(e=>e.a),p=!1;!t&&e.ensureProjectGitFn&&(p=!!(await e.ensureProjectGitFn()).didInit);let m=!1;if(!t&&e.autoInitFn)try{m=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}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:c,parentPid:l,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:g,destroy:_,ready:v,degraded:y,lockDir:b,agentPresenceBroadcaster:x}=h,S=u((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){g.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),C=new d({noServer:!0});C.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)});let w=e.keepaliveGraceMs??1e4,T=new Map,E=new Set,D=!1;S.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive socket error`)}),C.handleUpgrade(e,t,n,t=>{let n=parseKeepaliveConnectionId(e.url);if(n){let e=T.get(n);e!==void 0&&(clearTimeout(e),T.delete(n),i.info({connectionId:n},`[keepalive] reconnect during grace — timer cancelled`))}let r=setInterval(()=>{try{t.ping()}catch{}},3e4);r.unref?.();let a=n?setInterval(()=>{x?.bumpPresenceTs(toBroadcasterKey(n))},3e3):null;a?.unref?.(),t.on(`close`,()=>{if(clearInterval(r),a!==null&&clearInterval(a),!n)return;let e=setTimeout(()=>{if(T.delete(n),D)return;let e=(async()=>{i.info({connectionId:n},`[keepalive] grace expired — cleaning up sessions`);try{await h.sessionManager.closeAllForAgent(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] closeAllForAgent failed`)}try{h.agentFocusBroadcaster?.clearFocus(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearFocus failed`)}try{x?.clearPresence(toBroadcasterKey(n))}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearPresence failed`)}})();E.add(e),e.finally(()=>E.delete(e))},w);e.unref?.(),T.set(n,e),i.info({connectionId:n,graceMs:w},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`Upgrade socket error`)}),C.handleUpgrade(e,t,n,t=>{let n=g.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let O=null;r!==null&&(O=attachIdleShutdown({httpServer:S,thresholdMs:r??DEFAULT_IDLE_THRESHOLD_MS,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await _()})})),await new Promise((t,n)=>{let r=e=>n(e);S.once(`error`,r),S.listen(e.port,e.host,()=>{S.removeListener(`error`,r),t()})});let k=S.address(),A=typeof k==`object`&&k?k.port:e.port??0;if(f(b,A),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:b,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let j=!1,M=null,N=async()=>{if(!j){j=!0,D=!0,M!==null&&(clearInterval(M),M=null);try{O?.detach()}catch(e){i.warn({err:e},`[bootServer.destroy] idleHandle.detach failed`)}for(let e of T.values())clearTimeout(e);T.clear(),E.size>0&&await Promise.allSettled([...E]);try{try{S.closeAllConnections?.()}catch(e){i.warn({err:e},`[bootServer.destroy] closeAllConnections failed`)}let e;try{await Promise.race([new Promise(e=>S.close(()=>e())),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`httpServer.close timeout after 10s`)),1e4)})]).catch(e=>{i.warn({err:e},`[bootServer.destroy] httpServer.close did not complete within timeout`)})}finally{e!==void 0&&clearTimeout(e)}}finally{await _(),await shutdownTelemetry()}}};if(l!==void 0){let t=e.parentDeathPollMs??DEFAULT_PARENT_DEATH_POLL_MS,n=e.parentAliveCheck??isProcessAlive;M=setInterval(()=>{j||n(l)||(i.warn({parentPid:l,lockKind:c},`[boot] parent process gone — initiating graceful shutdown`),N().catch(e=>{i.error({err:e,parentPid:l},`[boot] parent-death shutdown failed`)}))},t),M.unref?.()}return{httpServer:S,destroy:N,lockDir:b,contentDir:e.contentDir,port:A,ready:v,degraded:y,didAutoInit:m,didGitInit:p,serverInstance:h}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):n===`win32`?existsSync(join(r.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function ensureProjectGit(e){let t=resolve(e),n=resolve(t,`.git`);if(existsSync(n))return{didInit:!1};let r=``;try{r=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let n=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)}`,n,{cause:e})}if(!existsSync(resolve(n,`HEAD`)))throw new ProjectGitInitError(`git init reported success but ${n}/HEAD is missing (partial init detected)`,r);return console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0}}export{detectProjectShape as $,validateAgentId as $t,applySeed as A,registerWrite as At,commitWip as B,safetyCheckpoint as Bt,SeedPrerequisiteError as C,pathToDocName as Ct,acquireUiLock as D,readUiLock as Dt,UiLockCollisionError as E,readStateManifest as Et,buildAndOpenSkill as F,rewriteWikiLinksForDocumentRename as Ft,createApiExtension as G,shadowGit as Gt,containsConflictMarkers as H,saveVersion as Ht,buildSkillZip as I,runCloneSubprocess as It,createLiveDerivedIndexExtension as J,startWatcher as Jt,createAssetServeMiddleware as K,shutdownTelemetry as Kt,buildWipTree as L,runDeviceFlowSubprocess as Lt,assertNeverDiskEvent as M,removeLastKnownHash as Mt,attachIdleShutdown as N,resolveBundledSkillDir as Nt,applyAgentMarkdownWrite as O,reconcile as Ot,bootServer as P,rewriteMarkdownLinksForDocumentRename as Pt,detectClaudeDesktopPresence as Q,updateUiLockPort as Qt,classifyEvents as R,safeContentPath as Rt,STATE_MANIFEST_FILENAME as S,parseKeepaliveConnectionId as St,StateManifestError as T,readBranchFromHead as Tt,contentHash as U,seedBasenameIndex as Ut,commitWipFromTree as V,saveInMemoryCheckpoint as Vt,contributorCount as W,setActiveSpanAttributes as Wt,createServer$1 as X,toBroadcasterKey as Xt,createPersistenceExtension as Y,starterFolderRule as Yt,createServerObserverExtension as Z,updateLastKnownHash as Zt,ProjectGitInitError as _,lastKnownHash as _t,BacklinkIndex as a,getShadowRepoPath as an,getMetrics as at,SERVICE_WRITER as b,loggerFactory as bt,FILE_SYSTEM_WRITER as c,readContributors as cn,incrementCollabSocketFilteredError as ct,HocuspocusAuthRejection as d,initTelemetry as dt,validateSkillZip as en,ensureProjectGit as et,HocuspocusAuthTokenSchema as f,installUserSkill as ft,PinoLogger as g,isSystemDoc as gt,OBSERVER_SYNC_ORIGIN as h,isSelfWrite as ht,AgentSessionManager as i,writeTracker as in,getMeter as it,assertCompatibleStateManifest as j,releaseUiLock as jt,applyExternalChange as k,recordContributor as kt,FILE_WATCHER_ORIGIN as l,incrementServerObserverFire as lt,MANAGED_RENAME_ORIGIN as m,isPairedWriteOrigin as mt,AgentFocusBroadcaster as n,withSpanSync as nn,extractWikiLinksFromMarkdown as nt,CC1Broadcaster as o,getWipRefPattern as on,getTracer as ot,LOG_MD_TEMPLATE as p,isConfigDoc as pt,createContentFilter as q,splitMarkdownBlocks as qt,AgentPresenceBroadcaster as r,writeStateManifest as rn,getLogger as rt,CONFLICT_MARKER_RE as s,parseWriterId as sn,handleCollabSocketError as st,AGENT_ID_RE as t,withSpan as tn,evictStaleTrackerEntries as tt,GIT_UPSTREAM_WRITER as u,initShadowRepo as ut,ROLLBACK_ORIGIN as v,listRescueCheckpoints as vt,SeedRootDirError as w,planSeed as wt,STARTER_FOLDERS as x,parseHocuspocusAuthToken as xt,SEED_CONFIG_FILENAME as y,loadPrincipal as yt,commitUpstreamImport as z,safeSubdir as zt};
|
|
142
|
+
//# sourceMappingURL=dist-CDuTCUx1.mjs.map
|