@inkeep/open-knowledge 0.0.0-dev-20260428172344 → 0.0.0-dev-20260428173955

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/cli.mjs +4 -4
  2. package/dist/constants-TQwGMmUq.mjs +2 -0
  3. package/dist/{dist-6JXIwkTW.mjs → dist-B0YYcQi2.mjs} +3 -3
  4. package/dist/{dist-DRC09WNZ.mjs → dist-CXdg7KnM.mjs} +3 -3
  5. package/dist/{dist-Rkr9VTaR.mjs → dist-Dp2ZKzHZ.mjs} +1 -1
  6. package/dist/index.mjs +1 -1
  7. package/dist/{init-DbVZJXmR.mjs → init-CdAYKIUQ.mjs} +1 -1
  8. package/dist/init-Cfz5PIsJ.mjs +1 -0
  9. package/dist/{init-Di2sbASA.mjs → init-DO08hYU-.mjs} +2 -2
  10. package/dist/{init-BbOWk8q3.mjs → init-tBs47qTU.mjs} +3 -3
  11. package/dist/loader-BrDZjZ-u.mjs +1 -0
  12. package/dist/{loader-DDxmojUu.mjs → loader-CZ-UM2X7.mjs} +2 -2
  13. package/dist/paths-C6QLabWV.mjs +2 -0
  14. package/dist/paths-Dti9tbQm.mjs +1 -0
  15. package/dist/{preview-VXVGRaUP.mjs → preview-DPnNj-m8.mjs} +2 -2
  16. package/dist/preview-DtcWIT_s.mjs +1 -0
  17. package/dist/public/assets/{ActivityModeContent-JeYMJ8N-.js → ActivityModeContent-D5tQuic6.js} +1 -1
  18. package/dist/public/assets/DocumentContext-5648awue.js +5 -0
  19. package/dist/public/assets/{GraphPanel-B9s5n-VJ.js → GraphPanel-CJ_U3W3L.js} +1 -1
  20. package/dist/public/assets/McpConsentDialogBody-DaoRt1sL.js +1 -0
  21. package/dist/public/assets/{PageListContext-DNRRECTw.js → PageListContext-B5SWnlyE.js} +62 -62
  22. package/dist/public/assets/{SourceEditor-DBzpEf4D.js → SourceEditor-v974jYM4.js} +2 -2
  23. package/dist/public/assets/{clipboard-C0HbTlCM.js → clipboard-jQ8LVmdA.js} +16 -16
  24. package/dist/public/assets/{index-BZbSuKIM.js → index--jIPq5k_.js} +72 -72
  25. package/dist/public/assets/index-B-gEZtZG.css +1 -0
  26. package/dist/public/assets/toggle-group-LDOO6zaV.js +1 -0
  27. package/dist/public/assets/{tooltip-nCu_fYrg.js → tooltip-D0MnQ7ZX.js} +1 -1
  28. package/dist/public/index.html +7 -7
  29. package/dist/src-BJrUlYqe.mjs +1 -0
  30. package/dist/start-BvVyhlsY.mjs +1 -0
  31. package/dist/{start-Diu1lafB.mjs → start-oei-FCzL.mjs} +2 -2
  32. package/package.json +1 -1
  33. package/dist/constants-DBvBsqEJ.mjs +0 -2
  34. package/dist/init-BB_9-RIR.mjs +0 -1
  35. package/dist/loader-DvcPWYAi.mjs +0 -1
  36. package/dist/paths-DXVpv4hT.mjs +0 -1
  37. package/dist/paths-DaG87qwf.mjs +0 -2
  38. package/dist/preview-D18jtdLK.mjs +0 -1
  39. package/dist/public/assets/DocumentContext-D9TYylem.js +0 -5
  40. package/dist/public/assets/McpConsentDialogBody-BbZirIXN.js +0 -1
  41. package/dist/public/assets/index-Bw1KsDm4.css +0 -1
  42. package/dist/public/assets/toggle-group-akWK7-wE.js +0 -1
  43. package/dist/src-DObpODAp.mjs +0 -1
  44. package/dist/start-Bh3tU8V0.mjs +0 -1
@@ -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{t as require_dist$1}from"./dist-BCyi1oM7.mjs";import{A as normalizeBridge,C as getFrontmatter,D as iconFromClientName,E as getWikiLinkText,F as toWikiLinkSlug,M as resolveInternalHref,N as sharedExtensions,O as isOrphanMode,P as stripFrontmatter,S as defaultScheduler,T as getParseHealth,Z as string,_ as applyIncrementalDiff,_t as Fragment,a as CC1BranchSwitchedPayloadSchema,b as colorFromSeed,c as CC1ServerInfoPayloadSchema,d as CC1_CHANNEL_SERVER_INFO,f as MarkdownManager,g as applyFastDiff,gt as PluginKey,h as SYSTEM_DOC_NAME,ht as getSchema,i as BridgeMergeContentLossError,j as prependFrontmatter,k as mergeThreeWay,l as CC1_CHANNEL_BRANCH_SWITCHED,n as ALLOWED_IMAGE_MIME_TYPES,o as CC1DerivedViewPayloadSchema,p as OK_DIR,q as object,r as ASSET_EXTENSIONS,s as CC1DiskAckPayloadSchema,t as AGENT_ICON_COLORS,u as CC1_CHANNEL_DISK_ACK,v as classifyMarkdownHref,vt as VFileMessage,w as getHeadingSlug,x as createCodeFenceTracker,y as classifyWikiLinkTarget}from"./dist-DRC09WNZ.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-n3Y5JWNv-3o7br8XE.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{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-BFkWzFey.mjs";import{r as diffLines,t as createPatch}from"./libesm-DC4M2SkF.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,lstatSync,mkdirSync,openSync,readFileSync,readdirSync,realpathSync,renameSync,rmSync,statSync,unlinkSync,writeFileSync,writeSync}from"node:fs";import{homedir,hostname,tmpdir}from"node:os";import{promisify}from"node:util";import{Readable}from"stream";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import*as zlib$1 from"zlib";import{setTimeout as setTimeout$1}from"node:timers/promises";import{mkdir,readFile,readdir,realpath,rename,writeFile}from"node:fs/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+`
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{t as require_dist$1}from"./dist-BCyi1oM7.mjs";import{A as normalizeBridge,C as getFrontmatter,D as iconFromClientName,E as getWikiLinkText,F as toWikiLinkSlug,M as resolveInternalHref,N as sharedExtensions,O as isOrphanMode,P as stripFrontmatter,S as defaultScheduler,T as getParseHealth,Z as string,_ as applyIncrementalDiff,_t as Fragment,a as CC1BranchSwitchedPayloadSchema,b as colorFromSeed,c as CC1ServerInfoPayloadSchema,d as CC1_CHANNEL_SERVER_INFO,f as MarkdownManager,g as applyFastDiff,gt as PluginKey,h as SYSTEM_DOC_NAME,ht as getSchema,i as BridgeMergeContentLossError,j as prependFrontmatter,k as mergeThreeWay,l as CC1_CHANNEL_BRANCH_SWITCHED,n as ALLOWED_IMAGE_MIME_TYPES,o as CC1DerivedViewPayloadSchema,p as OK_DIR,q as object,r as ASSET_EXTENSIONS,s as CC1DiskAckPayloadSchema,t as AGENT_ICON_COLORS,u as CC1_CHANNEL_DISK_ACK,v as classifyMarkdownHref,vt as VFileMessage,w as getHeadingSlug,x as createCodeFenceTracker,y as classifyWikiLinkTarget}from"./dist-CXdg7KnM.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-n3Y5JWNv-3o7br8XE.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{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-BFkWzFey.mjs";import{r as diffLines,t as createPatch}from"./libesm-DC4M2SkF.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,lstatSync,mkdirSync,openSync,readFileSync,readdirSync,realpathSync,renameSync,rmSync,statSync,unlinkSync,writeFileSync,writeSync}from"node:fs";import{homedir,hostname,tmpdir}from"node:os";import{promisify}from"node:util";import{Readable}from"stream";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import*as zlib$1 from"zlib";import{setTimeout as setTimeout$1}from"node:timers/promises";import{mkdir,readFile,readdir,realpath,rename,writeFile}from"node:fs/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$7=__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$7(),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:J,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 J(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$7(),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$7(),{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:J,nullTime:Y}=o,{pid:X}=process,Z=n.hostname(),Q=r.err,ee=_({level:`info`,levelComparison:g.ASC,levels:h,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:X,hostname:Z},serializers:Object.assign(Object.create(null),{err:Q}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:J,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),te=Object.assign(Object.create(null),r);function ne(...e){let t={},{opts:n,stream:r}=ee(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:X,name:Z,level:Q,customLevels:te,levelComparison:ne,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
  `:`
@@ -119,7 +119,7 @@ What to log:
119
119
  ---`,3);n!==-1&&(t=e.slice(n+4))}let n=[],r=new Map,i=createCodeFenceTracker();for(let e of t.split(`
120
120
  `)){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,installedAgentsProbe:S}=e,C=createConcurrencyGuard(),w=createInstalledAgentsProbe({probe:S??createOsProbe(process.platform)});function T(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 E(e){let t=T(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}let D={cluster:void 0,category:void 0,tags:void 0};function O(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return parseFrontmatterMetadata(e)}}catch{}try{let t=T(e);if(!t||!existsSync(t))return D;let{frontmatter:n}=stripFrontmatter(readFileSync(t,`utf-8`));return n?parseFrontmatterMetadata(n):D}catch{return D}}function k(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 A(e){return o?.().get(e)??e}function j(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function M(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function N(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 P(){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 F(){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 I=F();function L(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function R(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 t.unloadDocument(e))}return r}function z(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=safeContentPath(i,r),a=t.get(n);typeof a==`string`&&writeFileSync(e,a,`utf-8`);let o=typeof a==`string`?a:existsSync(e)?readFileSync(e,`utf-8`):null;typeof o==`string`&&registerWrite(e,contentHash(o))}}function B(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 V(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 H(e,t){let n=resolveContentEntryPath(r,`file`,e);mkdirSync(dirname(n),{recursive:!0}),writeFileSync(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 U(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=rewriteSupportedLinksForDocumentRename(s,e,n,r),a.rewrites===0)return;let{body:c}=stripFrontmatter(a.markdown),l=mdManager.parseWithFallback(c);updateYFragment(i,t,schema.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),applyFastDiff(o,s,a.markdown)},MANAGED_RENAME_ORIGIN),a}async function W(e,n){return I(async()=>{if(!p)throw Error(`Managed rename requires backlink index support`);let i=resolveContentEntryPath(r,`file`,e),o=resolveContentEntryPath(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(p.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],d=[];for(let t of[e,...c]){if(l.has(t))continue;let n=V(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&d.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let f=createManagedRenameRecoveryJournal({sourceDocName:e,destinationDocName:n,snapshots:B([...l.keys()],l)}),h=[];return await withManagedRenameRecovery(r,f,async()=>{for(let e of d)p.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?U(r,e,n):rewriteSupportedLinksForDocumentRename(l.get(r)??``,r,e,n);i.rewrites>0&&(H(r,i.markdown),h.push({docName:r,rewrites:i.rewrites})),p.updateDocumentFromMarkdown(r,i.markdown)}let r=rewriteSupportedLinksForDocumentRename((await R([e])).get(e)??l.get(e)??readFileSync(i,`utf-8`),e,e,n);await renameTrackedPathInGit(b,i,o)||(mkdirSync(dirname(o),{recursive:!0}),renameSync(i,o)),z(s,new Map([[e,r.markdown]])),setReconciledBase(n,r.markdown);let c=a();c instanceof Map&&updateFileIndex({kind:`rename`,oldPath:i,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),p.renameDocument(e,n,r.markdown),r.rewrites>0&&h.push({docName:n,rewrites:r.rewrites})}),p.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),m?.(`files`),m?.(`backlinks`),m?.(`graph`),h.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:h}})}let G=128;function K(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!AGENT_ID_RE.test(t)&&(t=void 0);let n=t?toBroadcasterKey(t):`claude-1`,r=typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=sanitizeGitIdentity(i));let a=typeof e.clientVersion==`string`?e.clientVersion:void 0;a!==void 0&&(a=sanitizeGitIdentity(a));let o=typeof e.label==`string`?e.label:void 0;o!==void 0&&(o=sanitizeGitIdentity(o));let s=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:s,clientName:i,clientVersion:a,label:o}}function q(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 J(e){return{principalId:x?.()?.id,agentType:q(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Y(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 X(e){return{value:e.value}}function Z(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}async function Q(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let o=A(a);if(isSystemDoc(o)){json(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:d,label:f}=K(i),p=normalizeSummary(i.summary);if(p.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let m=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),h=new Date().toISOString(),v=typeof i.content==`string`?i.content:`Hello from the agent! ${h}`,{response:y,stored:b}=Y(p);try{let e=iconFromClientName(u),t=AGENT_ICON_COLORS[e]??colorFromSeed(l??s);g?.setPresence(s,{displayName:c,icon:e,color:t,currentDoc:o,mode:`writing`,ts:Date.now()}),captureEffect(m.dc.document.getText(`source`),s,l,u),m.dc.document.transact(()=>{applyAgentMarkdownWrite(m.dc.document,`${v}\n`,`append`),m.dc.document.getMap(`agent-flash`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${v.slice(0,50)}`})},m.origin),recordContributor(o,s,c,l,void 0,J({clientName:u,clientVersion:d,label:f}),b),incrementAgentWriteCalls(),Z(p)}finally{g?.touchMode(s,`idle`)}N(o,`agent-write`),_?.(),json(t,200,{ok:!0,timestamp:h,...y?{summary:y}:{}})}catch(e){log$2.error({err:e},`[agent-write] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function ee(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.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{markdown:a,position:o}=i;if(!a||typeof a!=`string`){json(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!isSafeDocName(l)){json(t,400,{ok:!1,error:`Invalid docName`});return}let u=A(l);if(isSystemDoc(u)){json(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:p,clientName:m,clientVersion:v,label:y}=K(i),b=normalizeSummary(i.summary);if(b.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{response:x,stored:S}=Y(b),C=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),w=new Date().toISOString();try{let e=iconFromClientName(m),t=AGENT_ICON_COLORS[e]??colorFromSeed(p??d);g?.setPresence(d,{displayName:f,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),d,p,m),C.dc.document.transact(()=>{applyAgentMarkdownWrite(C.dc.document,a,s),C.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},C.origin),recordContributor(u,d,f,p,void 0,J({clientName:m,clientVersion:v,label:y}),S),incrementAgentWriteCalls(),Z(b)}finally{g?.touchMode(d,`idle`)}N(u,`agent-write-md`),h?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),_?.();let T=k(u),E=j(u),D=M();D===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":q(m)}),json(t,200,{ok:!0,timestamp:w,subscriberCount:E,systemSubscriberCount:D,...T?{hints:T}:{},...x?{summary:x}:{}})}catch(e){log$2.error({err:e},`[agent-write-md] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function te(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}let i=A(r);if(isSystemDoc(i)){json(n,400,{ok:!1,error:`'${i}' is a reserved document name`});return}let a=await t.openDirectConnection(i);try{let e=a.document;if(!e){json(n,500,{ok:!1,error:`Document not available`});return}json(n,200,{ok:!0,docName:i,content:e.getText(`source`).toString()})}finally{await a.disconnect()}}catch(e){console.error(`[document-read]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function ne(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)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=relative(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}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:E(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:E(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=O(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:E(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:E(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:E(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=>A(e)))]:void 0;json(t,200,{ok:!0,deadLinks:p.getDeadLinks(P(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:E(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(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.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{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){json(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){json(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),u;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}u=c}let d=typeof s==`string`&&s.length>0?s:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=A(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let{agentId:p,agentName:m,colorSeed:v,clientName:y,clientVersion:b,label:x}=K(i),S=normalizeSummary(i.summary);if(S.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let C=await n.getSession(f,p,{displayName:m,colorSeed:v,clientName:y}),w=new Date().toISOString(),T=!1,E=!1;try{let e=iconFromClientName(y),t=AGENT_ICON_COLORS[e]??colorFromSeed(v??p);if(g?.setPresence(p,{displayName:m,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),p,v,y),C.dc.document.transact(()=>{let e=C.dc.document.getXmlFragment(`default`),t=C.dc.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=prependFrontmatter(n,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(e,schema).toJSON())),i=u==null?r.indexOf(a):r.slice(u,u+a.length)===a?u:-1;if(i===-1){u==null?T=!0:E=!0;return}let{frontmatter:s,body:c}=stripFrontmatter(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),applyAgentMarkdownWrite(C.dc.document,c,`replace`),C.dc.document.getMap(`agent-flash`).set(p,{agentId:p,timestamp:Date.now(),type:`insert`,description:`Patched (${m}): ${a.slice(0,50)}`})},C.origin),!T&&!E){let{stored:e}=Y(S);recordContributor(f,p,m,v,void 0,J({clientName:y,clientVersion:b,label:x}),e),incrementAgentWriteCalls(),Z(S)}}finally{g?.touchMode(p,`idle`)}if(E){json(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(T){json(t,404,{ok:!1,error:`Text not found in document`});return}N(f,`agent-patch`),h?.setFocus(p,{agentName:m,currentDoc:f,writeKind:`edit`,ts:Date.now()}),_?.();let D=j(f),O=M();O===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":q(y)});let{response:k}=Y(S);json(t,200,{ok:!0,timestamp:w,subscriberCount:D,systemSubscriberCount:O,...k?{summary:k}:{}})}catch(e){log$2.error({err:e},`[agent-patch] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function de(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=K(i),d=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=A(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let p=typeof i.connectionId==`string`?i.connectionId:void 0;if(!p){json(t,400,{ok:!1,error:`connectionId required`});return}let m=i.scope,_=m===`session`||m===`file`?`session`:`last`;if(!n.hasSession(f,p)){json(t,404,{ok:!1,error:`No active session for this connectionId and docName`});return}let v=await n.getSession(f,p),y=!1;try{let e=iconFromClientName(c),t=AGENT_ICON_COLORS[e]??colorFromSeed(s??a);g?.setPresence(a,{displayName:o,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),y=applyAgentUndo(v,_),y&&recordContributor(f,p,o,s,void 0,J({clientName:c,clientVersion:l,label:u}))}finally{g?.touchMode(a,`idle`)}y&&N(f,`agent-undo`),h?.setFocus(p,{agentName:p,currentDoc:f,writeKind:`undo`,ts:Date.now()}),json(t,200,{ok:!0,docName:f,scope:_,undone:y})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),json(t,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=A(a);if(isSystemDoc(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=A(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 t.unloadDocument(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}=K(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(`
121
121
  `)}`: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(`
122
- `),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(e,n){if(e.method!==`POST`){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;try{i=await readBody(e)}catch{json(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{json(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:l,clientName:u,clientVersion:d,label:p}=K(a),{docName:m,commitSha:g,versionTag:_}=a,v=typeof m==`string`?m:``,y=typeof g==`string`?g:``,x=typeof _==`string`?_:void 0;if(!v){json(n,400,{ok:!1,error:`docName required`});return}if(!y||!/^[0-9a-f]{40}$/i.test(y)){json(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let S=a,C=typeof S.agentId==`string`&&S.agentId.length>0,w=normalizeSummary(S.summary);if(w.kind===`invalid`){json(n,400,{ok:!1,error:`summary must be a string`});return}let T=f??`.`,E=safeDocPath(v,T);if(`error`in E){json(n,400,{ok:!1,error:E.error});return}let D=E.path,O=shadowGit(r),k=Date.now();try{try{await O.raw(`cat-file`,`-e`,`${y}:${D}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await O.raw(`show`,`${y}:${D}`),i=new Date().toISOString();await safetyCheckpoint(r,T,{action:`rollback`,context:{docName:v,targetSha:y}});let a=t.documents.get(v);if(!a){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:c,body:m}=stripFrontmatter(e),g=mdManager.parseWithFallback(m),_=schema.nodeFromJSON(g),S=a.getXmlFragment(`default`);a.transact(()=>{updateYFragment(a,S,_,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,c)},ROLLBACK_ORIGIN);let E;if(C){let e=y.slice(0,8),t=w.kind===`value`,n=t?w:normalizeSummary(`Restored to ${e}`),r=Y(n);E=t||!r.response?r.response:X(r.response),recordContributor(v,o,s,l,formatRollbackSubject(v,y),J({clientName:u,clientVersion:d,label:p}),r.stored),incrementAgentWriteCalls(),Z(n,!t)}N(v,`rollback`);let A=Date.now()-k;if(console.log(`[rollback] docName=${v} from=${y.slice(0,8)} duration=${A}ms`),b){let e=`Restored to ${x??y.slice(0,8)}: ${v}`,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)})}C&&h?.setFocus(o,{agentName:s,currentDoc:v,writeKind:`rollback-apply`,ts:Date.now()}),json(n,200,{ok:!0,restoredFrom:y,timestamp:i,...E?{summary:E}:{}})}catch(e){console.error(`[rollback]`,e),json(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}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(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(`
122
+ `),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(e,n){if(e.method!==`POST`){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;try{i=await readBody(e)}catch{json(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{json(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:l,clientName:u,clientVersion:d,label:p}=K(a),{docName:m,commitSha:g,versionTag:_}=a,v=typeof m==`string`?m:``,y=typeof g==`string`?g:``,x=typeof _==`string`?_:void 0;if(!v){json(n,400,{ok:!1,error:`docName required`});return}if(!y||!/^[0-9a-f]{40}$/i.test(y)){json(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let S=a,C=typeof S.agentId==`string`&&S.agentId.length>0,w=normalizeSummary(S.summary);if(w.kind===`invalid`){json(n,400,{ok:!1,error:`summary must be a string`});return}let T=f??`.`,E=safeDocPath(v,T);if(`error`in E){json(n,400,{ok:!1,error:E.error});return}let D=E.path,O=shadowGit(r),k=Date.now();try{try{await O.raw(`cat-file`,`-e`,`${y}:${D}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await O.raw(`show`,`${y}:${D}`),i=new Date().toISOString();await safetyCheckpoint(r,T,{action:`rollback`,context:{docName:v,targetSha:y}});let a=t.documents.get(v);if(!a){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:c,body:m}=stripFrontmatter(e),g=mdManager.parseWithFallback(m),_=schema.nodeFromJSON(g),S=a.getXmlFragment(`default`);a.transact(()=>{updateYFragment(a,S,_,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,c)},ROLLBACK_ORIGIN);let E;if(C){let e=y.slice(0,8),t=w.kind===`value`,n=t?w:normalizeSummary(`Restored to ${e}`),r=Y(n);E=t||!r.response?r.response:X(r.response),recordContributor(v,o,s,l,formatRollbackSubject(v,y),J({clientName:u,clientVersion:d,label:p}),r.stored),incrementAgentWriteCalls(),Z(n,!t)}N(v,`rollback`);let A=Date.now()-k;if(console.log(`[rollback] docName=${v} from=${y.slice(0,8)} duration=${A}ms`),b){let e=`Restored to ${x??y.slice(0,8)}: ${v}`,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)})}C&&h?.setFocus(o,{agentName:s,currentDoc:v,writeKind:`rollback-apply`,ts:Date.now()}),json(n,200,{ok:!0,restoredFrom:y,timestamp:i,...E?{summary:E}:{}})}catch(e){console.error(`[rollback]`,e),json(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}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(`
123
123
  `)[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{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=K(i),{path:f}=i;if(!f||typeof f!=`string`||f.length===0){json(t,400,{ok:!1,error:`path is required`});return}if(!isSupportedDocFile(f)){json(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(f.includes(`..`)||f.startsWith(`/`)||f.includes(`\0`)||f.includes(`\\`)){json(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let h=resolve(r),g=resolve(h,f);if(!g.startsWith(`${h}/`)&&g!==h){json(t,400,{ok:!1,error:`path must not escape content directory`});return}let _=stripDocExtension(f);if(isSystemDoc(_)){json(t,400,{ok:!1,error:`'${_}' is a reserved document name`});return}mkdirSync(dirname(g),{recursive:!0});let v=``;try{writeFileSync(g,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){json(t,409,{ok:!1,error:`File already exists`});return}throw e}let y=stripDocExtension(f);recordContributor(y,o,s,c,void 0,J({clientName:l,clientVersion:u,label:d}));let b=typeof a==`function`?a():null;b instanceof Map&&updateFileIndex({kind:`create`,path:g,docName:y,content:``},b),p&&(p.updateDocumentFromMarkdown(y,``),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${y}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(t,200,{ok:!0,docName:y})}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=T(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{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=K(i),{docName:d,newDocName:f}=i;if(typeof d!=`string`||typeof f!=`string`){json(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!isValidRelativeContentPath(d)||!isValidRelativeContentPath(f)){json(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(isSystemDoc(d)||isSystemDoc(f)){json(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(d===f){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!p){json(t,503,{ok:!1,error:`Backlink index unavailable`});return}let m=i,h=typeof m.agentId==`string`&&m.agentId.length>0,g=normalizeSummary(m.summary);if(g.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let _=resolveContentEntryPath(r,`file`,d),v=resolveContentEntryPath(r,`file`,f);if(!existsSync(_)){json(t,404,{ok:!1,error:`Document does not exist`});return}if(existsSync(v)){json(t,409,{ok:!1,error:`Destination already exists`});return}let y=await W(d,f),b;if(h){let e=g.kind===`value`,t=e?g:normalizeSummary(`Renamed ${d} → ${f}`),n=Y(t);b=e||!n.response?n.response:X(n.response),recordContributor(f,a,o,s,formatRenameSubject(d,f),J({clientName:c,clientVersion:l,label:u}),n.stored),incrementAgentWriteCalls(),Z(t,!e),N(f,`rename`)}json(t,200,{ok:!0,renamed:y.renamed,rewrittenDocs:y.rewrittenDocs,...b?{summary:b}:{}})}catch(e){console.error(`[rename]`,e),json(t,500,{ok:!1,error:L(e)})}}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}K(i);let{kind:o,fromPath:s,toPath:c}=i;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){json(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!isValidRelativeContentPath(s)||!isValidRelativeContentPath(c)){json(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){json(t,200,{ok:!0,renamed:[]});return}let l=resolveContentEntryPath(r,o,s),u=resolveContentEntryPath(r,o,c);if(!existsSync(l)){json(t,404,{ok:!1,error:`${o} does not exist`});return}if(existsSync(u)){json(t,409,{ok:!1,error:`Destination already exists`});return}let d=statSync(l);if(o===`file`&&!d.isFile()||o===`folder`&&!d.isDirectory()){json(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let f=listAffectedDocNames(a(),o,s),h=o===`file`?[{fromDocName:s,toDocName:c}]:f.map(e=>({fromDocName:e,toDocName:remapDocNameForRename(e,o,s,c)})),g=await R(h.map(({fromDocName:e})=>e)),_=async()=>{await renameTrackedPathInGit(b,l,u)||(mkdirSync(dirname(u),{recursive:!0}),renameSync(l,u)),z(h,g)};if(o===`file`)await withManagedRenameRecovery(r,createManagedRenameRecoveryJournal({sourceDocName:s,destinationDocName:c,snapshots:B(h.map(({fromDocName:e})=>e),g)}),_);else{await _();let e=a();for(let{fromDocName:t,toDocName:n}of h)updateFileIndex({kind:`rename`,oldPath:resolveContentEntryPath(r,`file`,t),newPath:resolveContentEntryPath(r,`file`,n),oldDocName:t,newDocName:n,content:g.get(t)??readFileSync(resolveContentEntryPath(r,`file`,n),`utf-8`)},e);if(p){for(let{fromDocName:e,toDocName:t}of h)p.renameDocument(e,t,g.get(e)??readFileSync(resolveContentEntryPath(r,`file`,t),`utf-8`));p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist folder rename cache for ${s} -> ${c}:`,e)}),m?.(`backlinks`),m?.(`graph`)}m?.(`files`)}json(t,200,{ok:!0,renamed:h})}catch(e){console.error(`[rename-path]`,e),json(t,500,{ok:!1,error:`Failed to rename path`})}}async function Pe(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}K(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 R(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 Fe(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;try{e=extractPageTitle(readFileSync(resolve(r,`${t}${getDocExtension(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,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 Ie(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)){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 Le(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await readUploadBody(e,MAX_UPLOAD_BYTES)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?json(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?json(t,400,{ok:!1,error:`No file received`}):json(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:i,buffer:a,parentDocName:o}=n;if(K(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),!o){json(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){json(t,400,{ok:!1,error:`path-escape`});return}let s=resolve(r),c=resolve(s,dirname(o));if(!isWithinContentDir(c,s)){json(t,400,{ok:!1,error:`path-escape`});return}try{let e=realpathSync(c),n;try{n=realpathSync(s)}catch{n=s}if(!isWithinContentDir(e,n)){json(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){json(t,400,{ok:!1,error:`path-escape`});return}}let l=await fileTypeFromBuffer(a),u=l?.mime,d=l?.ext;if(!u){let e=a.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(u=`image/svg+xml`,d=`svg`)}if(!u||!d||!ALLOWED_MIME_TYPES.has(u)){json(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!i||i===`upload`||GENERIC_PASTE_NAMES.test(i)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:sanitizeFilename(i),mkdirSync(c,{recursive:!0});try{let e=writeUploadAtomic(c,f,a),n=relative(r,resolve(c,e));console.log(`[upload] ok ${n} ${a.length}`),json(t,200,{ok:!0,src:e})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${f} ${a.length} ${n}`),json(t,500,{ok:!1,error:`Failed to save file`})}}let Re=`/api/local-op/clone`,ze=`/api/local-op/open`,Be=600*1e3,Ve=45e3;async function He(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(!C.tryAcquire(Re)){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`)},Be);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
124
124
  `);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){C.release(Re);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 Ue(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(),C.release(Re)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),C.release(Re)})}async function Ue(e){let t=resolve(expandTilde(e)),n=resolve(t,`.open-knowledge`),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 We(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(!C.tryAcquire(ze)){json(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await Ue(n);`port`in e?json(t,200,{port:e.port}):json(t,504,{ok:!1,error:e.error})}finally{C.release(ze)}}let Ge=`/api/local-op/auth/login`,Ke=`/api/local-op/auth/status`,qe=`/api/local-op/auth/repos`,Je=`/api/local-op/auth/signout`,Ye=`/api/local-op/auth/pat`;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),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(!C.tryAcquire(Ge)){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`)},Be),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(`
125
125
  `);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()),C.release(Ge)}),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())),C.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(!C.tryAcquire(Ke)){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(`
@@ -139,4 +139,4 @@ What to log:
139
139
  ---`,4);if(!e.startsWith(`---
140
140
  `)||t<0)return;let n=e.slice(4,t),r=n.search(/^metadata:/m);if(r<0)return;let i=n.slice(r).split(`
141
141
  `).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}}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}}const SIDECAR_FILENAME=`skill-installed-version`,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,`.open-knowledge`,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 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)return n.info?.({event:`skill-install.skip-current`,version:a},`Open Knowledge skill already installed at current version; skipping.`),`skip-current`;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`)}export{extractWikiLinksFromMarkdown as $,getShadowRepoPath as $t,applySeed as A,rewriteMarkdownLinksForDocumentRename as At,containsConflictMarkers as B,splitMarkdownBlocks as Bt,SeedPrerequisiteError as C,readUiLock as Ct,acquireUiLock as D,releaseUiLock as Dt,UiLockCollisionError as E,registerWrite as Et,buildWipTree as F,saveInMemoryCheckpoint as Ft,createLiveDerivedIndexExtension as G,updateUiLockPort as Gt,contributorCount as H,starterFolderRule as Ht,classifyEvents as I,saveVersion as It,createServerObserverExtension as J,withSpan as Jt,createPersistenceExtension as K,validateAgentId as Kt,commitUpstreamImport as L,setActiveSpanAttributes as Lt,attachIdleShutdown as M,safeContentPath as Mt,bootServer as N,safeSubdir as Nt,applyAgentMarkdownWrite as O,removeLastKnownHash as Ot,buildSkillZip as P,safetyCheckpoint as Pt,evictStaleTrackerEntries as Q,require_picomatch as Qt,commitWip as R,shadowGit as Rt,STATE_MANIFEST_FILENAME as S,readStateManifest as St,StateManifestError as T,recordContributor as Tt,createApiExtension as U,toBroadcasterKey as Ut,contentHash as V,startWatcher as Vt,createContentFilter as W,updateLastKnownHash as Wt,detectProjectShape as X,writeStateManifest as Xt,detectClaudeDesktopPresence as Y,withSpanSync as Yt,ensureProjectGit as Z,writeTracker as Zt,ProjectGitInitError as _,parseHocuspocusAuthToken as _t,BacklinkIndex as a,incrementCollabSocketFilteredError as at,SERVICE_WRITER as b,planSeed as bt,FILE_SYSTEM_WRITER as c,initTelemetry as ct,HocuspocusAuthRejection as d,isSelfWrite as dt,getWipRefPattern as en,getLogger as et,HocuspocusAuthTokenSchema as f,isSystemDoc as ft,PinoLogger as g,loggerFactory as gt,OBSERVER_SYNC_ORIGIN as h,loadPrincipal as ht,AgentSessionManager as i,handleCollabSocketError as it,assertCompatibleStateManifest as j,rewriteWikiLinksForDocumentRename as jt,applyExternalChange as k,resolveBundledSkillDir as kt,FILE_WATCHER_ORIGIN as l,installUserSkill as lt,MANAGED_RENAME_ORIGIN as m,listRescueCheckpoints as mt,AgentFocusBroadcaster as n,readContributors as nn,getMetrics as nt,CC1Broadcaster as o,incrementServerObserverFire as ot,LOG_MD_TEMPLATE as p,lastKnownHash as pt,createServer$1 as q,validateSkillZip as qt,AgentPresenceBroadcaster as r,getTracer as rt,CONFLICT_MARKER_RE as s,initShadowRepo as st,AGENT_ID_RE as t,parseWriterId as tn,getMeter as tt,GIT_UPSTREAM_WRITER as u,isPairedWriteOrigin as ut,ROLLBACK_ORIGIN as v,parseKeepaliveConnectionId as vt,SeedRootDirError as w,reconcile as wt,STARTER_FOLDERS as x,readBranchFromHead as xt,SEED_CONFIG_FILENAME as y,pathToDocName as yt,commitWipFromTree as z,shutdownTelemetry as zt};
142
- //# sourceMappingURL=dist-6JXIwkTW.mjs.map
142
+ //# sourceMappingURL=dist-B0YYcQi2.mjs.map
@@ -182,7 +182,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
182
182
  `);l.push(m)}n.bulletCurrent=o,n.bulletLastUsed=s;let f=e.spread?`
183
183
 
184
184
  `:`
185
- `;return l.join(f)},mdxJsxFlowElement(e){let t=e.data?.sourceRaw;return typeof t==`string`?t:`<${e.name??``}/>`},mdxJsxTextElement(e){let t=e.data?.sourceRaw;return typeof t==`string`?t:`<${e.name??``}/>`},rawMdxFallback(e){return e.value??``}};function Fz(e){if(!e)return``;let t=0,n=!0;for(let r of e)r===`(`?t++:r===`)`&&(t--,t<0&&(n=!1));return t!==0&&(n=!1),n?e:e.replace(/[\\()]/g,`\\$&`)}function Iz(e){return e.replace(/(?<!\\)&(?=[A-Za-z][A-Za-z0-9]*;|#[0-9]+;|#[xX][0-9A-Fa-f]+;)/g,`\\&`)}function Lz(e,t,n){let r=e.unsafe;e.unsafe=r.filter(e=>!(e.character===`&`&&e.after===`[#A-Za-z]`||e.character===`<`||e.character===`[`||e.character===`(`));let i;try{i=e.safe(t,n)}finally{e.unsafe=r}return Iz(i)}var Rz=class{schema;handlers;pmNodeHandlers;pmMarkHandlers;parseProcessor;serializeProcessor;constructor(e){this.schema=Rl(e.extensions),this.handlers=Hz(this.schema);let{nodeHandlers:t,markHandlers:n}=Uz(this.schema);this.pmNodeHandlers=t,this.pmMarkHandlers=n,this.parseProcessor=kz({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers}),this.serializeProcessor=Az({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers,toMarkdownHandlers:Pz})}parse(e){return e.trim()?jz(e,this.parseProcessor).toJSON():{type:`doc`,content:[{type:`paragraph`,content:[]}]}}parseToMdast(e){return e.trim()?Mz(e,this.parseProcessor):{type:`root`,children:[]}}parseWithFallback(e){return e.trim()?FR(e,{parse:e=>this.parse(e)}):{type:`doc`,content:[{type:`paragraph`,content:[]}]}}serialize(e){let t;try{t=this.schema.nodeFromJSON(e)}catch(t){let n=`MarkdownManager.serialize() failed: schema rejected JSONContent (type=${e.type}, childCount=${e.content?.length??0})`;throw Error(n,{cause:t})}return Nz(t,this.serializeProcessor,{schema:this.schema,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers})}};function zz(e){if(e.type!==`paragraph`)return!1;let t=e.children??[];return t.length===0?!0:t.every(e=>e.type===`text`&&e.value===``)}function Bz(e){if(e.length===0)return{type:`inlineCode`,value:``};if(e.every(e=>e.type===`text`))return{type:`inlineCode`,value:e.map(e=>e.value).join(``)};if(e.length===1&&`children`in e[0]){let t=e[0];return{...t,children:[Bz(t.children)]}}return{type:`inlineCode`,value:Vz(e)}}function Vz(e){let t=``;for(let n of e)n.type===`text`?t+=n.value:`children`in n&&Array.isArray(n.children)?t+=Vz(n.children):`value`in n&&typeof n.value==`string`&&(t+=n.value);return t}function Hz(e){let t=e.nodes,n=e.marks,r={};t.paragraph&&(r.paragraph=(e,n,r)=>{let i=r.all(e).flat(),a=i.some(e=>e?.isBlock&&!e?.isInline),o=i.some(e=>e?.isInline||e?.isText||e?.isTextblock);if(a&&!o)return i.length===1?i[0]:i;if(a&&o){let e=i.filter(e=>!e?.isBlock||e?.isInline),n=i.filter(e=>e?.isBlock&&!e?.isInline),r=[],a=t.paragraph.createAndFill(null,e.length>0?e:null);return a&&r.push(a),r.push(...n),r.length===1?r[0]:r}return t.paragraph.createAndFill(null,i.length>0?i:null)}),t.blockquote&&(r.blockquote=KD(t.blockquote)),t.table&&(r.table=KD(t.table)),t.tableRow&&(r.tableRow=KD(t.tableRow)),t.tableCell&&(r.tableCell=(e=>(n,r,i)=>{let a=i.all(n).flat();if(a.length>0&&t.paragraph){let n=t.paragraph.create(null,a);return e.createAndFill(null,[n])}return e.createAndFill(null,null)})(t.tableCell),t.tableHeader),t.image&&(r.image=e=>t.image.createAndFill({src:e.url??``,alt:e.alt??null,title:e.title??null}),r.imageReference=e=>t.image.createAndFill({src:``,alt:e.alt??null,title:null})),n.escapeMark&&(r.text=t=>{let r=t.value??``,i=typeof t.data?.sourceRaw==`string`?t.data.sourceRaw:null;if(!r&&!i)return null;if(i){let t=r.replaceAll(`\xA0`,` `);return n.sourceLiteral?e.text(t,[n.sourceLiteral.create({sourceRaw:i})]):e.text(t)}let a=t.data?.escapedChars;if(!a?.length)return e.text(r.replaceAll(`\xA0`,` `));let o=[],s=0;for(let{offset:t}of a){if(t>s){let n=r.slice(s,t).replaceAll(`\xA0`,` `);n&&o.push(e.text(n))}if(t<r.length){let i=r[t].replaceAll(`\xA0`,` `);o.push(e.text(i,[n.escapeMark.create()])),s=t+1}}if(s<r.length){let t=r.slice(s).replaceAll(`\xA0`,` `);t&&o.push(e.text(t))}return o.length===1?o[0]:o}),n.code&&(r.inlineCode=t=>e.text(t.value,[n.code.create()]));let i=n.strike??n.delete;if(i&&(r.delete=qD(i)),n.emphasis&&(r.emphasis=qD(n.emphasis,e=>({sourceDelimiter:e.data?.sourceDelimiter??`*`}))),n.strong&&(r.strong=qD(n.strong,e=>({sourceDelimiter:e.data?.sourceDelimiter??`**`}))),t.heading&&(r.heading=KD(t.heading,e=>({level:e.depth,headingStyle:e.data?.sourceStyle??`atx`}))),t.codeBlock&&(r.code=n=>{let r=n.value?[e.text(n.value)]:[];return t.codeBlock.createAndFill({language:n.lang??null,meta:n.meta??null,fenceDelimiter:n.data?.sourceFenceChar??"`",fenceLength:n.data?.sourceFenceLength??3},r)}),t.thematicBreak&&(r.thematicBreak=e=>t.thematicBreak.createAndFill({sourceRaw:e.data?.sourceRaw??`---`})),t.hardBreak&&(r.break=e=>t.hardBreak.createAndFill({hardBreakStyle:e.data?.sourceStyle??`spaces`})),t.list&&(r.list=KD(t.list,e=>({ordered:!!e.ordered,start:e.start??1,spread:!!e.spread,bulletMarker:e.data?.bulletMarker??null,listMarkerDelimiter:e.data?.listMarkerDelimiter??null}))),t.listItem&&(r.listItem=KD(t.listItem,e=>({checked:e.checked??null,spread:!!e.spread}))),n.link){let t=n.sourceLiteral;r.link=(r,i,a)=>{if((r.children??[]).length===0){let n=typeof r.data?.sourceRaw==`string`?r.data.sourceRaw:`[](${r.url??``})`;return n?t?e.text(n,[t.create({sourceRaw:n})]):e.text(n):null}let o=a.all(r).flat(),s=n.link.create({href:r.url??``,title:r.title??null,linkStyle:r.data?.sourceStyle??`inline`,refLabel:null});return o.map(e=>e.mark(s.addToSet(e.marks)))},r.linkReference=(r,i,a)=>{if((r.children??[]).length===0){let n=typeof r.data?.sourceRaw==`string`?r.data.sourceRaw:`[${r.label??``}][${r.identifier??``}]`;return n?t?e.text(n,[t.create({sourceRaw:n})]):e.text(n):null}let o=a.all(r).flat(),s=n.link.create({href:``,title:null,linkStyle:r.referenceType??`shortcut`,refLabel:r.label??r.identifier??null});return o.map(e=>e.mark(s.addToSet(e.marks)))}}t.htmlBlock&&(r.html=e=>t.htmlBlock.createAndFill({content:e.value??``}));let a=t.linkDefinition??t.linkRefDef;if(a){let e=!!a.spec.attrs?.url,t=!!a.spec.attrs?.href,n=!!a.spec.attrs?.identifier;r.definition=r=>{let i={title:r.title??null};return n&&(i.identifier=r.identifier??``),i.label=r.label??r.identifier??``,e?i.url=r.url??``:t&&(i.href=r.url??``),a.createAndFill(i)}}if(t.jsxComponent){let n=e=>{if(e&&typeof e==`object`&&`sourceRaw`in e){let t=e.sourceRaw;if(typeof t==`string`)return t}};r.mdxJsxFlowElement=e=>t.jsxComponent.createAndFill({content:n(e.data)??``}),t.jsxInline?r.mdxJsxTextElement=(e,r,i)=>{let a=i.all(e).flat(),o={sourceRaw:n(e.data)??``,attributes:(e.attributes??[]).map(e=>`type`in e&&e.type===`mdxJsxExpressionAttribute`?{type:`spread`,value:e.value}:{type:`attr`,name:e.name,value:e.value})};return t.jsxInline.createAndFill(o,a.length>0?a:null)}:r.mdxJsxTextElement=e=>t.jsxComponent.createAndFill({content:n(e.data)??``}),r.mdxFlowExpression=e=>t.jsxComponent.createAndFill({content:n(e.data)??`{${e.value??``}}`}),r.mdxTextExpression=t=>{let r=n(t.data)??`{${t.value??``}}`;return e.text(r)}}t.wikiLink&&(r.wikiLink=e=>t.wikiLink.createAndFill({target:e.data?.target??``,alias:e.data?.alias??null,anchor:e.data?.anchor??null}));let o=n=>{let r=n.value??n.type;return t.rawMdxFallback?(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:n.type,reason:`Unhandled block mdast: ${n.type}`})),t.rawMdxFallback.createAndFill({reason:`Unhandled block mdast: ${n.type}`},r?[e.text(r)]:null)):null},s=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled inline mdast: ${t.type}`})),e.text(t.value??t.type));return r.math||=o,r.inlineMath||=s,r.footnoteReference||=s,r.rawMdxFallbackMdast=n=>{if(!t.rawMdxFallback)return null;let r=n.position?{start:n.position.start?.offset??0,end:n.position.end?.offset??0}:{start:0,end:0};return console.warn(JSON.stringify({event:`unknown-mdast-type`,type:n.originalType,reason:`Unhandled mdast: ${n.originalType}`})),t.rawMdxFallback.createAndFill({reason:`Unhandled mdast: ${n.originalType}`,originalSpan:r},n.value?[e.text(n.value)]:null)},r}function Uz(e){let t={},n={},r=e.nodes,i=e.marks;if(r.paragraph&&(t.paragraph=QD(`paragraph`)),r.blockquote&&(t.blockquote=QD(`blockquote`)),r.heading&&(t.heading=QD(`heading`,e=>({depth:e.attrs.level,data:{sourceStyle:e.attrs.headingStyle}}))),r.codeBlock&&(t.codeBlock=e=>({type:`code`,lang:e.attrs.language??null,meta:e.attrs.meta??null,value:e.textContent??``,data:{sourceFenceChar:e.attrs.fenceDelimiter,sourceFenceLength:e.attrs.fenceLength}})),r.thematicBreak&&(t.thematicBreak=e=>({type:`thematicBreak`,data:{sourceRaw:e.attrs.sourceRaw}})),r.hardBreak&&(t.hardBreak=e=>({type:`break`,data:{sourceStyle:e.attrs.hardBreakStyle}})),r.list&&(t.list=QD(`list`,e=>({ordered:e.attrs.ordered??!1,start:e.attrs.ordered?e.attrs.start??1:null,spread:e.attrs.spread??!1,data:{bulletMarker:e.attrs.bulletMarker,listMarkerDelimiter:e.attrs.listMarkerDelimiter}}))),r.listItem&&(t.listItem=(e,t,n)=>{let r=n.all(e),i=r.length>1&&zz(r[0])?r.slice(1):r;return{type:`listItem`,checked:e.attrs.checked??null,spread:e.attrs.spread??!1,children:i}}),r.table&&(t.table=QD(`table`)),r.tableRow&&(t.tableRow=QD(`tableRow`)),r.tableCell&&(t.tableCell=QD(`tableCell`)),r.tableHeader&&(t.tableHeader=QD(`tableCell`)),r.image&&(t.image=e=>({type:`image`,url:e.attrs.src,alt:e.attrs.alt,title:e.attrs.title})),r.htmlBlock&&(t.htmlBlock=e=>({type:`html`,value:e.attrs.content})),r.linkDefinition??r.linkRefDef){let e=r.linkDefinition?`linkDefinition`:`linkRefDef`;t[e]=e=>({type:`definition`,identifier:e.attrs.identifier??e.attrs.label??``,label:e.attrs.label??e.attrs.identifier??``,url:e.attrs.url??e.attrs.href??``,title:e.attrs.title})}if(r.jsxComponent&&(t.jsxComponent=e=>({type:`mdxJsxFlowElement`,name:null,attributes:[],children:[],data:{sourceRaw:String(e.attrs.content??``)}})),r.rawMdxFallback&&(t.rawMdxFallback=e=>{let t=e.textContent??``,n=typeof e.attrs.reason==`string`?e.attrs.reason:``,r=e.attrs.originalSpan;return{type:`rawMdxFallback`,value:t,data:{reason:n,originalSpan:r&&typeof r==`object`&&`start`in r&&`end`in r?{start:Number(r.start)||0,end:Number(r.end)||0}:{start:0,end:0}}}}),r.jsxInline&&(t.jsxInline=e=>{let t=e.attrs.sourceRaw||e.textContent||``;return{type:`mdxJsxTextElement`,name:null,attributes:[],children:[],data:{sourceRaw:String(t)}}}),r.wikiLink&&(t.wikiLink=e=>{let t=e.attrs.target??``,n=e.attrs.anchor??null,r=e.attrs.alias??null,i=r||(n?`${t}#${n}`:t);return{type:`wikiLink`,value:i,data:{target:t,anchor:n,alias:r},children:[{type:`text`,value:i}]}}),i.emphasis&&(n.emphasis=$D(`emphasis`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),i.strong&&(n.strong=$D(`strong`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),i.code&&(n.code=(e,t,n)=>Bz(n)),i.strike??i.delete){let e=i.strike?`strike`:`delete`;n[e]=$D(`delete`)}return i.link&&(n.link=(e,t,n)=>{let r=e.attrs.linkStyle;return r===`autolink`?{type:`link`,url:e.attrs.href??``,title:null,children:n,data:{sourceStyle:`autolink`}}:r===`inline`||!r?{type:`link`,url:e.attrs.href??``,title:e.attrs.title??null,children:n}:{type:`linkReference`,identifier:(e.attrs.refLabel??``).toLowerCase(),label:e.attrs.refLabel,referenceType:r,children:n}}),i.escapeMark&&(n.escapeMark=(e,t,n)=>{for(let e of n)if(e.type===`text`&&e.value){let t=e;t.data=t.data??{},t.data.escapedChars=t.data.escapedChars??[];for(let e=0;e<t.value.length;e++)t.data.escapedChars.push({offset:e,char:t.value[e]})}return n.length===1?n[0]:n}),i.sourceLiteral&&(n.sourceLiteral=(e,t,n)=>{let r=typeof e.attrs.sourceRaw==`string`?e.attrs.sourceRaw:``;if(n.length===1&&n[0]?.type===`text`){let e=n[0];return e.data=e.data??{},e.data.sourceRaw=r||e.value,e}return{type:`text`,value:r,data:{sourceRaw:r}}}),{nodeHandlers:t,markHandlers:n}}const Wz=/\p{M}+/gu,Gz=/[^\p{L}\p{N}]+/gu,Kz=/^-+|-+$/g;function qz(e){return e.trim().normalize(`NFKD`).replace(Wz,``).toLowerCase().replace(Gz,`-`).replace(Kz,``)}function Jz(e,t){let n=t.get(e)??0;return t.set(e,n+1),n===0?e:`${e}-${n}`}function Yz(e,t){let n=qz(e);return n?Jz(n,t):``}$I({ok:fL(!0),serverInstanceId:gI().min(1),currentBranch:gI().min(1).optional(),currentDiskAckSVs:cL(gI().min(1),gI().min(1)).optional()}).loose();const Xz=`server-info`,Zz=`branch-switched`,Qz=`disk-ack`,$z=uL([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`]),eB=$I({v:fL(1),ch:fL(Xz),seq:zI(),serverInstanceId:gI().min(1),currentBranch:gI().min(1).optional()}).loose(),tB=$I({v:fL(1),ch:fL(Zz),seq:zI(),branch:gI().min(1)}).loose(),nB=$I({v:fL(1),ch:$z,seq:zI()}).loose(),rB=$I({v:fL(1),ch:fL(Qz),seq:zI(),docName:gI().min(1),sv:gI().min(1)}).loose(),iB=new UL.default;function aB(e,t){if(e===t)return[{value:e}];let{chars1:n,chars2:r,lineArray:i}=iB.diff_linesToChars_(e,t),a=iB.diff_main(n,r,!1);iB.diff_charsToLines_(a,i),iB.diff_cleanupSemantic(a);let o=[];for(let[e,t]of a)e===UL.default.DIFF_DELETE?o.push({value:t,removed:!0}):e===UL.default.DIFF_INSERT?o.push({value:t,added:!0}):o.push({value:t});return o}const oB=new UL.default;function sB(e,t,n){if(t===n)return;let r=aB(t,n),i=0;for(let n=0;n<r.length;n++){let a=r[n],o=r[n+1];if(a.removed&&o?.added){if(t.substring(i,i+o.value.length)===o.value){i+=o.value.length,n++;continue}e.delete(i,a.value.length),e.insert(i,o.value),i+=o.value.length,n++}else a.removed?e.delete(i,a.value.length):(a.added&&e.insert(i,a.value),i+=a.value.length)}}function cB(e,t,n){if(t===n)return;let r=oB.diff_main(t,n);oB.diff_cleanupSemantic(r);let i=0;for(let[t,n]of r)t===0?i+=n.length:t===-1?e.delete(i,n.length):t===1&&(e.insert(i,n),i+=n.length)}function lB(e){let t=e.getMap(`metadata`).get(`frontmatter`);return typeof t==`string`?t:``}const uB=new UL.default;uB.Match_Threshold=.5;function dB(e,t,n){let r=fB(e,t,n);return vB(e,t,n,r),r}function fB(e,t,n){if(e===t)return n;if(e===n||t===n)return t;let r=HL(t.split(`
185
+ `;return l.join(f)},mdxJsxFlowElement(e){let t=e.data?.sourceRaw;return typeof t==`string`?t:`<${e.name??``}/>`},mdxJsxTextElement(e){let t=e.data?.sourceRaw;return typeof t==`string`?t:`<${e.name??``}/>`},rawMdxFallback(e){return e.value??``}};function Fz(e){if(!e)return``;let t=0,n=!0;for(let r of e)r===`(`?t++:r===`)`&&(t--,t<0&&(n=!1));return t!==0&&(n=!1),n?e:e.replace(/[\\()]/g,`\\$&`)}function Iz(e){return e.replace(/(?<!\\)&(?=[A-Za-z][A-Za-z0-9]*;|#[0-9]+;|#[xX][0-9A-Fa-f]+;)/g,`\\&`)}function Lz(e,t,n){let r=e.unsafe;e.unsafe=r.filter(e=>!(e.character===`&`&&e.after===`[#A-Za-z]`||e.character===`<`||e.character===`[`||e.character===`(`));let i;try{i=e.safe(t,n)}finally{e.unsafe=r}return Iz(i)}var Rz=class{schema;handlers;pmNodeHandlers;pmMarkHandlers;parseProcessor;serializeProcessor;constructor(e){this.schema=Rl(e.extensions),this.handlers=Hz(this.schema);let{nodeHandlers:t,markHandlers:n}=Uz(this.schema);this.pmNodeHandlers=t,this.pmMarkHandlers=n,this.parseProcessor=kz({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers}),this.serializeProcessor=Az({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers,toMarkdownHandlers:Pz})}parse(e){return e.trim()?jz(e,this.parseProcessor).toJSON():{type:`doc`,content:[{type:`paragraph`,content:[]}]}}parseToMdast(e){return e.trim()?Mz(e,this.parseProcessor):{type:`root`,children:[]}}parseWithFallback(e){return e.trim()?FR(e,{parse:e=>this.parse(e)}):{type:`doc`,content:[{type:`paragraph`,content:[]}]}}serialize(e){let t;try{t=this.schema.nodeFromJSON(e)}catch(t){let n=`MarkdownManager.serialize() failed: schema rejected JSONContent (type=${e.type}, childCount=${e.content?.length??0})`;throw Error(n,{cause:t})}return Nz(t,this.serializeProcessor,{schema:this.schema,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers})}};function zz(e){if(e.type!==`paragraph`)return!1;let t=e.children??[];return t.length===0?!0:t.every(e=>e.type===`text`&&e.value===``)}function Bz(e){if(e.length===0)return{type:`inlineCode`,value:``};if(e.every(e=>e.type===`text`))return{type:`inlineCode`,value:e.map(e=>e.value).join(``)};if(e.length===1&&`children`in e[0]){let t=e[0];return{...t,children:[Bz(t.children)]}}return{type:`inlineCode`,value:Vz(e)}}function Vz(e){let t=``;for(let n of e)n.type===`text`?t+=n.value:`children`in n&&Array.isArray(n.children)?t+=Vz(n.children):`value`in n&&typeof n.value==`string`&&(t+=n.value);return t}function Hz(e){let t=e.nodes,n=e.marks,r={};t.paragraph&&(r.paragraph=(e,n,r)=>{let i=r.all(e).flat(),a=i.some(e=>e?.isBlock&&!e?.isInline),o=i.some(e=>e?.isInline||e?.isText||e?.isTextblock);if(a&&!o)return i.length===1?i[0]:i;if(a&&o){let e=i.filter(e=>!e?.isBlock||e?.isInline),n=i.filter(e=>e?.isBlock&&!e?.isInline),r=[],a=t.paragraph.createAndFill(null,e.length>0?e:null);return a&&r.push(a),r.push(...n),r.length===1?r[0]:r}return t.paragraph.createAndFill(null,i.length>0?i:null)}),t.blockquote&&(r.blockquote=KD(t.blockquote)),t.table&&(r.table=KD(t.table)),t.tableRow&&(r.tableRow=KD(t.tableRow)),t.tableCell&&(r.tableCell=(e=>(n,r,i)=>{let a=i.all(n).flat();if(a.length>0&&t.paragraph){let n=t.paragraph.create(null,a);return e.createAndFill(null,[n])}return e.createAndFill(null,null)})(t.tableCell),t.tableHeader),t.image&&(r.image=e=>t.image.createAndFill({src:e.url??``,alt:e.alt??null,title:e.title??null}),r.imageReference=e=>t.image.createAndFill({src:``,alt:e.alt??null,title:null})),n.escapeMark&&(r.text=t=>{let r=t.value??``,i=typeof t.data?.sourceRaw==`string`?t.data.sourceRaw:null;if(!r&&!i)return null;if(i){let t=r.replaceAll(`\xA0`,` `);return n.sourceLiteral?e.text(t,[n.sourceLiteral.create({sourceRaw:i})]):e.text(t)}let a=t.data?.escapedChars;if(!a?.length)return e.text(r.replaceAll(`\xA0`,` `));let o=[],s=0;for(let{offset:t}of a){if(t>s){let n=r.slice(s,t).replaceAll(`\xA0`,` `);n&&o.push(e.text(n))}if(t<r.length){let i=r[t].replaceAll(`\xA0`,` `);o.push(e.text(i,[n.escapeMark.create()])),s=t+1}}if(s<r.length){let t=r.slice(s).replaceAll(`\xA0`,` `);t&&o.push(e.text(t))}return o.length===1?o[0]:o}),n.code&&(r.inlineCode=t=>e.text(t.value,[n.code.create()]));let i=n.strike??n.delete;if(i&&(r.delete=qD(i)),n.emphasis&&(r.emphasis=qD(n.emphasis,e=>({sourceDelimiter:e.data?.sourceDelimiter??`*`}))),n.strong&&(r.strong=qD(n.strong,e=>({sourceDelimiter:e.data?.sourceDelimiter??`**`}))),t.heading&&(r.heading=KD(t.heading,e=>({level:e.depth,headingStyle:e.data?.sourceStyle??`atx`}))),t.codeBlock&&(r.code=n=>{let r=n.value?[e.text(n.value)]:[];return t.codeBlock.createAndFill({language:n.lang??null,meta:n.meta??null,fenceDelimiter:n.data?.sourceFenceChar??"`",fenceLength:n.data?.sourceFenceLength??3},r)}),t.thematicBreak&&(r.thematicBreak=e=>t.thematicBreak.createAndFill({sourceRaw:e.data?.sourceRaw??`---`})),t.hardBreak&&(r.break=e=>t.hardBreak.createAndFill({hardBreakStyle:e.data?.sourceStyle??`spaces`})),t.list&&(r.list=KD(t.list,e=>({ordered:!!e.ordered,start:e.start??1,spread:!!e.spread,bulletMarker:e.data?.bulletMarker??null,listMarkerDelimiter:e.data?.listMarkerDelimiter??null}))),t.listItem&&(r.listItem=KD(t.listItem,e=>({checked:e.checked??null,spread:!!e.spread}))),n.link){let t=n.sourceLiteral;r.link=(r,i,a)=>{if((r.children??[]).length===0){let n=typeof r.data?.sourceRaw==`string`?r.data.sourceRaw:`[](${r.url??``})`;return n?t?e.text(n,[t.create({sourceRaw:n})]):e.text(n):null}let o=a.all(r).flat(),s=n.link.create({href:r.url??``,title:r.title??null,linkStyle:r.data?.sourceStyle??`inline`,refLabel:null});return o.map(e=>e.mark(s.addToSet(e.marks)))},r.linkReference=(r,i,a)=>{if((r.children??[]).length===0){let n=typeof r.data?.sourceRaw==`string`?r.data.sourceRaw:`[${r.label??``}][${r.identifier??``}]`;return n?t?e.text(n,[t.create({sourceRaw:n})]):e.text(n):null}let o=a.all(r).flat(),s=n.link.create({href:``,title:null,linkStyle:r.referenceType??`shortcut`,refLabel:r.label??r.identifier??null});return o.map(e=>e.mark(s.addToSet(e.marks)))}}t.htmlBlock&&(r.html=e=>t.htmlBlock.createAndFill({content:e.value??``}));let a=t.linkDefinition??t.linkRefDef;if(a){let e=!!a.spec.attrs?.url,t=!!a.spec.attrs?.href,n=!!a.spec.attrs?.identifier;r.definition=r=>{let i={title:r.title??null};return n&&(i.identifier=r.identifier??``),i.label=r.label??r.identifier??``,e?i.url=r.url??``:t&&(i.href=r.url??``),a.createAndFill(i)}}if(t.jsxComponent){let n=e=>{if(e&&typeof e==`object`&&`sourceRaw`in e){let t=e.sourceRaw;if(typeof t==`string`)return t}};r.mdxJsxFlowElement=e=>t.jsxComponent.createAndFill({content:n(e.data)??``}),t.jsxInline?r.mdxJsxTextElement=(e,r,i)=>{let a=i.all(e).flat(),o={sourceRaw:n(e.data)??``,attributes:(e.attributes??[]).map(e=>`type`in e&&e.type===`mdxJsxExpressionAttribute`?{type:`spread`,value:e.value}:{type:`attr`,name:e.name,value:e.value})};return t.jsxInline.createAndFill(o,a.length>0?a:null)}:r.mdxJsxTextElement=e=>t.jsxComponent.createAndFill({content:n(e.data)??``}),r.mdxFlowExpression=e=>t.jsxComponent.createAndFill({content:n(e.data)??`{${e.value??``}}`}),r.mdxTextExpression=t=>{let r=n(t.data)??`{${t.value??``}}`;return e.text(r)}}t.wikiLink&&(r.wikiLink=e=>t.wikiLink.createAndFill({target:e.data?.target??``,alias:e.data?.alias??null,anchor:e.data?.anchor??null}));let o=n=>{let r=n.value??n.type;return t.rawMdxFallback?(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:n.type,reason:`Unhandled block mdast: ${n.type}`})),t.rawMdxFallback.createAndFill({reason:`Unhandled block mdast: ${n.type}`},r?[e.text(r)]:null)):null},s=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled inline mdast: ${t.type}`})),e.text(t.value??t.type));return r.math||=o,r.inlineMath||=s,r.footnoteReference||=s,r.rawMdxFallbackMdast=n=>{if(!t.rawMdxFallback)return null;let r=n.position?{start:n.position.start?.offset??0,end:n.position.end?.offset??0}:{start:0,end:0};return console.warn(JSON.stringify({event:`unknown-mdast-type`,type:n.originalType,reason:`Unhandled mdast: ${n.originalType}`})),t.rawMdxFallback.createAndFill({reason:`Unhandled mdast: ${n.originalType}`,originalSpan:r},n.value?[e.text(n.value)]:null)},r}function Uz(e){let t={},n={},r=e.nodes,i=e.marks;if(r.paragraph&&(t.paragraph=QD(`paragraph`)),r.blockquote&&(t.blockquote=QD(`blockquote`)),r.heading&&(t.heading=QD(`heading`,e=>({depth:e.attrs.level,data:{sourceStyle:e.attrs.headingStyle}}))),r.codeBlock&&(t.codeBlock=e=>({type:`code`,lang:e.attrs.language??null,meta:e.attrs.meta??null,value:e.textContent??``,data:{sourceFenceChar:e.attrs.fenceDelimiter,sourceFenceLength:e.attrs.fenceLength}})),r.thematicBreak&&(t.thematicBreak=e=>({type:`thematicBreak`,data:{sourceRaw:e.attrs.sourceRaw}})),r.hardBreak&&(t.hardBreak=e=>({type:`break`,data:{sourceStyle:e.attrs.hardBreakStyle}})),r.list&&(t.list=QD(`list`,e=>({ordered:e.attrs.ordered??!1,start:e.attrs.ordered?e.attrs.start??1:null,spread:e.attrs.spread??!1,data:{bulletMarker:e.attrs.bulletMarker,listMarkerDelimiter:e.attrs.listMarkerDelimiter}}))),r.listItem&&(t.listItem=(e,t,n)=>{let r=n.all(e),i=r.length>1&&zz(r[0])?r.slice(1):r;return{type:`listItem`,checked:e.attrs.checked??null,spread:e.attrs.spread??!1,children:i}}),r.table&&(t.table=QD(`table`)),r.tableRow&&(t.tableRow=QD(`tableRow`)),r.tableCell&&(t.tableCell=QD(`tableCell`)),r.tableHeader&&(t.tableHeader=QD(`tableCell`)),r.image&&(t.image=e=>({type:`image`,url:e.attrs.src,alt:e.attrs.alt,title:e.attrs.title})),r.htmlBlock&&(t.htmlBlock=e=>({type:`html`,value:e.attrs.content})),r.linkDefinition??r.linkRefDef){let e=r.linkDefinition?`linkDefinition`:`linkRefDef`;t[e]=e=>({type:`definition`,identifier:e.attrs.identifier??e.attrs.label??``,label:e.attrs.label??e.attrs.identifier??``,url:e.attrs.url??e.attrs.href??``,title:e.attrs.title})}if(r.jsxComponent&&(t.jsxComponent=e=>({type:`mdxJsxFlowElement`,name:null,attributes:[],children:[],data:{sourceRaw:String(e.attrs.content??``)}})),r.rawMdxFallback&&(t.rawMdxFallback=e=>{let t=e.textContent??``,n=typeof e.attrs.reason==`string`?e.attrs.reason:``,r=e.attrs.originalSpan;return{type:`rawMdxFallback`,value:t,data:{reason:n,originalSpan:r&&typeof r==`object`&&`start`in r&&`end`in r?{start:Number(r.start)||0,end:Number(r.end)||0}:{start:0,end:0}}}}),r.jsxInline&&(t.jsxInline=e=>{let t=e.attrs.sourceRaw||e.textContent||``;return{type:`mdxJsxTextElement`,name:null,attributes:[],children:[],data:{sourceRaw:String(t)}}}),r.wikiLink&&(t.wikiLink=e=>{let t=e.attrs.target??``,n=e.attrs.anchor??null,r=e.attrs.alias??null,i=r||(n?`${t}#${n}`:t);return{type:`wikiLink`,value:i,data:{target:t,anchor:n,alias:r},children:[{type:`text`,value:i}]}}),i.emphasis&&(n.emphasis=$D(`emphasis`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),i.strong&&(n.strong=$D(`strong`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),i.code&&(n.code=(e,t,n)=>Bz(n)),i.strike??i.delete){let e=i.strike?`strike`:`delete`;n[e]=$D(`delete`)}return i.link&&(n.link=(e,t,n)=>{let r=e.attrs.linkStyle;return r===`autolink`?{type:`link`,url:e.attrs.href??``,title:null,children:n,data:{sourceStyle:`autolink`}}:r===`inline`||!r?{type:`link`,url:e.attrs.href??``,title:e.attrs.title??null,children:n}:{type:`linkReference`,identifier:(e.attrs.refLabel??``).toLowerCase(),label:e.attrs.refLabel,referenceType:r,children:n}}),i.escapeMark&&(n.escapeMark=(e,t,n)=>{for(let e of n)if(e.type===`text`&&e.value){let t=e;t.data=t.data??{},t.data.escapedChars=t.data.escapedChars??[];for(let e=0;e<t.value.length;e++)t.data.escapedChars.push({offset:e,char:t.value[e]})}return n.length===1?n[0]:n}),i.sourceLiteral&&(n.sourceLiteral=(e,t,n)=>{let r=typeof e.attrs.sourceRaw==`string`?e.attrs.sourceRaw:``;if(n.length===1&&n[0]?.type===`text`){let e=n[0];return e.data=e.data??{},e.data.sourceRaw=r||e.value,e}return{type:`text`,value:r,data:{sourceRaw:r}}}),{nodeHandlers:t,markHandlers:n}}const Wz=/\p{M}+/gu,Gz=/[^\p{L}\p{N}]+/gu,Kz=/^-+|-+$/g;function qz(e){return e.trim().normalize(`NFKD`).replace(Wz,``).toLowerCase().replace(Gz,`-`).replace(Kz,``)}function Jz(e,t){let n=t.get(e)??0;return t.set(e,n+1),n===0?e:`${e}-${n}`}function Yz(e,t){let n=qz(e);return n?Jz(n,t):``}$I({ok:fL(!0),serverInstanceId:gI().min(1),currentBranch:gI().min(1).optional(),currentDiskAckSVs:cL(gI().min(1),gI().min(1)).optional()}).loose(),$I({id:gI().min(1),display_name:gI().min(1),display_email:gI(),source:uL([`git-config`,`synthesized`]),created_at:gI().min(1)}).loose();const Xz=`server-info`,Zz=`branch-switched`,Qz=`disk-ack`,$z=uL([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`]),eB=$I({v:fL(1),ch:fL(Xz),seq:zI(),serverInstanceId:gI().min(1),currentBranch:gI().min(1).optional()}).loose(),tB=$I({v:fL(1),ch:fL(Zz),seq:zI(),branch:gI().min(1)}).loose(),nB=$I({v:fL(1),ch:$z,seq:zI()}).loose(),rB=$I({v:fL(1),ch:fL(Qz),seq:zI(),docName:gI().min(1),sv:gI().min(1)}).loose(),iB=new UL.default;function aB(e,t){if(e===t)return[{value:e}];let{chars1:n,chars2:r,lineArray:i}=iB.diff_linesToChars_(e,t),a=iB.diff_main(n,r,!1);iB.diff_charsToLines_(a,i),iB.diff_cleanupSemantic(a);let o=[];for(let[e,t]of a)e===UL.default.DIFF_DELETE?o.push({value:t,removed:!0}):e===UL.default.DIFF_INSERT?o.push({value:t,added:!0}):o.push({value:t});return o}const oB=new UL.default;function sB(e,t,n){if(t===n)return;let r=aB(t,n),i=0;for(let n=0;n<r.length;n++){let a=r[n],o=r[n+1];if(a.removed&&o?.added){if(t.substring(i,i+o.value.length)===o.value){i+=o.value.length,n++;continue}e.delete(i,a.value.length),e.insert(i,o.value),i+=o.value.length,n++}else a.removed?e.delete(i,a.value.length):(a.added&&e.insert(i,a.value),i+=a.value.length)}}function cB(e,t,n){if(t===n)return;let r=oB.diff_main(t,n);oB.diff_cleanupSemantic(r);let i=0;for(let[t,n]of r)t===0?i+=n.length:t===-1?e.delete(i,n.length):t===1&&(e.insert(i,n),i+=n.length)}function lB(e){let t=e.getMap(`metadata`).get(`frontmatter`);return typeof t==`string`?t:``}const uB=new UL.default;uB.Match_Threshold=.5;function dB(e,t,n){let r=fB(e,t,n);return vB(e,t,n,r),r}function fB(e,t,n){if(e===t)return n;if(e===n||t===n)return t;let r=HL(t.split(`
186
186
  `),e.split(`
187
187
  `),n.split(`
188
188
  `)),i=[];for(let e=0;e<r.length;e++){let t=r[e];if(`ok`in t&&t.ok)i.push(t.ok.join(`
@@ -195,5 +195,5 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
195
195
  `).map(e=>e.trimEnd()).join(`
196
196
  `).replace(/\n{3,}/g,`
197
197
 
198
- `).replace(/\n+$/,``)}const xB={setTimeout:(e,t)=>globalThis.setTimeout(e,t),clearTimeout:e=>globalThis.clearTimeout(e),now:()=>Date.now()};function SB(){let e=!1,t=``,n=0;return r=>{let i=CB(r);return e?(i&&i.char===t&&i.len>=n&&!i.hasInfo&&(e=!1,t=``,n=0),!0):i?(e=!0,t=i.char,n=i.len,!0):!1}}function CB(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const wB=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],TB={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function EB(e){let t=0;for(let n of e)t=(t<<5)-t+n.charCodeAt(0)|0;return wB[Math.abs(t)%wB.length]}const DB={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,copilot:`github`,cline:`cline`};function OB(e){return e?DB[e]??`bot`:`bot`}function kB(e,t){let n=e.trim();if(!n||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(n)||n.startsWith(`//`)||n.startsWith(`/`)||n.startsWith(`#`))return null;let r=n.indexOf(`#`),i=r>=0?n.slice(0,r):n,a=r>=0?n.slice(r+1):null,o=(i.split(`?`)[0]??``).trim();if(!o)return null;let s=o.endsWith(`.md`)?o.slice(0,-3):o,c=t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of s.split(`/`))if(e===`..`){if(c.length===0)return null;c.pop()}else e!==`.`&&e!==``&&c.push(e);return c.length===0?null:{docName:c.join(`/`),anchor:a||null}}const AB=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function jB(e){let t=e.trim();return AB.test(t)||t.startsWith(`//`)}function MB(e,t){let n=e.trim();if(!n)return null;if(n.startsWith(`#`)){let e=n.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}let r=kB(n,t);return r?{kind:`doc`,docName:r.docName,anchor:r.anchor}:n.startsWith(`/`)||jB(n)?{kind:`external`,url:n}:null}function NB(e,t){let n=e.trim();return n?jB(n)?{kind:`external`,url:t?`${n}#${t}`:n}:{kind:`doc`,docName:n,anchor:t?.trim()||null}:null}export{qI as $,bB as A,UI as B,lB as C,OB as D,CR as E,qz as F,eL as G,iL as H,hL as I,gL as J,zI as K,uL as L,kB as M,wR as N,KL as O,tR as P,nL as Q,GI as R,xB as S,kR as T,oL as U,PL as V,fL as W,cL as X,LL as Y,gI as Z,sB as _,m as _t,tB as a,pN as at,EB as b,eB as c,yj as ct,Xz as d,YA as dt,SI as et,Rz as f,Q as ft,cB as g,En as gt,WL as h,Rl as ht,hB as i,XP as it,nR as j,dB as k,Zz as l,xj as lt,GL as m,Z as mt,JL as n,WF as nt,nB as o,DM as ot,qL as p,$ as pt,$I as q,YL as r,YP as rt,rB as s,_j as st,TB as t,KF as tt,Qz as u,Cj as ut,MB as v,u as vt,Yz as w,SB as x,NB as y,ZI as z};
199
- //# sourceMappingURL=dist-DRC09WNZ.mjs.map
198
+ `).replace(/\n+$/,``)}const xB={setTimeout:(e,t)=>globalThis.setTimeout(e,t),clearTimeout:e=>globalThis.clearTimeout(e),now:()=>Date.now()};function SB(){let e=!1,t=``,n=0;return r=>{let i=CB(r);return e?(i&&i.char===t&&i.len>=n&&!i.hasInfo&&(e=!1,t=``,n=0),!0):i?(e=!0,t=i.char,n=i.len,!0):!1}}function CB(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const wB=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],TB={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function EB(e,t=wB){let n=0;for(let t of e)n=(n<<5)-n+t.charCodeAt(0)|0;return t[Math.abs(n)%t.length]}const DB={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,copilot:`github`,cline:`cline`};function OB(e){return e?DB[e]??`bot`:`bot`}function kB(e,t){let n=e.trim();if(!n||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(n)||n.startsWith(`//`)||n.startsWith(`/`)||n.startsWith(`#`))return null;let r=n.indexOf(`#`),i=r>=0?n.slice(0,r):n,a=r>=0?n.slice(r+1):null,o=(i.split(`?`)[0]??``).trim();if(!o)return null;let s=o.endsWith(`.md`)?o.slice(0,-3):o,c=t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of s.split(`/`))if(e===`..`){if(c.length===0)return null;c.pop()}else e!==`.`&&e!==``&&c.push(e);return c.length===0?null:{docName:c.join(`/`),anchor:a||null}}const AB=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function jB(e){let t=e.trim();return AB.test(t)||t.startsWith(`//`)}function MB(e,t){let n=e.trim();if(!n)return null;if(n.startsWith(`#`)){let e=n.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}let r=kB(n,t);return r?{kind:`doc`,docName:r.docName,anchor:r.anchor}:n.startsWith(`/`)||jB(n)?{kind:`external`,url:n}:null}function NB(e,t){let n=e.trim();return n?jB(n)?{kind:`external`,url:t?`${n}#${t}`:n}:{kind:`doc`,docName:n,anchor:t?.trim()||null}:null}export{qI as $,bB as A,UI as B,lB as C,OB as D,CR as E,qz as F,eL as G,iL as H,hL as I,gL as J,zI as K,uL as L,kB as M,wR as N,KL as O,tR as P,nL as Q,GI as R,xB as S,kR as T,oL as U,PL as V,fL as W,cL as X,LL as Y,gI as Z,sB as _,m as _t,tB as a,pN as at,EB as b,eB as c,yj as ct,Xz as d,YA as dt,SI as et,Rz as f,Q as ft,cB as g,En as gt,WL as h,Rl as ht,hB as i,XP as it,nR as j,dB as k,Zz as l,xj as lt,GL as m,Z as mt,JL as n,WF as nt,nB as o,DM as ot,qL as p,$ as pt,$I as q,YL as r,YP as rt,rB as s,_j as st,TB as t,KF as tt,Qz as u,Cj as ut,MB as v,u as vt,Yz as w,SB as x,NB as y,ZI as z};
199
+ //# sourceMappingURL=dist-CXdg7KnM.mjs.map
@@ -1 +1 @@
1
- import"./dist-DRC09WNZ.mjs";import{l as e,o as t}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{Ct as n,D as r,Dt as i,E as a,Gt as o,N as s,Z as c,_ as l,et as u}from"./dist-6JXIwkTW.mjs";export{l as ProjectGitInitError,a as UiLockCollisionError,r as acquireUiLock,s as bootServer,c as ensureProjectGit,u as getLogger,t as isProcessAlive,e as readServerLock,n as readUiLock,i as releaseUiLock,o as updateUiLockPort};
1
+ import"./dist-CXdg7KnM.mjs";import{l as e,o as t}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{Ct as n,D as r,Dt as i,E as a,Gt as o,N as s,Z as c,_ as l,et as u}from"./dist-B0YYcQi2.mjs";export{l as ProjectGitInitError,a as UiLockCollisionError,r as acquireUiLock,s as bootServer,c as ensureProjectGit,u as getLogger,t as isProcessAlive,e as readServerLock,n as readUiLock,i as releaseUiLock,o as updateUiLockPort};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{c as e,i as t,l as n,s as r,t as i,u as a}from"./init-BbOWk8q3.mjs";import{n as o,r as s}from"./loader-DDxmojUu.mjs";import"./src-DObpODAp.mjs";export{n as ALL_EDITOR_IDS,s as ConfigSchema,a as EDITOR_TARGETS,i as detectInstalledEditors,o as loadConfig,t as readExistingMcpEntry,r as writeEditorMcpConfig,e as writeUserMcpConfigs};
1
+ import{c as e,i as t,l as n,s as r,t as i,u as a}from"./init-tBs47qTU.mjs";import{n as o,r as s}from"./loader-CZ-UM2X7.mjs";import"./src-BJrUlYqe.mjs";export{n as ALL_EDITOR_IDS,s as ConfigSchema,a as EDITOR_TARGETS,i as detectInstalledEditors,o as loadConfig,t as readExistingMcpEntry,r as writeEditorMcpConfig,e as writeUserMcpConfigs};
@@ -1 +1 @@
1
- import{a as e,c as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./init-BbOWk8q3.mjs";export{s as detectInstalledEditors,r as formatInitResult,a as initCommand,n as readExistingMcpEntry,e as resolveMcpScope,i as runInit,o as writeEditorMcpConfig,t as writeUserMcpConfigs};
1
+ import{a as e,c as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./init-tBs47qTU.mjs";export{s as detectInstalledEditors,r as formatInitResult,a as initCommand,n as readExistingMcpEntry,e as resolveMcpScope,i as runInit,o as writeEditorMcpConfig,t as writeUserMcpConfigs};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./init-DO08hYU-.mjs";export{t as ensureOkGitignoredAtRoot,e as initContent};
@@ -1,4 +1,4 @@
1
- import{n as e,t}from"./constants-DBvBsqEJ.mjs";import{p as n}from"./dist-DRC09WNZ.mjs";import{join as r,resolve as i}from"node:path";import{existsSync as a,mkdirSync as o,readFileSync as s,writeFileSync as c}from"node:fs";const l=`# Open Knowledge — workspace configuration
1
+ import{n as e,t}from"./constants-TQwGMmUq.mjs";import{p as n}from"./dist-CXdg7KnM.mjs";import{join as r,resolve as i}from"node:path";import{existsSync as a,mkdirSync as o,readFileSync as s,writeFileSync as c}from"node:fs";const l=`# Open Knowledge — workspace configuration
2
2
  #
3
3
  # This file overrides built-in defaults for this workspace. Every key below
4
4
  # is commented out and shows its current default value. Uncomment any key
@@ -117,4 +117,4 @@ import{n as e,t}from"./constants-DBvBsqEJ.mjs";import{p as n}from"./dist-DRC09WN
117
117
 
118
118
  `)?`
119
119
  `:``}${i}`,`utf-8`),`appended`)}const f=[{name:`.gitignore`,content:`${t}/\nserver.lock\nui.lock\nsync-state.json\n`},{name:e,content:l}];function p(e){let a=i(e,n),s=[],c=[];o(a,{recursive:!0}),o(r(a,t),{recursive:!0});for(let e of f)u(r(a,e.name),e.content)?s.push(e.name):c.push(e.name);return{created:s,skipped:c}}export{p as n,d as t};
120
- //# sourceMappingURL=init-Di2sbASA.mjs.map
120
+ //# sourceMappingURL=init-DO08hYU-.mjs.map
@@ -1,4 +1,4 @@
1
- import{n as e,t}from"./esm-wByiX8MO.mjs";import{r as n}from"./constants-DBvBsqEJ.mjs";import{p as r}from"./dist-DRC09WNZ.mjs";import{Y as i,Z as a,_ as o,lt as s}from"./dist-6JXIwkTW.mjs";import{n as c}from"./init-Di2sbASA.mjs";import{t as l}from"./preview-VXVGRaUP.mjs";import{s as u,t as d}from"./colors-DoPZvo1q.mjs";import{t as f}from"./is-object-BNVklKxg.mjs";import{basename as p,dirname as m,join as h,posix as g,relative as _,resolve as v,sep as y,win32 as b}from"node:path";import{existsSync as x,mkdirSync as S,readFileSync as C,writeFileSync as w}from"node:fs";import{homedir as T}from"node:os";import E from"@inquirer/checkbox";
1
+ import{n as e,t}from"./esm-wByiX8MO.mjs";import{r as n}from"./constants-TQwGMmUq.mjs";import{p as r}from"./dist-CXdg7KnM.mjs";import{Y as i,Z as a,_ as o,lt as s}from"./dist-B0YYcQi2.mjs";import{n as c}from"./init-DO08hYU-.mjs";import{t as l}from"./preview-DPnNj-m8.mjs";import{s as u,t as d}from"./colors-DoPZvo1q.mjs";import{t as f}from"./is-object-BNVklKxg.mjs";import{basename as p,dirname as m,join as h,posix as g,relative as _,resolve as v,sep as y,win32 as b}from"node:path";import{existsSync as x,mkdirSync as S,readFileSync as C,writeFileSync as w}from"node:fs";import{homedir as T}from"node:os";import E from"@inquirer/checkbox";
2
2
  /*!
3
3
  * Copyright (c) Squirrel Chat et al., All rights reserved.
4
4
  * SPDX-License-Identifier: BSD-3-Clause
@@ -251,5 +251,5 @@ let F=/^[a-z0-9-_]+$/i;function I(e){let t=typeof e;if(t===`object`){if(Array.is
251
251
  `)?n:`${n}\n`,`utf-8`)}const Re=e=>e!==`project`,Y=e=>e!==`user`;async function ze(){let e=await E({message:`Where should the MCP server be configured?
252
252
  `,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function Be(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??ze)():`both`}const Ve=`0.0.1`,X=`open-knowledge-ui`;function He(e,t={}){let n=h(e,`.claude`,`launch.json`),r=t.mode===`dev`?{name:X,runtimeExecutable:`node`,runtimeArgs:[V(t.cliEntryPath),`ui`],port:3e3}:{name:X,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:3e3};try{if(!x(n))return S(m(n),{recursive:!0}),w(n,`${JSON.stringify({version:Ve,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let e=C(n,`utf-8`).trim(),t=e?JSON.parse(e):{};if(!f(t))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let i=Array.isArray(t.configurations)?t.configurations:[],a=i.findIndex(e=>f(e)&&e.name===X);a>=0?i[a]=r:i.push(r);let o={...t,version:t.version??Ve,configurations:i};return w(n,`${JSON.stringify(o,null,2)}\n`,`utf-8`),{action:a>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function Z(e,t,n){try{return x(e.detectPath?.(t,n)??m(e.configPath(t,n)))}catch{return!1}}function Q(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}if(!i&&!n.skipAvailabilityCheck&&!Z(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};let s;try{s=e.format===`toml`?Fe(o):Pe(o)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let c=s[e.topLevelKey]??{},l=c[a],u;try{u=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let d={...s,[e.topLevelKey]:{...c,[a]:u}};try{e.format===`toml`?Le(o,d):Ie(o,d)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:l===void 0?`written`:`overwritten`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}function Ue(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!x(n)))return{editorId:e.id,label:e.label,path:n}}async function We(e){let t=J(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>Q(t,``,n,e.home))}function Ge(e,t,n){let r;try{r=e.configPath(t,n)}catch{return null}let i;try{i=e.format===`toml`?Fe(r):Pe(r)}catch{return null}let a=i[e.topLevelKey];if(!f(a))return null;let o=a[e.serverName(t)];return f(o)?o:null}async function Ke(e={}){let t=v(e.cwd??process.cwd()),n={mode:e.pin?`pinned`:e.devMcp?`dev`:`published`,cliEntryPath:e.cliEntryPath},r=await a(t),o;try{o=c(t)}catch(n){let i=q.claude.configPath(t,e.home);return{contentCreated:[],contentSkipped:[],editors:[],legacyProjectConfigs:[],didGitInit:r.didInit,claudeDesktopDetected:!1,mcpAction:`failed`,mcpPath:i,mcpError:`Content scaffolding failed: ${n instanceof Error?n.message:String(n)}`}}let l=await Be({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),u=e.editors??$(t,e.home),d=e.editors??B.filter(e=>q[e].projectConfigPath!==void 0),f=J(u),p=J(d),m=e.mcp===!1||l===null,h=Array.from(new Map([...f,...m?[]:p].map(e=>[e.id,e])).values()),g=f.filter(n=>Z(n,t,e.home)),_=[],y=new Set;for(let r of h){if(m){let n=``;try{n=r.configPath(t,e.home)}catch{}_.push({editorId:r.id,label:r.label,action:`skipped-flag`,configPath:n,serverName:r.serverName(t)});continue}if(Re(l)&&f.includes(r)&&_.push(Q(r,t,n,e.home)),Y(l)&&p.includes(r)&&r.projectConfigPath){let i=r.projectConfigPath(t),a=Q(r,t,n,e.home,i);_.push(a),(a.action===`written`||a.action===`overwritten`)&&y.add(i)}}let b=!m&&l!==null&&Y(l)?p.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,x=m?[]:g.map(e=>Ue(e,t)).filter(e=>e!==void 0).filter(e=>!y.has(e.path)),S=g.some(e=>e.id===`claude`)&&!m?He(t,n):void 0,C=await(e.installUserSkill??s)({home:e.home}),w=i({home:e.home}),T=m?`skipped-flag`:`skipped-missing`,E=_.find(e=>e.editorId===`claude`)??_[0]??{action:T,configPath:q.claude.configPath(t,e.home)};return{contentCreated:o.created,contentSkipped:o.skipped,editors:_,legacyProjectConfigs:x,launchJson:S,skillInstall:C,didGitInit:r.didInit,claudeDesktopDetected:w,mcpAction:E.action,mcpPath:E.configPath,mcpError:`error`in E?E.error:void 0,projectScopeUnsupportedLabels:b}}function qe(e,t){let n=[],i=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),a=e.editors.some(e=>e.action===`failed`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),s=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),c=e=>{let n=e.configPath.startsWith(t)?_(t,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${n} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${n} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${n} FAILED: ${e.error}`}};e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`);let f=h(t,r);if(e.contentCreated.length>0?(n.push(`Content scaffolded at ${f}/`),n.push(` Created: ${e.contentCreated.join(`, `)}`)):n.push(`Content already present at ${f}/`),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)if(n.push(`MCP server configuration:`),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`);else if(o)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(s)n.push(`MCP server configuration:`),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(`MCP server configuration:`);for(let r of e.editors){let i=r.configPath.startsWith(t)?_(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),a=r.serverName===`open-knowledge`?``:` (${r.serverName})`,o=r.configScope===`project`?` (project)`:``,s=`${r.label}${o}`,l=` `.repeat(Math.max(1,20-s.length)),u=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${s}${l}${i} registered${a}${u}`);break;case`overwritten`:n.push(` ${s}${l}${i} updated${a}${u}`);break;case`skipped-missing`:n.push(` ${s}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${s}${l}${i} FAILED: ${r.error}`);break;case`skipped-flag`:break}r.editorId===`claude`&&e.launchJson&&n.push(c(e.launchJson))}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(a&&(n.push(``),n.push(`For failed editors, add the MCP server entry manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${_(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(`User-global skill:`),e.skillInstall){case`installed`:n.push(" open-knowledge installed to detected agent hosts via `npx skills`");break;case`skip-current`:n.push(` open-knowledge already installed at current version`);break;case`failed`:n.push(` ${u(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${u(` npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy`)}`);break}if(e.claudeDesktopDetected&&(n.push(``),n.push(`Claude Desktop App detected. To enable in Claude Chat & Cowork, run: ${d(`ok install-skill`)}`)),e.preview?(n.push(``),n.push(l(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),i){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`Next steps:`),n.push(` 1. Open your editor (${r.join(` / `)})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ok seed`),n.push(` 4. Use the three MCP workflow tools as you build the wiki:`),n.push(` - mcp__open-knowledge__ingest — capture an external source`),n.push(` - mcp__open-knowledge__research — gather sources and write findings`),n.push(` - mcp__open-knowledge__consolidate — promote research to canonical articles`)}return n.join(`
253
253
  `)}function $(e,t){let n=[];for(let r of B)Z(q[r],e,t)&&n.push(r);return n}function Je(){return new t(`init`).description(`Scaffold ${r}/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the ${r}/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).addOption(new e(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).option(`--pin`,"Pin the MCP entry to the absolute path of the current CLI binary instead of `npx`. Use a stable shim like /usr/local/bin/ok for upgrade-safe pinning; npx-cache or worktree paths will go stale on reinstall.").option(`--no-pin`,"Use the default unpinned `npx @inkeep/open-knowledge mcp` MCP entry").action(async e=>{let t=process.cwd(),n;try{n=await Ke({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,pin:e.pin})}catch(e){if(e instanceof o){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
254
- `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-D18jtdLK.mjs`),{loadConfig:r}=await import(`./loader-DvcPWYAi.mjs`),{resolveContentDir:i}=await import(`./paths-DXVpv4hT.mjs`),{config:a}=r(t),o=i(a,t);n.preview=e({projectDir:t,contentDir:o,include:a.content.include,exclude:a.content.exclude})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${qe(n,t)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{Be as a,We as c,Ge as i,B as l,qe as n,Ke as o,Je as r,Q as s,$ as t,q as u};
255
- //# sourceMappingURL=init-BbOWk8q3.mjs.map
254
+ `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-DtcWIT_s.mjs`),{loadConfig:r}=await import(`./loader-BrDZjZ-u.mjs`),{resolveContentDir:i}=await import(`./paths-Dti9tbQm.mjs`),{config:a}=r(t),o=i(a,t);n.preview=e({projectDir:t,contentDir:o,include:a.content.include,exclude:a.content.exclude})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${qe(n,t)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{Be as a,We as c,Ge as i,B as l,qe as n,Ke as o,Je as r,Q as s,$ as t,q as u};
255
+ //# sourceMappingURL=init-tBs47qTU.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e}from"./loader-CZ-UM2X7.mjs";export{e as loadConfig};
@@ -1,3 +1,3 @@
1
- import{t as e}from"./dist-BCyi1oM7.mjs";import{n as t}from"./constants-DBvBsqEJ.mjs";import{B as n,K as r,Z as i,et as a,p as o,q as s,z as c}from"./dist-DRC09WNZ.mjs";import{t as l}from"./is-object-BNVklKxg.mjs";import{resolve as u}from"node:path";import{existsSync as d,readFileSync as f}from"node:fs";import{homedir as p}from"node:os";import{realpath as m}from"node:fs/promises";async function h(e){let t=u(e);try{return await m(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}const g=s({title:i().optional(),description:i().optional(),tags:c(i()).optional()}).strict(),_=s({match:i().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:g}).strict(),v=s({content:s({dir:i().default(`.`),include:c(i()).min(1).default([`**/*.md`,`**/*.mdx`]),exclude:c(i()).default([])}).default({dir:`.`,include:[`**/*.md`,`**/*.mdx`],exclude:[]}),github:s({oauthAppClientId:i().default(`Ov23liqlSd0V1MwR6rhI`)}).default({oauthAppClientId:`Ov23liqlSd0V1MwR6rhI`}),sync:s({enabled:n().optional(),pushIntervalSeconds:r().int().min(1).default(60),pullIntervalSeconds:r().int().min(1).default(30),autoCommit:n().default(!0),autoPush:n().default(!0),autoPull:n().default(!0),commitMessage:i().default(`auto`)}).default({pushIntervalSeconds:60,pullIntervalSeconds:30,autoCommit:!0,autoPush:!0,autoPull:!0,commitMessage:`auto`}),server:s({port:r().int().min(0).max(65535).default(0),host:i().regex(/^[\w.\-:]+$/,`Invalid hostname`).default(`localhost`),openOnAgentEdit:n().default(!1)}).default({port:0,host:`localhost`,openOnAgentEdit:!1}),persistence:s({debounceMs:r().int().min(0).default(2e3),maxDebounceMs:r().int().min(0).default(1e4)}).default({debounceMs:2e3,maxDebounceMs:1e4}),preview:s({baseUrl:a().optional()}).default({}),folders:c(_).default([]),mcp:s({autoStart:n().default(!0),tools:s({read_document:s({historyDepth:r().int().min(0).default(5)}).default({historyDepth:5}),search:s({maxResults:r().int().min(1).default(50)}).default({maxResults:50})}).default({read_document:{historyDepth:5},search:{maxResults:50}})}).default({autoStart:!0,tools:{read_document:{historyDepth:5},search:{maxResults:50}}})});var y=e();function b(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];l(a)&&l(i)?n[r]=b(i,a):a!==void 0&&(n[r]=a)}return n}function x(e){if(!d(e))return null;try{let t=(0,y.parse)(f(e,`utf-8`));return l(t)?t:null}catch(t){return console.warn(`[config] Failed to parse ${e}: ${t instanceof Error?t.message:t}`),null}}function S(e){let n=e??process.cwd(),r=[],i=u(p(),o,t),a={},s=x(i);s&&(a=b(a,s),r.push(i));let c=u(n,o,t),l=x(c);l&&(a=b(a,l),r.push(c));let d=v.safeParse(a);if(!d.success){let e=d.error.issues.map(e=>` ${e.path.join(`.`)}: ${e.message}`);throw Error(`Invalid configuration:\n${e.join(`
1
+ import{t as e}from"./dist-BCyi1oM7.mjs";import{n as t}from"./constants-TQwGMmUq.mjs";import{B as n,K as r,Z as i,et as a,p as o,q as s,z as c}from"./dist-CXdg7KnM.mjs";import{t as l}from"./is-object-BNVklKxg.mjs";import{resolve as u}from"node:path";import{existsSync as d,readFileSync as f}from"node:fs";import{homedir as p}from"node:os";import{realpath as m}from"node:fs/promises";async function h(e){let t=u(e);try{return await m(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}const g=s({title:i().optional(),description:i().optional(),tags:c(i()).optional()}).strict(),_=s({match:i().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:g}).strict(),v=s({content:s({dir:i().default(`.`),include:c(i()).min(1).default([`**/*.md`,`**/*.mdx`]),exclude:c(i()).default([])}).default({dir:`.`,include:[`**/*.md`,`**/*.mdx`],exclude:[]}),github:s({oauthAppClientId:i().default(`Ov23liqlSd0V1MwR6rhI`)}).default({oauthAppClientId:`Ov23liqlSd0V1MwR6rhI`}),sync:s({enabled:n().optional(),pushIntervalSeconds:r().int().min(1).default(60),pullIntervalSeconds:r().int().min(1).default(30),autoCommit:n().default(!0),autoPush:n().default(!0),autoPull:n().default(!0),commitMessage:i().default(`auto`)}).default({pushIntervalSeconds:60,pullIntervalSeconds:30,autoCommit:!0,autoPush:!0,autoPull:!0,commitMessage:`auto`}),server:s({port:r().int().min(0).max(65535).default(0),host:i().regex(/^[\w.\-:]+$/,`Invalid hostname`).default(`localhost`),openOnAgentEdit:n().default(!1)}).default({port:0,host:`localhost`,openOnAgentEdit:!1}),persistence:s({debounceMs:r().int().min(0).default(2e3),maxDebounceMs:r().int().min(0).default(1e4)}).default({debounceMs:2e3,maxDebounceMs:1e4}),preview:s({baseUrl:a().optional()}).default({}),folders:c(_).default([]),mcp:s({autoStart:n().default(!0),tools:s({read_document:s({historyDepth:r().int().min(0).default(5)}).default({historyDepth:5}),search:s({maxResults:r().int().min(1).default(50)}).default({maxResults:50})}).default({read_document:{historyDepth:5},search:{maxResults:50}})}).default({autoStart:!0,tools:{read_document:{historyDepth:5},search:{maxResults:50}}})});var y=e();function b(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];l(a)&&l(i)?n[r]=b(i,a):a!==void 0&&(n[r]=a)}return n}function x(e){if(!d(e))return null;try{let t=(0,y.parse)(f(e,`utf-8`));return l(t)?t:null}catch(t){return console.warn(`[config] Failed to parse ${e}: ${t instanceof Error?t.message:t}`),null}}function S(e){let n=e??process.cwd(),r=[],i=u(p(),o,t),a={},s=x(i);s&&(a=b(a,s),r.push(i));let c=u(n,o,t),l=x(c);l&&(a=b(a,l),r.push(c));let d=v.safeParse(a);if(!d.success){let e=d.error.issues.map(e=>` ${e.path.join(`.`)}: ${e.message}`);throw Error(`Invalid configuration:\n${e.join(`
2
2
  `)}`)}return{config:d.data,sources:r}}function C(e,t=process.env){let n=e;return t.PORT&&(n={...n,server:{...n.server,port:Number(t.PORT)}}),t.HOST&&(n={...n,server:{...n.server,host:t.HOST}}),n}function w(e){let t=e.env??process.env,n=e.cacheMs??1e3,r=e.loadConfigFn??S,i=new Map,a=new Map,o=h(e.startupCwd);return async s=>{let c=await h(s??e.startupCwd),l=Date.now(),u=i.get(c);if(u&&u.expiresAt>l)return u.config;let d=a.get(c);if(d)return await d;let f=(async()=>{if(c===await o){let r=C(e.startupConfig,t);return i.set(c,{config:r,expiresAt:Date.now()+n}),r}let a=C(r(c).config,t);return i.set(c,{config:a,expiresAt:Date.now()+n}),a})();a.set(c,f);try{return await f}finally{a.delete(c)}}}export{h as i,S as n,v as r,w as t};
3
- //# sourceMappingURL=loader-DDxmojUu.mjs.map
3
+ //# sourceMappingURL=loader-CZ-UM2X7.mjs.map
@@ -0,0 +1,2 @@
1
+ import"./constants-TQwGMmUq.mjs";import{p as e}from"./dist-CXdg7KnM.mjs";import{resolve as t}from"node:path";function n(e,n){return t(n,e.content.dir)}function r(n){return t(n,e)}export{r as n,n as t};
2
+ //# sourceMappingURL=paths-C6QLabWV.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./paths-C6QLabWV.mjs";export{t as resolveContentDir,e as resolveLockDir};
@@ -1,3 +1,3 @@
1
- import"./constants-DBvBsqEJ.mjs";import{p as e}from"./dist-DRC09WNZ.mjs";import{W as t}from"./dist-6JXIwkTW.mjs";import{join as n,relative as r}from"node:path";import{existsSync as i,lstatSync as a,readdirSync as o,realpathSync as s,statSync as c}from"node:fs";function l(e){let{projectDir:i,contentDir:l,include:u,exclude:d,sampleCap:f=5}=e,p=[],m=[];try{a(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let h;try{h=t({projectDir:i,contentDir:l,includePatterns:u,excludePatterns:d})}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[e instanceof Error?e.message:String(e)]}}function g(e){let t;try{t=o(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);p.push(`could not read directory ${r(l,e)||`.`}: ${n}`);return}for(let i of t){let t=n(e,i.name);if(i.isSymbolicLink()){let e;try{e=s(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?p.push(`broken or cyclic symlink: ${r(l,t)}`):p.push(`cannot resolve symlink ${r(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=c(e)}catch{continue}if(n.isDirectory()){let e=r(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(n.isFile()){let e=r(l,t);if(h.isExcluded(e))continue;m.push(e)}}else if(i.isDirectory()){let e=r(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(i.isFile()){let e=r(l,t);if(h.isExcluded(e))continue;m.push(e)}}}return g(l),{totalCount:m.length,sample:m.slice(0,f),contentDir:l,include:u,exclude:d,warnings:p}}function u(t,a){let o=[],s=r(a,t.contentDir),c=s===``?`./`:`./${s}`;o.push(`Content:`),o.push(` Found ${t.totalCount} markdown files in ${c}`);let l=t.include.join(`, `),u=t.exclude.length>0?t.exclude.join(`, `):`(none)`;if(o.push(` Scope: include=${l} exclude=${u}`),t.sample.length>0){let e=t.sample.join(`, `),n=t.totalCount>t.sample.length?`, …`:``;o.push(` Sample: ${e}${n}`)}if(t.warnings.length>0)for(let e of t.warnings)o.push(` Warning: ${e}`);return o.push(``),i(n(a,`.open-knowledge`,`config.yml`))?(o.push(` To adjust, edit ${e}/config.yml:`),o.push(` content:`),o.push(` include: ${JSON.stringify(t.include)}`),o.push(` exclude: ${JSON.stringify(t.exclude)}`)):(o.push(" Run `open-knowledge init` to scaffold config, then adjust:"),o.push(` ${e}/config.yml → content.include / content.exclude`)),o.push(``),o.push(` Re-check anytime: open-knowledge preview`),o.join(`
1
+ import"./constants-TQwGMmUq.mjs";import{p as e}from"./dist-CXdg7KnM.mjs";import{W as t}from"./dist-B0YYcQi2.mjs";import{join as n,relative as r}from"node:path";import{existsSync as i,lstatSync as a,readdirSync as o,realpathSync as s,statSync as c}from"node:fs";function l(e){let{projectDir:i,contentDir:l,include:u,exclude:d,sampleCap:f=5}=e,p=[],m=[];try{a(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let h;try{h=t({projectDir:i,contentDir:l,includePatterns:u,excludePatterns:d})}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[e instanceof Error?e.message:String(e)]}}function g(e){let t;try{t=o(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);p.push(`could not read directory ${r(l,e)||`.`}: ${n}`);return}for(let i of t){let t=n(e,i.name);if(i.isSymbolicLink()){let e;try{e=s(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?p.push(`broken or cyclic symlink: ${r(l,t)}`):p.push(`cannot resolve symlink ${r(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=c(e)}catch{continue}if(n.isDirectory()){let e=r(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(n.isFile()){let e=r(l,t);if(h.isExcluded(e))continue;m.push(e)}}else if(i.isDirectory()){let e=r(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(i.isFile()){let e=r(l,t);if(h.isExcluded(e))continue;m.push(e)}}}return g(l),{totalCount:m.length,sample:m.slice(0,f),contentDir:l,include:u,exclude:d,warnings:p}}function u(t,a){let o=[],s=r(a,t.contentDir),c=s===``?`./`:`./${s}`;o.push(`Content:`),o.push(` Found ${t.totalCount} markdown files in ${c}`);let l=t.include.join(`, `),u=t.exclude.length>0?t.exclude.join(`, `):`(none)`;if(o.push(` Scope: include=${l} exclude=${u}`),t.sample.length>0){let e=t.sample.join(`, `),n=t.totalCount>t.sample.length?`, …`:``;o.push(` Sample: ${e}${n}`)}if(t.warnings.length>0)for(let e of t.warnings)o.push(` Warning: ${e}`);return o.push(``),i(n(a,`.open-knowledge`,`config.yml`))?(o.push(` To adjust, edit ${e}/config.yml:`),o.push(` content:`),o.push(` include: ${JSON.stringify(t.include)}`),o.push(` exclude: ${JSON.stringify(t.exclude)}`)):(o.push(" Run `open-knowledge init` to scaffold config, then adjust:"),o.push(` ${e}/config.yml → content.include / content.exclude`)),o.push(``),o.push(` Re-check anytime: open-knowledge preview`),o.join(`
2
2
  `)}export{l as n,u as t};
3
- //# sourceMappingURL=preview-VXVGRaUP.mjs.map
3
+ //# sourceMappingURL=preview-DPnNj-m8.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./preview-DPnNj-m8.mjs";export{t as formatPreviewBlock,e as previewContent};