@inkeep/open-knowledge 0.58.0-beta.5 → 0.58.0-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{acp-harness-probe-HyCUAcqz.mjs → acp-harness-probe-Dc4QtyQO.mjs} +2 -2
- package/dist/cli.mjs +7 -7
- package/dist/constants-c1VuifcA.mjs +2 -0
- package/dist/index.d.mts +6 -1
- package/dist/index.mjs +1 -1
- package/dist/{init-D6ieeOmh.mjs → init-CpcterGz.mjs} +4 -4
- package/dist/init-DV09g6ez.mjs +1 -0
- package/dist/{launch-json-removal-BosWz0v3.mjs → launch-json-removal-Ci74hesJ.mjs} +2 -2
- package/dist/loader-Cl4ixwGJ.mjs +1 -0
- package/dist/{loader-DFNYYp22.mjs → loader-D0BmknIi.mjs} +2 -2
- package/dist/{open-browser-BPu-89ta.mjs → open-browser-Cqyn_9Z_.mjs} +2 -2
- package/dist/{preview-CcR7xZvt.mjs → preview-BrV2S7Xj.mjs} +2 -2
- package/dist/preview-CbWq8-zC.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-7yIJaJ6P.js → ActivityModeContent-B0Fp59Qv.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-BKGkMpsG.js → AgentDiffPane-BbIuRvv1.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-DgSsGod3.js → CodeMirrorPropInput-BIdbAIO5.js} +1 -1
- package/dist/public/assets/{DocumentContext-DPq9sJWi.js → DocumentContext-DC_8e-cY.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-CFQbYcpO.js → EditorModeToggle-CAig-JLx.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-DYqK-sce.js → EnableSyncConfirmDialog-CfR-i3bq.js} +1 -1
- package/dist/public/assets/FeedbackForm-CxomQJwt.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-D75a2XUJ.js → ImportSkillDialog-CsbbMAso.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-CEAJETDd.js → LintConfigEditor-CMwVctJo.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-CFyAtv5K.js → ManagedArtifactProperties-BW4zT-vN.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-Bph9HlOT.js +1 -0
- package/dist/public/assets/{MermaidDocEditor-Di4SmFxl.js → MermaidDocEditor-DmX2UpSP.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-croqN1WB.js → PropertyDisplayRow-WuuztauZ.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-BUwT3twG.js → SchemaConfigEditor-DuCTZiY-.js} +1 -1
- package/dist/public/assets/{SessionsHost-CjL4hVGx.js → SessionsHost-BTd7O7Aa.js} +2 -2
- package/dist/public/assets/SettingsDialogBody-CkI0KfUL.js +13 -0
- package/dist/public/assets/{ShareReceiveMissDialog-B9zIOjTz.js → ShareReceiveMissDialog-CiPRwQlY.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-Dy6qlv4u.js → SkillToolbarControls-BsmREi0B.js} +1 -1
- package/dist/public/assets/{SourceEditor-mQz1l9nC.js → SourceEditor-CVACSHpy.js} +1 -1
- package/dist/public/assets/{TerminalPanel-BoyBy9g0.js → TerminalPanel-BW1Psxow.js} +2 -2
- package/dist/public/assets/{TerminalWindowApp-KyeXtMf3.js → TerminalWindowApp-DX6H7O5q.js} +1 -1
- package/dist/public/assets/{TextDocEditor-CD-I-oOU.js → TextDocEditor-ywHStFmo.js} +1 -1
- package/dist/public/assets/{ThreadView-BtDD-SRc.js → ThreadView-CoW0wzMZ.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-Da3-e9fr.js → TimelineDiffPane-3beAKThM.js} +1 -1
- package/dist/public/assets/{auth-state-cache-CuH6CKxc.js → auth-state-cache-BBp_stem.js} +4 -4
- package/dist/public/assets/{comment-chips-D5xKtU9g.js → comment-chips-Bfc8H6sv.js} +1 -1
- package/dist/public/assets/{config-provider-B7ZUW3Cz.js → config-provider-Wm9R6Y25.js} +3 -3
- package/dist/public/assets/{follow-file-uY0slLW-.js → follow-file-BpuglSLQ.js} +1 -1
- package/dist/public/assets/i18n-BbGgvVoN.js +1 -0
- package/dist/public/assets/index-B1a_Nq9z.js +2095 -0
- package/dist/public/assets/messages-6l97Z9l-.js +1 -0
- package/dist/public/assets/messages-B6xCk04J.js +1 -0
- package/dist/public/assets/messages-BdOR8jpl.js +1 -0
- package/dist/public/assets/messages-BiqhEyiZ.js +1 -0
- package/dist/public/assets/messages-CWuRF_g4.js +1 -0
- package/dist/public/assets/messages-ChE4ifHJ.js +1 -0
- package/dist/public/assets/messages-D-dvdC6u.js +1 -0
- package/dist/public/assets/messages-D3F4EU1O.js +1 -0
- package/dist/public/assets/messages-D7hPscmx.js +1 -0
- package/dist/public/assets/messages-Debu1u7T.js +1 -0
- package/dist/public/assets/messages-Dr79fPY9.js +1 -0
- package/dist/public/assets/messages-Dwk3zwPu.js +1 -0
- package/dist/public/assets/{pending-receive-nav-store-Wyoy5niY.js → pending-receive-nav-store-BaSwjYK0.js} +1 -1
- package/dist/public/assets/{selection-context-D7vwZXJ0.js → selection-context-DaLbLtKV.js} +1 -1
- package/dist/public/assets/{skill-actions-CBVW4hba.js → skill-actions-BG-1EQmx.js} +1 -1
- package/dist/public/assets/{src-itM4u1hC.js → src-_CcgHCm_.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-OOjImtVw.js → typing-burst-detector-BySvqCzC.js} +1 -1
- package/dist/public/assets/{uninstall-C7egmAzI.js → uninstall-DgUSAKgm.js} +1 -1
- package/dist/public/assets/{use-activity-panel-BIIDpwUa.js → use-activity-panel-o4JQhNM3.js} +1 -1
- package/dist/public/assets/{use-open-skill-CRmHOtbi.js → use-open-skill-CR8e9H_i.js} +1 -1
- package/dist/public/assets/{use-popular-skills-A2kqZ0fe.js → use-popular-skills-BySTLo8O.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-C0IIE3r2.js → use-terminal-enabled-CfeUtq4N.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-BZCJGFcX.js → use-timeline-entry-diff-W_B-6UDh.js} +1 -1
- package/dist/public/index.html +19 -19
- package/dist/public/uninstall.html +3 -3
- package/dist/{repair-launch-json-hw9gMhyK.mjs → repair-launch-json-PUVNVFKs.mjs} +2 -2
- package/dist/{repair-mcp-configs-Bx8Usc5z.mjs → repair-mcp-configs-BOQLD8vy.mjs} +2 -2
- package/dist/repair-skills-BUtcN0G7.mjs +1 -0
- package/dist/repair-skills-D2MDLtIb.mjs +4 -0
- package/dist/{skill-teardown-DkXFhNS5.mjs → skill-teardown-u_V1IN7V.mjs} +2 -2
- package/dist/src-CClot_u_.mjs +1 -0
- package/dist/{src-vUi58oUc.mjs → src-CyDF8_Em.mjs} +3 -3
- package/dist/{src-DXUB2UY6.mjs → src-D88J_dwf.mjs} +1 -1
- package/dist/{src-C8tGPqIo.mjs → src-oJpaRu7w.mjs} +2 -2
- package/dist/start-C0IEJ4Mw.mjs +1 -0
- package/dist/{start-FqbGTZfE.mjs → start-Dcjq6fwo.mjs} +4 -4
- package/dist/{ui-CSG2PuL4.mjs → ui-CTuTY_Ny.mjs} +3 -3
- package/dist/{write-project-skill-CQEMn_bx.mjs → write-project-skill-CqrttBia.mjs} +2 -2
- package/package.json +4 -4
- package/dist/constants-B2EFNagU.mjs +0 -2
- package/dist/init-YPSUWBAm.mjs +0 -1
- package/dist/loader-BbP1oXK-.mjs +0 -1
- package/dist/preview-4CO3p1vc.mjs +0 -1
- package/dist/public/assets/FeedbackForm-Bf4DDe7f.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-7eNmgu7b.js +0 -1
- package/dist/public/assets/SettingsDialogBody-3h2sdeud.js +0 -13
- package/dist/public/assets/i18n-B3oDuqj2.js +0 -1
- package/dist/public/assets/index-CkPbFGTQ.js +0 -2095
- package/dist/public/assets/messages-BUKQqP5n.js +0 -1
- package/dist/public/assets/messages-BmlnDR4L.js +0 -1
- package/dist/public/assets/messages-BqnLMqg_.js +0 -1
- package/dist/public/assets/messages-BuSTFUZ-.js +0 -1
- package/dist/public/assets/messages-CNspiWFZ.js +0 -1
- package/dist/public/assets/messages-Ct3bLMYi.js +0 -1
- package/dist/public/assets/messages-CuDAWjTY.js +0 -1
- package/dist/public/assets/messages-DC-hhIW5.js +0 -1
- package/dist/public/assets/messages-DDpSh6SS.js +0 -1
- package/dist/public/assets/messages-DtiULVMq.js +0 -1
- package/dist/public/assets/messages-LVLy1rup.js +0 -1
- package/dist/public/assets/messages-OZvFoE_L.js +0 -1
- package/dist/repair-skills-BL2fDxUw.mjs +0 -1
- package/dist/repair-skills-CVxJr9ri.mjs +0 -4
- package/dist/src-tAM8LtL6.mjs +0 -1
- package/dist/start-CAdeeJ4_.mjs +0 -1
|
@@ -29,7 +29,7 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,At as i,Bt
|
|
|
29
29
|
`);return t===``?void 0:t}function GE(...e){let t=e.filter(e=>e!==void 0&&e!==``).join(`
|
|
30
30
|
`);return t===``?void 0:t}function KE(e,t){let n=t.authStderr===null?void 0:t.authStderr.join(`
|
|
31
31
|
`);return GE(HE(e),n)}function qE(e){return(e??[]).flatMap(e=>{if(typeof e!=`object`||!e)return[];let{id:t,name:n,description:r,type:i}=e;return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,name:n,...typeof r==`string`?{description:r}:{},...typeof i==`string`?{kind:i}:{}}]})}const JE=new Set([`create`,`subscribe`,`unsubscribe`,`prompt`,`steer`,`queue_edit`,`queue_hold`,`queue_remove`,`permission_response`,`runtime_consent_response`,`cancel`,`set_mode`,`set_config_option`,`close`,`rename`,`resume`,`retry`,`authenticate`,`delete`,`list`]);function YE(e){if(e===void 0)return!0;if(!Array.isArray(e))return!1;for(let t of e){if(typeof t!=`object`||!t)return!1;let e=t;if(e.kind===`file`||e.kind===`folder`){if(typeof e.path!=`string`||typeof e.name!=`string`)return!1}else if(e.kind===`image`){if(typeof e.data!=`string`||typeof e.mimeType!=`string`||typeof e.name!=`string`||e.sizeBytes!==void 0&&typeof e.sizeBytes!=`number`)return!1}else if(e.kind===`blob`){if(typeof e.data!=`string`||typeof e.textPayload!=`boolean`||typeof e.mimeType!=`string`||typeof e.name!=`string`||e.sizeBytes!==void 0&&typeof e.sizeBytes!=`number`)return!1}else return!1}return!0}function XE(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;if(typeof n.op!=`string`||!JE.has(n.op))return null;let r=e=>typeof n[e]==`string`&&n[e]!==``;switch(n.op){case`create`:{if(!r(`reqId`))return null;let e=n.agent;if(typeof e!=`object`||!e||e.source!==`registry`&&e.source!==`custom`||typeof e.id!=`string`||e.id===``||n.prompt!==void 0&&typeof n.prompt!=`string`||n.docName!==void 0&&typeof n.docName!=`string`)return null;if(n.settings!==void 0){let e=n.settings;if(typeof e!=`object`||!e)return null;if(e.config!==void 0){let t=e.config;if(typeof t!=`object`||!t||Array.isArray(t))return null;for(let e of Object.values(t))if(typeof e!=`string`&&typeof e!=`boolean`)return null}if(e.modeId!==void 0&&typeof e.modeId!=`string`)return null}return YE(n.attachments)?n:null}case`subscribe`:return!r(`threadId`)||n.sinceSeq!==void 0&&typeof n.sinceSeq!=`number`?null:n;case`prompt`:return!r(`threadId`)||!r(`reqId`)||typeof n.content!=`string`||!YE(n.attachments)?null:n;case`steer`:{if(!r(`threadId`)||!r(`reqId`)||typeof n.content!=`string`||!YE(n.attachments))return null;let e=Array.isArray(n.attachments)&&n.attachments.length>0;return n.content===``&&!e?null:n}case`queue_edit`:return!r(`threadId`)||!r(`id`)||!r(`content`)||n.reqId!==void 0&&!r(`reqId`)?null:n;case`queue_hold`:return!r(`threadId`)||!r(`id`)||typeof n.held!=`boolean`?null:n;case`queue_remove`:return!r(`threadId`)||!r(`id`)?null:n;case`permission_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;if(typeof e!=`object`||!e)return null;if(e.kind===`selected`){if(typeof e.optionId!=`string`||e.optionId===``)return null}else if(e.kind!==`cancelled`)return null;return n}case`runtime_consent_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;return typeof e!=`object`||!e||e.kind!==`granted`&&e.kind!==`declined`?null:n}case`set_mode`:return!r(`threadId`)||!r(`modeId`)?null:n;case`rename`:return!r(`threadId`)||!r(`title`)?null:n;case`set_config_option`:return!r(`threadId`)||!r(`configId`)||typeof n.value!=`string`&&typeof n.value!=`boolean`||n.value===``?null:n;case`resume`:return!r(`threadId`)||!r(`reqId`)||n.prompt!==void 0&&typeof n.prompt!=`string`||!YE(n.attachments)?null:n;case`retry`:return!r(`threadId`)||!r(`reqId`)?null:n;case`authenticate`:return!r(`threadId`)||!r(`reqId`)||!r(`methodId`)?null:n;case`unsubscribe`:case`cancel`:case`close`:case`delete`:return r(`threadId`)?n:null;case`list`:return n;default:return null}}function ZE(e,t,n){let r=new Map,i=t=>{try{e.send(JSON.stringify(t))}catch(e){n.warn({err:e},`[acp-thread-socket] send failed`)}},a=(e,t,n)=>i(QE(e,t,n));e.on(`message`,e=>{let s=XE(typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):``);if(s===null){a(`bad-frame`,`unrecognized frame`);return}(async()=>{try{switch(s.op){case`list`:i({op:`threads`,threads:t.listThreads()});return;case`create`:{let e=await t.createThread({agent:s.agent,prompt:s.prompt,attachments:s.attachments,docName:s.docName,titleHint:s.titleHint,settings:s.settings});i({op:`created`,reqId:s.reqId,info:e}),await o(e.threadId,0);return}case`subscribe`:await o(s.threadId,s.sinceSeq??0);return;case`resume`:{let e=await t.resumeThread(s.threadId,s.prompt,s.attachments);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`retry`:{let e=await t.retryThread(s.threadId);i({op:`retried`,reqId:s.reqId,info:e});return}case`authenticate`:{let e=await t.authenticateThread(s.threadId,s.methodId);i({op:`authenticated`,reqId:s.reqId,info:e});return}case`delete`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.deleteThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}case`unsubscribe`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId));return}case`prompt`:t.sendPrompt(s.threadId,s.content,s.attachments);return;case`steer`:t.steerPrompt(s.threadId,s.content,s.attachments);return;case`queue_edit`:{let e=t.editQueued(s.threadId,s.id,s.content);s.reqId!==void 0&&(e?i({op:`queue_edited`,reqId:s.reqId,threadId:s.threadId}):a(`not-ready`,`queued message already dispatched`,{reqId:s.reqId,threadId:s.threadId}));return}case`queue_hold`:t.holdQueued(s.threadId,s.id,s.held);return;case`queue_remove`:t.removeQueued(s.threadId,s.id);return;case`permission_response`:t.respondPermission(s.threadId,s.requestId,s.outcome);return;case`runtime_consent_response`:t.respondRuntimeConsent(s.threadId,s.requestId,s.outcome);return;case`cancel`:t.cancel(s.threadId);return;case`set_mode`:t.setMode(s.threadId,s.modeId);return;case`rename`:await t.renameThread(s.threadId,s.title);return;case`set_config_option`:t.setConfigOption(s.threadId,s.configId,s.value);return;case`close`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.closeThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}}}catch(e){e instanceof AE?a(e.code,e.message,{reqId:`reqId`in s?s.reqId:void 0,threadId:`threadId`in s?s.threadId:void 0}):(n.error({err:e,op:s.op},`[acp-thread-socket] frame handling failed`),a(`internal`,`internal error`,{reqId:`reqId`in s?s.reqId:void 0}))}})()});let o=async(e,n)=>{if(r.has(e))return;let o=e=>i(e);r.set(e,o);try{let s=t.getInfo(e);if(s===void 0){r.delete(e),a(`unknown-thread`,`no thread '${e}'`,{threadId:e});return}i({op:`subscribed`,threadId:e,fromSeq:Math.max(n,0),info:s}),await t.subscribe(e,n,o)}catch(t){if(r.delete(e),t instanceof AE)a(t.code,t.message,{threadId:e});else throw t}};e.on(`close`,()=>{for(let[e,n]of r)t.unsubscribe(e,n);r.clear()}),e.on(`error`,e=>{n.warn({err:e},`[acp-thread-socket] socket error`)})}function QE(e,t,n){return{op:`error`,code:e,message:t,...n}}var $E=class{hocuspocus;log=N(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){bh(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){bh(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(Gt);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),eD(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function eD(e){return e?.awareness??null}var tD=class{hocuspocus;log=N(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!bh(e))return;let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!bh(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!bh(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!bh(e))return;let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return kse(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(Gt);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),nD(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function nD(e){return e?.awareness??null}var rD=class extends Error{};const iD=[`/.well-known/agent-skills/index.json`,`/.well-known/skills/index.json`],aD=1024*1024;async function oD(e,t,n,r){let i=t;for(let t=0;t<=5;t++){let t=await e(i,{...r,redirect:`manual`});if(t.status<300||t.status>=400)return t;let a=t.headers.get(`location`);if(a===null||a===``)throw new rD(`Website skill redirect carried no location: ${i}`);let o;try{o=new URL(a,i)}catch{throw new rD(`Website skill redirect target is not a URL: ${a}`)}if(o.protocol!==`https:`||o.origin!==n)throw new rD(`Website skill redirect left the origin (${n}): ${o.href}`);i=o.href}throw new rD(`Website skill fetch exceeded 5 redirects: ${t}`)}function sD(e){let t;try{t=new URL(e)}catch{throw new rD(`Invalid website skill origin: ${e}`)}if(t.protocol!==`https:`||t.username||t.password)throw new rD(`Website skill origins must be credential-free HTTPS URLs: ${e}`);if(t.pathname!==`/`||t.search||t.hash)throw new rD(`Website skill origins cannot include a path, query, or fragment: ${e}`);return t.origin}function cD(e){return!e||e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function lD(e){if(!e||typeof e!=`object`)return null;let t=e.skills;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||typeof e!=`object`)return null;let{name:t,description:r,files:i}=e;if(typeof t!=`string`||!cD(t)||t.includes(`/`)||r!==void 0&&typeof r!=`string`||!Array.isArray(i)||i.length===0||i.length>513||!i.every(e=>typeof e==`string`&&cD(e))||new Set(i).size!==i.length||!i.includes(`SKILL.md`))return null;n.push({name:t,description:r??``,files:i})}return n}function uD(e,t,n,r){let i=[n,...r.split(`/`)].map(encodeURIComponent).join(`/`);return new URL(`${t}/${i}`,e).href}async function dD(e,t,n){let r=[];for(let i of iD){let a=new URL(i,e).href;try{let o=await oD(t,a,e,{signal:AbortSignal.timeout(n)});if(!o.ok){r.push(`${i}: HTTP ${o.status}`);continue}let s=await o.text();if(Buffer.byteLength(s)>aD){r.push(`${i}: index exceeds ${aD} bytes`);continue}let c;try{c=JSON.parse(s)}catch{r.push(`${i}: response is not JSON`);continue}let l=lD(c);if(!l){r.push(`${i}: unsupported or malformed index`);continue}return{basePath:i.slice(0,-11),skills:l}}catch(e){r.push(`${i}: ${e instanceof Error?e.message:String(e)}`)}}throw new rD(`No usable website skill index at ${e} (${r.join(`; `)})`)}async function fD(e,t={}){let{skills:n}=t.index??await pD(e,t);return n.map(({name:e,description:t})=>({name:e,description:t}))}async function pD(e,t={}){let n=sD(e),r=t.fetchImpl??globalThis.fetch;if(!r)throw new rD(`No fetch implementation available.`);return dD(n,r,t.timeoutMs??15e3)}async function mD(e,t={}){if(!cD(e.skill)||e.skill.includes(`/`))throw new rD(`Invalid website skill name: ${e.skill}`);let n=sD(e.origin),r=t.fetchImpl??globalThis.fetch;if(!r)throw new rD(`No fetch implementation available.`);let i=t.timeoutMs??15e3,{basePath:a,skills:o}=t.index??await dD(n,r,i),s=o.find(t=>t.name===e.skill);if(!s)throw new rD(`Website skill index does not contain ${e.skill}`);let c=Lu(F(ed(),`ok-skill-site-`)),l=F(c,s.name),u=0;try{let e=[...s.files],t=async e=>{let t=await oD(r,uD(n,a,s.name,e),n,{signal:AbortSignal.timeout(i)});if(!t.ok)throw new rD(`Website skill file returned HTTP ${t.status}: ${e}`);let o=Number(t.headers.get(`content-length`));if(Number.isFinite(o)&&o>16777216)throw new rD(`Website skill file exceeds ${wn} bytes: ${e}`);let c=new Uint8Array(await t.arrayBuffer());if(c.byteLength>16777216)throw new rD(`Website skill file exceeds ${wn} bytes: ${e}`);if(u+=c.byteLength,u>67108864)throw new rD(`Website skill bundle exceeds ${tr} bytes.`);let d=F(l,...e.split(`/`));Iu(P(d),{recursive:!0}),Yu(d,c)};return await Promise.all(Array.from({length:Math.min(8,e.length)},async()=>{for(let n=e.shift();n!==void 0;n=e.shift())await t(n)})),{dir:l,cleanup:()=>Gu(c,{recursive:!0,force:!0})}}catch(t){throw Gu(c,{recursive:!0,force:!0}),t instanceof rD?t:new rD(`Could not fetch website skill ${e.skill}: ${t instanceof Error?t.message:String(t)}`)}}const hD=_d(du),gD=/^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/,_D=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/];function vD(e){let t=e.trim();if(t===``)return null;if(t.startsWith(`file://`))return{kind:`local`,path:t.slice(7)};if(t.startsWith(`/`)||t.startsWith(`.`)||t.startsWith(`~`))return{kind:`local`,path:t};if(t.startsWith(`git@`)||t.includes(`://`))return _D.some(e=>e.test(t))?{kind:`git`,url:t}:null;let n=gD.exec(t);if(n){let[,e,t,r]=n;return{kind:`git`,url:`https://github.com/${e}/${t}.git`,subpath:r}}return null}function yD(e){let t=e.trim();if(t===``)return null;let n=e=>{let t=e.split(`/`).filter(Boolean).map(decodeURIComponent);if(t.length!==3)return null;let[n,r,i]=t,a=n===`site`?r:n,o=i;return a&&o?{owner:a,skill:o}:null};if(/^https?:\/\//i.test(t))try{let e=new URL(t),r=e.hostname.toLowerCase();return r!==`skills.sh`&&r!==`www.skills.sh`?null:n(e.pathname)}catch{return null}let r=/^skills\.sh\/(.+)$/i.exec(t);if(r)return n(r[1]??``);let i=/^skills\.sh\s+([\w.-]+)\/([\w.-]+)$/i.exec(t);if(i){let[,e,t]=i;return e&&t?{owner:e,skill:t}:null}return null}async function bD(e,t={}){if(e.kind===`well-known`)return mD(e,t);if(e.kind===`local`){let t=L(e.path.replace(/^~(?=\/|$)/,process.env.HOME??`~`));if(!z(t))throw new rD(`Local path not found: ${t}`);return{dir:t,cleanup:()=>{}}}if(/^[a-z][a-z0-9+.-]+:/i.test(e.url)&&!_D.some(t=>t.test(e.url)))throw new rD(`Unsupported git transport: ${e.url}`);let n=Lu(F(ed(),`ok-skill-import-`));try{await hD(`git`,[`-c`,`core.symlinks=false`,`clone`,`-q`,`--depth`,`1`,`--`,e.url,n],{timeout:6e4,maxBuffer:16*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}})}catch(t){Gu(n,{recursive:!0,force:!0});let r=t instanceof Error?t.message:String(t);throw new rD(`git clone failed for ${e.url}: ${r}`)}let r;try{r=fu(`git`,[`-C`,n,`rev-parse`,`HEAD`],{stdio:`pipe`}).toString().trim()}catch{}let i=e.subpath?L(n,e.subpath):n,a=I(n,i);if(a.startsWith(`..`)||yu(a))throw Gu(n,{recursive:!0,force:!0}),new rD(`subpath escapes the clone: ${e.subpath}`);if(!z(i))throw Gu(n,{recursive:!0,force:!0}),new rD(`subpath not found in repo: ${e.subpath}`);return{dir:i,ref:r,cleanup:()=>Gu(n,{recursive:!0,force:!0})}}const xD=[`.ok`,`skills-lock.json`],SD=ye({source:u(),pluginProvider:u().optional(),skill:u().optional(),ref:u().optional(),contentHash:u(),files:M(u()).optional(),localHash:u().optional(),baselineRef:u().optional(),publisher:u().optional(),importedAt:a(),autoUpdate:D().optional()}),CD=ye({schema:x(1),skills:C(u(),SD).default({})});function wD(){return{schema:1,skills:{}}}function TD(e){let t;try{t=JSON.parse(e)}catch{return null}let n=CD.safeParse(t);return n.success?n.data:null}function ED(e,t,n){return{...e,skills:{...e.skills,[t]:n}}}const DD=new Set(Object.values(ca));function OD(e,t,n,r){return e.startsWith(`open-knowledge-pack-`)?kD(e,t,n):!DD.has(e)||r?.selfIdentifiesAsPack!==!0?null:kD(e,t,n)}function kD(e,t,n){return{source:za,skill:e,contentHash:t,importedAt:n}}function AD(e,t){for(let[n,r]of Object.entries(e.skills))if(r.contentHash===t)return n;return null}function jD(e,t){let n=t,r=``,{frontmatter:i}=Ur(e);if(i!==``){let{map:e}=Ta(Fr(i)),t=e?.name,a=e?.description;typeof t==`string`&&t.trim()!==``&&(n=t),typeof a==`string`&&(r=a)}return{name:n,description:r}}const MD=new Set([`.git`,`node_modules`]),ND=new Set([...MD,`scripts`,`references`]);function PD(e){let t=[],n=r=>{for(let i of Hu(r,{withFileTypes:!0})){let a=F(r,i.name);if(i.isDirectory()){MD.has(i.name)||n(a);continue}if(!i.isFile())continue;let o=I(e,a).split(`\\`).join(`/`);if(o===`SKILL.md`)continue;let s=B(a);t.push(s.includes(0)?{relPath:o,content:null,bytes:new Uint8Array(s)}:{relPath:o,content:s.toString(`utf-8`)})}};return n(e),t.sort((e,t)=>e.relPath.localeCompare(t.relPath))}function FD(e){let t=F(e,`SKILL.md`);return z(t)?jD(B(t,`utf-8`),gu(e)):null}function ID(e){let t=0,n=0,r=null,i=(e,t)=>(r=`Skill bundle could not be read (${e}): ${t instanceof Error?t.message:String(t)}`,null);try{n=z(F(e,`SKILL.md`))?qu(F(e,`SKILL.md`)).size:0}catch(e){return i(`stat SKILL.md`,e)??r}if(n>16777216)return`SKILL.md is ${n} bytes; the import per-file cap is ${wn}.`;if(n>67108864)return`Skill exceeds ${tr} bytes; that is the import bundle cap.`;let a=o=>{if(r!==null)return;let s;try{s=Hu(o,{withFileTypes:!0})}catch(e){i(`read directory`,e);return}for(let c of s){if(r!==null)return;let s=F(o,c.name);if(c.isDirectory()){MD.has(c.name)||a(s);continue}if(!c.isFile())continue;let l=I(e,s).split(`\\`).join(`/`);if(l===`SKILL.md`)continue;if(t+=1,t>512){r=`Skill has more than 512 dependent files; that is the import cap.`;return}let u;try{u=qu(s).size}catch(e){i(`stat ${l}`,e);return}if(u>16777216){r=`${l} is ${u} bytes; the import per-file cap is ${wn}.`;return}if(n+=u,n>67108864){r=`Skill exceeds ${tr} bytes; that is the import bundle cap.`;return}}};try{a(e)}catch(e){return`Skill bundle could not be measured: ${e instanceof Error?e.message:String(e)}`}return r}function LD(e){let t=F(e,`SKILL.md`);if(!z(t))return null;let n=B(t,`utf-8`),{name:r,description:i}=jD(n,gu(e)),a=PD(e),o=ud(`sha256`);o.update(`SKILL.md\n${n}\n`);for(let e of a)o.update(`${e.relPath}\n`),o.update(e.bytes??e.content??``),o.update(`
|
|
32
|
-
`);return{name:r,description:i,skillMd:n,files:a,contentHash:o.digest(`hex`)}}function RD(e){if(z(F(e,`SKILL.md`)))return[{name:gu(e),dir:e}];let t=[],n=0,r=(e,i)=>{if(i>8||++n>5e3)return;if(z(F(e,`SKILL.md`))){t.push({name:gu(e),dir:e});return}let a;try{a=Hu(e,{withFileTypes:!0})}catch{return}for(let t of a)t.isDirectory()&&!ND.has(t.name)&&r(F(e,t.name),i+1)};return r(e,0),t.sort((e,t)=>e.name.localeCompare(t.name))}function zD(e){let t=e?.skills;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.source==`string`&&t.source?t.source:void 0,i=typeof t.id==`string`&&t.id?t.id:r;if(!i||!r)continue;let a=typeof t.name==`string`&&t.name?t.name:vt(i);xo(a,r)||n.push({id:i,name:a,source:r,description:typeof t.description==`string`?t.description:``,installs:Number.isInteger(t.installs)&&t.installs>=0?t.installs:null,publisher:qo(r)})}return n}const BD={"&":`&`,"<":`<`,">":`>`,""":`"`,"'":`'`,"'":`'`,"'":`'`};function VD(e){return e.replace(/&(?:amp|lt|gt|quot|apos|#39|#x27);/g,e=>BD[e]??e)}function HD(e){let t={},n=e.match(/<meta\b[^>]*>/gi)??[];for(let e of n){let n=e.match(/\bproperty\s*=\s*["'](og:[^"']+)["']/i)?.[1]?.toLowerCase();if(!n)continue;let r=e.match(/\bcontent\s*=\s*["']([^"']*)["']/i)?.[1];if(r==null)continue;let i=VD(r);n===`og:title`&&t.title==null?t.title=i:n===`og:description`&&t.description==null?t.description=i:n===`og:image`&&t.image==null&&(t.image=i)}return t}function UD(e){let t=e?.items;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.full_name==`string`&&t.full_name?t.full_name:void 0;r&&n.push({id:r,name:typeof t.name==`string`&&t.name?t.name:vt(r),source:r,description:typeof t.description==`string`?t.description:``,installs:null,publisher:qo(r)})}return n}function WD(e){return e.trim().toLowerCase()}function GD(e){return e.split(`/`).filter(Boolean).pop()??e}function KD(e){let t=lr(e.trim());if(t?.kind===`site`)return{hostname:t.hostname};let n=yD(e);if(!n)return null;let r=lr(n.owner);return r?.kind===`site`?{hostname:r.hostname,skill:n.skill}:null}async function qD(e,t,n={}){let r=KD(e);if(r){let e=t??r.skill;if(!e)throw new rD(`Website skill sources require a skill name.`);return{source:r.hostname,skill:e,publisher:r.hostname,spec:{kind:`well-known`,origin:`https://${r.hostname}`,skill:e}}}let i=yD(e);if(!i)return null;let a=n.fetchImpl??globalThis.fetch;if(!a)throw new rD(`No fetch implementation available.`);let o=t??i.skill,s=WD(o),c=WD(i.owner),l;try{let e=await a(`https://skills.sh/api/search?q=${encodeURIComponent(o)}&limit=30`,{signal:AbortSignal.timeout(n.timeoutMs??8e3)});if(!e.ok)throw new rD(`skills.sh lookup failed with HTTP ${e.status}`);l=await e.json()}catch(e){throw e instanceof rD?e:new rD(`skills.sh lookup failed: ${e instanceof Error?e.message:String(e)}`)}let u=zD(l).find(e=>{if((e.publisher?WD(e.publisher):``)!==c)return!1;let t=WD(e.name),n=WD(GD(e.id));return t===s||n===s});if(!u)throw new rD(`No skills.sh result matched ${i.owner}/${i.skill}`);let d=lr(u.source),f=d?.kind===`site`?{kind:`well-known`,origin:`https://${d.hostname}`,skill:t??u.name}:vD(u.source);if(!f||f.kind===`local`)throw new rD(`skills.sh returned an unsafe source for ${i.owner}/${i.skill}: ${u.source}`);return{source:u.source,skill:t??u.name,...u.publisher?{publisher:u.publisher}:{},spec:f}}const JD=[`agents`,`claude`,`cursor`,`codex`,`opencode`,`pi`,`copilot`];function YD(e){let t=JD.indexOf(e);return t===-1?JD.length:t}function XD(e){let t=new Map,n=new Map;for(let r of e){let e=`${r.scope}|${r.name}`,i=`${e}|${r.contentHash}`,a=t.get(i);a||(a=[],t.set(i,a)),a.push(r);let o=n.get(e);o||(o=new Set,n.set(e,o)),o.add(r.contentHash)}let r=[];for(let e of t.values()){let t=[...e].sort((e,t)=>{let n=Number(e.viaLink===!0)-Number(t.viaLink===!0);if(n!==0)return n;let r=Number(t.preferredSource===!0)-Number(e.preferredSource===!0);if(r!==0)return r;let i=YD(e.editor)-YD(t.editor);return i===0?e.editor.localeCompare(t.editor):i}),i=t[0];i&&r.push({name:i.name,scope:i.scope,contentHash:i.contentHash,canonical:i,copies:t.slice(1),isFork:(n.get(`${i.scope}|${i.name}`)?.size??1)>1})}return r.sort((e,t)=>e.scope.localeCompare(t.scope)||e.name.localeCompare(t.name)||e.contentHash.localeCompare(t.contentHash))}function ZD(e){if(!z(e))return[];try{return Hu(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(e=>F(e.parentPath,e.name)).sort()}catch{return[]}}function QD(e,t,n,r){let i=F(e,`SKILL.md`);if(!z(i))return null;let a=gu(e),o=a,s=``;try{({name:o,description:s}=jD(B(i,`utf-8`),a))}catch{}return{name:o,description:s,home:e,harness:t,skillMd:i,scripts:ZD(F(e,`scripts`)),references:ZD(F(e,`references`)),provenance:n,inert:r}}function $D(e){if(!z(e))return[];try{return Hu(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function eO(e){let t=e=>{try{return qu(e).isDirectory()}catch{return!1}};return{commands:t(F(e,`commands`)),hooks:t(F(e,`hooks`)),mcp:z(F(e,`.mcp.json`))}}const tO={commands:!1,hooks:!1,mcp:!1};function nO(e,t){let n=[];for(let r of $D(e)){let i=QD(F(e,r),t,{},tO);i&&n.push({packName:i.name,packVersion:`0.0.0`,harness:t,skills:[i]})}return n}function rO(e){try{return Hu(e).length>0}catch{return!1}}function iO(e){let t=new Set,n=(e,r)=>{if(r>4)return;let i;try{i=Hu(e,{withFileTypes:!0})}catch{return}if(z(F(e,`SKILL.md`))||z(F(e,`SKILL.mdx`))){t.add(e.split(`/`).pop()??e);return}for(let t of i)t.isDirectory()&&n(F(e,t.name),r+1)};return n(F(e,`skills`),0),[...t].sort()}function aO(e){return{commands:rO(F(e,`commands`)),hooks:rO(F(e,`hooks`))||z(F(e,`hooks.json`)),mcp:z(F(e,`.mcp.json`)),agents:rO(F(e,`agents`))}}function oO(e){let t=e.lastIndexOf(`@`);return t<=0?{plugin:e}:{plugin:e.slice(0,t),marketplace:e.slice(t+1)}}function sO(e){let t=new Map;for(let n of e){if(n.orphaned_at||!n.installPath||!z(n.installPath))continue;let e=`${n.scope??``} ${n.projectPath??``}`,r=t.get(e);(!r||(n.lastUpdated??``)>(r.lastUpdated??``))&&t.set(e,n)}return[...t.values()]}function cO(e){let t=F(e,`.claude-plugin`,`plugin.json`);try{let e=JSON.parse(B(t,`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function lO(e,t){let n=F(e,`installed_plugins.json`);if(!z(n))return[];let r;try{r=JSON.parse(B(n,`utf-8`))}catch(e){return console.warn(`[skills-catalog] failed to parse installed_plugins.json, skipping Claude plugins`,{manifestPath:n,err:e}),[]}let i=r?.plugins;if(!i||typeof i!=`object`)return[];let a=[];for(let[e,n]of Object.entries(i)){if(!Array.isArray(n))continue;let{plugin:r,marketplace:i}=oO(e);for(let e of sO(n)){let n=e.installPath,o=eO(n),s=cO(n),c=F(n,`skills`),l=[];for(let n of $D(c)){let a={plugin:r,...i?{marketplace:i}:{},...e.version?{version:e.version}:{},...e.gitCommitSha?{gitCommitSha:e.gitCommitSha}:{},...e.scope?{scope:e.scope}:{},...e.projectPath?{projectPath:e.projectPath}:{}},s=QD(F(c,n),t,a,o);s&&l.push(s)}l.length!==0&&a.push({packName:r,packVersion:e.version??s.version??`0.0.0`,...typeof s.description==`string`?{packDescription:s.description}:{},...typeof s.author?.name==`string`?{packAuthor:s.author.name}:{},harness:t,skills:l})}}return a}const uO=/^(.*\/plugins\/cache\/([^/]+)\/([^/]+))\/([^/]+)(?:\/.*)?$/,dO=/^(.*\/plugins)\/(?:cache|marketplaces)\/([^/]+)\//,fO=/^(.*\/plugins\/marketplaces\/([^/]+))(?:\/.*)?$/;function pO(e){return e.replaceAll(`\\`,`/`).replace(/\/+$/,``)}function mO(e){let t=dO.exec(pO(e));if(!t)return null;try{let e=B(`${t[1]}/known_marketplaces.json`,`utf-8`),n=JSON.parse(e)[t[2]];return n?.source?.source===`github`&&n.source.repo?`https://github.com/${n.source.repo}`:null}catch{return null}}function hO(e,t){let n=L(e);try{qu(n).isDirectory()||(n=P(n))}catch{return null}let r=L(t);for(;n===r||n.startsWith(`${r}/`);){try{let e=JSON.parse(B(F(n,`.claude-plugin`,`plugin.json`),`utf-8`));if(typeof e.name==`string`&&e.name.length>0)return{name:e.name,...typeof e.version==`string`?{version:e.version}:{}}}catch{}if(n===r)break;n=P(n)}return null}function gO(e){let t=pO(e),n=uO.exec(t);if(n){let t=hO(e,`${n[1]}/${n[4]}`);return!t||t.name!==n[3]?null:{plugin:n[3],marketplace:n[2],version:t.version??n[4]}}let r=fO.exec(t);if(!r)return null;let i=hO(e,r[1]);return i?{plugin:i.name,marketplace:r[2],...i.version?{version:i.version}:{}}:null}function _O(e){return[...e].sort((e,t)=>e.localeCompare(t,void 0,{numeric:!0})).pop()}function vO(e){let t=pO(e),n=uO.exec(t);if(!n)return e;let[r,i]=[n[1],n[4]],a=t.slice(n[0].indexOf(`/${i}`)+i.length+1),o;try{o=Hu(r,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return e}let s=_O(o);if(s===void 0||s===i)return e;let c=`${r}/${s}${a}`;return z(c)?c:e}function yO(e,t){for(let n of t)try{let t=JSON.parse(B(F(e,n),`utf-8`));if(typeof t.name==`string`&&t.name.length>0)return{plugin:t.name,...typeof t.version==`string`?{version:t.version}:{},...typeof t.description==`string`?{description:t.description}:{}}}catch{}return null}function bO(e){let t=yO(e,[`.claude-plugin/plugin.json`]);if(t)return{...t,setupSupported:!0};try{let t=JSON.parse(B(F(e,`.claude-plugin`,`marketplace.json`),`utf-8`)),n=t.plugins?.find(e=>e.source===`./`)??t.plugins?.[0],r=typeof n?.name==`string`?n.name:t.name;if(typeof r==`string`&&r.length>0)return{plugin:r,...typeof n?.description==`string`?{description:n.description}:{},setupSupported:!0}}catch{}return null}const xO={id:`claude`,homes:e=>[{harness:`claude`,dir:F(e,`.claude`,`plugins`)}],enumerate:lO,inspectSource:gO,repositoryUrl:mO,resolveUpdateSource:vO,detectDir:bO};function SO(e,t){return{id:e,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let n=yO(e,t);return n?{...n,setupSupported:!1}:null}}}function CO(e,t){try{return JSON.parse(B(F(e,t),`utf-8`)).skills!==void 0}catch{return!1}}const wO=[xO,SO(`codex`,[`.codex-plugin/plugin.json`]),SO(`gemini`,[`gemini-extension.json`]),{id:`copilot`,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let t=yO(e,[`.plugin/plugin.json`,`.github/plugin/plugin.json`]);if(t)return{...t,setupSupported:!1};if(!CO(e,`plugin.json`))return null;let n=yO(e,[`plugin.json`]);return n?{...n,setupSupported:!1}:null}}];function TO(e){return wO.find(t=>t.id===e)}function EO(e){if(e===void 0)return wO;let t=TO(e);return t?[t]:[]}function DO(e){return wO.flatMap(t=>t.homes(e).map(e=>({provider:t.id,...e})))}function OO(e,t,n=e){let r=TO(e);if(!r)throw Error(`unknown plugin provider: ${e}`);return r.enumerate(t,n).map(t=>({...t,skills:t.skills.map(t=>({...t,provenance:{...t.provenance,pluginProvider:e}}))}))}function kO(e,t){for(let n of EO(t)){let t=n.inspectSource(e);if(!t)continue;let r=n.repositoryUrl(e);return{provider:n.id,...t,...r?{repositoryUrl:r}:{}}}return null}function AO(e){for(let t of wO){let n=t.detectDir(e);if(!n)continue;let r=iO(e);return r.length===0?null:{provider:t.id,plugin:n.plugin,...n.version?{version:n.version}:{},...n.description?{description:n.description}:{},bundledSkills:r,capabilities:aO(e),setupSupported:n.setupSupported}}return null}function jO(e,t){for(let n of EO(t)){if(!n.inspectSource(e))continue;let t=n.repositoryUrl(e);if(t)return t}return null}function MO(e,t){for(let n of EO(t))if(n.inspectSource(e))return n.resolveUpdateSource(e);return e}function NO(e=Zu()){let t=ns.flatMap(t=>{let n=dr[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:F(e,...n.split(`/`))}]});return[...DO(e).map(e=>({kind:`plugin-provider`,...e})),...t,{harness:`agents`,kind:`skill-dir`,dir:F(e,`.agents`,`skills`)}]}function PO(e){return ns.flatMap(t=>{let n=Zo[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:F(e,...n.split(`/`))}]})}function FO(e){return Object.keys(e.provenance).length>0}function IO(e){return e.provenance.plugin!==void 0}function LO(e,t){if(IO(e)!==IO(t))return IO(e)?e:t;if(FO(e)!==FO(t))return FO(e)?e:t;let n=e.scripts.length+e.references.length;return t.scripts.length+t.references.length>n?t:e}function RO(e,t){return{name:e.name,description:e.description,files:{skillMd:e.skillMd,scripts:e.scripts,references:e.references},sourceHarness:e.harness,sourceHarnesses:t,home:e.home,provenance:e.provenance,inert:e.inert}}function zO(e){try{return LD(e.home)?.contentHash??`unreadable:${e.home}`}catch{return`unreadable:${e.home}`}}function BO(e){let t=new Map;for(let n of e){let e=Rn(n.provenance.scope),r=`${e}\0${e===`project`?n.provenance.projectPath??``:``}\0${n.name}\0${zO(n)}`,i=t.get(r);i?(i.winner=LO(i.winner,n),i.harnesses.add(n.harness)):t.set(r,{winner:n,harnesses:new Set([n.harness])})}return[...t.values()].map(({winner:e,harnesses:t})=>RO(e,[...t].sort())).sort((e,t)=>e.name.localeCompare(t.name)||Rn(e.provenance.scope).localeCompare(Rn(t.provenance.scope))||e.home.localeCompare(t.home))}function VO(e){let t=new Map;for(let n of e){let e=t.get(n.packName),r=e??{version:`0.0.0`,skills:new Set,hosts:new Set};r.version===`0.0.0`&&n.packVersion!==`0.0.0`&&(r.version=n.packVersion),!r.description&&n.packDescription&&(r.description=n.packDescription),!r.author&&n.packAuthor&&(r.author=n.packAuthor);for(let e of n.skills)r.skills.add(e.name);r.hosts.add(n.harness),e||t.set(n.packName,r)}return[...t.entries()].map(([e,t])=>({schema:1,name:e,version:t.version,...t.description?{description:t.description}:{},...t.author?{author:{name:t.author}}:{},skills:[...t.skills].sort(),hostCompatibility:[...t.hosts].sort()})).sort((e,t)=>e.name.localeCompare(t.name))}function HO(e={}){let t=[];for(let n of NO(e.home))try{switch(n.kind){case`plugin-provider`:t.push(...OO(n.provider,n.dir,n.harness));break;case`skill-dir`:t.push(...nO(n.dir,n.harness));break;default:throw Error(`unhandled harness home kind: ${String(n)}`)}}catch(e){console.warn(`[skills-catalog] failed to enumerate harness home, skipping`,{harness:n.harness,dir:n.dir,err:e})}e.projectDir!==void 0&&t.push(...UO(e.projectDir));let n=e.projectDir===void 0?t:t.map(t=>({...t,skills:t.skills.filter(t=>_a(t.provenance,e.projectDir))})).filter(e=>e.skills.length>0);return{skills:BO(n.flatMap(e=>e.skills)),packs:VO(n)}}function UO(e){let t=KO(L(e,`.ok`,`skills`)),n=[];for(let r of PO(e))try{for(let i of nO(r.dir,r.harness)){let r=i.skills.filter(e=>!GO(e,t));r.length!==0&&n.push({...i,skills:r.map(t=>WO(t,e))})}}catch(e){console.warn(`[skills-catalog] failed to enumerate project harness skills, skipping`,{harness:r.harness,dir:r.dir,err:e})}return n}function WO(e,t){return{...e,provenance:{...e.provenance,scope:`project`,projectPath:t}}}function GO(e,t){if(e.name.startsWith(`open-knowledge`))return!0;let n=KO(e.home);return n===t||n.startsWith(t+R)}function KO(e){try{return V(e)}catch{return L(e)}}function qO(e){if(!e.includes(`self.__next_f`))return e;let t=/self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g,n=``;for(let r of e.matchAll(t))n+=JSON.parse(r[1]);return n}const JO=[`skillId`,`source`,`installs`];function YO(e){let t={};if(e.length>8192)return t;let n=new Uint8Array(e.length),r=0,i=!1,a=!1;for(let t=0;t<e.length;t++){n[t]=Math.min(r,255);let o=e[t];if(a){a=!1;continue}if(o===`\\`){a=i;continue}if(o===`"`){i=!i;continue}i||(o===`{`||o===`[`?r++:(o===`}`||o===`]`)&&r--)}for(let r of e.matchAll(/"(skillId|source|installs)"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?)/g)){let e=r[1];if(r.index===void 0||n[r.index]!==1||e in t)continue;let i=r[2];t[e]=i.startsWith(`"`)?JSON.parse(i):Number(i)}return t}function*XO(e){let t=[],n=!1,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){r=!1;continue}if(a===`\\`){r=n;continue}if(a===`"`){n=!n;continue}if(!n){if(a===`{`)t.push(i);else if(a===`}`){let n=t.pop();if(n===void 0)continue;let r=e.slice(n,i+1);if(!JO.every(e=>r.includes(`"${e}"`)))continue;try{let e=JSON.parse(r);if(typeof e==`object`&&e&&!Array.isArray(e)){yield e;continue}}catch{}yield YO(r)}}}}function ZO(e){let t=qO(e),n=[];for(let e of XO(t)){let{skillId:t,source:r,installs:i}=e;typeof t!=`string`||t===``||typeof r!=`string`||r===``||typeof i!=`number`||!Number.isFinite(i)||n.push({skillId:t,source:r,installs:i})}return n}function QO(e){let t=new Map;for(let n of ZO(e)){let e=`${n.source}/${n.skillId}`;t.has(e)||xo(n.skillId,n.source)||t.set(e,{id:e,name:n.skillId,source:n.source,description:``,installs:n.installs,publisher:qo(n.source)})}return[...t.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}const $O=/href="\/([^"/]+)\/([^"/]+)\/([^"/?#]+)"([\s\S]*?)<\/a>/g,ek=/<span[^>]*font-mono[^>]*>\s*([\d,]+)\s*<\/span>/;function tk(e,t){let n=new Map;$O.lastIndex=0;for(let r=$O.exec(e);r!==null;r=$O.exec(e)){let[,e,i,a,o]=r;if(!e||!i||!a||!o||`${e}/${i}`!==t||xo(a,t))continue;let s=Number.parseInt(ek.exec(o)?.[1]?.replaceAll(`,`,``)??``,10);if(!Number.isInteger(s)||s<0)continue;let c=`${t}/${a}`;n.has(c)||n.set(c,{id:c,name:a,source:t,description:``,installs:s,publisher:qo(t)})}return[...n.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}function nk(e,t){return`${e}/${t}`}function rk(e){if(e.preferredSource===!0)return-1;let t=JD.indexOf(e.editor);return t===-1?JD.length:t}function ik(e){let t=XD(e),n=new Set,r=new Map,i=new Set,a=new Map;for(let e of t){n.add(e.canonical.dir);for(let t of e.copies)i.add(t.dir);let t=nk(e.scope,e.name),o=rk(e.canonical),s=a.get(t);(s===void 0||o<s)&&(a.set(t,o),r.set(t,e.canonical.dir))}return{admittedDirs:n,canonicalDir:r,excludedCopyDirs:i}}var ak=n(((e,t)=>{t.exports=n;function n(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}n.prototype.go=function(e){this.pending<this.max?i(this,e):this.waiting.push(e)},n.prototype.wait=function(e){this.pending===0?e(this.error):this.listeners.push(e)},n.prototype.hold=function(){return r(this)};function r(e){e.pending+=1;var t=!1;return n;function n(n){if(t)throw Error(`callback called twice`);if(t=!0,e.error=e.error||n,--e.pending,e.waiting.length>0&&e.pending<e.max)i(e,e.waiting.shift());else if(e.pending===0){var a=e.listeners;e.listeners=[],a.forEach(r)}}function r(t){t(e.error)}}function i(e,t){t(r(e))}})),ok=n((t=>{var n=e(`fs`),r=e(`util`),i=e(`stream`),a=i.Readable,o=i.PassThrough,s=ak(),c=e(`events`).EventEmitter;t.BufferSlicer=d,t.FdSlicer=l,r.inherits(l,c);function l(e){c.call(this),this.fd=e,this.pend=new s,this.pend.max=1,this.refCount=0}l.prototype.read=function(e,t,r,i,a){var o=this;o.pend.go(function(s){n.read(o.fd,e,t,r,i,function(e,t,n){s(),a(e,t,n)})})},l.prototype.createReadStream=function(e){return new u(this,e)},l.prototype.ref=function(){this.refCount+=1},l.prototype.unref=function(){var e=this;if(--e.refCount,e.refCount<0)throw Error(`invalid unref`);if(e.refCount>0)return;n.close(e.fd,t);function t(t){t?e.emit(`error`,t):e.emit(`close`)}},r.inherits(u,a);function u(e,t){t||={},a.call(this,t),this.context=e,this.context.ref(),this.start=t.start||0,this.endOffset=t.end,this.pos=this.start}u.prototype._read=function(e){var t=this,r=Math.min(t._readableState.highWaterMark,e);if(t.endOffset!=null&&(r=Math.min(r,t.endOffset-t.pos)),r<=0){t.push(null),this._cleanup();return}t.context.pend.go(function(e){var i=Buffer.allocUnsafe(r);n.read(t.context.fd,i,0,r,t.pos,function(n,r){n?t.destroy(n):r===0?(t.push(null),t._cleanup()):(t.pos+=r,t.push(i.slice(0,r))),e()})})},u.prototype._destroy=function(e,t){this._cleanup(),t(e)},u.prototype._cleanup=function(){this.context!=null&&(this.context.unref(),this.context=null)},r.inherits(d,c);function d(e){c.call(this),this.refCount=0,this.buffer=e}d.prototype.read=function(e,t,n,r,i){if(!(0<=t&&t<=e.length))throw RangeError(`offset outside buffer: 0 <= `+t+` <= `+e.length);if(r<0)throw RangeError(`position is negative: `+r);if(t+n>e.length&&(n=e.length-t),r+n>this.buffer.length&&(n=this.buffer.length-r),n<=0){setImmediate(function(){i(null,0)});return}this.buffer.copy(e,t,r,r+n),setImmediate(function(){i(null,n)})},d.prototype.createReadStream=function(e){e||={};var t=new o(e);t.start=e.start||0,t.endOffset=e.end,t.pos=t.endOffset||this.buffer.length;for(var n=this.buffer.slice(t.start,t.pos),r=65536,i=0;;){var a=i+r;if(a>=n.length){i<n.length&&t.write(n.slice(i,n.length));break}t.write(n.slice(i,a)),i=a}return t.end(),t},d.prototype.ref=function(){this.refCount+=1},d.prototype.unref=function(){if(--this.refCount,this.refCount<0)throw Error(`invalid unref`)}})),$ce=n(((e,t)=>{let n=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function r(e){let t=-1;for(let r of e)t=n[(t^r)&255]^t>>>8;return(t^-1)>>>0}t.exports=r})),ele=n((t=>{e(`fs`);var n=e(`zlib`),r=ok(),i=e(`util`),a=e(`events`).EventEmitter,o=e(`stream`).Transform,s=e(`stream`).PassThrough,c=e(`stream`).Writable;let l=typeof n.crc32==`function`?n.crc32:$ce();t.fromBuffer=u;function u(e,t,n){typeof t==`function`&&(n=t,t=null),t??={},t.autoClose=!1,t.lazyEntries??=!1,t.decodeStrings??=!0,t.validateEntrySizes??=!0,t.strictFileNames??=!1,d(new r.BufferSlicer(e),e.length,t,n)}function d(e,t,n,r){typeof n==`function`&&(r=n,n=null),n??={},n.autoClose??=!0,n.lazyEntries??=!1,n.decodeStrings??=!0;var i=!!n.decodeStrings;if(n.validateEntrySizes??=!0,n.strictFileNames??=!1,r??=ne,typeof t!=`number`)throw Error(`expected totalSize parameter to be a number`);if(t>2**53-1)throw Error(`zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.`);e.ref();var a=22,o=20,s=Math.min(o+a+65535,t),c=te(s);x(e,c,0,s,t-c.length,function(l){if(l)return r(l);for(var u=s-a;u>=0;--u)if(c.readUInt32LE(u)===101010256){var d=c.subarray(u),p=d.readUInt16LE(4),m=d.readUInt16LE(10),h=d.readUInt32LE(16),g=d.readUInt16LE(20),_=d.length-a;if(g!==_)return r(Error(`Invalid comment length. Expected: `+_+`. Found: `+g+". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?"));var v=i?E(d.subarray(22),!1):d.subarray(22);if(u-o>=0&&c.readUInt32LE(u-o)===117853008){var y=ee(c.subarray(u-o,u-o+o),8),b=te(56);return x(e,b,0,b.length,y,function(a){return a?r(a):b.readUInt32LE(0)===101075792?(p=b.readUInt32LE(16),p===0?(m=ee(b,32),h=ee(b,48),r(null,new f(e,h,t,m,v,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames))):r(Error(`multi-disk zip files are not supported: found disk number: `+p))):r(Error(`invalid zip64 end of central directory record signature`))})}return p===0?r(null,new f(e,h,t,m,v,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames)):r(Error(`multi-disk zip files are not supported: found disk number: `+p))}r(Error(`End of central directory record signature not found. Either not a zip file, or file is truncated.`))})}i.inherits(f,a);function f(e,t,n,r,i,o,s,c,l,u){var d=this;a.call(d),d.reader=e,d.reader.on(`error`,function(e){m(d,e)}),d.reader.once(`close`,function(){d.emit(`close`)}),d.readEntryCursor=t,d.fileSize=n,d.entryCount=r,d.comment=i,d.entriesRead=0,d.autoClose=!!o,d.lazyEntries=!!s,d.decodeStrings=!!c,d.validateEntrySizes=!!l,d.strictFileNames=!!u,d.isOpen=!0,d.emittedError=!1,d.hasEachEntryBeenCalled=!1,d.lazyEntries||d._readEntry()}f.prototype.close=function(){this.isOpen&&(this.isOpen=!1,this.reader.unref())};function p(e,t){e.autoClose&&e.close(),m(e,t)}function m(e,t){e.emittedError||(e.emittedError=!0,e.emit(`error`,t))}f.prototype.readEntry=function(){if(!this.lazyEntries)throw Error(`readEntry() called without lazyEntries:true`);this._readEntry()},f.prototype._readEntry=function(){var e=this;if(e.entryCount===e.entriesRead){setImmediate(function(){e.autoClose&&e.close(),!e.emittedError&&e.emit(`end`)});return}if(!e.emittedError){var t=te(46);x(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return p(e,n);if(!e.emittedError){var r=new h,i=t.readUInt32LE(0);if(i!==33639248)return p(e,Error(`invalid central directory file header signature: 0x`+i.toString(16)));if(r.versionMadeBy=t.readUInt16LE(4),r.versionNeededToExtract=t.readUInt16LE(6),r.generalPurposeBitFlag=t.readUInt16LE(8),r.compressionMethod=t.readUInt16LE(10),r.lastModFileTime=t.readUInt16LE(12),r.lastModFileDate=t.readUInt16LE(14),r.crc32=t.readUInt32LE(16),r.compressedSize=t.readUInt32LE(20),r.uncompressedSize=t.readUInt32LE(24),r.fileNameLength=t.readUInt16LE(28),r.extraFieldLength=t.readUInt16LE(30),r.fileCommentLength=t.readUInt16LE(32),r.internalFileAttributes=t.readUInt16LE(36),r.externalFileAttributes=t.readUInt32LE(38),r.relativeOffsetOfLocalHeader=t.readUInt32LE(42),r.generalPurposeBitFlag&64)return p(e,Error(`strong encryption is not supported`));e.readEntryCursor+=46,t=te(r.fileNameLength+r.extraFieldLength+r.fileCommentLength),x(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return p(e,n);if(!e.emittedError){r.fileNameRaw=t.subarray(0,r.fileNameLength);var i=r.fileNameLength+r.extraFieldLength;r.extraFieldRaw=t.subarray(r.fileNameLength,i),r.fileCommentRaw=t.subarray(i,i+r.fileCommentLength);try{r.extraFields=b(r.extraFieldRaw)}catch(t){return p(e,t)}if(e.decodeStrings){var a=(r.generalPurposeBitFlag&2048)!=0;r.fileComment=E(r.fileCommentRaw,a),r.fileName=v(r.generalPurposeBitFlag,r.fileNameRaw,r.extraFields,e.strictFileNames);var o=y(r.fileName);if(o!=null)return p(e,Error(o))}else r.fileComment=r.fileCommentRaw,r.fileName=r.fileNameRaw;r.comment=r.fileComment,e.readEntryCursor+=t.length,e.entriesRead+=1;for(var s=0;s<r.extraFields.length;s++){var c=r.extraFields[s];if(c.id===1){var l=c.data,u=0;if(r.uncompressedSize===4294967295){if(u+8>l.length)return p(e,Error(`zip64 extended information extra field does not include uncompressed size`));r.uncompressedSize=ee(l,u),u+=8}if(r.compressedSize===4294967295){if(u+8>l.length)return p(e,Error(`zip64 extended information extra field does not include compressed size`));r.compressedSize=ee(l,u),u+=8}if(r.relativeOffsetOfLocalHeader===4294967295){if(u+8>l.length)return p(e,Error(`zip64 extended information extra field does not include relative header offset`));r.relativeOffsetOfLocalHeader=ee(l,u),u+=8}break}}if(e.validateEntrySizes&&r.compressionMethod===0){var d=r.uncompressedSize;if(r.isEncrypted()&&(d+=12),r.compressedSize!==d){var f=`compressed/uncompressed size mismatch for stored file: `+r.compressedSize+` != `+r.uncompressedSize;return p(e,Error(f))}}e.emit(`entry`,r),e.lazyEntries||e._readEntry()}})}})}},f.prototype.eachEntry=function(){let e=this;if(!e.lazyEntries)throw Error(`eachEntry() requires lazyEntries: true`);if(e.hasEachEntryBeenCalled)throw Error(`eachEntry() must only be called once per ZipFile`);e.hasEachEntryBeenCalled=!0;let t=null;e.on(`entry`,r),e.on(`end`,i),e.on(`error`,a);function n(){e.removeListener(`entry`,r),e.removeListener(`end`,i),e.removeListener(`error`,a),e.autoClose&&e.close()}function r(e){let{resolve:n}=t;t=null,n({value:e})}function i(){let{resolve:e}=t;t=null,n(),e({done:!0})}function a(e){let{reject:r}=t;t=null,n(),r(e)}return{[Symbol.asyncIterator](){return this},next(){let n=new Promise((e,n)=>{if(t!=null)throw Error(`next() called before previous Promise was resolved.`);t={resolve:e,reject:n}});return e.readEntry(),n},return(e){return n(),Promise.resolve({done:!0,value:e})},throw(e){return n(),Promise.reject(e)}}},f.prototype.openReadStream=function(e,t,n){var r=this,i=0,a=e.compressedSize;if(n??(n=t,t=null),t==null)t={};else{if(t.decodeFileData===!1){if(t.decrypt!=null)throw Error(`cannot use options.decrypt when options.decodeFileData === false`);if(t.decompress!=null)throw Error(`cannot use options.decompress when options.decodeFileData === false`)}else{if(t.decrypt!=null){if(!e.isEncrypted())throw Error(`options.decrypt can only be specified for encrypted entries. See also option decodeFileData.`);if(t.decrypt!==!1)throw Error(`invalid options.decrypt value: `+t.decrypt);if(e.isCompressed()&&t.decompress!==!1)throw Error(`entry is encrypted and compressed, and options.decompress !== false. See also option decodeFileData.`)}if(t.decompress!=null){if(!e.isCompressed())throw Error(`options.decompress can only be specified for compressed entries. See also option decodeFileData.`);if(!(t.decompress===!1||t.decompress===!0))throw Error(`invalid options.decompress value: `+t.decompress);s=t.decompress}}if(t.start!=null){if(i=t.start,i<0)throw Error(`options.start < 0`);if(i>e.compressedSize)throw Error(`options.start > entry.compressedSize`)}if(t.end!=null){if(a=t.end,a<0)throw Error(`options.end < 0`);if(a>e.compressedSize)throw Error(`options.end > entry.compressedSize`);if(a<i)throw Error(`options.end < options.start`)}}var o=t.decodeFileData===!1||(e.compressionMethod===0||e.compressionMethod===8&&t.decompress===!1)&&(!e.isEncrypted()||t.decrypt===!1);if((t.start!=null||t.end!=null)&&!o)throw Error(`start/end range require options.decodeFileData === false for non-trivial encoded entries.`);if(!r.isOpen)return n(Error(`closed`));if(e.isEncrypted()&&!o&&t.decrypt!==!1)return n(Error(`entry is encrypted, and options.decodeFileData !== false`));var s;if(o)s=!1;else if(e.compressionMethod===8)s=t.decodeFileData!==!0;else return n(Error(`unsupported compression method: `+e.compressionMethod));r.readLocalFileHeader(e,{minimal:!0},function(t,o){if(t)return n(t);r.openReadStreamLowLevel(o.fileDataStart,e.compressedSize,i,a,s,e.uncompressedSize,n)})},f.prototype.openReadStreamLowLevel=function(e,t,r,i,a,o,s){var c=this;e+t;var l=c.reader.createReadStream({start:e+r,end:e+i}),u=l;if(a){var d=!1,f=n.createInflateRaw();l.on(`error`,function(e){setImmediate(function(){d||f.emit(`error`,e)})}),l.pipe(f),c.validateEntrySizes?(u=new S(o),f.on(`error`,function(e){setImmediate(function(){d||u.emit(`error`,e)})}),f.pipe(u)):u=f,D(u,function(){d=!0,f!==u&&f.unpipe(u),l.unpipe(f),l.destroy()})}s(null,u)},f.prototype.readLocalFileHeader=function(e,t,n){var r=this;n??(n=t,t=null),t??={},r.reader.ref();var i=te(30);x(r.reader,i,0,i.length,e.relativeOffsetOfLocalHeader,function(a){try{if(a)return n(a);var o=i.readUInt32LE(0);if(o!==67324752)return n(Error(`invalid local file header signature: 0x`+o.toString(16)));var s=i.readUInt16LE(26),c=i.readUInt16LE(28),l=e.relativeOffsetOfLocalHeader+30+s+c;if(l+e.compressedSize>r.fileSize)return n(Error(`file data overflows file bounds: `+l+` + `+e.compressedSize+` > `+r.fileSize));if(t.minimal)return n(null,{fileDataStart:l});var u=new g;u.fileDataStart=l,u.versionNeededToExtract=i.readUInt16LE(4),u.generalPurposeBitFlag=i.readUInt16LE(6),u.compressionMethod=i.readUInt16LE(8),u.lastModFileTime=i.readUInt16LE(10),u.lastModFileDate=i.readUInt16LE(12),u.crc32=i.readUInt32LE(14),u.compressedSize=i.readUInt32LE(18),u.uncompressedSize=i.readUInt32LE(22),u.fileNameLength=s,u.extraFieldLength=c,i=te(s+c),r.reader.ref(),x(r.reader,i,0,i.length,e.relativeOffsetOfLocalHeader+30,function(e){try{return e?n(e):(u.fileName=i.subarray(0,s),u.extraField=i.subarray(s),n(null,u))}finally{r.reader.unref()}})}finally{r.reader.unref()}})},f.prototype.openReadStreamPromise=function(e,t){return new Promise((n,r)=>{this.openReadStream(e,t,function(e,t){if(e)return r(e);n(t)})})},f.prototype.openReadStreamLowLevelPromise=function(e,t,n,r,i,a){return new Promise((o,s)=>{this.openReadStream(e,t,n,r,i,a,function(e,t){if(e)return s(e);o(t)})})},f.prototype.readLocalFileHeaderPromise=function(e,t){return new Promise((n,r)=>{this.readLocalFileHeader(e,t,function(e,t){if(e)return r(e);n(t)})})};function h(){}h.prototype.getLastModDate=function(e){if(e??={},!e.forceDosFormat)for(var t=0;t<this.extraFields.length;t++){var n=this.extraFields[t];if(n.id===21589){var r=n.data;if(r.length<5||!(r[0]&1))continue;var i=r.readInt32LE(1);return new Date(i*1e3)}else if(n.id===10){var r=n.data;if(r.length!==32||r.readUInt16LE(4)!==1||r.readUInt16LE(6)!==24)continue;var a=(r.readUInt32LE(8)+4294967296*r.readInt32LE(12))/1e4-0xa9730b66800;return new Date(a)}}return _(this.lastModFileDate,this.lastModFileTime,e.timezone)},h.prototype.canDecodeFileData=function(){return!this.isEncrypted()&&(this.compressionMethod===0||this.compressionMethod===8)},h.prototype.isEncrypted=function(){return(this.generalPurposeBitFlag&1)!=0},h.prototype.isCompressed=function(){return this.compressionMethod===8};function g(){}function _(e,t,n){var r=e&31,i=(e>>5&15)-1,a=(e>>9&127)+1980,o=0,s=(t&31)*2,c=t>>5&63,l=t>>11&31;if(n==null||n===`local`)return new Date(a,i,r,l,c,s,o);if(n===`UTC`)return new Date(Date.UTC(a,i,r,l,c,s,o));throw Error(`unrecognized options.timezone: `+options.timezone)}function v(e,t,n,r){for(var i=null,a=0;a<n.length;a++){var o=n[a];if(o.id===28789){if(o.data.length<6||o.data.readUInt8(0)!==1)continue;var s=o.data.readUInt32LE(1);if(l(t)!==s)continue;i=E(o.data.subarray(5),!0);break}}return i??=E(t,(e&2048)!=0),r||(i=i.replace(/\\/g,`/`)),i}function y(e){return e.indexOf(`\\`)===-1?/^[a-zA-Z]:/.test(e)||/^\//.test(e)?`absolute path: `+e:e.split(`/`).indexOf(`..`)===-1?null:`invalid relative path: `+e:`invalid characters in fileName: `+e}function b(e){for(var t=[],n=0;n<e.length-3;){var r=e.readUInt16LE(n+0),i=e.readUInt16LE(n+2),a=n+4,o=a+i;if(o>e.length)throw Error(`extra field length exceeds extra field buffer size`);var s=e.subarray(a,o);t.push({id:r,data:s}),n=o}return t}function x(e,t,n,r,i,a){if(r===0)return setImmediate(function(){a(null,te(0))});e.read(t,n,r,i,function(e,t){if(e)return a(e);if(t<r)return a(Error(`unexpected EOF`));a()})}i.inherits(S,o);function S(e){o.call(this),this.actualByteCount=0,this.expectedByteCount=e}S.prototype._transform=function(e,t,n){if(this.actualByteCount+=e.length,this.actualByteCount>this.expectedByteCount){var r=`too many bytes in the stream. expected `+this.expectedByteCount+`. got at least `+this.actualByteCount;return n(Error(r))}n(null,e)},S.prototype._flush=function(e){if(this.actualByteCount<this.expectedByteCount){var t=`not enough bytes in the stream. expected `+this.expectedByteCount+`. got only `+this.actualByteCount;return e(Error(t))}e()},i.inherits(C,a);function C(){a.call(this),this.refCount=0}C.prototype.ref=function(){this.refCount+=1},C.prototype.unref=function(){var e=this;if(--e.refCount,e.refCount>0)return;if(e.refCount<0)throw Error(`invalid unref`);e.close(t);function t(t){if(t)return e.emit(`error`,t);e.emit(`close`)}},C.prototype.createReadStream=function(e){e??={};var t=e.start,n=e.end;if(t===n){var r=new s;return setImmediate(function(){r.end()}),r}var i=this._readStreamForRange(t,n),a=!1,o=new w(this);i.on(`error`,function(e){setImmediate(function(){a||o.emit(`error`,e)})}),D(o,function(){i.unpipe(o),o.unref(),i.destroy()});var c=new S(n-t);return o.on(`error`,function(e){setImmediate(function(){a||c.emit(`error`,e)})}),D(c,function(){a=!0,o.unpipe(c),o.destroy()}),i.pipe(o).pipe(c)},C.prototype._readStreamForRange=function(e,t){throw Error(`not implemented`)},C.prototype.read=function(e,t,n,r,i){var a=this.createReadStream({start:r,end:r+n}),o=new c,s=0;o._write=function(n,r,i){n.copy(e,t+s,0,n.length),s+=n.length,i()},o.on(`finish`,i),a.on(`error`,function(e){i(e)}),a.pipe(o)},C.prototype.close=function(e){setImmediate(e)},i.inherits(w,s);function w(e){s.call(this),this.context=e,this.context.ref(),this.unreffedYet=!1}w.prototype._flush=function(e){this.unref(),e()},w.prototype.unref=function(e){this.unreffedYet||(this.unreffedYet=!0,this.context.unref())};var T=`\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`;function E(e,t){if(t)return e.toString(`utf8`);for(var n=``,r=0;r<e.length;r++)n+=T[e[r]];return n}function ee(e,t){var n=e.readUInt32LE(t);return e.readUInt32LE(t+4)*4294967296+n}var te=typeof Buffer.allocUnsafe==`function`?function(e){return Buffer.allocUnsafe(e)}:function(e){return new Buffer(e)};function D(e,t){typeof e.destroy==`function`?e._destroy=function(e,n){t(),n?.(e)}:e.destroy=t}function ne(e){if(e)throw e}})),sk=me(),tle=ele();const ck={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,gemini:`gemini`,opencode:`opencode`,"pi-acp":`pi`},nle={claude:`claude`,codex:`codex`,cursor:`cursor-agent`,gemini:`gemini`,opencode:`opencode`,pi:`pi`,antigravity:`agy`,copilot:`copilot`,openclaw:`openclaw`,hermes:`hermes`};async function rle(e,t){let n={cmd:nle[e],args:[],env:dT(),kind:`custom`,pathFromOverlay:!1};try{return await ST(n),`present`}catch(e){if(!(e instanceof cT)||e.code!==`command-not-found`)return`unknown`;let r=await t().catch(()=>null);if(r===null)return`not-found`;try{return await ST(_T(n,r)),`present`}catch{return`not-found`}}}function ile(e={}){let t=e.resolveLoginShellPath??oT(N(`acp-harness`)),n=e.probe??(e=>rle(e,t)),r=e.now??Date.now,i=e.ttlMs??6e4,a=[...new Set(Object.values(ck))].filter(e=>e!==void 0),o=null;return()=>{let e=r();if(o!==null&&o.expiresAt>e)return o.value;let t=Promise.all(a.map(async e=>{try{return[e,await n(e)]}catch{return[e,`unknown`]}})).then(e=>Object.fromEntries(e));return o={expiresAt:e+i,value:t},t}}let ale=0;const ole=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function lk(e,t,n,r,i){let a=e.doc;if(!a)return()=>{};let o=++ale,s=a.getMap(`agent-effects`),c=u=>{if(u.transaction.origin!==n)return;e.unobserve(c),a.off(`destroy`,l);let d=`${t}:${o}`,f={sessionId:t,timestamp:Date.now(),delta:u.delta,agent_type:i??`agent`,color_seed:r??t};try{a.transact(()=>{if(s.set(d,f),s.size>50){let e=[...s.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,s.size-50))s.delete(t)}},ole)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),Ose(),process.env.NODE_ENV!==`production`)throw e}},l=()=>{e.unobserve(c)};return e.observe(c),a.once(`destroy`,l),()=>{e.unobserve(c),a.off(`destroy`,l)}}const sle=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function uk(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(sle,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+`…`,truncatedFrom:e.length}}function cle(e){let t=e.host;if(!t)return null;let n=e[`x-forwarded-proto`];return`${(Array.isArray(n)?n[0]:n)===`https`?`wss`:`ws`}://${t}/collab`}function dk(e,t){let n=uk(e.summary);if(n.kind===`invalid`)return{kind:`invalid-summary`};let r=Sh(e),i=t?.()??null;return r.rawAgentId!==void 0&&r.writerId!==void 0?{kind:`agent`,writerId:r.writerId,displayName:r.displayName,colorSeed:r.colorSeed??r.rawAgentId,clientName:r.clientName,clientVersion:r.clientVersion,label:r.label,actor:{principalId:i?.id,agentType:xh(r.clientName),clientName:r.clientName,clientVersion:r.clientVersion,label:r.label},summary:n}:i?{kind:`principal`,writerId:i.id,displayName:i.display_name,colorSeed:i.id,actor:{principalId:i.id},summary:n}:{kind:`anonymous`,summary:n}}function lle(e){return fk(e,{maxBytes:1048576,timeoutMs:3e4})}async function fk(e,t){let n=[],r=0,i=AbortSignal.timeout(t.timeoutMs),a=()=>e.destroy(new mk(t.timeoutMs));i.addEventListener(`abort`,a,{once:!0});try{for await(let i of e){if(r+=i.length,r>t.maxBytes)throw new pk(t.maxBytes);n.push(i)}return Buffer.concat(n)}finally{i.removeEventListener(`abort`,a)}}var pk=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${ule(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},mk=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function ule(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function hk(e,t,n,r={}){let i=e.safeParse(t);if(i.success)return{ok:!0,value:i.data};let a=i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return G(n,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:r.handler,detail:a}),{ok:!1}}function K(e,t,n={}){return async(r,i)=>{if(n.method!==void 0&&r.method!==n.method){G(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:n.handler,extraHeaders:{Allow:n.method}});return}if(n.preBodyGate!==void 0&&!n.preBodyGate(r,i)){!i.headersSent&&!i.writableEnded&&!i.destroyed&&G(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:n.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(n.skipBodyParse){let a=hk(e,{},i,n);if(!a.ok)return;await t(r,i,a.value);return}let a;try{a=await lle(r)}catch(e){if(e instanceof pk){G(i,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:n.handler,cause:e});return}if(e instanceof mk){G(i,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:n.handler,cause:e});return}G(i,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:n.handler,cause:e});return}let o;try{o=a.length===0?{}:JSON.parse(a.toString(`utf8`))}catch(e){G(i,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:n.handler,cause:e});return}let s=hk(e,o,i,n);s.ok&&await t(r,i,s.value)}}const gk=()=>N(`http`);function q(e,t,n,r,i={}){if(e.headersSent||e.writableEnded||e.destroyed){gk().error({event:`api.success.double-write`,status:t,handler:i.handler},`successResponse called after headers already sent — suppressed`),dS().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}});return}let a=n.safeParse(r);if(!a.success){gk().error({event:`api.success.malformed-body`,issues:a.error.issues,bodyKeys:typeof r==`object`&&r?Object.keys(r):null,handler:i.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),G(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}let o;try{o=JSON.stringify(a.data)}catch(n){gk().error({event:`api.success.unserializable-body`,bodyKeys:typeof a.data==`object`&&a.data!==null?Object.keys(a.data):null,handler:i.handler,originalStatus:t,err:n},`successResponse parsed body is not JSON-serializable — emitting fallback`),G(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}e.writeHead(t,{...i.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(o)}function _k(e,t,n,r=32){if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n>e.length||t>=n)throw Error(`invalid selection range [${t}, ${n}) for body length ${e.length}`);let i=e.slice(t,n),a=e.slice(Math.max(0,t-r),t),o=e.slice(n,Math.min(e.length,n+r));if(xk(e,i)>1){let s=r;for(;!fle(e,a,i,o)&&s<e.length;)s=Math.min(s*2,e.length),a=e.slice(Math.max(0,t-s),t),o=e.slice(n,Math.min(e.length,n+s))}return{exact:i,prefix:a,suffix:o,start:t,end:n}}function dle(e,t){return Sk(e,t).map(e=>({start:e,end:e+t.length}))}function vk(e,t,n,{contextIsMarkdown:r=!1}={}){let i=n.prefix??``,a=n.suffix??``,o=[],s=-1;for(let n of t){let t=Aa(e,n,{prefix:i,suffix:a},{syntaxIn:`haystack`,syntaxInContext:r});t>s?(s=t,o=[n]):t===s&&o.push(n)}return o}function yk(e,t){let{exact:n,prefix:r,suffix:i,start:a}=t,o=a+n.length;if(o<=e.length&&e.slice(a,o)===n)return{status:`anchored`,start:a,end:o};if(r!==``&&i!==``&&!e.includes(r+n+i)&&e.includes(r+i))return{status:`orphaned`};let s=Sk(e,n);if(s.length===0)return bk(e,t);let c=Xa(t,{syntaxInContext:!0}),l=t=>c===0||Aa(e,t,{prefix:r,suffix:i},{syntaxIn:`haystack`,syntaxInContext:!0})>=c;if(s.length===1){let r={start:s[0],end:s[0]+n.length};return l(r)?{status:`anchored`,start:r.start,end:r.end}:bk(e,t)}let u=vk(e,s.map(e=>({start:e,end:e+n.length})),{prefix:r,suffix:i},{contextIsMarkdown:!0});if(!l(u[0]))return bk(e,t);if(u.length===1)return{status:`anchored`,start:u[0].start,end:u[0].end};let d=[],f=1/0;for(let e of u){let t=Math.abs(e.start-a);t<f?(f=t,d=[e]):t===f&&d.push(e)}return d.length===1?{status:`anchored`,start:d[0].start,end:d[0].end}:{status:`orphaned`}}function bk(e,t){let{prefix:n,suffix:r,exact:i}=t,a=n===``?[0]:Sk(e,n).map(e=>e+n.length),o=r===``?[e.length]:Sk(e,r);if(a.length!==1||o.length!==1)return{status:`orphaned`};let s=a[0],c=o[0];if(c<s||c===s)return{status:`orphaned`};let l=Ui(i.length);return c-s>l?{status:`orphaned`}:{status:`anchored`,start:s,end:c,rewritten:!0}}function xk(e,t){if(t===``)return 0;let n=0,r=e.indexOf(t);for(;r!==-1;)n+=1,r=e.indexOf(t,r+1);return n}function Sk(e,t){let n=[];if(t===``)return n;let r=e.indexOf(t);for(;r!==-1;)n.push(r),r=e.indexOf(t,r+1);return n}function fle(e,t,n,r){return xk(e,t+n+r)===1}function Ck(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];for(let e of n){if(r==null)return;if(typeof e==`number`){if(!Array.isArray(r)||e>=r.length)return;r=r[e];continue}if(typeof r!=`object`||Array.isArray(r))return;let t=r;if(!Object.hasOwn(t,e))return;r=t[e]}return r}function wk(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):null}function ple(e,t){if(t===``)return!1;let n=e.indexOf(t);return n!==-1&&e.indexOf(t,n+1)!==-1}var Tk=class extends Error{},Ek=class extends Error{},Dk=class extends Error{},Ok=class extends Error{},mle=class{store;index;getDocBody;getDocFrontmatter;now;newId;indexReady=null;constructor(e){this.store=e.store,this.index=e.index,this.getDocBody=e.getDocBody,this.getDocFrontmatter=e.getDocFrontmatter,this.now=e.now??Date.now,this.newId=e.newId??dd}buildIndex(){return this.indexReady??=this.index.build(this.store),this.indexReady}async createThread(e){await this.buildIndex();let t=e.propertyKey,n,r;if(t===void 0){let t=await this.requireDocBody(e.docName),{start:i,end:a}=this.resolveRange(t,e);n={kind:`body`},r=_k(t,i,a)}else{let i=e.propertyPath??[];n={kind:`property`,key:t,path:i};let a=e.quote?.trim();if(a===void 0||a.length===0)await this.requirePropertyTarget(e.docName,t,i),r=null;else{let n=await this.requirePropertyText(e.docName,t,i),{start:a,end:o}=this.resolveRange(n,e);r=_k(n,a,o)}}let i=this.newId(),a=this.now(),o=await this.store.createThread({threadId:i,docName:e.docName,target:n,anchor:r,createdBy:e.author,createdAt:a,body:e.body});return this.index.upsert(o),e.queue===!0?this.mutate(i,{queued:!0}):o}async listThreads(e){return await this.buildIndex(),e===void 0?this.index.listAll():this.index.listForDoc(e)}async countThreads(e){return await this.buildIndex(),`prefix`in e?this.index.countsUnderPrefix(e.prefix):this.index.countsForDocs(e.docNames)}async readThread(e){return this.requireMeta(e)}async editComment(e,t){return this.mutate(e,{latestComment:t,updatedAt:this.now()})}async resolve(e){return this.mutate(e,{state:`resolved`})}async reopen(e){return await this.mutate(e,{state:`anchored`,queued:!0}),this.refindOnLoad(e)}async replaceAnchor(e,t){let n=await this.requireMeta(e);if(n.target.kind===`property`)throw new Dk(n.target.key);let r=await this.requireDocBody(n.docName),{start:i,end:a}=this.resolveRange(r,t),o=_k(r,i,a);return this.mutate(e,{anchor:o,state:`anchored`})}async queueForDispatch(e,t){await this.mutate(e,{queued:!0});let n=await this.refindOnLoad(e,t);return{meta:n,orphaned:n.state===`orphaned`}}async prepareDispatch(e){let t=await this.getDocBody((await this.requireMeta(e)).docName),n=await this.queueForDispatch(e,t),{anchor:r,docName:i,target:a}=n.meta,o=await this.latestComment(e);return a.kind===`property`?{meta:n.meta,payload:{docName:i,instruction:o,property:kk(a.key,a.path),passage:r===null?null:{exact:r.exact,prefix:r.prefix,suffix:r.suffix},anchorLost:n.orphaned,passageRepeats:!1}}:{meta:n.meta,payload:{docName:i,instruction:o,property:null,passage:r===null?null:{exact:r.exact,prefix:r.prefix,suffix:r.suffix},anchorLost:n.orphaned,passageRepeats:r!==null&&t!==null&&ple(t,r.exact)}}}async completeDispatch(e){return this.mutate(e,{queued:!1,state:`resolved`})}async prepareDispatchBatch(e){let t=[];for(let n of e)try{let e=await this.prepareDispatch(n);t.push({threadId:n,ok:!0,...e})}catch(e){if(e instanceof Ek){t.push({threadId:n,ok:!1,error:`not-found`});continue}throw e}return t}async completeDispatchBatch(e){let t=[];for(let n of e)try{t.push({threadId:n,ok:!0,meta:await this.completeDispatch(n)})}catch(e){if(e instanceof Ek){t.push({threadId:n,ok:!1,error:`not-found`});continue}throw e}return t}async latestComment(e){return(await this.requireMeta(e)).latestComment.trim()}async unqueue(e){return this.mutate(e,{queued:!1})}async delete(e){await this.buildIndex(),await this.store.delete(e),this.index.remove(e)}async renameDoc(e,t){if(e===t)return;await this.buildIndex();let n=this.index.threadsForDoc(e);n.length!==0&&(this.index.renameDoc(e,t),await Promise.all(n.map(e=>this.store.update(e,{docName:t}))))}async deleteDoc(e){await this.buildIndex();let t=this.index.threadsForDoc(e);for(let e of t)await this.store.delete(e),this.index.remove(e);return t.length}async refindDoc(e){await this.buildIndex();let t=this.index.listForDoc(e).filter(e=>e.state!==`resolved`);if(t.length===0)return!1;let n=await this.getDocBody(e);if(n===null)return!1;let r=t.some(e=>e.target.kind===`property`)?await this.getDocFrontmatter(e):null,i=!1;for(let a of t){if(a.target.kind===`property`){let t=await this.refindProperty(e,a.target,a.anchor,r);if(t===null||t.state===a.state)continue;await this.mutate(a.threadId,{state:t.state}),i=!0;continue}if(a.anchor===null)continue;let t=yk(n,a.anchor);if(t.status===`orphaned`){if(a.state===`orphaned`)continue;await this.mutate(a.threadId,{state:`orphaned`}),i=!0;continue}let o=t.rewritten===!0?_k(n,t.start,t.end):void 0,s=a.state!==`anchored`;o===void 0&&!s||(await this.mutate(a.threadId,{...o?{anchor:o}:{},state:`anchored`}),(s||o!==void 0)&&(i=!0))}return i}async refindOnLoad(e,t){let n=await this.requireMeta(e);if(n.state===`resolved`)return n;if(n.target.kind===`property`){let t=await this.refindProperty(n.docName,n.target,n.anchor);return t===null||t.anchor===void 0&&t.state===n.state?n:this.mutate(e,{...t.anchor?{anchor:t.anchor}:{},state:t.state})}let r=t===void 0?await this.getDocBody(n.docName):t;if(r===null)return n;let i=n.anchor;if(i===null)return n;let a=yk(r,i);if(a.status===`orphaned`)return n.state===`orphaned`?n:this.mutate(e,{state:`orphaned`});let o=a.rewritten?_k(r,a.start,a.end):a.start!==i.start||a.end!==i.end?{...i,start:a.start,end:a.end}:void 0;return o===void 0&&n.state===`anchored`?n:this.mutate(e,{...o?{anchor:o}:{},state:`anchored`})}async mutate(e,t){let n=await this.store.update(e,t);if(!n)throw new Ek(e);return this.index.upsert(n),n}resolveRange(e,t){if(t.start!==void 0&&t.end!==void 0)return{start:t.start,end:t.end};let n=t.quote?.trim();if(n===void 0||n.length===0)throw Error(`either start/end offsets or a non-empty quote is required`);let r=dle(e,n),i=r.length>0?r:Xi(e,n,{syntaxIn:`haystack`});if(i.length===0)throw new Ok(n);return i.length===1?i[0]:vk(e,i,{prefix:t.prefix,suffix:t.suffix})[0]}async requireMeta(e){let t=await this.store.readMeta(e);if(!t)throw new Ek(e);return t}async requireDocBody(e){let t=await this.getDocBody(e);if(t===null)throw new Tk(e);return t}async requirePropertyText(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new Tk(e);let i=Ck(r,t,n);if(i===void 0)throw new Dk(kk(t,n));let a=wk(i);if(a===null)throw new Dk(kk(t,n));return a}async requirePropertyTarget(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new Tk(e);if(Ck(r,t,n)===void 0)throw new Dk(kk(t,n))}async refindProperty(e,t,n,r){let i=r===void 0?await this.getDocFrontmatter(e):r;if(i===null)return null;let a=Ck(i,t.key,t.path);if(a===void 0)return{state:`orphaned`};if(n===null)return{state:`anchored`};let o=wk(a);if(o===null)return{state:`orphaned`};let s=yk(o,n);return s.status===`orphaned`?{state:`orphaned`}:s.rewritten?{state:`anchored`,anchor:_k(o,s.start,s.end)}:s.start!==n.start||s.end!==n.end?{state:`anchored`,anchor:{...n,start:s.start,end:s.end}}:{state:`anchored`}}};function kk(e,t){let n=e;for(let e of t)n+=typeof e==`number`?`[${e}]`:`.${e}`;return n}const Ak=`comments`,hle={maxBytes:64*1024,timeoutMs:1e4},jk={start:i().int().nonnegative().optional(),end:i().int().nonnegative().optional(),quote:u().min(1).optional(),prefix:u().max(1e3).optional(),suffix:u().max(1e3).optional()},gle=j({docName:u().min(1),...jk,propertyKey:u().min(1).optional(),propertyPath:M(p([u(),i().int().nonnegative()])).optional(),body:u(),queue:D().optional(),summary:u().optional()}),Mk=ze(),_le=Fe(`action`,[j({action:x(`edit`),id:Mk,body:u(),summary:u().optional()}),j({action:x(`resolve`),id:Mk,summary:u().optional()}),j({action:x(`reopen`),id:Mk,summary:u().optional()}),j({action:x(`replace`),id:Mk,...jk,summary:u().optional()}),j({action:x(`queue`),id:Mk,summary:u().optional()}),j({action:x(`unqueue`),id:Mk,summary:u().optional()}),j({action:x(`dispatch-prepare`),id:Mk,summary:u().optional()}),j({action:x(`dispatch-complete`),id:Mk,summary:u().optional()}),j({action:x(`dispatch-prepare-batch`),ids:M(Mk).min(1).max(200),summary:u().optional()}),j({action:x(`dispatch-complete-batch`),ids:M(Mk).min(1).max(200),summary:u().optional()})]);function vle(e){let{service:t,getPrincipal:n,onChanged:r}=e;async function i(e,n){let r=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??void 0;try{q(n,200,Yr,{threads:await t.listThreads(r)},{handler:Ak})}catch(e){Lk(n,e,`Failed to list comment threads.`)}}function a(e,t){let n=new URL(e.url??``,`http://localhost`).searchParams.get(`id`);return n?Mk.safeParse(n).success?n:(Fk(t,`id must be a comment thread UUID.`),null):(Fk(t,`id query parameter is required.`),null)}async function o(e,n){let r=a(e,n);if(r!==null)try{q(n,200,Ht,await t.readThread(r),{handler:Ak})}catch(e){if(e instanceof Ek)return Ik(n,`Comment thread not found.`);Lk(n,e,`Failed to read comment thread.`)}}async function s(e,i){let a=await Nk(e,i,gle);if(!a)return;let o=dk(a,n);if(o.kind===`invalid-summary`)return Fk(i,`Summary must be a string.`);let s=Pk(o);if(!s)return Fk(i,`A principal or agent identity is required to comment.`);try{let e=await t.createThread({docName:a.docName,start:a.start,end:a.end,quote:a.quote,prefix:a.prefix,suffix:a.suffix,propertyKey:a.propertyKey,propertyPath:a.propertyPath,author:s,body:a.body,queue:a.queue});r?.(),q(i,201,Ht,e,{handler:Ak})}catch(e){if(e instanceof Tk)return Ik(i,`Document not found.`);if(e instanceof Ok)return Fk(i,`The quoted passage is not in the document.`);if(e instanceof Dk)return Fk(i,`That property is not in the document: ${e.message}`);if(e instanceof RangeError||e instanceof Error&&/invalid selection|is required/.test(e.message))return Fk(i,`Selection range is invalid for the document.`);Lk(i,e,`Failed to create comment thread.`)}}async function c(e,i){let a=await Nk(e,i,_le);if(!a)return;let o=dk(a,n);if(o.kind===`invalid-summary`)return Fk(i,`Summary must be a string.`);try{switch(a.action){case`edit`:return Pk(o)?u(i,await t.editComment(a.id,a.body)):Fk(i,`An identity is required to edit a comment.`);case`resolve`:return u(i,await t.resolve(a.id));case`reopen`:return u(i,await t.reopen(a.id));case`replace`:return u(i,await t.replaceAnchor(a.id,{start:a.start,end:a.end,quote:a.quote,prefix:a.prefix,suffix:a.suffix}));case`queue`:{let e=await t.queueForDispatch(a.id);return r?.(),q(i,200,Pr,e,{handler:Ak})}case`unqueue`:return u(i,await t.unqueue(a.id));case`dispatch-prepare`:{let e=await t.prepareDispatch(a.id);return r?.(),q(i,200,Vr,e,{handler:Ak})}case`dispatch-complete`:return u(i,await t.completeDispatch(a.id));case`dispatch-prepare-batch`:{let e=await t.prepareDispatchBatch(a.ids);return r?.(),q(i,200,fn,{results:e},{handler:Ak})}case`dispatch-complete-batch`:{let e=await t.completeDispatchBatch(a.ids);return r?.(),q(i,200,yn,{results:e},{handler:Ak})}}}catch(e){if(e instanceof Ek)return Ik(i,`Comment thread not found.`);if(e instanceof Tk)return Ik(i,`Document not found.`);if(e instanceof Ok)return Fk(i,`The quoted passage is not in the document.`);if(e instanceof Dk)return Fk(i,`That property is not in the document: ${e.message}`);if(e instanceof Error&&/invalid selection|is required/.test(e.message))return Fk(i,`Selection range is invalid for the document.`);Lk(i,e,`Failed to update comment thread.`)}}async function l(e,n){let i=a(e,n);if(i!==null)try{await t.delete(i),r?.(),q(n,200,ro,{threadId:i},{handler:Ak})}catch(e){Lk(n,e,`Failed to delete comment thread.`)}}function u(e,t){r?.(),q(e,200,Ht,t,{handler:Ak})}return{list:i,read:o,create:s,mutate:c,remove:l}}async function Nk(e,t,n){let r;try{r=await fk(e,hle)}catch{return Fk(t,`Request body could not be read.`),null}let i;try{i=JSON.parse(r.toString(`utf8`)||`{}`)}catch{return Fk(t,`Request body must be valid JSON.`),null}let a=n.safeParse(i);return a.success?a.data:(Fk(t,`Request body is invalid.`),null)}function Pk(e){return e.kind===`agent`||e.kind===`principal`?e.writerId:null}function Fk(e,t){G(e,400,`urn:ok:error:invalid-request`,t,{handler:Ak})}function Ik(e,t){G(e,404,`urn:ok:error:not-found`,t,{handler:Ak})}function Lk(e,t,n){G(e,500,`urn:ok:error:internal-server-error`,n,{handler:Ak,cause:t})}var yle=class{threads=new Map;docToThreads=new Map;async build(e){this.threads.clear(),this.docToThreads.clear();for(let t of await e.scanCoverSheets())this.upsert(t)}upsert(e){let t=this.threads.get(e.threadId);t!==void 0&&t.docName!==e.docName&&this.detach(t.docName,e.threadId),this.threads.set(e.threadId,e);let n=this.docToThreads.get(e.docName);n||(n=new Set,this.docToThreads.set(e.docName,n)),n.add(e.threadId)}remove(e){let t=this.threads.get(e);t!==void 0&&(this.threads.delete(e),this.detach(t.docName,e))}renameDoc(e,t){let n=this.docToThreads.get(e);if(!n)return;this.docToThreads.delete(e);let r=this.docToThreads.get(t)??new Set;for(let e of n){r.add(e);let n=this.threads.get(e);n&&this.threads.set(e,{...n,docName:t})}this.docToThreads.set(t,r)}listForDoc(e){let t=[];for(let n of this.docToThreads.get(e)??[]){let e=this.threads.get(n);e&&t.push(e)}return t}listAll(){return[...this.threads.values()]}threadsForDoc(e){return[...this.docToThreads.get(e)??[]]}countsForDocs(e){let t=new Map;for(let n of e)t.set(n,this.countForDoc(n));return t}countsUnderPrefix(e){let t=e===``?``:e.endsWith(`/`)?e:`${e}/`,n=new Map;for(let e of this.docToThreads.keys()){if(!e.startsWith(t))continue;let r=this.countForDoc(e);r>0&&n.set(e,r)}return n}countForDoc(e){let t=0;for(let n of this.docToThreads.get(e)??[])this.threads.get(n)?.state!==`resolved`&&t++;return t}get size(){return this.threads.size}detach(e,t){let n=this.docToThreads.get(e);n&&(n.delete(t),n.size===0&&this.docToThreads.delete(e))}},ble=class{dir;log;writeQueues=new Map;dirReady=null;constructor(e,t){this.dir=F(e,`comments`),this.log=t}init(){return this.ensureDir()}ensureDir(){return this.dirReady??=Ps(this.dir,{recursive:!0}).then(()=>void 0),this.dirReady}metaPath(e){return F(this.dir,`${e}.meta.json`)}enqueueResult(e,t){let n=(this.writeQueues.get(e)??Promise.resolve()).then(()=>t());return this.writeQueues.set(e,n.then(()=>void 0,()=>void 0)),n}async whenIdle(e){await(this.writeQueues.get(e)??Promise.resolve())}createThread(e){let t=Ht.parse({threadId:e.threadId,docName:e.docName,target:e.target,anchor:e.anchor,state:`anchored`,queued:!1,latestComment:e.body,createdBy:e.createdBy,createdAt:e.createdAt});return this.enqueueResult(e.threadId,async()=>(await this.ensureDir(),await this.write(t),t))}update(e,t){return this.enqueueResult(e,async()=>{await this.ensureDir();let n=await this.readMeta(e);if(!n)return null;let r=Ht.parse({...n,...xle(t)});return await this.write(r),r})}write(e){return Os(this.metaPath(e.threadId),Sle(e),{fs:Ms})}async readMeta(e){let t;try{t=await id(this.metaPath(e),`utf8`)}catch{return null}let n=Ht.safeParse(Cle(t));return n.success?n.data:(this.log.warn({threadId:e},`[comments] skipping unreadable thread meta`),null)}async scanCoverSheets(){let e;try{e=await ad(this.dir)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(`.meta.json`))continue;let e=await this.readMeta(n.slice(0,-10));e&&t.push(e)}return t}async delete(e){await this.enqueueResult(e,async()=>{await Is(this.metaPath(e),{force:!0}),await Is(F(this.dir,`${e}.ndjson`),{force:!0})})}};function xle(e){let{docName:t,anchor:n,state:r,queued:i,latestComment:a,updatedAt:o}=e;return{...t!==void 0&&{docName:t},...n!==void 0&&{anchor:n},...r!==void 0&&{state:r},...i!==void 0&&{queued:i},...a!==void 0&&{latestComment:a},...o!==void 0&&{updatedAt:o}}}function Sle(e){return`${JSON.stringify(e,null,1)}\n`}function Cle(e){try{return JSON.parse(e)}catch{return}}function Rk(e,t){return L(t,e.content.dir)}function zk(e){return L(e,`.ok`,ge)}function Bk(e){return zk(e)}const Vk={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},Hk={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function Uk(e,t){if(typeof e!=`string`||!yu(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let n=L(e),r=L(n,t),i=I(n,r);return i===``?{ok:!0,abs:r,rel:``}:i===`..`||i.startsWith(`../`)||yu(i)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:r,rel:i}}function Wk(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const Gk="Absolute host path inside the target OpenKnowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",Kk=u().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),qk="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",wle=u().length(40).regex(/^[0-9a-f]+$/i).describe(qk),Jk=u().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),Yk=u().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),Xk=u().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),Zk=j({value:u(),truncatedFrom:i().optional(),hint:u().optional()}).describe(`Normalized change-note summary, when one was recorded.`),Qk=M(C(u(),_())),$k=C(u(),_()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),Tle=M(rt).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" }`. Report-only — the write landed regardless; fix in a follow-up edit.');function Ele(e,t){for(let n of Jn){let r=Uk(e,`${t}${n}`);if(r.ok&&z(r.abs))return n}}const eA={summary:Zk.optional(),warnings:M(va).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit."),brokenLinks:Tle,templateHint:M(j({name:u(),description:u().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.")};function tA(e,t,n){let r={};return e&&(r.previewUrl=e.url,r.previewUrlSource=e.source),t&&(r.warning=t),Object.keys(n).length>0&&(r.document=n),r}function nA(e){let t=typeof e.detail==`string`?` (${e.detail})`:``;return`Error: ${typeof e.error==`string`?e.error:`request failed`}${t}`}function J(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const Dle=u().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function rA(e){return{text:Dle,...e}}function iA(e,t,n){let r={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:r,...n?{isError:!0}:{}}}const aA="Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nDo not fall back to native file edits for in-scope markdown; route writes through OpenKnowledge so attribution and live sync stay intact.";async function oA(e,t){return typeof e==`function`?await e(t):e}async function Ole(e,t){return typeof e==`function`?await e(t):e}async function sA(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let i=n===void 0?r:L(n);try{let e=await Ole(t,r);return{ok:!0,cwd:r,executionCwd:i,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function cA(e,t,n,r){let i=await lA(e,t,n,r);return i.ok?i.url?{ok:!0,cwd:i.cwd,executionCwd:i.executionCwd,config:i.config,url:i.url}:{ok:!1,result:J(aA,!0)}:{ok:!1,result:J(`Error: ${i.error}`,!0)}}async function lA(e,t,n,r){let i=await sA(e,t,r);if(!i.ok)return i;let{cwd:a,executionCwd:o,config:s}=i;try{return{ok:!0,cwd:a,executionCwd:o,config:s,url:await oA(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function uA(e){let t=e.replace(/^\/+/,``);return t!==`.ok`&&!t.startsWith(`.ok/`)?null:t.startsWith(`.ok/skills/`)?"Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes the SKILL.md wherever the skill lives (a NEW skill lands at the project default skill home, e.g. `.agents/skills/<name>/`). To author or improve a skill, use the `open-knowledge-write-skill` skill.":t.startsWith(`.ok/templates/`)?"Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.":"Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target."}function dA(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let n=e,r=t;for(;r.endsWith(`.mdx`)||r.endsWith(`.md`);)n=n.slice(0,r.endsWith(`.mdx`)?-4:-3),r=n.toLowerCase();let i=Zt(n);return i.ok?{ok:!0,docName:n}:{ok:!1,error:`Error: "${e}" is invalid — ${i.reason}.`}}function fA(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...n}=t;return{ok:!0,...n}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let n=t;if(typeof n.type==`string`&&typeof n.title==`string`){let{type:e,title:t,status:r,instance:i,detail:a,...o}=n;return{...o,ok:!1,error:t,type:e,...typeof r==`number`?{status:r}:{},...typeof i==`string`?{instance:i}:{},...typeof a==`string`?{detail:a}:{}}}let{ok:r,error:i,...a}=n,o=typeof i==`string`?i:typeof n.message==`string`?n.message:`Server returned HTTP ${e.status}`;return{...a,ok:!1,error:o}}function pA(e,t){return t?{url:e,local:t}:e}async function mA(e,t,n,r,i){let a;try{a=await e(t,n,r===void 0?void 0:{body:r,contentType:`application/json`})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}if(a===null)return null;let o=a.status>=200&&a.status<=299,s;try{s=JSON.parse(a.bodyText)}catch(e){let t=e instanceof Error?e.message:String(e),n=i?{httpStatus:a.status}:{};return o?{ok:!1,...n,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,...n,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}let c=fA({ok:o,status:a.status},s);return i?{...c,httpStatus:a.status}:c}async function hA(e,t){if(typeof e!=`string`){let n=await mA(e.local,`GET`,t,void 0,!0);if(n!==null)return n;e=e.url}let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let r;try{r=await n.json()}catch(e){let t=e instanceof Error?e.message:String(e);return n.ok?{ok:!1,httpStatus:n.status,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,httpStatus:n.status,error:`Server returned HTTP ${n.status} with non-JSON body: ${t}`}}return{...fA(n,r),httpStatus:n.status}}async function gA(e,t,n){let r=await hA(e,t);if(!r.ok)return{error:typeof r.error==`string`?r.error:`request failed`};let{ok:i,...a}=r,o=a[n];return{rows:Array.isArray(o)?o:[],data:a}}async function _A(e,t,n,r){let i;if(r!==void 0)try{i=JSON.stringify(r)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}if(typeof t!=`string`){let r=await mA(t.local,e,n,i,!1);if(r!==null)return r;t=t.url}let a;try{a=await fetch(`${t}${n}`,{method:e,headers:i===void 0?void 0:{"Content-Type":`application/json`},body:i,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let o;try{o=await a.json()}catch(e){let t=e instanceof Error?e.message:String(e);return a.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}return fA(a,o)}function vA(e,t,n){return _A(`POST`,e,t,n)}function yA(e,t,n){return _A(`PUT`,e,t,n)}function bA(e,t){return _A(`DELETE`,e,t)}function kle(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:n,to:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`?[{existing:t,incoming:n,to:r}]:[]}):[]}function xA(e){let t=e.severity===`error`?`✘`:`⚠`,n=e.range?.start?.line;return` ${t} ${n===void 0?`line ?`:`line ${n+1}`} ${e.source!==void 0&&e.code!==void 0?`${e.source}/${e.code}`:`?`}: ${e.message??``}`.trimEnd()}function SA(e,t){let n=[];return e>0&&n.push(`${e} error${e===1?``:`s`}`),t>0&&n.push(`${t} warning${t===1?``:`s`}`),n.length>0?n.join(`, `):`no problems`}function CA(e){return e?Fr(e).split(/\r?\n/):[]}function wA(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function TA(e,t){let n=`${t}:`;for(let t of CA(e))if(t.startsWith(n))return wA(t.slice(n.length))||null;return null}function EA(e){let t=[],n=``,r=null;for(let i of e){if(r){n+=i,i===r&&(r=null);continue}if(i===`"`||i===`'`){r=i,n+=i;continue}if(i===`,`){let e=wA(n);e&&t.push(e),n=``;continue}n+=i}let i=wA(n);return i&&t.push(i),t}function DA(e){let t=[],n=new Set;for(let r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function Ale(e){let{frontmatter:t}=Ur(e);if(!t)return[];let n=CA(t);for(let e=0;e<n.length;e+=1){let t=n[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let r=t[1]?.trim()??``;if(r){if(r.startsWith(`[`)&&r.endsWith(`]`))return DA(EA(r.slice(1,-1)));let e=wA(r);return e?[e]:[]}let i=[];for(let t=e+1;t<n.length;t+=1){let e=n[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=wA(e.replace(/^\s*-\s+/,``));t&&i.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return DA(i)}return[]}function OA(e,t){let{frontmatter:n,body:r}=Ur(e);return TA(n,`title`)||(kA(r)??t)}function kA(e){let t=e.match(/^# (.+)$/m);return t?t[1].trim():void 0}function AA(e){let{frontmatter:t}=Ur(e),n=TA(t,`icon`);if(!(!n||n.length>2048))return n}const jle=/^[>|][+-]?\d*$/;function jA(e,t){let{frontmatter:n}=Ur(e),r=TA(n,t);if(!(!r||jle.test(r)))return r}function MA(e){return jA(e,`description`)}function NA(e){return jA(e,`type`)}function Mle(e){return e?.trim()?{cluster:TA(e,`cluster`)??void 0,category:TA(e,`category`)??void 0,tags:Nle(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function Nle(e,t){let n=`${t}:`,r=CA(e);for(let e=0;e<r.length;e+=1){let t=r[e];if(!t?.startsWith(n))continue;let i=t.slice(n.length).trim();if(i){if(i.startsWith(`[`)&&i.endsWith(`]`)){let e=EA(i.slice(1,-1));return e.length>0?e:void 0}let e=wA(i);return e?[e]:void 0}let a=[];for(let t=e+1;t<r.length;t+=1){let e=r[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=wA(e.replace(/^\s*-\s+/,``));t&&a.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return a.length>0?a:void 0}}function Ple(e,t){let n=OA(e,t),r=Ale(e),i=DA([n,...r]),a=[],o=new Set;for(let e of i){let t=na(e);!t||o.has(t)||(o.add(t),a.push(t))}return{docName:t,title:n,aliases:r,matchLabels:i,normalizedMatchLabels:a}}function Fle(e,t){let n=Rle(e,t,`frontmatter.yml`);if(!z(n))return{};let r=Lle(n);return r==null?{}:Ile(r)}function Ile(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const PA=new Set;function Lle(e){let t;try{t=B(e,`utf-8`)}catch{return null}let n;try{n=(0,sk.parse)(t)}catch(t){if(!PA.has(e)){PA.add(e);let n=t instanceof Error?t.message:String(t);N(`folder-frontmatter`).warn({path:e,reason:n},`malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${n}`)}return null}return typeof n!=`object`||!n||Array.isArray(n)?null:(PA.delete(e),n)}function Rle(e,t,n){let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return r===``||r===`.`?F(e,`.ok`,n):F(e,r,`.ok`,n)}function FA(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function zle(e){try{return qu(L(e,`.git`)).isDirectory()}catch{return!1}}function Ble(e){return fc({baseDir:L(e),timeout:{block:5e3}})}async function Vle(e,t,n=5){if(!zle(e))return{commits:[],source:`git-absent`};let r=Ble(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
|
|
32
|
+
`);return{name:r,description:i,skillMd:n,files:a,contentHash:o.digest(`hex`)}}function RD(e){if(z(F(e,`SKILL.md`)))return[{name:gu(e),dir:e}];let t=[],n=0,r=(e,i)=>{if(i>8||++n>5e3)return;if(z(F(e,`SKILL.md`))){t.push({name:gu(e),dir:e});return}let a;try{a=Hu(e,{withFileTypes:!0})}catch{return}for(let t of a)t.isDirectory()&&!ND.has(t.name)&&r(F(e,t.name),i+1)};return r(e,0),t.sort((e,t)=>e.name.localeCompare(t.name))}function zD(e){let t=e?.skills;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.source==`string`&&t.source?t.source:void 0,i=typeof t.id==`string`&&t.id?t.id:r;if(!i||!r)continue;let a=typeof t.name==`string`&&t.name?t.name:vt(i);xo(a,r)||n.push({id:i,name:a,source:r,description:typeof t.description==`string`?t.description:``,installs:Number.isInteger(t.installs)&&t.installs>=0?t.installs:null,publisher:qo(r)})}return n}const BD={"&":`&`,"<":`<`,">":`>`,""":`"`,"'":`'`,"'":`'`,"'":`'`};function VD(e){return e.replace(/&(?:amp|lt|gt|quot|apos|#39|#x27);/g,e=>BD[e]??e)}function HD(e){let t={},n=e.match(/<meta\b[^>]*>/gi)??[];for(let e of n){let n=e.match(/\bproperty\s*=\s*["'](og:[^"']+)["']/i)?.[1]?.toLowerCase();if(!n)continue;let r=e.match(/\bcontent\s*=\s*["']([^"']*)["']/i)?.[1];if(r==null)continue;let i=VD(r);n===`og:title`&&t.title==null?t.title=i:n===`og:description`&&t.description==null?t.description=i:n===`og:image`&&t.image==null&&(t.image=i)}return t}function UD(e){let t=e?.items;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.full_name==`string`&&t.full_name?t.full_name:void 0;r&&n.push({id:r,name:typeof t.name==`string`&&t.name?t.name:vt(r),source:r,description:typeof t.description==`string`?t.description:``,installs:null,publisher:qo(r)})}return n}function WD(e){return e.trim().toLowerCase()}function GD(e){return e.split(`/`).filter(Boolean).pop()??e}function KD(e){let t=lr(e.trim());if(t?.kind===`site`)return{hostname:t.hostname};let n=yD(e);if(!n)return null;let r=lr(n.owner);return r?.kind===`site`?{hostname:r.hostname,skill:n.skill}:null}async function qD(e,t,n={}){let r=KD(e);if(r){let e=t??r.skill;if(!e)throw new rD(`Website skill sources require a skill name.`);return{source:r.hostname,skill:e,publisher:r.hostname,spec:{kind:`well-known`,origin:`https://${r.hostname}`,skill:e}}}let i=yD(e);if(!i)return null;let a=n.fetchImpl??globalThis.fetch;if(!a)throw new rD(`No fetch implementation available.`);let o=t??i.skill,s=WD(o),c=WD(i.owner),l;try{let e=await a(`https://skills.sh/api/search?q=${encodeURIComponent(o)}&limit=30`,{signal:AbortSignal.timeout(n.timeoutMs??8e3)});if(!e.ok)throw new rD(`skills.sh lookup failed with HTTP ${e.status}`);l=await e.json()}catch(e){throw e instanceof rD?e:new rD(`skills.sh lookup failed: ${e instanceof Error?e.message:String(e)}`)}let u=zD(l).find(e=>{if((e.publisher?WD(e.publisher):``)!==c)return!1;let t=WD(e.name),n=WD(GD(e.id));return t===s||n===s});if(!u)throw new rD(`No skills.sh result matched ${i.owner}/${i.skill}`);let d=lr(u.source),f=d?.kind===`site`?{kind:`well-known`,origin:`https://${d.hostname}`,skill:t??u.name}:vD(u.source);if(!f||f.kind===`local`)throw new rD(`skills.sh returned an unsafe source for ${i.owner}/${i.skill}: ${u.source}`);return{source:u.source,skill:t??u.name,...u.publisher?{publisher:u.publisher}:{},spec:f}}const JD=[`agents`,`claude`,`cursor`,`codex`,`opencode`,`pi`,`copilot`];function YD(e){let t=JD.indexOf(e);return t===-1?JD.length:t}function XD(e){let t=new Map,n=new Map;for(let r of e){let e=`${r.scope}|${r.name}`,i=`${e}|${r.contentHash}`,a=t.get(i);a||(a=[],t.set(i,a)),a.push(r);let o=n.get(e);o||(o=new Set,n.set(e,o)),o.add(r.contentHash)}let r=[];for(let e of t.values()){let t=[...e].sort((e,t)=>{let n=Number(e.viaLink===!0)-Number(t.viaLink===!0);if(n!==0)return n;let r=Number(t.preferredSource===!0)-Number(e.preferredSource===!0);if(r!==0)return r;let i=YD(e.editor)-YD(t.editor);return i===0?e.editor.localeCompare(t.editor):i}),i=t[0];i&&r.push({name:i.name,scope:i.scope,contentHash:i.contentHash,canonical:i,copies:t.slice(1),isFork:(n.get(`${i.scope}|${i.name}`)?.size??1)>1})}return r.sort((e,t)=>e.scope.localeCompare(t.scope)||e.name.localeCompare(t.name)||e.contentHash.localeCompare(t.contentHash))}function ZD(e){if(!z(e))return[];try{return Hu(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(e=>F(e.parentPath,e.name)).sort()}catch{return[]}}function QD(e,t,n,r){let i=F(e,`SKILL.md`);if(!z(i))return null;let a=gu(e),o=a,s=``;try{({name:o,description:s}=jD(B(i,`utf-8`),a))}catch{}return{name:o,description:s,home:e,harness:t,skillMd:i,scripts:ZD(F(e,`scripts`)),references:ZD(F(e,`references`)),provenance:n,inert:r}}function $D(e){if(!z(e))return[];try{return Hu(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function eO(e){let t=e=>{try{return qu(e).isDirectory()}catch{return!1}};return{commands:t(F(e,`commands`)),hooks:t(F(e,`hooks`)),mcp:z(F(e,`.mcp.json`))}}const tO={commands:!1,hooks:!1,mcp:!1};function nO(e,t){let n=[];for(let r of $D(e)){let i=QD(F(e,r),t,{},tO);i&&n.push({packName:i.name,packVersion:`0.0.0`,harness:t,skills:[i]})}return n}function rO(e){try{return Hu(e).length>0}catch{return!1}}function iO(e){let t=new Set,n=(e,r)=>{if(r>4)return;let i;try{i=Hu(e,{withFileTypes:!0})}catch{return}if(z(F(e,`SKILL.md`))||z(F(e,`SKILL.mdx`))){t.add(e.split(`/`).pop()??e);return}for(let t of i)t.isDirectory()&&n(F(e,t.name),r+1)};return n(F(e,`skills`),0),[...t].sort()}function aO(e){return{commands:rO(F(e,`commands`)),hooks:rO(F(e,`hooks`))||z(F(e,`hooks.json`)),mcp:z(F(e,`.mcp.json`)),agents:rO(F(e,`agents`))}}function oO(e){let t=e.lastIndexOf(`@`);return t<=0?{plugin:e}:{plugin:e.slice(0,t),marketplace:e.slice(t+1)}}function sO(e){let t=new Map;for(let n of e){if(n.orphaned_at||!n.installPath||!z(n.installPath))continue;let e=`${n.scope??``} ${n.projectPath??``}`,r=t.get(e);(!r||(n.lastUpdated??``)>(r.lastUpdated??``))&&t.set(e,n)}return[...t.values()]}function cO(e){let t=F(e,`.claude-plugin`,`plugin.json`);try{let e=JSON.parse(B(t,`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function lO(e,t){let n=F(e,`installed_plugins.json`);if(!z(n))return[];let r;try{r=JSON.parse(B(n,`utf-8`))}catch(e){return console.warn(`[skills-catalog] failed to parse installed_plugins.json, skipping Claude plugins`,{manifestPath:n,err:e}),[]}let i=r?.plugins;if(!i||typeof i!=`object`)return[];let a=[];for(let[e,n]of Object.entries(i)){if(!Array.isArray(n))continue;let{plugin:r,marketplace:i}=oO(e);for(let e of sO(n)){let n=e.installPath,o=eO(n),s=cO(n),c=F(n,`skills`),l=[];for(let n of $D(c)){let a={plugin:r,...i?{marketplace:i}:{},...e.version?{version:e.version}:{},...e.gitCommitSha?{gitCommitSha:e.gitCommitSha}:{},...e.scope?{scope:e.scope}:{},...e.projectPath?{projectPath:e.projectPath}:{}},s=QD(F(c,n),t,a,o);s&&l.push(s)}l.length!==0&&a.push({packName:r,packVersion:e.version??s.version??`0.0.0`,...typeof s.description==`string`?{packDescription:s.description}:{},...typeof s.author?.name==`string`?{packAuthor:s.author.name}:{},harness:t,skills:l})}}return a}const uO=/^(.*\/plugins\/cache\/([^/]+)\/([^/]+))\/([^/]+)(?:\/.*)?$/,dO=/^(.*\/plugins)\/(?:cache|marketplaces)\/([^/]+)\//,fO=/^(.*\/plugins\/marketplaces\/([^/]+))(?:\/.*)?$/;function pO(e){return e.replaceAll(`\\`,`/`).replace(/\/+$/,``)}function mO(e){let t=dO.exec(pO(e));if(!t)return null;try{let e=B(`${t[1]}/known_marketplaces.json`,`utf-8`),n=JSON.parse(e)[t[2]];return n?.source?.source===`github`&&n.source.repo?`https://github.com/${n.source.repo}`:null}catch{return null}}function hO(e,t){let n=L(e);try{qu(n).isDirectory()||(n=P(n))}catch{return null}let r=L(t);for(;n===r||n.startsWith(`${r}/`);){try{let e=JSON.parse(B(F(n,`.claude-plugin`,`plugin.json`),`utf-8`));if(typeof e.name==`string`&&e.name.length>0)return{name:e.name,...typeof e.version==`string`?{version:e.version}:{}}}catch{}if(n===r)break;n=P(n)}return null}function gO(e){let t=pO(e),n=uO.exec(t);if(n){let t=hO(e,`${n[1]}/${n[4]}`);return!t||t.name!==n[3]?null:{plugin:n[3],marketplace:n[2],version:t.version??n[4]}}let r=fO.exec(t);if(!r)return null;let i=hO(e,r[1]);return i?{plugin:i.name,marketplace:r[2],...i.version?{version:i.version}:{}}:null}function _O(e){return[...e].sort((e,t)=>e.localeCompare(t,void 0,{numeric:!0})).pop()}function vO(e){let t=pO(e),n=uO.exec(t);if(!n)return e;let[r,i]=[n[1],n[4]],a=t.slice(n[0].indexOf(`/${i}`)+i.length+1),o;try{o=Hu(r,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return e}let s=_O(o);if(s===void 0||s===i)return e;let c=`${r}/${s}${a}`;return z(c)?c:e}function yO(e,t){for(let n of t)try{let t=JSON.parse(B(F(e,n),`utf-8`));if(typeof t.name==`string`&&t.name.length>0)return{plugin:t.name,...typeof t.version==`string`?{version:t.version}:{},...typeof t.description==`string`?{description:t.description}:{}}}catch{}return null}function bO(e){let t=yO(e,[`.claude-plugin/plugin.json`]);if(t)return{...t,setupSupported:!0};try{let t=JSON.parse(B(F(e,`.claude-plugin`,`marketplace.json`),`utf-8`)),n=t.plugins?.find(e=>e.source===`./`)??t.plugins?.[0],r=typeof n?.name==`string`?n.name:t.name;if(typeof r==`string`&&r.length>0)return{plugin:r,...typeof n?.description==`string`?{description:n.description}:{},setupSupported:!0}}catch{}return null}const xO={id:`claude`,homes:e=>[{harness:`claude`,dir:F(e,`.claude`,`plugins`)}],enumerate:lO,inspectSource:gO,repositoryUrl:mO,resolveUpdateSource:vO,detectDir:bO};function SO(e,t){return{id:e,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let n=yO(e,t);return n?{...n,setupSupported:!1}:null}}}function CO(e,t){try{return JSON.parse(B(F(e,t),`utf-8`)).skills!==void 0}catch{return!1}}const wO=[xO,SO(`codex`,[`.codex-plugin/plugin.json`]),SO(`gemini`,[`gemini-extension.json`]),{id:`copilot`,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let t=yO(e,[`.plugin/plugin.json`,`.github/plugin/plugin.json`]);if(t)return{...t,setupSupported:!1};if(!CO(e,`plugin.json`))return null;let n=yO(e,[`plugin.json`]);return n?{...n,setupSupported:!1}:null}}];function TO(e){return wO.find(t=>t.id===e)}function EO(e){if(e===void 0)return wO;let t=TO(e);return t?[t]:[]}function DO(e){return wO.flatMap(t=>t.homes(e).map(e=>({provider:t.id,...e})))}function OO(e,t,n=e){let r=TO(e);if(!r)throw Error(`unknown plugin provider: ${e}`);return r.enumerate(t,n).map(t=>({...t,skills:t.skills.map(t=>({...t,provenance:{...t.provenance,pluginProvider:e}}))}))}function kO(e,t){for(let n of EO(t)){let t=n.inspectSource(e);if(!t)continue;let r=n.repositoryUrl(e);return{provider:n.id,...t,...r?{repositoryUrl:r}:{}}}return null}function AO(e){for(let t of wO){let n=t.detectDir(e);if(!n)continue;let r=iO(e);return r.length===0?null:{provider:t.id,plugin:n.plugin,...n.version?{version:n.version}:{},...n.description?{description:n.description}:{},bundledSkills:r,capabilities:aO(e),setupSupported:n.setupSupported}}return null}function jO(e,t){for(let n of EO(t)){if(!n.inspectSource(e))continue;let t=n.repositoryUrl(e);if(t)return t}return null}function MO(e,t){for(let n of EO(t))if(n.inspectSource(e))return n.resolveUpdateSource(e);return e}function NO(e=Zu()){let t=ns.flatMap(t=>{let n=dr[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:F(e,...n.split(`/`))}]});return[...DO(e).map(e=>({kind:`plugin-provider`,...e})),...t,{harness:`agents`,kind:`skill-dir`,dir:F(e,`.agents`,`skills`)}]}function PO(e){return ns.flatMap(t=>{let n=Zo[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:F(e,...n.split(`/`))}]})}function FO(e){return Object.keys(e.provenance).length>0}function IO(e){return e.provenance.plugin!==void 0}function LO(e,t){if(IO(e)!==IO(t))return IO(e)?e:t;if(FO(e)!==FO(t))return FO(e)?e:t;let n=e.scripts.length+e.references.length;return t.scripts.length+t.references.length>n?t:e}function RO(e,t){return{name:e.name,description:e.description,files:{skillMd:e.skillMd,scripts:e.scripts,references:e.references},sourceHarness:e.harness,sourceHarnesses:t,home:e.home,provenance:e.provenance,inert:e.inert}}function zO(e){try{return LD(e.home)?.contentHash??`unreadable:${e.home}`}catch{return`unreadable:${e.home}`}}function BO(e){let t=new Map;for(let n of e){let e=Rn(n.provenance.scope),r=`${e}\0${e===`project`?n.provenance.projectPath??``:``}\0${n.name}\0${zO(n)}`,i=t.get(r);i?(i.winner=LO(i.winner,n),i.harnesses.add(n.harness)):t.set(r,{winner:n,harnesses:new Set([n.harness])})}return[...t.values()].map(({winner:e,harnesses:t})=>RO(e,[...t].sort())).sort((e,t)=>e.name.localeCompare(t.name)||Rn(e.provenance.scope).localeCompare(Rn(t.provenance.scope))||e.home.localeCompare(t.home))}function VO(e){let t=new Map;for(let n of e){let e=t.get(n.packName),r=e??{version:`0.0.0`,skills:new Set,hosts:new Set};r.version===`0.0.0`&&n.packVersion!==`0.0.0`&&(r.version=n.packVersion),!r.description&&n.packDescription&&(r.description=n.packDescription),!r.author&&n.packAuthor&&(r.author=n.packAuthor);for(let e of n.skills)r.skills.add(e.name);r.hosts.add(n.harness),e||t.set(n.packName,r)}return[...t.entries()].map(([e,t])=>({schema:1,name:e,version:t.version,...t.description?{description:t.description}:{},...t.author?{author:{name:t.author}}:{},skills:[...t.skills].sort(),hostCompatibility:[...t.hosts].sort()})).sort((e,t)=>e.name.localeCompare(t.name))}function HO(e={}){let t=[];for(let n of NO(e.home))try{switch(n.kind){case`plugin-provider`:t.push(...OO(n.provider,n.dir,n.harness));break;case`skill-dir`:t.push(...nO(n.dir,n.harness));break;default:throw Error(`unhandled harness home kind: ${String(n)}`)}}catch(e){console.warn(`[skills-catalog] failed to enumerate harness home, skipping`,{harness:n.harness,dir:n.dir,err:e})}e.projectDir!==void 0&&t.push(...UO(e.projectDir));let n=e.projectDir===void 0?t:t.map(t=>({...t,skills:t.skills.filter(t=>_a(t.provenance,e.projectDir))})).filter(e=>e.skills.length>0);return{skills:BO(n.flatMap(e=>e.skills)),packs:VO(n)}}function UO(e){let t=KO(L(e,`.ok`,`skills`)),n=[];for(let r of PO(e))try{for(let i of nO(r.dir,r.harness)){let r=i.skills.filter(e=>!GO(e,t));r.length!==0&&n.push({...i,skills:r.map(t=>WO(t,e))})}}catch(e){console.warn(`[skills-catalog] failed to enumerate project harness skills, skipping`,{harness:r.harness,dir:r.dir,err:e})}return n}function WO(e,t){return{...e,provenance:{...e.provenance,scope:`project`,projectPath:t}}}function GO(e,t){if(e.name.startsWith(`open-knowledge`))return!0;let n=KO(e.home);return n===t||n.startsWith(t+R)}function KO(e){try{return V(e)}catch{return L(e)}}function qO(e){if(!e.includes(`self.__next_f`))return e;let t=/self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g,n=``;for(let r of e.matchAll(t))n+=JSON.parse(r[1]);return n}const JO=[`skillId`,`source`,`installs`];function YO(e){let t={};if(e.length>8192)return t;let n=new Uint8Array(e.length),r=0,i=!1,a=!1;for(let t=0;t<e.length;t++){n[t]=Math.min(r,255);let o=e[t];if(a){a=!1;continue}if(o===`\\`){a=i;continue}if(o===`"`){i=!i;continue}i||(o===`{`||o===`[`?r++:(o===`}`||o===`]`)&&r--)}for(let r of e.matchAll(/"(skillId|source|installs)"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?)/g)){let e=r[1];if(r.index===void 0||n[r.index]!==1||e in t)continue;let i=r[2];t[e]=i.startsWith(`"`)?JSON.parse(i):Number(i)}return t}function*XO(e){let t=[],n=!1,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){r=!1;continue}if(a===`\\`){r=n;continue}if(a===`"`){n=!n;continue}if(!n){if(a===`{`)t.push(i);else if(a===`}`){let n=t.pop();if(n===void 0)continue;let r=e.slice(n,i+1);if(!JO.every(e=>r.includes(`"${e}"`)))continue;try{let e=JSON.parse(r);if(typeof e==`object`&&e&&!Array.isArray(e)){yield e;continue}}catch{}yield YO(r)}}}}function ZO(e){let t=qO(e),n=[];for(let e of XO(t)){let{skillId:t,source:r,installs:i}=e;typeof t!=`string`||t===``||typeof r!=`string`||r===``||typeof i!=`number`||!Number.isFinite(i)||n.push({skillId:t,source:r,installs:i})}return n}function QO(e){let t=new Map;for(let n of ZO(e)){let e=`${n.source}/${n.skillId}`;t.has(e)||xo(n.skillId,n.source)||t.set(e,{id:e,name:n.skillId,source:n.source,description:``,installs:n.installs,publisher:qo(n.source)})}return[...t.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}const $O=/href="\/([^"/]+)\/([^"/]+)\/([^"/?#]+)"([\s\S]*?)<\/a>/g,ek=/<span[^>]*font-mono[^>]*>\s*([\d,]+)\s*<\/span>/;function tk(e,t){let n=new Map;$O.lastIndex=0;for(let r=$O.exec(e);r!==null;r=$O.exec(e)){let[,e,i,a,o]=r;if(!e||!i||!a||!o||`${e}/${i}`!==t||xo(a,t))continue;let s=Number.parseInt(ek.exec(o)?.[1]?.replaceAll(`,`,``)??``,10);if(!Number.isInteger(s)||s<0)continue;let c=`${t}/${a}`;n.has(c)||n.set(c,{id:c,name:a,source:t,description:``,installs:s,publisher:qo(t)})}return[...n.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}function nk(e,t){return`${e}/${t}`}function rk(e){if(e.preferredSource===!0)return-1;let t=JD.indexOf(e.editor);return t===-1?JD.length:t}function ik(e){let t=XD(e),n=new Set,r=new Map,i=new Set,a=new Map;for(let e of t){n.add(e.canonical.dir);for(let t of e.copies)i.add(t.dir);let t=nk(e.scope,e.name),o=rk(e.canonical),s=a.get(t);(s===void 0||o<s)&&(a.set(t,o),r.set(t,e.canonical.dir))}return{admittedDirs:n,canonicalDir:r,excludedCopyDirs:i}}var ak=n(((e,t)=>{t.exports=n;function n(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}n.prototype.go=function(e){this.pending<this.max?i(this,e):this.waiting.push(e)},n.prototype.wait=function(e){this.pending===0?e(this.error):this.listeners.push(e)},n.prototype.hold=function(){return r(this)};function r(e){e.pending+=1;var t=!1;return n;function n(n){if(t)throw Error(`callback called twice`);if(t=!0,e.error=e.error||n,--e.pending,e.waiting.length>0&&e.pending<e.max)i(e,e.waiting.shift());else if(e.pending===0){var a=e.listeners;e.listeners=[],a.forEach(r)}}function r(t){t(e.error)}}function i(e,t){t(r(e))}})),ok=n((t=>{var n=e(`fs`),r=e(`util`),i=e(`stream`),a=i.Readable,o=i.PassThrough,s=ak(),c=e(`events`).EventEmitter;t.BufferSlicer=d,t.FdSlicer=l,r.inherits(l,c);function l(e){c.call(this),this.fd=e,this.pend=new s,this.pend.max=1,this.refCount=0}l.prototype.read=function(e,t,r,i,a){var o=this;o.pend.go(function(s){n.read(o.fd,e,t,r,i,function(e,t,n){s(),a(e,t,n)})})},l.prototype.createReadStream=function(e){return new u(this,e)},l.prototype.ref=function(){this.refCount+=1},l.prototype.unref=function(){var e=this;if(--e.refCount,e.refCount<0)throw Error(`invalid unref`);if(e.refCount>0)return;n.close(e.fd,t);function t(t){t?e.emit(`error`,t):e.emit(`close`)}},r.inherits(u,a);function u(e,t){t||={},a.call(this,t),this.context=e,this.context.ref(),this.start=t.start||0,this.endOffset=t.end,this.pos=this.start}u.prototype._read=function(e){var t=this,r=Math.min(t._readableState.highWaterMark,e);if(t.endOffset!=null&&(r=Math.min(r,t.endOffset-t.pos)),r<=0){t.push(null),this._cleanup();return}t.context.pend.go(function(e){var i=Buffer.allocUnsafe(r);n.read(t.context.fd,i,0,r,t.pos,function(n,r){n?t.destroy(n):r===0?(t.push(null),t._cleanup()):(t.pos+=r,t.push(i.slice(0,r))),e()})})},u.prototype._destroy=function(e,t){this._cleanup(),t(e)},u.prototype._cleanup=function(){this.context!=null&&(this.context.unref(),this.context=null)},r.inherits(d,c);function d(e){c.call(this),this.refCount=0,this.buffer=e}d.prototype.read=function(e,t,n,r,i){if(!(0<=t&&t<=e.length))throw RangeError(`offset outside buffer: 0 <= `+t+` <= `+e.length);if(r<0)throw RangeError(`position is negative: `+r);if(t+n>e.length&&(n=e.length-t),r+n>this.buffer.length&&(n=this.buffer.length-r),n<=0){setImmediate(function(){i(null,0)});return}this.buffer.copy(e,t,r,r+n),setImmediate(function(){i(null,n)})},d.prototype.createReadStream=function(e){e||={};var t=new o(e);t.start=e.start||0,t.endOffset=e.end,t.pos=t.endOffset||this.buffer.length;for(var n=this.buffer.slice(t.start,t.pos),r=65536,i=0;;){var a=i+r;if(a>=n.length){i<n.length&&t.write(n.slice(i,n.length));break}t.write(n.slice(i,a)),i=a}return t.end(),t},d.prototype.ref=function(){this.refCount+=1},d.prototype.unref=function(){if(--this.refCount,this.refCount<0)throw Error(`invalid unref`)}})),$ce=n(((e,t)=>{let n=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function r(e){let t=-1;for(let r of e)t=n[(t^r)&255]^t>>>8;return(t^-1)>>>0}t.exports=r})),ele=n((t=>{e(`fs`);var n=e(`zlib`),r=ok(),i=e(`util`),a=e(`events`).EventEmitter,o=e(`stream`).Transform,s=e(`stream`).PassThrough,c=e(`stream`).Writable;let l=typeof n.crc32==`function`?n.crc32:$ce();t.fromBuffer=u;function u(e,t,n){typeof t==`function`&&(n=t,t=null),t??={},t.autoClose=!1,t.lazyEntries??=!1,t.decodeStrings??=!0,t.validateEntrySizes??=!0,t.strictFileNames??=!1,d(new r.BufferSlicer(e),e.length,t,n)}function d(e,t,n,r){typeof n==`function`&&(r=n,n=null),n??={},n.autoClose??=!0,n.lazyEntries??=!1,n.decodeStrings??=!0;var i=!!n.decodeStrings;if(n.validateEntrySizes??=!0,n.strictFileNames??=!1,r??=ne,typeof t!=`number`)throw Error(`expected totalSize parameter to be a number`);if(t>2**53-1)throw Error(`zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.`);e.ref();var a=22,o=20,s=Math.min(o+a+65535,t),c=te(s);x(e,c,0,s,t-c.length,function(l){if(l)return r(l);for(var u=s-a;u>=0;--u)if(c.readUInt32LE(u)===101010256){var d=c.subarray(u),p=d.readUInt16LE(4),m=d.readUInt16LE(10),h=d.readUInt32LE(16),g=d.readUInt16LE(20),_=d.length-a;if(g!==_)return r(Error(`Invalid comment length. Expected: `+_+`. Found: `+g+". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?"));var v=i?E(d.subarray(22),!1):d.subarray(22);if(u-o>=0&&c.readUInt32LE(u-o)===117853008){var y=ee(c.subarray(u-o,u-o+o),8),b=te(56);return x(e,b,0,b.length,y,function(a){return a?r(a):b.readUInt32LE(0)===101075792?(p=b.readUInt32LE(16),p===0?(m=ee(b,32),h=ee(b,48),r(null,new f(e,h,t,m,v,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames))):r(Error(`multi-disk zip files are not supported: found disk number: `+p))):r(Error(`invalid zip64 end of central directory record signature`))})}return p===0?r(null,new f(e,h,t,m,v,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames)):r(Error(`multi-disk zip files are not supported: found disk number: `+p))}r(Error(`End of central directory record signature not found. Either not a zip file, or file is truncated.`))})}i.inherits(f,a);function f(e,t,n,r,i,o,s,c,l,u){var d=this;a.call(d),d.reader=e,d.reader.on(`error`,function(e){m(d,e)}),d.reader.once(`close`,function(){d.emit(`close`)}),d.readEntryCursor=t,d.fileSize=n,d.entryCount=r,d.comment=i,d.entriesRead=0,d.autoClose=!!o,d.lazyEntries=!!s,d.decodeStrings=!!c,d.validateEntrySizes=!!l,d.strictFileNames=!!u,d.isOpen=!0,d.emittedError=!1,d.hasEachEntryBeenCalled=!1,d.lazyEntries||d._readEntry()}f.prototype.close=function(){this.isOpen&&(this.isOpen=!1,this.reader.unref())};function p(e,t){e.autoClose&&e.close(),m(e,t)}function m(e,t){e.emittedError||(e.emittedError=!0,e.emit(`error`,t))}f.prototype.readEntry=function(){if(!this.lazyEntries)throw Error(`readEntry() called without lazyEntries:true`);this._readEntry()},f.prototype._readEntry=function(){var e=this;if(e.entryCount===e.entriesRead){setImmediate(function(){e.autoClose&&e.close(),!e.emittedError&&e.emit(`end`)});return}if(!e.emittedError){var t=te(46);x(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return p(e,n);if(!e.emittedError){var r=new h,i=t.readUInt32LE(0);if(i!==33639248)return p(e,Error(`invalid central directory file header signature: 0x`+i.toString(16)));if(r.versionMadeBy=t.readUInt16LE(4),r.versionNeededToExtract=t.readUInt16LE(6),r.generalPurposeBitFlag=t.readUInt16LE(8),r.compressionMethod=t.readUInt16LE(10),r.lastModFileTime=t.readUInt16LE(12),r.lastModFileDate=t.readUInt16LE(14),r.crc32=t.readUInt32LE(16),r.compressedSize=t.readUInt32LE(20),r.uncompressedSize=t.readUInt32LE(24),r.fileNameLength=t.readUInt16LE(28),r.extraFieldLength=t.readUInt16LE(30),r.fileCommentLength=t.readUInt16LE(32),r.internalFileAttributes=t.readUInt16LE(36),r.externalFileAttributes=t.readUInt32LE(38),r.relativeOffsetOfLocalHeader=t.readUInt32LE(42),r.generalPurposeBitFlag&64)return p(e,Error(`strong encryption is not supported`));e.readEntryCursor+=46,t=te(r.fileNameLength+r.extraFieldLength+r.fileCommentLength),x(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return p(e,n);if(!e.emittedError){r.fileNameRaw=t.subarray(0,r.fileNameLength);var i=r.fileNameLength+r.extraFieldLength;r.extraFieldRaw=t.subarray(r.fileNameLength,i),r.fileCommentRaw=t.subarray(i,i+r.fileCommentLength);try{r.extraFields=b(r.extraFieldRaw)}catch(t){return p(e,t)}if(e.decodeStrings){var a=(r.generalPurposeBitFlag&2048)!=0;r.fileComment=E(r.fileCommentRaw,a),r.fileName=v(r.generalPurposeBitFlag,r.fileNameRaw,r.extraFields,e.strictFileNames);var o=y(r.fileName);if(o!=null)return p(e,Error(o))}else r.fileComment=r.fileCommentRaw,r.fileName=r.fileNameRaw;r.comment=r.fileComment,e.readEntryCursor+=t.length,e.entriesRead+=1;for(var s=0;s<r.extraFields.length;s++){var c=r.extraFields[s];if(c.id===1){var l=c.data,u=0;if(r.uncompressedSize===4294967295){if(u+8>l.length)return p(e,Error(`zip64 extended information extra field does not include uncompressed size`));r.uncompressedSize=ee(l,u),u+=8}if(r.compressedSize===4294967295){if(u+8>l.length)return p(e,Error(`zip64 extended information extra field does not include compressed size`));r.compressedSize=ee(l,u),u+=8}if(r.relativeOffsetOfLocalHeader===4294967295){if(u+8>l.length)return p(e,Error(`zip64 extended information extra field does not include relative header offset`));r.relativeOffsetOfLocalHeader=ee(l,u),u+=8}break}}if(e.validateEntrySizes&&r.compressionMethod===0){var d=r.uncompressedSize;if(r.isEncrypted()&&(d+=12),r.compressedSize!==d){var f=`compressed/uncompressed size mismatch for stored file: `+r.compressedSize+` != `+r.uncompressedSize;return p(e,Error(f))}}e.emit(`entry`,r),e.lazyEntries||e._readEntry()}})}})}},f.prototype.eachEntry=function(){let e=this;if(!e.lazyEntries)throw Error(`eachEntry() requires lazyEntries: true`);if(e.hasEachEntryBeenCalled)throw Error(`eachEntry() must only be called once per ZipFile`);e.hasEachEntryBeenCalled=!0;let t=null;e.on(`entry`,r),e.on(`end`,i),e.on(`error`,a);function n(){e.removeListener(`entry`,r),e.removeListener(`end`,i),e.removeListener(`error`,a),e.autoClose&&e.close()}function r(e){let{resolve:n}=t;t=null,n({value:e})}function i(){let{resolve:e}=t;t=null,n(),e({done:!0})}function a(e){let{reject:r}=t;t=null,n(),r(e)}return{[Symbol.asyncIterator](){return this},next(){let n=new Promise((e,n)=>{if(t!=null)throw Error(`next() called before previous Promise was resolved.`);t={resolve:e,reject:n}});return e.readEntry(),n},return(e){return n(),Promise.resolve({done:!0,value:e})},throw(e){return n(),Promise.reject(e)}}},f.prototype.openReadStream=function(e,t,n){var r=this,i=0,a=e.compressedSize;if(n??(n=t,t=null),t==null)t={};else{if(t.decodeFileData===!1){if(t.decrypt!=null)throw Error(`cannot use options.decrypt when options.decodeFileData === false`);if(t.decompress!=null)throw Error(`cannot use options.decompress when options.decodeFileData === false`)}else{if(t.decrypt!=null){if(!e.isEncrypted())throw Error(`options.decrypt can only be specified for encrypted entries. See also option decodeFileData.`);if(t.decrypt!==!1)throw Error(`invalid options.decrypt value: `+t.decrypt);if(e.isCompressed()&&t.decompress!==!1)throw Error(`entry is encrypted and compressed, and options.decompress !== false. See also option decodeFileData.`)}if(t.decompress!=null){if(!e.isCompressed())throw Error(`options.decompress can only be specified for compressed entries. See also option decodeFileData.`);if(!(t.decompress===!1||t.decompress===!0))throw Error(`invalid options.decompress value: `+t.decompress);s=t.decompress}}if(t.start!=null){if(i=t.start,i<0)throw Error(`options.start < 0`);if(i>e.compressedSize)throw Error(`options.start > entry.compressedSize`)}if(t.end!=null){if(a=t.end,a<0)throw Error(`options.end < 0`);if(a>e.compressedSize)throw Error(`options.end > entry.compressedSize`);if(a<i)throw Error(`options.end < options.start`)}}var o=t.decodeFileData===!1||(e.compressionMethod===0||e.compressionMethod===8&&t.decompress===!1)&&(!e.isEncrypted()||t.decrypt===!1);if((t.start!=null||t.end!=null)&&!o)throw Error(`start/end range require options.decodeFileData === false for non-trivial encoded entries.`);if(!r.isOpen)return n(Error(`closed`));if(e.isEncrypted()&&!o&&t.decrypt!==!1)return n(Error(`entry is encrypted, and options.decodeFileData !== false`));var s;if(o)s=!1;else if(e.compressionMethod===8)s=t.decodeFileData!==!0;else return n(Error(`unsupported compression method: `+e.compressionMethod));r.readLocalFileHeader(e,{minimal:!0},function(t,o){if(t)return n(t);r.openReadStreamLowLevel(o.fileDataStart,e.compressedSize,i,a,s,e.uncompressedSize,n)})},f.prototype.openReadStreamLowLevel=function(e,t,r,i,a,o,s){var c=this;e+t;var l=c.reader.createReadStream({start:e+r,end:e+i}),u=l;if(a){var d=!1,f=n.createInflateRaw();l.on(`error`,function(e){setImmediate(function(){d||f.emit(`error`,e)})}),l.pipe(f),c.validateEntrySizes?(u=new S(o),f.on(`error`,function(e){setImmediate(function(){d||u.emit(`error`,e)})}),f.pipe(u)):u=f,D(u,function(){d=!0,f!==u&&f.unpipe(u),l.unpipe(f),l.destroy()})}s(null,u)},f.prototype.readLocalFileHeader=function(e,t,n){var r=this;n??(n=t,t=null),t??={},r.reader.ref();var i=te(30);x(r.reader,i,0,i.length,e.relativeOffsetOfLocalHeader,function(a){try{if(a)return n(a);var o=i.readUInt32LE(0);if(o!==67324752)return n(Error(`invalid local file header signature: 0x`+o.toString(16)));var s=i.readUInt16LE(26),c=i.readUInt16LE(28),l=e.relativeOffsetOfLocalHeader+30+s+c;if(l+e.compressedSize>r.fileSize)return n(Error(`file data overflows file bounds: `+l+` + `+e.compressedSize+` > `+r.fileSize));if(t.minimal)return n(null,{fileDataStart:l});var u=new g;u.fileDataStart=l,u.versionNeededToExtract=i.readUInt16LE(4),u.generalPurposeBitFlag=i.readUInt16LE(6),u.compressionMethod=i.readUInt16LE(8),u.lastModFileTime=i.readUInt16LE(10),u.lastModFileDate=i.readUInt16LE(12),u.crc32=i.readUInt32LE(14),u.compressedSize=i.readUInt32LE(18),u.uncompressedSize=i.readUInt32LE(22),u.fileNameLength=s,u.extraFieldLength=c,i=te(s+c),r.reader.ref(),x(r.reader,i,0,i.length,e.relativeOffsetOfLocalHeader+30,function(e){try{return e?n(e):(u.fileName=i.subarray(0,s),u.extraField=i.subarray(s),n(null,u))}finally{r.reader.unref()}})}finally{r.reader.unref()}})},f.prototype.openReadStreamPromise=function(e,t){return new Promise((n,r)=>{this.openReadStream(e,t,function(e,t){if(e)return r(e);n(t)})})},f.prototype.openReadStreamLowLevelPromise=function(e,t,n,r,i,a){return new Promise((o,s)=>{this.openReadStream(e,t,n,r,i,a,function(e,t){if(e)return s(e);o(t)})})},f.prototype.readLocalFileHeaderPromise=function(e,t){return new Promise((n,r)=>{this.readLocalFileHeader(e,t,function(e,t){if(e)return r(e);n(t)})})};function h(){}h.prototype.getLastModDate=function(e){if(e??={},!e.forceDosFormat)for(var t=0;t<this.extraFields.length;t++){var n=this.extraFields[t];if(n.id===21589){var r=n.data;if(r.length<5||!(r[0]&1))continue;var i=r.readInt32LE(1);return new Date(i*1e3)}else if(n.id===10){var r=n.data;if(r.length!==32||r.readUInt16LE(4)!==1||r.readUInt16LE(6)!==24)continue;var a=(r.readUInt32LE(8)+4294967296*r.readInt32LE(12))/1e4-0xa9730b66800;return new Date(a)}}return _(this.lastModFileDate,this.lastModFileTime,e.timezone)},h.prototype.canDecodeFileData=function(){return!this.isEncrypted()&&(this.compressionMethod===0||this.compressionMethod===8)},h.prototype.isEncrypted=function(){return(this.generalPurposeBitFlag&1)!=0},h.prototype.isCompressed=function(){return this.compressionMethod===8};function g(){}function _(e,t,n){var r=e&31,i=(e>>5&15)-1,a=(e>>9&127)+1980,o=0,s=(t&31)*2,c=t>>5&63,l=t>>11&31;if(n==null||n===`local`)return new Date(a,i,r,l,c,s,o);if(n===`UTC`)return new Date(Date.UTC(a,i,r,l,c,s,o));throw Error(`unrecognized options.timezone: `+options.timezone)}function v(e,t,n,r){for(var i=null,a=0;a<n.length;a++){var o=n[a];if(o.id===28789){if(o.data.length<6||o.data.readUInt8(0)!==1)continue;var s=o.data.readUInt32LE(1);if(l(t)!==s)continue;i=E(o.data.subarray(5),!0);break}}return i??=E(t,(e&2048)!=0),r||(i=i.replace(/\\/g,`/`)),i}function y(e){return e.indexOf(`\\`)===-1?/^[a-zA-Z]:/.test(e)||/^\//.test(e)?`absolute path: `+e:e.split(`/`).indexOf(`..`)===-1?null:`invalid relative path: `+e:`invalid characters in fileName: `+e}function b(e){for(var t=[],n=0;n<e.length-3;){var r=e.readUInt16LE(n+0),i=e.readUInt16LE(n+2),a=n+4,o=a+i;if(o>e.length)throw Error(`extra field length exceeds extra field buffer size`);var s=e.subarray(a,o);t.push({id:r,data:s}),n=o}return t}function x(e,t,n,r,i,a){if(r===0)return setImmediate(function(){a(null,te(0))});e.read(t,n,r,i,function(e,t){if(e)return a(e);if(t<r)return a(Error(`unexpected EOF`));a()})}i.inherits(S,o);function S(e){o.call(this),this.actualByteCount=0,this.expectedByteCount=e}S.prototype._transform=function(e,t,n){if(this.actualByteCount+=e.length,this.actualByteCount>this.expectedByteCount){var r=`too many bytes in the stream. expected `+this.expectedByteCount+`. got at least `+this.actualByteCount;return n(Error(r))}n(null,e)},S.prototype._flush=function(e){if(this.actualByteCount<this.expectedByteCount){var t=`not enough bytes in the stream. expected `+this.expectedByteCount+`. got only `+this.actualByteCount;return e(Error(t))}e()},i.inherits(C,a);function C(){a.call(this),this.refCount=0}C.prototype.ref=function(){this.refCount+=1},C.prototype.unref=function(){var e=this;if(--e.refCount,e.refCount>0)return;if(e.refCount<0)throw Error(`invalid unref`);e.close(t);function t(t){if(t)return e.emit(`error`,t);e.emit(`close`)}},C.prototype.createReadStream=function(e){e??={};var t=e.start,n=e.end;if(t===n){var r=new s;return setImmediate(function(){r.end()}),r}var i=this._readStreamForRange(t,n),a=!1,o=new w(this);i.on(`error`,function(e){setImmediate(function(){a||o.emit(`error`,e)})}),D(o,function(){i.unpipe(o),o.unref(),i.destroy()});var c=new S(n-t);return o.on(`error`,function(e){setImmediate(function(){a||c.emit(`error`,e)})}),D(c,function(){a=!0,o.unpipe(c),o.destroy()}),i.pipe(o).pipe(c)},C.prototype._readStreamForRange=function(e,t){throw Error(`not implemented`)},C.prototype.read=function(e,t,n,r,i){var a=this.createReadStream({start:r,end:r+n}),o=new c,s=0;o._write=function(n,r,i){n.copy(e,t+s,0,n.length),s+=n.length,i()},o.on(`finish`,i),a.on(`error`,function(e){i(e)}),a.pipe(o)},C.prototype.close=function(e){setImmediate(e)},i.inherits(w,s);function w(e){s.call(this),this.context=e,this.context.ref(),this.unreffedYet=!1}w.prototype._flush=function(e){this.unref(),e()},w.prototype.unref=function(e){this.unreffedYet||(this.unreffedYet=!0,this.context.unref())};var T=`\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`;function E(e,t){if(t)return e.toString(`utf8`);for(var n=``,r=0;r<e.length;r++)n+=T[e[r]];return n}function ee(e,t){var n=e.readUInt32LE(t);return e.readUInt32LE(t+4)*4294967296+n}var te=typeof Buffer.allocUnsafe==`function`?function(e){return Buffer.allocUnsafe(e)}:function(e){return new Buffer(e)};function D(e,t){typeof e.destroy==`function`?e._destroy=function(e,n){t(),n?.(e)}:e.destroy=t}function ne(e){if(e)throw e}})),sk=me(),tle=ele();const ck={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,gemini:`gemini`,opencode:`opencode`,"pi-acp":`pi`},nle={claude:`claude`,codex:`codex`,cursor:`cursor-agent`,gemini:`gemini`,opencode:`opencode`,pi:`pi`,antigravity:`agy`,copilot:`copilot`,openclaw:`openclaw`,hermes:`hermes`};async function rle(e,t,n=ST){let r={cmd:nle[e],args:[],env:dT(),kind:`custom`,pathFromOverlay:!1};try{return await n(r),`present`}catch(i){if(!(i instanceof cT)||i.code!==`command-not-found`)return N(`acp-harness`).warn({cli:e,err:i},`harness preflight failed before absence could be verified; availability unknown`),`unknown`;let a=null,o;try{a=await t()}catch(e){o=e}if(a===null)return N(`acp-harness`).warn({cli:e,err:o},`login-shell PATH capture failed; harness absence unverified — availability unknown`),`unknown`;try{return await n(_T(r,a)),`present`}catch(t){return t instanceof cT&&t.code===`command-not-found`?`not-found`:(N(`acp-harness`).warn({cli:e,err:t},`harness preflight on the login-shell PATH failed before absence could be verified; availability unknown`),`unknown`)}}}function ile(e={}){let t=e.resolveLoginShellPath??oT(N(`acp-harness`)),n=e.preflight??ST,r=e.probe??(e=>rle(e,t,n)),i=e.now??Date.now,a=e.ttlMs??6e4,o=[...new Set(Object.values(ck))].filter(e=>e!==void 0),s=null;return()=>{let e=i();if(s!==null&&s.expiresAt>e)return s.value;let t=Promise.all(o.map(async e=>{try{return[e,await r(e)]}catch(t){return N(`acp-harness`).warn({cli:e,err:t},`harness availability probe rejected; availability unknown`),[e,`unknown`]}})).then(e=>Object.fromEntries(e));return s={expiresAt:e+a,value:t},t}}let ale=0;const ole=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function lk(e,t,n,r,i){let a=e.doc;if(!a)return()=>{};let o=++ale,s=a.getMap(`agent-effects`),c=u=>{if(u.transaction.origin!==n)return;e.unobserve(c),a.off(`destroy`,l);let d=`${t}:${o}`,f={sessionId:t,timestamp:Date.now(),delta:u.delta,agent_type:i??`agent`,color_seed:r??t};try{a.transact(()=>{if(s.set(d,f),s.size>50){let e=[...s.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,s.size-50))s.delete(t)}},ole)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),Ose(),process.env.NODE_ENV!==`production`)throw e}},l=()=>{e.unobserve(c)};return e.observe(c),a.once(`destroy`,l),()=>{e.unobserve(c),a.off(`destroy`,l)}}const sle=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function uk(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`string`)return{kind:`invalid`};if(e.length===0||e.trim().length===0)return{kind:`absent`};let t=e.replace(sle,` `);return t.length<=80?{kind:`value`,value:t}:{kind:`value`,value:t.slice(0,79)+`…`,truncatedFrom:e.length}}function cle(e){let t=e.host;if(!t)return null;let n=e[`x-forwarded-proto`];return`${(Array.isArray(n)?n[0]:n)===`https`?`wss`:`ws`}://${t}/collab`}function dk(e,t){let n=uk(e.summary);if(n.kind===`invalid`)return{kind:`invalid-summary`};let r=Sh(e),i=t?.()??null;return r.rawAgentId!==void 0&&r.writerId!==void 0?{kind:`agent`,writerId:r.writerId,displayName:r.displayName,colorSeed:r.colorSeed??r.rawAgentId,clientName:r.clientName,clientVersion:r.clientVersion,label:r.label,actor:{principalId:i?.id,agentType:xh(r.clientName),clientName:r.clientName,clientVersion:r.clientVersion,label:r.label},summary:n}:i?{kind:`principal`,writerId:i.id,displayName:i.display_name,colorSeed:i.id,actor:{principalId:i.id},summary:n}:{kind:`anonymous`,summary:n}}function lle(e){return fk(e,{maxBytes:1048576,timeoutMs:3e4})}async function fk(e,t){let n=[],r=0,i=AbortSignal.timeout(t.timeoutMs),a=()=>e.destroy(new mk(t.timeoutMs));i.addEventListener(`abort`,a,{once:!0});try{for await(let i of e){if(r+=i.length,r>t.maxBytes)throw new pk(t.maxBytes);n.push(i)}return Buffer.concat(n)}finally{i.removeEventListener(`abort`,a)}}var pk=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${ule(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},mk=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function ule(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function hk(e,t,n,r={}){let i=e.safeParse(t);if(i.success)return{ok:!0,value:i.data};let a=i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return G(n,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:r.handler,detail:a}),{ok:!1}}function K(e,t,n={}){return async(r,i)=>{if(n.method!==void 0&&r.method!==n.method){G(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:n.handler,extraHeaders:{Allow:n.method}});return}if(n.preBodyGate!==void 0&&!n.preBodyGate(r,i)){!i.headersSent&&!i.writableEnded&&!i.destroyed&&G(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:n.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(n.skipBodyParse){let a=hk(e,{},i,n);if(!a.ok)return;await t(r,i,a.value);return}let a;try{a=await lle(r)}catch(e){if(e instanceof pk){G(i,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:n.handler,cause:e});return}if(e instanceof mk){G(i,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:n.handler,cause:e});return}G(i,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:n.handler,cause:e});return}let o;try{o=a.length===0?{}:JSON.parse(a.toString(`utf8`))}catch(e){G(i,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:n.handler,cause:e});return}let s=hk(e,o,i,n);s.ok&&await t(r,i,s.value)}}const gk=()=>N(`http`);function q(e,t,n,r,i={}){if(e.headersSent||e.writableEnded||e.destroyed){gk().error({event:`api.success.double-write`,status:t,handler:i.handler},`successResponse called after headers already sent — suppressed`),dS().add(1,{type:`urn:ok:error:internal-server-error`,...i.handler?{handler:i.handler}:{}});return}let a=n.safeParse(r);if(!a.success){gk().error({event:`api.success.malformed-body`,issues:a.error.issues,bodyKeys:typeof r==`object`&&r?Object.keys(r):null,handler:i.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),G(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}let o;try{o=JSON.stringify(a.data)}catch(n){gk().error({event:`api.success.unserializable-body`,bodyKeys:typeof a.data==`object`&&a.data!==null?Object.keys(a.data):null,handler:i.handler,originalStatus:t,err:n},`successResponse parsed body is not JSON-serializable — emitting fallback`),G(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:i.handler});return}e.writeHead(t,{...i.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(o)}function _k(e,t,n,r=32){if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n>e.length||t>=n)throw Error(`invalid selection range [${t}, ${n}) for body length ${e.length}`);let i=e.slice(t,n),a=e.slice(Math.max(0,t-r),t),o=e.slice(n,Math.min(e.length,n+r));if(xk(e,i)>1){let s=r;for(;!fle(e,a,i,o)&&s<e.length;)s=Math.min(s*2,e.length),a=e.slice(Math.max(0,t-s),t),o=e.slice(n,Math.min(e.length,n+s))}return{exact:i,prefix:a,suffix:o,start:t,end:n}}function dle(e,t){return Sk(e,t).map(e=>({start:e,end:e+t.length}))}function vk(e,t,n,{contextIsMarkdown:r=!1}={}){let i=n.prefix??``,a=n.suffix??``,o=[],s=-1;for(let n of t){let t=Aa(e,n,{prefix:i,suffix:a},{syntaxIn:`haystack`,syntaxInContext:r});t>s?(s=t,o=[n]):t===s&&o.push(n)}return o}function yk(e,t){let{exact:n,prefix:r,suffix:i,start:a}=t,o=a+n.length;if(o<=e.length&&e.slice(a,o)===n)return{status:`anchored`,start:a,end:o};if(r!==``&&i!==``&&!e.includes(r+n+i)&&e.includes(r+i))return{status:`orphaned`};let s=Sk(e,n);if(s.length===0)return bk(e,t);let c=Xa(t,{syntaxInContext:!0}),l=t=>c===0||Aa(e,t,{prefix:r,suffix:i},{syntaxIn:`haystack`,syntaxInContext:!0})>=c;if(s.length===1){let r={start:s[0],end:s[0]+n.length};return l(r)?{status:`anchored`,start:r.start,end:r.end}:bk(e,t)}let u=vk(e,s.map(e=>({start:e,end:e+n.length})),{prefix:r,suffix:i},{contextIsMarkdown:!0});if(!l(u[0]))return bk(e,t);if(u.length===1)return{status:`anchored`,start:u[0].start,end:u[0].end};let d=[],f=1/0;for(let e of u){let t=Math.abs(e.start-a);t<f?(f=t,d=[e]):t===f&&d.push(e)}return d.length===1?{status:`anchored`,start:d[0].start,end:d[0].end}:{status:`orphaned`}}function bk(e,t){let{prefix:n,suffix:r,exact:i}=t,a=n===``?[0]:Sk(e,n).map(e=>e+n.length),o=r===``?[e.length]:Sk(e,r);if(a.length!==1||o.length!==1)return{status:`orphaned`};let s=a[0],c=o[0];if(c<s||c===s)return{status:`orphaned`};let l=Ui(i.length);return c-s>l?{status:`orphaned`}:{status:`anchored`,start:s,end:c,rewritten:!0}}function xk(e,t){if(t===``)return 0;let n=0,r=e.indexOf(t);for(;r!==-1;)n+=1,r=e.indexOf(t,r+1);return n}function Sk(e,t){let n=[];if(t===``)return n;let r=e.indexOf(t);for(;r!==-1;)n.push(r),r=e.indexOf(t,r+1);return n}function fle(e,t,n,r){return xk(e,t+n+r)===1}function Ck(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];for(let e of n){if(r==null)return;if(typeof e==`number`){if(!Array.isArray(r)||e>=r.length)return;r=r[e];continue}if(typeof r!=`object`||Array.isArray(r))return;let t=r;if(!Object.hasOwn(t,e))return;r=t[e]}return r}function wk(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):null}function ple(e,t){if(t===``)return!1;let n=e.indexOf(t);return n!==-1&&e.indexOf(t,n+1)!==-1}var Tk=class extends Error{},Ek=class extends Error{},Dk=class extends Error{},Ok=class extends Error{},mle=class{store;index;getDocBody;getDocFrontmatter;now;newId;indexReady=null;constructor(e){this.store=e.store,this.index=e.index,this.getDocBody=e.getDocBody,this.getDocFrontmatter=e.getDocFrontmatter,this.now=e.now??Date.now,this.newId=e.newId??dd}buildIndex(){return this.indexReady??=this.index.build(this.store),this.indexReady}async createThread(e){await this.buildIndex();let t=e.propertyKey,n,r;if(t===void 0){let t=await this.requireDocBody(e.docName),{start:i,end:a}=this.resolveRange(t,e);n={kind:`body`},r=_k(t,i,a)}else{let i=e.propertyPath??[];n={kind:`property`,key:t,path:i};let a=e.quote?.trim();if(a===void 0||a.length===0)await this.requirePropertyTarget(e.docName,t,i),r=null;else{let n=await this.requirePropertyText(e.docName,t,i),{start:a,end:o}=this.resolveRange(n,e);r=_k(n,a,o)}}let i=this.newId(),a=this.now(),o=await this.store.createThread({threadId:i,docName:e.docName,target:n,anchor:r,createdBy:e.author,createdAt:a,body:e.body});return this.index.upsert(o),e.queue===!0?this.mutate(i,{queued:!0}):o}async listThreads(e){return await this.buildIndex(),e===void 0?this.index.listAll():this.index.listForDoc(e)}async countThreads(e){return await this.buildIndex(),`prefix`in e?this.index.countsUnderPrefix(e.prefix):this.index.countsForDocs(e.docNames)}async readThread(e){return this.requireMeta(e)}async editComment(e,t){return this.mutate(e,{latestComment:t,updatedAt:this.now()})}async resolve(e){return this.mutate(e,{state:`resolved`})}async reopen(e){return await this.mutate(e,{state:`anchored`,queued:!0}),this.refindOnLoad(e)}async replaceAnchor(e,t){let n=await this.requireMeta(e);if(n.target.kind===`property`)throw new Dk(n.target.key);let r=await this.requireDocBody(n.docName),{start:i,end:a}=this.resolveRange(r,t),o=_k(r,i,a);return this.mutate(e,{anchor:o,state:`anchored`})}async queueForDispatch(e,t){await this.mutate(e,{queued:!0});let n=await this.refindOnLoad(e,t);return{meta:n,orphaned:n.state===`orphaned`}}async prepareDispatch(e){let t=await this.getDocBody((await this.requireMeta(e)).docName),n=await this.queueForDispatch(e,t),{anchor:r,docName:i,target:a}=n.meta,o=await this.latestComment(e);return a.kind===`property`?{meta:n.meta,payload:{docName:i,instruction:o,property:kk(a.key,a.path),passage:r===null?null:{exact:r.exact,prefix:r.prefix,suffix:r.suffix},anchorLost:n.orphaned,passageRepeats:!1}}:{meta:n.meta,payload:{docName:i,instruction:o,property:null,passage:r===null?null:{exact:r.exact,prefix:r.prefix,suffix:r.suffix},anchorLost:n.orphaned,passageRepeats:r!==null&&t!==null&&ple(t,r.exact)}}}async completeDispatch(e){return this.mutate(e,{queued:!1,state:`resolved`})}async prepareDispatchBatch(e){let t=[];for(let n of e)try{let e=await this.prepareDispatch(n);t.push({threadId:n,ok:!0,...e})}catch(e){if(e instanceof Ek){t.push({threadId:n,ok:!1,error:`not-found`});continue}throw e}return t}async completeDispatchBatch(e){let t=[];for(let n of e)try{t.push({threadId:n,ok:!0,meta:await this.completeDispatch(n)})}catch(e){if(e instanceof Ek){t.push({threadId:n,ok:!1,error:`not-found`});continue}throw e}return t}async latestComment(e){return(await this.requireMeta(e)).latestComment.trim()}async unqueue(e){return this.mutate(e,{queued:!1})}async delete(e){await this.buildIndex(),await this.store.delete(e),this.index.remove(e)}async renameDoc(e,t){if(e===t)return;await this.buildIndex();let n=this.index.threadsForDoc(e);n.length!==0&&(this.index.renameDoc(e,t),await Promise.all(n.map(e=>this.store.update(e,{docName:t}))))}async deleteDoc(e){await this.buildIndex();let t=this.index.threadsForDoc(e);for(let e of t)await this.store.delete(e),this.index.remove(e);return t.length}async refindDoc(e){await this.buildIndex();let t=this.index.listForDoc(e).filter(e=>e.state!==`resolved`);if(t.length===0)return!1;let n=await this.getDocBody(e);if(n===null)return!1;let r=t.some(e=>e.target.kind===`property`)?await this.getDocFrontmatter(e):null,i=!1;for(let a of t){if(a.target.kind===`property`){let t=await this.refindProperty(e,a.target,a.anchor,r);if(t===null||t.state===a.state)continue;await this.mutate(a.threadId,{state:t.state}),i=!0;continue}if(a.anchor===null)continue;let t=yk(n,a.anchor);if(t.status===`orphaned`){if(a.state===`orphaned`)continue;await this.mutate(a.threadId,{state:`orphaned`}),i=!0;continue}let o=t.rewritten===!0?_k(n,t.start,t.end):void 0,s=a.state!==`anchored`;o===void 0&&!s||(await this.mutate(a.threadId,{...o?{anchor:o}:{},state:`anchored`}),(s||o!==void 0)&&(i=!0))}return i}async refindOnLoad(e,t){let n=await this.requireMeta(e);if(n.state===`resolved`)return n;if(n.target.kind===`property`){let t=await this.refindProperty(n.docName,n.target,n.anchor);return t===null||t.anchor===void 0&&t.state===n.state?n:this.mutate(e,{...t.anchor?{anchor:t.anchor}:{},state:t.state})}let r=t===void 0?await this.getDocBody(n.docName):t;if(r===null)return n;let i=n.anchor;if(i===null)return n;let a=yk(r,i);if(a.status===`orphaned`)return n.state===`orphaned`?n:this.mutate(e,{state:`orphaned`});let o=a.rewritten?_k(r,a.start,a.end):a.start!==i.start||a.end!==i.end?{...i,start:a.start,end:a.end}:void 0;return o===void 0&&n.state===`anchored`?n:this.mutate(e,{...o?{anchor:o}:{},state:`anchored`})}async mutate(e,t){let n=await this.store.update(e,t);if(!n)throw new Ek(e);return this.index.upsert(n),n}resolveRange(e,t){if(t.start!==void 0&&t.end!==void 0)return{start:t.start,end:t.end};let n=t.quote?.trim();if(n===void 0||n.length===0)throw Error(`either start/end offsets or a non-empty quote is required`);let r=dle(e,n),i=r.length>0?r:Xi(e,n,{syntaxIn:`haystack`});if(i.length===0)throw new Ok(n);return i.length===1?i[0]:vk(e,i,{prefix:t.prefix,suffix:t.suffix})[0]}async requireMeta(e){let t=await this.store.readMeta(e);if(!t)throw new Ek(e);return t}async requireDocBody(e){let t=await this.getDocBody(e);if(t===null)throw new Tk(e);return t}async requirePropertyText(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new Tk(e);let i=Ck(r,t,n);if(i===void 0)throw new Dk(kk(t,n));let a=wk(i);if(a===null)throw new Dk(kk(t,n));return a}async requirePropertyTarget(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new Tk(e);if(Ck(r,t,n)===void 0)throw new Dk(kk(t,n))}async refindProperty(e,t,n,r){let i=r===void 0?await this.getDocFrontmatter(e):r;if(i===null)return null;let a=Ck(i,t.key,t.path);if(a===void 0)return{state:`orphaned`};if(n===null)return{state:`anchored`};let o=wk(a);if(o===null)return{state:`orphaned`};let s=yk(o,n);return s.status===`orphaned`?{state:`orphaned`}:s.rewritten?{state:`anchored`,anchor:_k(o,s.start,s.end)}:s.start!==n.start||s.end!==n.end?{state:`anchored`,anchor:{...n,start:s.start,end:s.end}}:{state:`anchored`}}};function kk(e,t){let n=e;for(let e of t)n+=typeof e==`number`?`[${e}]`:`.${e}`;return n}const Ak=`comments`,hle={maxBytes:64*1024,timeoutMs:1e4},jk={start:i().int().nonnegative().optional(),end:i().int().nonnegative().optional(),quote:u().min(1).optional(),prefix:u().max(1e3).optional(),suffix:u().max(1e3).optional()},gle=j({docName:u().min(1),...jk,propertyKey:u().min(1).optional(),propertyPath:M(p([u(),i().int().nonnegative()])).optional(),body:u(),queue:D().optional(),summary:u().optional()}),Mk=ze(),_le=Fe(`action`,[j({action:x(`edit`),id:Mk,body:u(),summary:u().optional()}),j({action:x(`resolve`),id:Mk,summary:u().optional()}),j({action:x(`reopen`),id:Mk,summary:u().optional()}),j({action:x(`replace`),id:Mk,...jk,summary:u().optional()}),j({action:x(`queue`),id:Mk,summary:u().optional()}),j({action:x(`unqueue`),id:Mk,summary:u().optional()}),j({action:x(`dispatch-prepare`),id:Mk,summary:u().optional()}),j({action:x(`dispatch-complete`),id:Mk,summary:u().optional()}),j({action:x(`dispatch-prepare-batch`),ids:M(Mk).min(1).max(200),summary:u().optional()}),j({action:x(`dispatch-complete-batch`),ids:M(Mk).min(1).max(200),summary:u().optional()})]);function vle(e){let{service:t,getPrincipal:n,onChanged:r}=e;async function i(e,n){let r=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??void 0;try{q(n,200,Yr,{threads:await t.listThreads(r)},{handler:Ak})}catch(e){Lk(n,e,`Failed to list comment threads.`)}}function a(e,t){let n=new URL(e.url??``,`http://localhost`).searchParams.get(`id`);return n?Mk.safeParse(n).success?n:(Fk(t,`id must be a comment thread UUID.`),null):(Fk(t,`id query parameter is required.`),null)}async function o(e,n){let r=a(e,n);if(r!==null)try{q(n,200,Ht,await t.readThread(r),{handler:Ak})}catch(e){if(e instanceof Ek)return Ik(n,`Comment thread not found.`);Lk(n,e,`Failed to read comment thread.`)}}async function s(e,i){let a=await Nk(e,i,gle);if(!a)return;let o=dk(a,n);if(o.kind===`invalid-summary`)return Fk(i,`Summary must be a string.`);let s=Pk(o);if(!s)return Fk(i,`A principal or agent identity is required to comment.`);try{let e=await t.createThread({docName:a.docName,start:a.start,end:a.end,quote:a.quote,prefix:a.prefix,suffix:a.suffix,propertyKey:a.propertyKey,propertyPath:a.propertyPath,author:s,body:a.body,queue:a.queue});r?.(),q(i,201,Ht,e,{handler:Ak})}catch(e){if(e instanceof Tk)return Ik(i,`Document not found.`);if(e instanceof Ok)return Fk(i,`The quoted passage is not in the document.`);if(e instanceof Dk)return Fk(i,`That property is not in the document: ${e.message}`);if(e instanceof RangeError||e instanceof Error&&/invalid selection|is required/.test(e.message))return Fk(i,`Selection range is invalid for the document.`);Lk(i,e,`Failed to create comment thread.`)}}async function c(e,i){let a=await Nk(e,i,_le);if(!a)return;let o=dk(a,n);if(o.kind===`invalid-summary`)return Fk(i,`Summary must be a string.`);try{switch(a.action){case`edit`:return Pk(o)?u(i,await t.editComment(a.id,a.body)):Fk(i,`An identity is required to edit a comment.`);case`resolve`:return u(i,await t.resolve(a.id));case`reopen`:return u(i,await t.reopen(a.id));case`replace`:return u(i,await t.replaceAnchor(a.id,{start:a.start,end:a.end,quote:a.quote,prefix:a.prefix,suffix:a.suffix}));case`queue`:{let e=await t.queueForDispatch(a.id);return r?.(),q(i,200,Pr,e,{handler:Ak})}case`unqueue`:return u(i,await t.unqueue(a.id));case`dispatch-prepare`:{let e=await t.prepareDispatch(a.id);return r?.(),q(i,200,Vr,e,{handler:Ak})}case`dispatch-complete`:return u(i,await t.completeDispatch(a.id));case`dispatch-prepare-batch`:{let e=await t.prepareDispatchBatch(a.ids);return r?.(),q(i,200,fn,{results:e},{handler:Ak})}case`dispatch-complete-batch`:{let e=await t.completeDispatchBatch(a.ids);return r?.(),q(i,200,yn,{results:e},{handler:Ak})}}}catch(e){if(e instanceof Ek)return Ik(i,`Comment thread not found.`);if(e instanceof Tk)return Ik(i,`Document not found.`);if(e instanceof Ok)return Fk(i,`The quoted passage is not in the document.`);if(e instanceof Dk)return Fk(i,`That property is not in the document: ${e.message}`);if(e instanceof Error&&/invalid selection|is required/.test(e.message))return Fk(i,`Selection range is invalid for the document.`);Lk(i,e,`Failed to update comment thread.`)}}async function l(e,n){let i=a(e,n);if(i!==null)try{await t.delete(i),r?.(),q(n,200,ro,{threadId:i},{handler:Ak})}catch(e){Lk(n,e,`Failed to delete comment thread.`)}}function u(e,t){r?.(),q(e,200,Ht,t,{handler:Ak})}return{list:i,read:o,create:s,mutate:c,remove:l}}async function Nk(e,t,n){let r;try{r=await fk(e,hle)}catch{return Fk(t,`Request body could not be read.`),null}let i;try{i=JSON.parse(r.toString(`utf8`)||`{}`)}catch{return Fk(t,`Request body must be valid JSON.`),null}let a=n.safeParse(i);return a.success?a.data:(Fk(t,`Request body is invalid.`),null)}function Pk(e){return e.kind===`agent`||e.kind===`principal`?e.writerId:null}function Fk(e,t){G(e,400,`urn:ok:error:invalid-request`,t,{handler:Ak})}function Ik(e,t){G(e,404,`urn:ok:error:not-found`,t,{handler:Ak})}function Lk(e,t,n){G(e,500,`urn:ok:error:internal-server-error`,n,{handler:Ak,cause:t})}var yle=class{threads=new Map;docToThreads=new Map;async build(e){this.threads.clear(),this.docToThreads.clear();for(let t of await e.scanCoverSheets())this.upsert(t)}upsert(e){let t=this.threads.get(e.threadId);t!==void 0&&t.docName!==e.docName&&this.detach(t.docName,e.threadId),this.threads.set(e.threadId,e);let n=this.docToThreads.get(e.docName);n||(n=new Set,this.docToThreads.set(e.docName,n)),n.add(e.threadId)}remove(e){let t=this.threads.get(e);t!==void 0&&(this.threads.delete(e),this.detach(t.docName,e))}renameDoc(e,t){let n=this.docToThreads.get(e);if(!n)return;this.docToThreads.delete(e);let r=this.docToThreads.get(t)??new Set;for(let e of n){r.add(e);let n=this.threads.get(e);n&&this.threads.set(e,{...n,docName:t})}this.docToThreads.set(t,r)}listForDoc(e){let t=[];for(let n of this.docToThreads.get(e)??[]){let e=this.threads.get(n);e&&t.push(e)}return t}listAll(){return[...this.threads.values()]}threadsForDoc(e){return[...this.docToThreads.get(e)??[]]}countsForDocs(e){let t=new Map;for(let n of e)t.set(n,this.countForDoc(n));return t}countsUnderPrefix(e){let t=e===``?``:e.endsWith(`/`)?e:`${e}/`,n=new Map;for(let e of this.docToThreads.keys()){if(!e.startsWith(t))continue;let r=this.countForDoc(e);r>0&&n.set(e,r)}return n}countForDoc(e){let t=0;for(let n of this.docToThreads.get(e)??[])this.threads.get(n)?.state!==`resolved`&&t++;return t}get size(){return this.threads.size}detach(e,t){let n=this.docToThreads.get(e);n&&(n.delete(t),n.size===0&&this.docToThreads.delete(e))}},ble=class{dir;log;writeQueues=new Map;dirReady=null;constructor(e,t){this.dir=F(e,`comments`),this.log=t}init(){return this.ensureDir()}ensureDir(){return this.dirReady??=Ps(this.dir,{recursive:!0}).then(()=>void 0),this.dirReady}metaPath(e){return F(this.dir,`${e}.meta.json`)}enqueueResult(e,t){let n=(this.writeQueues.get(e)??Promise.resolve()).then(()=>t());return this.writeQueues.set(e,n.then(()=>void 0,()=>void 0)),n}async whenIdle(e){await(this.writeQueues.get(e)??Promise.resolve())}createThread(e){let t=Ht.parse({threadId:e.threadId,docName:e.docName,target:e.target,anchor:e.anchor,state:`anchored`,queued:!1,latestComment:e.body,createdBy:e.createdBy,createdAt:e.createdAt});return this.enqueueResult(e.threadId,async()=>(await this.ensureDir(),await this.write(t),t))}update(e,t){return this.enqueueResult(e,async()=>{await this.ensureDir();let n=await this.readMeta(e);if(!n)return null;let r=Ht.parse({...n,...xle(t)});return await this.write(r),r})}write(e){return Os(this.metaPath(e.threadId),Sle(e),{fs:Ms})}async readMeta(e){let t;try{t=await id(this.metaPath(e),`utf8`)}catch{return null}let n=Ht.safeParse(Cle(t));return n.success?n.data:(this.log.warn({threadId:e},`[comments] skipping unreadable thread meta`),null)}async scanCoverSheets(){let e;try{e=await ad(this.dir)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(`.meta.json`))continue;let e=await this.readMeta(n.slice(0,-10));e&&t.push(e)}return t}async delete(e){await this.enqueueResult(e,async()=>{await Is(this.metaPath(e),{force:!0}),await Is(F(this.dir,`${e}.ndjson`),{force:!0})})}};function xle(e){let{docName:t,anchor:n,state:r,queued:i,latestComment:a,updatedAt:o}=e;return{...t!==void 0&&{docName:t},...n!==void 0&&{anchor:n},...r!==void 0&&{state:r},...i!==void 0&&{queued:i},...a!==void 0&&{latestComment:a},...o!==void 0&&{updatedAt:o}}}function Sle(e){return`${JSON.stringify(e,null,1)}\n`}function Cle(e){try{return JSON.parse(e)}catch{return}}function Rk(e,t){return L(t,e.content.dir)}function zk(e){return L(e,`.ok`,ge)}function Bk(e){return zk(e)}const Vk={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},Hk={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}};function Uk(e,t){if(typeof e!=`string`||!yu(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let n=L(e),r=L(n,t),i=I(n,r);return i===``?{ok:!0,abs:r,rel:``}:i===`..`||i.startsWith(`../`)||yu(i)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:r,rel:i}}function Wk(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const Gk="Absolute host path inside the target OpenKnowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",Kk=u().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),qk="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",wle=u().length(40).regex(/^[0-9a-f]+$/i).describe(qk),Jk=u().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),Yk=u().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),Xk=u().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),Zk=j({value:u(),truncatedFrom:i().optional(),hint:u().optional()}).describe(`Normalized change-note summary, when one was recorded.`),Qk=M(C(u(),_())),$k=C(u(),_()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),Tle=M(rt).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" }`. Report-only — the write landed regardless; fix in a follow-up edit.');function Ele(e,t){for(let n of Jn){let r=Uk(e,`${t}${n}`);if(r.ok&&z(r.abs))return n}}const eA={summary:Zk.optional(),warnings:M(va).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit."),brokenLinks:Tle,templateHint:M(j({name:u(),description:u().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.")};function tA(e,t,n){let r={};return e&&(r.previewUrl=e.url,r.previewUrlSource=e.source),t&&(r.warning=t),Object.keys(n).length>0&&(r.document=n),r}function nA(e){let t=typeof e.detail==`string`?` (${e.detail})`:``;return`Error: ${typeof e.error==`string`?e.error:`request failed`}${t}`}function J(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const Dle=u().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function rA(e){return{text:Dle,...e}}function iA(e,t,n){let r={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:r,...n?{isError:!0}:{}}}const aA="Error: Hocuspocus server is not running. Start it with `ok start`, then retry.\nDo not fall back to native file edits for in-scope markdown; route writes through OpenKnowledge so attribution and live sync stay intact.";async function oA(e,t){return typeof e==`function`?await e(t):e}async function Ole(e,t){return typeof e==`function`?await e(t):e}async function sA(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let i=n===void 0?r:L(n);try{let e=await Ole(t,r);return{ok:!0,cwd:r,executionCwd:i,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function cA(e,t,n,r){let i=await lA(e,t,n,r);return i.ok?i.url?{ok:!0,cwd:i.cwd,executionCwd:i.executionCwd,config:i.config,url:i.url}:{ok:!1,result:J(aA,!0)}:{ok:!1,result:J(`Error: ${i.error}`,!0)}}async function lA(e,t,n,r){let i=await sA(e,t,r);if(!i.ok)return i;let{cwd:a,executionCwd:o,config:s}=i;try{return{ok:!0,cwd:a,executionCwd:o,config:s,url:await oA(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function uA(e){let t=e.replace(/^\/+/,``);return t!==`.ok`&&!t.startsWith(`.ok/`)?null:t.startsWith(`.ok/skills/`)?"Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes the SKILL.md wherever the skill lives (a NEW skill lands at the project default skill home, e.g. `.agents/skills/<name>/`). To author or improve a skill, use the `open-knowledge-write-skill` skill.":t.startsWith(`.ok/templates/`)?"Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.":"Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target."}function dA(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let n=e,r=t;for(;r.endsWith(`.mdx`)||r.endsWith(`.md`);)n=n.slice(0,r.endsWith(`.mdx`)?-4:-3),r=n.toLowerCase();let i=Zt(n);return i.ok?{ok:!0,docName:n}:{ok:!1,error:`Error: "${e}" is invalid — ${i.reason}.`}}function fA(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...n}=t;return{ok:!0,...n}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let n=t;if(typeof n.type==`string`&&typeof n.title==`string`){let{type:e,title:t,status:r,instance:i,detail:a,...o}=n;return{...o,ok:!1,error:t,type:e,...typeof r==`number`?{status:r}:{},...typeof i==`string`?{instance:i}:{},...typeof a==`string`?{detail:a}:{}}}let{ok:r,error:i,...a}=n,o=typeof i==`string`?i:typeof n.message==`string`?n.message:`Server returned HTTP ${e.status}`;return{...a,ok:!1,error:o}}function pA(e,t){return t?{url:e,local:t}:e}async function mA(e,t,n,r,i){let a;try{a=await e(t,n,r===void 0?void 0:{body:r,contentType:`application/json`})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}if(a===null)return null;let o=a.status>=200&&a.status<=299,s;try{s=JSON.parse(a.bodyText)}catch(e){let t=e instanceof Error?e.message:String(e),n=i?{httpStatus:a.status}:{};return o?{ok:!1,...n,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,...n,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}let c=fA({ok:o,status:a.status},s);return i?{...c,httpStatus:a.status}:c}async function hA(e,t){if(typeof e!=`string`){let n=await mA(e.local,`GET`,t,void 0,!0);if(n!==null)return n;e=e.url}let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let r;try{r=await n.json()}catch(e){let t=e instanceof Error?e.message:String(e);return n.ok?{ok:!1,httpStatus:n.status,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,httpStatus:n.status,error:`Server returned HTTP ${n.status} with non-JSON body: ${t}`}}return{...fA(n,r),httpStatus:n.status}}async function gA(e,t,n){let r=await hA(e,t);if(!r.ok)return{error:typeof r.error==`string`?r.error:`request failed`};let{ok:i,...a}=r,o=a[n];return{rows:Array.isArray(o)?o:[],data:a}}async function _A(e,t,n,r){let i;if(r!==void 0)try{i=JSON.stringify(r)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}if(typeof t!=`string`){let r=await mA(t.local,e,n,i,!1);if(r!==null)return r;t=t.url}let a;try{a=await fetch(`${t}${n}`,{method:e,headers:i===void 0?void 0:{"Content-Type":`application/json`},body:i,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let o;try{o=await a.json()}catch(e){let t=e instanceof Error?e.message:String(e);return a.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}return fA(a,o)}function vA(e,t,n){return _A(`POST`,e,t,n)}function yA(e,t,n){return _A(`PUT`,e,t,n)}function bA(e,t){return _A(`DELETE`,e,t)}function kle(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:n,to:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`?[{existing:t,incoming:n,to:r}]:[]}):[]}function xA(e){let t=e.severity===`error`?`✘`:`⚠`,n=e.range?.start?.line;return` ${t} ${n===void 0?`line ?`:`line ${n+1}`} ${e.source!==void 0&&e.code!==void 0?`${e.source}/${e.code}`:`?`}: ${e.message??``}`.trimEnd()}function SA(e,t){let n=[];return e>0&&n.push(`${e} error${e===1?``:`s`}`),t>0&&n.push(`${t} warning${t===1?``:`s`}`),n.length>0?n.join(`, `):`no problems`}function CA(e){return e?Fr(e).split(/\r?\n/):[]}function wA(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function TA(e,t){let n=`${t}:`;for(let t of CA(e))if(t.startsWith(n))return wA(t.slice(n.length))||null;return null}function EA(e){let t=[],n=``,r=null;for(let i of e){if(r){n+=i,i===r&&(r=null);continue}if(i===`"`||i===`'`){r=i,n+=i;continue}if(i===`,`){let e=wA(n);e&&t.push(e),n=``;continue}n+=i}let i=wA(n);return i&&t.push(i),t}function DA(e){let t=[],n=new Set;for(let r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function Ale(e){let{frontmatter:t}=Ur(e);if(!t)return[];let n=CA(t);for(let e=0;e<n.length;e+=1){let t=n[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let r=t[1]?.trim()??``;if(r){if(r.startsWith(`[`)&&r.endsWith(`]`))return DA(EA(r.slice(1,-1)));let e=wA(r);return e?[e]:[]}let i=[];for(let t=e+1;t<n.length;t+=1){let e=n[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=wA(e.replace(/^\s*-\s+/,``));t&&i.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return DA(i)}return[]}function OA(e,t){let{frontmatter:n,body:r}=Ur(e);return TA(n,`title`)||(kA(r)??t)}function kA(e){let t=e.match(/^# (.+)$/m);return t?t[1].trim():void 0}function AA(e){let{frontmatter:t}=Ur(e),n=TA(t,`icon`);if(!(!n||n.length>2048))return n}const jle=/^[>|][+-]?\d*$/;function jA(e,t){let{frontmatter:n}=Ur(e),r=TA(n,t);if(!(!r||jle.test(r)))return r}function MA(e){return jA(e,`description`)}function NA(e){return jA(e,`type`)}function Mle(e){return e?.trim()?{cluster:TA(e,`cluster`)??void 0,category:TA(e,`category`)??void 0,tags:Nle(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function Nle(e,t){let n=`${t}:`,r=CA(e);for(let e=0;e<r.length;e+=1){let t=r[e];if(!t?.startsWith(n))continue;let i=t.slice(n.length).trim();if(i){if(i.startsWith(`[`)&&i.endsWith(`]`)){let e=EA(i.slice(1,-1));return e.length>0?e:void 0}let e=wA(i);return e?[e]:void 0}let a=[];for(let t=e+1;t<r.length;t+=1){let e=r[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=wA(e.replace(/^\s*-\s+/,``));t&&a.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return a.length>0?a:void 0}}function Ple(e,t){let n=OA(e,t),r=Ale(e),i=DA([n,...r]),a=[],o=new Set;for(let e of i){let t=na(e);!t||o.has(t)||(o.add(t),a.push(t))}return{docName:t,title:n,aliases:r,matchLabels:i,normalizedMatchLabels:a}}function Fle(e,t){let n=Rle(e,t,`frontmatter.yml`);if(!z(n))return{};let r=Lle(n);return r==null?{}:Ile(r)}function Ile(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const PA=new Set;function Lle(e){let t;try{t=B(e,`utf-8`)}catch{return null}let n;try{n=(0,sk.parse)(t)}catch(t){if(!PA.has(e)){PA.add(e);let n=t instanceof Error?t.message:String(t);N(`folder-frontmatter`).warn({path:e,reason:n},`malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${n}`)}return null}return typeof n!=`object`||!n||Array.isArray(n)?null:(PA.delete(e),n)}function Rle(e,t,n){let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return r===``||r===`.`?F(e,`.ok`,n):F(e,r,`.ok`,n)}function FA(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function zle(e){try{return qu(L(e,`.git`)).isDirectory()}catch{return!1}}function Ble(e){return fc({baseDir:L(e),timeout:{block:5e3}})}async function Vle(e,t,n=5){if(!zle(e))return{commits:[],source:`git-absent`};let r=Ble(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
|
|
33
33
|
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const IA=5e3;async function Hle(e){try{let t=(await fc({baseDir:e,timeout:{block:IA}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function Ule(e,t){return fc({baseDir:t,timeout:{block:IA}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function Wle(e,t){let n=Pd(t);return e.startsWith(n)?e.slice(n.length):e}async function Gle(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,n)}catch{return[]}let o=Wle(t,r),s=Kd(o),c=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,l=``,u=``]=t.split(`\0`),d=n.trim();d.length===40&&c.push({hash:d,date:i,writerName:a,message:l,contributors:zd(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function Kle(e,t,n,r,i){let a;try{a=await Hb(e,t)}catch(e){return N(`shadow-log`).warn({branch:t,relPath:n,err:e},`[shadow-log] chain anchors unresolved; per-path history degraded to empty`),[]}if(a.length===0)return[];let o=``;try{o=await e.raw(`log`,...a,`-${Math.max(r*3,20)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,n)}catch(e){return N(`shadow-log`).warn({branch:t,relPath:n,anchorCount:a.length,err:e},`[shadow-log] ancestry walk failed; per-path history degraded to empty`),[]}let s=[];for(let e of o.split(``)){if(s.length>=r)break;let n=e.trimStart();if(!n)continue;let[a=``,o=``,c=``,l=``,u=``]=n.split(`\0`),d=a.trim();if(d.length!==40||i.has(d)||l.startsWith(`checkpoint:`)||l.startsWith(`park:`)||l.startsWith(`import:`)||l.startsWith(`upstream:`))continue;let f=ene(u),p=f?.writer_id??``,m=Kd(p);i.add(d),s.push({hash:d,date:o,writerName:f?.display_name??c,message:l,contributors:zd(u),writerId:p,isAgent:m.isAgent,writerClassification:m.classification,branch:t})}return s}async function qle(e,t,n=5){let r=Zte(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await Hle(e);if(!i)return{commits:[],source:`shadow-repo`};let a=Ule(r,L(e)),o=``;try{o=await a.raw(`for-each-ref`,Pd(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
|
|
34
34
|
`).map(e=>e.trim()).filter(Boolean),c=(s.length===0?[]:await Promise.all(s.map(e=>Gle(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n);if(c.length<n){let e=new Set(c.map(e=>e.hash)),r=await Kle(a,i,t,n-c.length,e);r.length>0&&(c=[...c,...r].sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n))}return{commits:c,source:`shadow-repo`}}function LA(e,t,n={}){let r=Xle(t),i=r===``?[]:r.split(`/`),a=new Set,o=[];zA(e,r,`local`,a,o);for(let t=i.length-1;t>=1;t--)zA(e,i.slice(0,t).join(`/`),`inherited`,a,o);return i.length>0&&zA(e,``,`inherited`,a,o),o}async function Jle(e){let t=[],n=new Map,r=e=>{let t=n.get(e);return t||(t=new Set,n.set(e,t)),t},i=0,a=!1,o=[``];for(;o.length>0;){let n=o.shift()??``;if(i++>=RA){a=!0,N(`templates`).warn({projectDir:e,cap:RA,queueDepth:o.length},`project scan hit the ${RA}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${o.length}.`);break}zA(e,n,`local`,r(n),t);let s=n?F(e,n):e,c;try{c=await ad(s,{withFileTypes:!0})}catch(e){if(Sc(e)!==`ENOENT`&&!BA.has(s)){BA.add(s);let t=e instanceof Error?e.message:String(e);N(`templates`).warn({dir:s,reason:t},`failed to read directory ${s} during project scan — skipped. Reason: ${t}`)}continue}c.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of c){if(Yle.has(e.name)||e.name.startsWith(`.`))continue;let t=e.isDirectory();if(!t&&e.isSymbolicLink()){let n=F(s,e.name);try{t=(await sd(n)).isDirectory()}catch(e){if(Sc(e)!==`ENOENT`&&!BA.has(n)){BA.add(n);let t=e instanceof Error?e.message:String(e);N(`templates`).warn({link:n,reason:t},`failed to resolve symlink ${n} during project scan — skipped. Reason: ${t}`)}continue}}if(!t)continue;let r=n?Su.join(n,e.name):e.name;o.push(r)}}return{templates:t,truncated:a}}const RA=2e3,Yle=new Set([`node_modules`,`dist`,`build`]);function zA(e,t,n,r,i){let a=t?F(e,t,`.ok`,`templates`):F(e,`.ok`,`templates`);if(!z(a))return;let o;try{o=Hu(a)}catch{return}for(let e of o){if(!e.endsWith(`.md`))continue;let o=e.slice(0,-3);if(r.has(o))continue;let s=F(a,e),c;try{c=qu(s)}catch{continue}if(!c.isFile())continue;let l=Zle(s),u={name:o,path:t?Su.join(t,`.ok`,`templates`,e):Su.join(`.ok`,`templates`,e),source_folder:t,scope:n};l.title!==void 0&&(u.title=l.title),l.description!==void 0&&(u.description=l.description),r.add(o),i.push(u)}}function Xle(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const BA=new Set;function Zle(e){let t;try{t=B(e,`utf-8`)}catch(t){if(Sc(t)!==`ENOENT`&&!BA.has(e)){BA.add(e);let n=t instanceof Error?t.message:String(t);N(`templates`).warn({path:e,reason:n},`failed to read template at ${e} — metadata skipped. Reason: ${n}`)}return{}}let{identity:n}=ut(t);typeof n.title!=`string`&&!BA.has(e)&&(BA.add(e),N(`templates`).warn({path:e},`template at ${e} has no title — YAML may be malformed or the title is missing.`));let r={};return typeof n.title==`string`&&(r.title=n.title),typeof n.description==`string`&&(r.description=n.description),r}const VA=1e3,Qle=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),$le=/\.(md|mdx)$/i;function eue(e,t){if(e===null||t===null)return null;let n=e,r=t;return n===0&&r===0?`orphan`:n>=5?`hub`:n>0&&r>0?`connector`:`leaf`}function HA(e,t){let n=e.frontmatterSchemas;if(!n||n.length===0)return[];let r=I(e.contentDir??e.projectDir,L(e.projectDir,t));if(r.startsWith(`..`))return[];let i=[];for(let e of n)e.enabled!==!1&&Oo(e.appliesTo).matches(r)&&(i.includes(e.file)||i.push(e.file));return i}function tue(e,t){return HA(e,t===``?`⁂`:`${t}/⁂`)}function UA(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const WA=new Set;async function GA(e){try{let t=await id(e,`utf-8`);return{frontmatter:Ba(t)??{},firstHeading:kA(Ur(t).body)}}catch(t){if(t?.code!==`ENOENT`&&!WA.has(e)){WA.add(e);let n=t instanceof Error?t.message:String(t);N(`enrichment`).warn({path:e,reason:n},`failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${n}`)}return null}}async function nue(e,t){if(!e)return null;let n=await hA(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function rue(e,t){if(!e)return null;let n=await hA(e,`/api/comments?doc=${encodeURIComponent(t)}`);return n.ok?iue(n.threads):null}function iue(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n,r=e.state;if(r!==`anchored`&&r!==`orphaned`||typeof e.threadId!=`string`||e.threadId===``)continue;let i=(typeof e.anchor==`object`&&e.anchor!==null?e.anchor:{}).exact;t.push({threadId:e.threadId,body:typeof e.latestComment==`string`?e.latestComment:``,quote:typeof i==`string`?i:``,state:r,queued:e.queued===!0})}return t}async function aue(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await hA(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function oue(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));return KA(await Promise.all(r.map(async t=>{let n=await hA(e,`/api/comment-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})))}async function sue(e,t){if(!e)return null;let n=await hA(e,`/api/comment-counts?prefix=${encodeURIComponent(t)}`);return n.ok?KA([n.counts??{}]):null}function KA(e){let t=new Map,n=!1;for(let r of e)if(r){n=!0;for(let[e,n]of Object.entries(r))typeof n==`number`&&Number.isFinite(n)&&t.set(e,n)}return n?t:null}async function cue(e,t){if(!e)return null;let n=await hA(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function qA(e,t){let n=e?.title;if(typeof n!=`string`)return t;let r=n.trim();return r===``?t:r}function JA(e,t){let n=e??{};return{title:qA(n,t),description:typeof n.description==`string`?n.description:void 0,tags:Array.isArray(n.tags)?n.tags.filter(e=>typeof e==`string`):[],frontmatter:n}}async function lue(e,t,n={}){let r=Uk(t.projectDir,e);if(!r.ok)throw Error(`enrichPath: ${r.reason}`);let i=r.rel,a=r.abs,o=t.historyDepth??5,s=n.includeRichFields===!0,c=GA(a),l=HA(t,i),u=l.length>0?{schemas_applicable:l}:{};if(!s){let e=await c,t=JA(e?.frontmatter??null,e?.firstHeading);return{path:i,title:t.title,description:t.description,tags:t.tags,frontmatter:t.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null,graphRole:null,commentCount:null,comments:null,...u}}let[d,f,p,m,h,g]=await Promise.all([c,nue(t.serverUrl,UA(i)).catch(()=>null),cue(t.serverUrl,UA(i)).catch(()=>null),qle(t.projectDir,i,o).catch(()=>({commits:[],source:`shadow-repo`})),Vle(t.projectDir,i,o).catch(()=>({commits:[],source:`git`})),rue(t.serverUrl,UA(i)).catch(()=>null)]),_=JA(d?.frontmatter??null,d?.firstHeading);return{path:i,title:_.title,description:_.description,tags:_.tags,frontmatter:_.frontmatter,backlinkCount:f?.length??null,backlinks:f,forwardLinkCount:p?.length??null,forwardLinks:p,history:m.commits,historySource:m.source,projectHistory:h.commits,projectHistorySource:h.source,graphRole:eue(f?.length??null,p?.length??null),commentCount:g?.length??null,comments:g,...u}}async function uue(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=VA){n.truncated=!0;break}let a;try{a=await ad(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=VA){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(Qle.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&$le.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await sd(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:I(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function YA(e,t){let n=Uk(t.projectDir,e);if(!n.ok)throw Error(`enrichDirectory: ${n.reason}`);let r=n.rel,i=n.abs,a=await uue(i,t.projectDir),o;if(a.mostRecent){let e=await GA(a.mostRecent.absPath);o={path:a.mostRecent.relPath,title:qA(e?.frontmatter,e?.firstHeading)??gu(a.mostRecent.relPath),updatedAt:new Date(a.mostRecent.mtimeMs).toISOString()}}let s={path:r,type:`directory`,directMdCount:a.directMdCount,recursiveMdCount:a.recursiveMdCount,childDirCount:a.childDirCount,mostRecentMd:o,truncated:a.truncated},c=Fle(t.projectDir,r);c.title!==void 0&&(s.title=c.title),c.description!==void 0&&(s.description=c.description),(c.tags?.length??0)>0&&(s.tags=c.tags);let l=LA(t.projectDir,r);l.length>0&&(s.templates_available=l);let u=tue(t,r);u.length>0&&(s.schemas_applicable=u);let d=await sue(t.serverUrl,r).catch(()=>null);if(d&&d.size>0){let e=0;for(let t of d.values())e+=t;s.commentCount=e,s.commentedDocs=[...d].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,due).map(([e,t])=>({docName:e,count:t}))}return s}const due=5;async function XA(e,t,n){let r=await YA(e,n);if(t<=1)return r;let i=r.path,a=L(n.projectDir,i),o;try{o=await ad(a,{withFileTypes:!0})}catch{return r}let s=[];for(let e of o){if(!e.isDirectory()||fue.has(e.name)||e.name.startsWith(`.`))continue;let r=await XA(i?`${i}/${e.name}`:e.name,t-1,n);s.push(r)}return s.length>0&&(r.subfolders=s),r}const fue=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function ZA(e,t){let n={...e};for(let[e,r]of Object.entries(t))if(r!==void 0){if(pue(r)){delete n[e];continue}n[e]=r}return n}function pue(e){return Dr(e)}function mue(e){if(!yu(e.anchorDir))return{ok:!1,error:{code:`BAD_CONTENT_DIR`,message:`anchorDir must be absolute`}};let t=L(e.anchorDir),n=e.folderRel.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(n.split(`/`).some(e=>e===`..`))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Folder path escapes the content directory: ${e.folderRel}`}};let r=n===``?t:L(t,n);if(r!==t&&!r.startsWith(t+R))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder escapes the content directory: ${r}`}};let i=F(r,`.ok`),a=F(i,`frontmatter.yml`);try{let n=hue(a),r=Object.keys(e.patch).length===0?{}:ZA(n,e.patch);if(Object.keys(r).length===0)return z(a)?(Ju(a),gue(i),{ok:!0,path:QA(t,a),action:`deleted`}):{ok:!0,path:QA(t,a),action:`noop`};Iu(i,{recursive:!0});let o=(0,sk.stringify)(r),s=`${a}.tmp.${process.pid}.${Date.now()}`;return Yu(s,o,`utf-8`),Wu(s,a),{ok:!0,path:QA(t,a),action:`written`}}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write folder frontmatter for "${n||`.`}": ${e.message}`}}}}function hue(e){if(!z(e))return{};let t=(0,sk.parse)(B(e,`utf-8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:{...t}}function gue(e){if(!z(e))return;let t;try{t=Hu(e)}catch{return}if(t.length===0)try{Ku(e)}catch{}}function QA(e,t){return t.startsWith(e+R)?t.slice(e.length+1).split(R).join(`/`):t}const $A=1024,ej=[`anthropic`,`claude`],tj=`SKILL.md`;function nj(e){let t=uj(e.name);if(!t.ok)return{ok:!1,error:t.error};let n=yue(e.frontmatter,e.name);if(!n.ok)return{ok:!1,error:n.error};let r=`---\n${xue(e.frontmatter)}---\n${e.body}`,i=[],a=e.body.split(`
|
|
35
35
|
`).length;return a>500&&i.push(`SKILL.md body is ${a} lines — keep it under 500 for performance (every line is a recurring token cost). Move detail into one-level-deep references/.`),{ok:!0,content:r,warnings:i}}function rj(e){let t=lj(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=nj({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!n.ok)return{ok:!1,error:n.error};let{content:r,warnings:i}=n,{skillDir:a,filePath:o}=dj(e.skillsRoot,e.name);try{Hs(a,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create skill directory at ${fj(e.skillsRoot,a)}: ${t.message}`}}}let s=!z(o),c=`${o}.tmp.${process.pid}.${Date.now()}`;try{Zs(c,r,`utf-8`),Fs(c,o)}catch(t){try{Ls(c)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill at ${fj(e.skillsRoot,o)}: ${t.message}`}}}return{ok:!0,path:fj(e.skillsRoot,o),created:s,warnings:i}}function ij(e,t){if(typeof t!=`string`||t.length===0||t.includes(`\0`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path.`}};let n=t.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);if(n.length===0||n.some(e=>e===`..`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path: ${t}`}};if(n.length===1&&n[0]===tj)return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`SKILL.md is written through the skill write path, not as a bundle file.`}};let r=F(e,...n);return r!==e&&!r.startsWith(e+R)?{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file escapes the skill dir: ${t}`}}:{ok:!0,abs:r}}function aj(e){let t=0,n=r=>{let i;try{i=Hu(r)}catch{return}for(let a of i){let i=F(r,a),o;try{o=qu(i).isDirectory()}catch{continue}o?n(i):r===e&&a===tj||t++}};return n(e),t}function oj(e){let t=e.bytes??e.content??``,n=lj(e.skillsRoot);if(!n.ok)return{ok:!1,error:n.error};let r=uj(e.name);if(!r.ok)return{ok:!1,error:r.error};let{skillDir:i,filePath:a}=dj(e.skillsRoot,e.name);if(!z(a))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill "${e.name}" — create it (write its SKILL.md) before adding bundle files.`}};let o=ij(i,e.relPath);if(!o.ok)return{ok:!1,error:o.error};let{abs:s}=o,c=typeof t==`string`?Buffer.byteLength(t,`utf-8`):t.length,l=e.limits?.maxFileBytes??262144,u=e.limits?.maxFiles??50;if(c>l)return{ok:!1,error:{code:`FILE_TOO_LARGE`,message:`Skill file ${e.relPath} is ${c} bytes — the per-file cap is ${l}.`}};let d=!z(s);if(d&&aj(i)>=u)return{ok:!1,error:{code:`TOO_MANY_FILES`,message:`Skill "${e.name}" already holds ${u} bundle files (the cap) — delete one before adding another.`}};try{Hs(F(s,`..`),{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create directory for ${e.relPath}: ${t.message}`}}}let f=`${s}.tmp.${process.pid}.${Date.now()}`;try{typeof t==`string`?Zs(f,t,`utf-8`):Zs(f,t),Fs(f,s)}catch(t){try{Ls(f)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill file ${e.relPath}: ${t.message}`}}}return{ok:!0,path:fj(e.skillsRoot,s),created:d}}function _ue(e){let t=lj(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=uj(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillDir:r}=dj(e.skillsRoot,e.name),i=ij(r,e.relPath);if(!i.ok)return{ok:!1,error:i.error};let a=ij(r,e.toRelPath);if(!a.ok)return{ok:!1,error:a.error};if(!z(i.abs))return{ok:!1,error:{code:`FILE_NOT_FOUND`,message:`No bundle file at ${e.relPath}.`}};if(z(a.abs))return{ok:!1,error:{code:`DEST_EXISTS`,message:`A bundle file already exists at ${e.toRelPath} — renames never overwrite.`}};try{Hs(F(a.abs,`..`),{recursive:!0}),Fs(i.abs,a.abs)}catch(t){return{ok:!1,error:{code:`RENAME_FAILED`,message:`Failed to rename ${e.relPath} -> ${e.toRelPath}: ${t.message}`}}}let o=F(i.abs,`..`);if(o!==r&&pj(o))try{Us(o)}catch{}return{ok:!0}}function sj(e){let t=lj(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=uj(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillDir:r}=dj(e.skillsRoot,e.name),i=ij(r,e.relPath);if(!i.ok)return{ok:!1,error:i.error};let{abs:a}=i,o=z(a);if(o){try{Ls(a)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill file ${e.relPath}: ${t.message}`}}}let t=F(a,`..`);if(t!==r&&pj(t))try{Us(t)}catch{}}return{ok:!0,path:fj(e.skillsRoot,a),existed:o}}function cj(e){let t=lj(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=uj(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillsRoot:r}=t,{skillDir:i}=dj(e.skillsRoot,e.name),a=z(i);if(a)try{Ks(i,{recursive:!0,force:!0})}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill at ${fj(e.skillsRoot,i)}: ${t.message}`}}}return bue(r),{ok:!0,path:fj(e.skillsRoot,i),existed:a}}async function vue(e){let t=lj(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=uj(e.fromName);if(!n.ok)return{ok:!1,error:n.error};let r=uj(e.toName);if(!r.ok)return{ok:!1,error:r.error};let i=dj(e.skillsRoot,e.fromName),a=dj(e.skillsRoot,e.toName);if(i.skillDir===a.skillDir)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same skill.`}};if(!z(i.skillDir))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill at ${fj(e.skillsRoot,i.skillDir)}.`}};if(z(a.skillDir))return{ok:!1,error:{code:`SKILL_EXISTS`,message:`A skill already exists at ${fj(e.skillsRoot,a.skillDir)}.`}};let o;try{o=await e.relocate(i.skillDir,a.skillDir)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move skill: ${e.message}`}}}return{ok:!0,fromPath:fj(e.skillsRoot,i.skillDir),toPath:fj(e.skillsRoot,a.skillDir),committed:o}}function lj(e){return yu(e)?{ok:!0,skillsRoot:e}:{ok:!1,error:{code:`BAD_SKILLS_ROOT`,message:`skillsRoot must be absolute`}}}function uj(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name is required.`}}:e.length>64?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must be ≤64 characters.`}}:Do.test(e)?ej.some(t=>e.includes(t))?{ok:!1,error:{code:`RESERVED_NAME`,message:`Skill name may not contain reserved words (${ej.join(`, `)}).`}}:{ok:!0}:{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must match /^[a-z0-9-]+$/ (got: ${JSON.stringify(e)}). Lowercase letters, digits, hyphens — no slashes, dots, spaces, or uppercase.`}}}function yue(e,t){return!e||typeof e!=`object`?{ok:!1,error:{code:`BAD_FRONTMATTER`,message:`Skill frontmatter (name, description) is required.`}}:typeof e.name!=`string`||e.name.length===0?{ok:!1,error:{code:`SKILL_NAME_REQUIRED`,message:`Skill frontmatter.name is required.`}}:e.name===t?pi(e.name)?{ok:!1,error:{code:`XML_TAG_IN_NAME`,message:"Skill frontmatter.name may not contain XML tags (`<...>`)."}}:typeof e.description==`string`?e.description.length>$A?{ok:!1,error:{code:`DESCRIPTION_TOO_LONG`,message:`Skill frontmatter.description must be ≤${$A} characters (got ${e.description.length}).`}}:pi(e.description)?{ok:!1,error:{code:`XML_TAG_IN_DESCRIPTION`,message:"Skill frontmatter.description may not contain XML tags (`<...>`) — they break the Cowork parser and skill loader."}}:{ok:!0}:{ok:!1,error:{code:`SKILL_DESCRIPTION_REQUIRED`,message:`Skill frontmatter.description must be a string — it is the primary triggering surface (when to use the skill).`}}:{ok:!1,error:{code:`NAME_DIR_MISMATCH`,message:`Skill frontmatter.name (${JSON.stringify(e.name)}) must equal the skill directory name (${JSON.stringify(t)}).`}}}function dj(e,t){let n=F(e,t);return{skillDir:n,filePath:F(n,tj)}}function bue(e){if(z(e)&&pj(e))try{Us(e)}catch{}let t=bu(F(e,`..`));if(t.endsWith(`${R}.ok`)&&z(t)&&pj(t))try{Us(t)}catch{}}function fj(e,t){return bu(t.startsWith(e+R)?t.slice(e.length+1):t).split(R).join(`/`)}function xue(e){return(0,sk.stringify)({name:e.name,description:e.description})}function pj(e){try{return Hu(e).length===0}catch{return!1}}const Sue=[`date`,`user`],mj=/\{\{([^{}\n]+?)\}\}/g;function Cue(e){let t=[];for(let n of e.matchAll(mj)){let e=(n[1]??``).trim();gj(e)||t.push({token:e,offset:n.index??0})}return t}function hj(e,t){return e.replace(mj,(e,n)=>{let r=n.trim();return gj(r)?t[r]:e})}function gj(e){return Sue.includes(e)}function _j(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}const vj=io;function yj(e){if(!vj.test(e.name))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(e.name)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let t=Due(e.frontmatter.title);if(!t.ok)return{ok:!1,error:t.error};let n=Oue(e.body);if(!n.ok)return{ok:!1,error:n.error};let r=kue(e.body);if(!r.ok)return{ok:!1,error:r.error};let i={};e.frontmatter.title!==void 0&&(i.title=e.frontmatter.title),e.frontmatter.description!==void 0&&(i.description=e.frontmatter.description),Array.isArray(e.frontmatter.tags)&&e.frontmatter.tags.length>0&&(i.tags=e.frontmatter.tags);let a=$o(i,e.body),o=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&o.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,content:a,warnings:o}}function wue(e){let t=xj(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let n=yj({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!n.ok)return{ok:!1,error:n.error};let{content:r,warnings:i}=n,{templatesDir:a,filePath:o}=Sj(e.projectDir,t.folderRel,e.name);try{Iu(a,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${Cj(e.projectDir,a)}: ${t.message}`}}}let s=!z(o),c=`${o}.tmp.${process.pid}.${Date.now()}`;try{Yu(c,r,`utf-8`),Wu(c,o)}catch(t){try{Ju(c)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${Cj(e.projectDir,o)}: ${t.message}`}}}return{ok:!0,path:Cj(e.projectDir,o),created:s,warnings:i}}function Tue(e){let t=xj(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:n,okDir:r,filePath:i}=Sj(e.projectDir,t.folderRel,e.name),a=z(i);if(a)try{Ju(i)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${Cj(e.projectDir,i)}: ${t.message}`}}}return{ok:!0,path:Cj(e.projectDir,i),existed:a,cleanedEmpty:bj(n,r)}}function bj(e,t){let n=!1,r=!1;if(z(e)&&wj(e))try{Ku(e),n=!0}catch{}if(z(t)&&wj(t))try{Ku(t),r=!0}catch{}return{templatesDir:n,okDir:r}}async function Eue(e){let t=xj(e.projectDir,e.fromFolder,e.fromName);if(!t.ok)return{ok:!1,error:t.error};let n=xj(e.projectDir,e.toFolder,e.toName);if(!n.ok)return{ok:!1,error:n.error};let r=Sj(e.projectDir,t.folderRel,e.fromName),i=Sj(e.projectDir,n.folderRel,e.toName);if(r.filePath===i.filePath)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same template.`}};if(!z(r.filePath))return{ok:!1,error:{code:`TEMPLATE_NOT_FOUND`,message:`No template at ${Cj(e.projectDir,r.filePath)}.`}};if(z(i.filePath))return{ok:!1,error:{code:`TEMPLATE_EXISTS`,message:`A template already exists at ${Cj(e.projectDir,i.filePath)}.`}};try{Iu(i.templatesDir,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create destination template directory at ${Cj(e.projectDir,i.templatesDir)}: ${t.message}`}}}let a;try{a=await e.relocate(r.filePath,i.filePath)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move template: ${e.message}`}}}let o=bj(r.templatesDir,r.okDir);return{ok:!0,fromPath:Cj(e.projectDir,r.filePath),toPath:Cj(e.projectDir,i.filePath),committed:a,cleanedEmpty:o}}function xj(e,t,n){if(!yu(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!vj.test(n))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(n)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(r.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let i=r?L(e,r):e,a=L(e);return!i.startsWith(a+R)&&i!==a?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${i}`}}:{ok:!0,folderRel:r}}function Due(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function Oue(e){let t=Cue(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function Sj(e,t,n){let r=t?F(e,t,`.ok`):F(e,`.ok`),i=F(r,`templates`);return{okDir:r,templatesDir:i,filePath:F(i,`${n}.md`)}}function Cj(e,t){return bu(t.startsWith(e+R)?t.slice(e.length+1):t).split(R).join(`/`)}function kue(e){let{frontmatter:t}=Ur(e);if(t===``)return{ok:!0};let n=Fr(t);return RegExp(`^template:`,`m`).test(n)?{ok:!1,error:{code:`TEMPLATE_RESERVED_KEY`,message:`Template starter content may not declare a top-level \`${hi}:\` frontmatter key — it is reserved for the template's identity.`}}:{ok:!0}}function wj(e){try{return Hu(e).length===0}catch{return!1}}let Tj=new Map;function Ej(e,t,n,r,i,a,o,s){let c=Tj.get(t);if(c||(c={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[],previousPaths:[]},Tj.set(t,c)),c.docs.add(e),i!==void 0&&(c.subjectOverride=i),a!==void 0){let e=c.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),c.actor=e}if(typeof o==`string`&&o.length>0&&c.summaries.push(o),s&&s.length>0)for(let e of s)c.previousPaths.push(e)}function Aue(e){let t=e instanceof Set?e:new Set(e);if(t.size!==0)for(let[e,n]of Tj){for(let e of t)n.docs.delete(e);n.docs.size===0&&Tj.delete(e)}}function Dj(){let e=Tj;return Tj=new Map,e}function Oj(e){for(let[t,n]of e){let e=Tj.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[],previousPaths:[]},Tj.set(t,e));for(let t of n.docs)e.docs.add(t);n.summaries.length>0&&(e.summaries=[...n.summaries,...e.summaries]),n.previousPaths.length>0&&(e.previousPaths=[...n.previousPaths,...e.previousPaths])}}function kj(e){if(e.size===0)return``;let t=[``];for(let n of e.values()){let e={v:1,id:n.writerId,name:n.displayName,colorSeed:n.colorSeed,docs:[...n.docs]};n.summaries.length>0&&(e.summaries=[...n.summaries]),t.push(`ok-contributors: ${JSON.stringify(e)}`)}return t.join(`
|
|
@@ -1170,7 +1170,7 @@ tags: [lore, history]
|
|
|
1170
1170
|
`);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{Y.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),ze.release(Di))}),u.on(`error`,e=>{clearTimeout(d),c||(c=!0,t.writableEnded||(i(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),ze.release(Di))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),ze.release(Di))})}let oa=`local-op-auth-signout`,la=K(ja,async(e,t,n)=>{let r=n.host??Pi();if(!ze.tryAcquire(Oi)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:oa,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=le,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=pu(e,i,JM({..._i,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),q(t,200,Za,{},{handler:oa})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:oa,cause:e})}finally{ze.release(Oi)}},{handler:oa,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:oa})}),ha=`/api/local-op/auth/set-identity`,ga=`local-op-auth-set-identity`,va=K(ti,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!A){G(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:ga});return}if(!ze.tryAcquire(ha)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:ga,extraHeaders:{"Retry-After":`5`}});return}try{_B(A,r,i),ce?.()?.refreshIdentity().catch(()=>{}),q(t,200,Za,{},{handler:ga})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:ga,cause:e})}finally{ze.release(ha)}},{handler:ga,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ga})});async function xa(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();if(!e){q(t,200,gi,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),q(t,200,gi,e.getStatus(),{handler:`sync-status`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Sa=K(ute,async(e,t,n)=>{let r=ce?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;q(t,202,See,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?ce?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Ca(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();q(t,200,ii,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let wa=K(Go,async(e,t,n)=>{let r=ce?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),q(t,200,pte,{},{handler:`sync-resolve-conflict`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?ce?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Ta(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!A){G(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){G(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=Vx(i),o=s.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=ce?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!o&&!l){G(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=fc({baseDir:A,timeout:{block:15e3}}),f=c?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(f){try{let e=async e=>{if(!e)return``;try{return await d.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},n=await e(f.theirsSha),r=await e(f.baseSha),a=Vx(i),o=s.documents.get(a),c=``,l=!1,u=null;if(o){let e=o.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=Ee?Ee(a):null;t!==null&&(c=t,l=!0)}else{_L(F(A,i),A);try{c=B(F(A,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;q(t,200,Gi,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),a=e.present?e.content:``,o=r.present?r.content:``,c=n.present&&r.present?`both-modified`:!n.present&&r.present?`delete-modify`:n.present&&!r.present?`modify-delete`:`both-modified`,l=n.present?n.content:``,d=null;if(u===`ytext`){let e=Vx(i),t=s.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=Ee?Ee(e):null;t!==null&&!rve(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else Y.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}q(t,200,Gi,{file:i,base:a,ours:l,theirs:o,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Ea(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=qJ(a);if(a!==null&&a!==``&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,$i,{plan:await eY({projectDir:l,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof PJ){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof FJ){G(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Da=K(Lo,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){G(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=qJ(a);if(typeof a==`string`&&a.length>0&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,zee,{result:await QJ(i,{projectDir:l,packId:o})},{handler:`seed-apply`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})}),ka=K(Uee,async(e,t,n)=>{let r=qJ(n.packId);if(r===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-install-pack-skill`,detail:`Pack id "${n.packId}" is not registered.`});return}try{q(t,200,rte,await Ohe(l,r),{handler:`seed-install-pack-skill`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install pack skill.`,{handler:`seed-install-pack-skill`,cause:e})}},{handler:`seed-install-pack-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-install-pack-skill`})});async function Aa(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}q(t,200,Zee,{packs:JJ()},{handler:`seed-packs`})}}let Ma=K(Lee,async(e,t,n)=>{if(n.out!==void 0&&!IG(n.out)){G(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{q(t,200,Yee,await PI({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function Na(e,t){if(r(e,t,{handler:`installed-agents`}))try{await tfe(e,t,nt.probeAll)}catch(n){t.headersSent||(Y.error({err:n,requestId:cS(e)},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}function Pa(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return G(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=L(l),o=i===``?a:L(a,i);return o!==a&&!o.startsWith(`${a}${R}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}function Fa(e,t,n=`template`){return!e||!io.test(e)?(G(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function Ia(e,t,n){let r=t===``?[]:t.split(`/`);for(let t=r.length;t>=0;t--){let i=t===0?``:r.slice(0,t).join(`/`),a=i===``?e:L(e,i);if(a!==e&&!a.startsWith(`${e}${R}`))continue;let o=L(a,`.ok`,`templates`,`${n}.md`);if(z(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function Ra(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}let Va=_W({GET:K(En,async(e,t)=>{try{let n=Pa(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await YA(n.folderRel,{projectDir:n.resolvedContentDir}),i=L(L(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(z(i))try{let e=(0,sk.parse)(await id(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);Y.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}q(t,200,Qr,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:K(gee,async(e,t,n)=>{try{if(Fe){G(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Pa(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=mue({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:a.error.message,{handler:`folder-config-put`,detail:a.error.code,cause:Error(a.error.message)});return}i.push({path:a.path,action:a.action}),a.action!==`noop`&&(cr(e,ar(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await lr(`folder-config-put`))}q(t,200,qe,{applied:i},{handler:`folder-config-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`}),Ua=K(En,async(e,t)=>{try{let{entries:e,truncated:n}=Ype({homedirOverride:he});q(t,200,fee,{themes:e,truncated:n},{handler:`saved-themes-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list saved themes.`,{handler:`saved-themes-list`,cause:e})}},{handler:`saved-themes-list`,method:`GET`,skipBodyParse:!0}),Ga=K(ste,async(e,t,n)=>{try{let e=await Qpe({name:n.name,stem:n.stem,scheme:n.scheme,extension:n.extension,homedirOverride:he,lockTimeoutMs:_e});if(!e.ok){if(e.code===`lock-timeout`){G(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-save`,detail:e.code,extraHeaders:{"Retry-After":`5`}});return}if(e.code===`name-taken`){G(t,409,`urn:ok:error:theme-name-taken`,`A saved theme with that name already exists.`,{handler:`saved-theme-save`,detail:n.name});return}G(t,400,`urn:ok:error:theme-name-invalid`,`That name cannot be used as a theme id.`,{handler:`saved-theme-save`,detail:e.code});return}q(t,201,Eee,{id:e.id,filename:e.filename},{handler:`saved-theme-save`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to save theme.`,{handler:`saved-theme-save`,cause:e})}},{handler:`saved-theme-save`,method:`POST`}),qa=K(En,async(e,t)=>{try{let n=Nc(e).get(`id`)??``;if(n===``){G(t,400,`urn:ok:error:invalid-request`,`Missing theme id.`,{handler:`saved-theme-delete`});return}let r=await eme({id:n,homedirOverride:he,lockTimeoutMs:_e});if(!r.ok){if(r.code===`lock-timeout`){G(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-delete`,detail:r.code,extraHeaders:{"Retry-After":`5`}});return}G(t,r.code===`invalid-id`?400:409,`urn:ok:error:invalid-request`,`Cannot delete saved theme.`,{handler:`saved-theme-delete`,detail:r.code});return}q(t,200,ht,r.existed?{existed:!0,filename:r.filename,scheme:r.scheme}:{existed:!1},{handler:`saved-theme-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete theme.`,{handler:`saved-theme-delete`,cause:e})}},{handler:`saved-theme-delete`,method:`DELETE`,skipBodyParse:!0}),Ja=_W({POST:Ga,PUT:K(jt,async(e,t,n)=>{try{let e=await $pe({id:n.id,scheme:n.scheme,homedirOverride:he,lockTimeoutMs:_e});if(!e.ok){if(e.code===`lock-timeout`){G(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-update`,detail:e.code,extraHeaders:{"Retry-After":`5`}});return}if(e.code===`not-found`){G(t,404,`urn:ok:error:not-found`,`Saved theme not found.`,{handler:`saved-theme-update`});return}if(e.code===`ambiguous-id`||e.code===`unsafe-target`){G(t,409,`urn:ok:error:invalid-request`,e.code===`ambiguous-id`?`Multiple saved theme files claim that id.`:`The saved theme id conflicts with a file that cannot be safely updated.`,{handler:`saved-theme-update`,detail:e.code});return}G(t,400,`urn:ok:error:invalid-request`,`Not a saved theme id.`,{handler:`saved-theme-update`,detail:e.code});return}q(t,200,Ct,{id:e.id,filename:e.filename},{handler:`saved-theme-update`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to update theme.`,{handler:`saved-theme-update`,cause:e})}},{handler:`saved-theme-update`,method:`PUT`}),DELETE:qa},{handler:`saved-theme`});function Ya(e,t,n){let r=s.documents.get(e);return r&&mS(r)?(_S(n,new gS({file:`${e}.md`}),t),!0):!1}function Xa(e,t,n){let r=s.documents.get(e);return r&&mS(r)?(_S(n,new gS({file:`${e}.md`}),t),!0):!1}let Qa=K(En,VB(async(e,t)=>{let n=await Jle(L(l));q(t,200,sa,{templates:n.templates.map(e=>{let{scope:t,...n}=e;return n}),truncated:n.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),$a=e=>{let{body:t}=Ur(e);return{frontmatter:Ba(e)??{},body:t}},eo=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Fa(r,t,`template-get`))return;let i=Pa(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Ia(o,a,r);if(!s){G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=ut(await id(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,Aee,{template:{name:r,folder:l,scope:u,path:I(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),to=K(ete,async(e,t,n)=>{try{if(Fe){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!Fa(r,t,`template-put`))return;let i=Pa(n.folder,t,`folder`,`template-put`);if(!i||Ya(qo(i.folderRel,r),`template-put`,t))return;let a=yj({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:Ra(n.frontmatter)});if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=L(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),s=!z(o),l=I(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=qo(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=$n(n),h=await c.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Fb(h.dc.document,a.content,`agent`)},h.origin);let g=await Gt(u);if(g?.kind===`failure`){Kt(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){qt(t,`template-put`);return}gn(u,a.content),cr(e,ar(`template`,i.folderRel,r),`${s?`template-create`:`template-edit`}: ${l}`),await lr(`template-put`),q(t,200,po,{path:l,created:s,warnings:a.warnings},{handler:`template-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),no=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Fa(r,t,`template-delete`))return;let i=Pa(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=go(n,me);if(a.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Ya(qo(i.folderRel,r),`template-delete`,t))return;await wn([qo(i.folderRel,r)],`deleted-upstream`);let o=Tue({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!o.ok){let e=o.error.code===`WRITE_ERROR`||o.error.code===`UNLINK_FAILED`||o.error.code===`BAD_PROJECT_DIR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:o.error.code,cause:Error(o.error.message)});return}o.existed&&(cr(a,ar(`template`,i.folderRel,r),`template-delete: ${o.path}`),await lr(`template-delete`),Te?.setDeleted(qo(i.folderRel,r))),q(t,200,kee,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),ro=_W({GET:eo,PUT:to,POST:K(Bee,async(e,t,n)=>{try{let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Fa(n.fromName,t,`template-move`)||!Fa(n.toName,t,`template-move`))return;let r=Pa(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Pa(n.toFolder,t,`folder`,`template-move`);if(!i||Ya(qo(r.folderRel,n.fromName),`template-move`,t))return;await wn([qo(r.folderRel,n.fromName)],`renamed`);let a=await Eue({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await FZ(A,e,t);return n||PZ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Ia(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){G(t,400,`urn:ok:error:invalid-request`,`Template "${n.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${r.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:a.error.message});return}if(a.error.code===`TEMPLATE_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,a.error.message,{handler:`template-move`,detail:a.error.code});return}let e=a.error.code===`WRITE_ERROR`||a.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:a.error.code,cause:Error(a.error.message)});return}Te?.setDeleted(qo(r.folderRel,n.fromName));let o=null;if(n.body!==void 0||n.frontmatter!==void 0){let e;if(typeof n.body==`string`)e=n.body;else try{e=or(B(L(i.resolvedContentDir,a.toPath),`utf-8`))}catch{e=null}if(e===null)o={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=wue({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Ra(n.frontmatter)});t.ok||(o=t.error)}}try{gn(qo(i.folderRel,n.toName),B(L(i.resolvedContentDir,a.toPath),`utf-8`))}catch{}if(cr(e,ar(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await lr(`template-move`),k?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}q(t,200,ko,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:no},{handler:`template`}),ao=K(mee,async(e,t,n)=>{try{if(Fe){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!RZ(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=Tt(r);if(Zx(i)||Qx(i)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let a=bZ(l,`file`,i);if(!z(a)){G(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let o=s.documents.get(i);if(n.deleteSource){let e=ce?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=o!==void 0&&mS(o),a=n.has(r);if(i||a){_S(t,new gS({file:r}),`template-import`);return}}let u=``;if(o)u=o.getText(`source`).toString();else{let e=await s.openDirectConnection(i);try{let n=e.document;if(!n){G(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=n.getText(`source`).toString()}finally{await e.disconnect()}}let d=n.name;if(!d){let{basename:e}=xZ(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!Fa(d,t,`template-import`))return;let f=Pa(n.targetFolder,t,`folder`,`template-import`);if(!f||Ya(qo(f.folderRel,d),`template-import`,t))return;let{frontmatter:p,body:m}=Ur(u),h=Fr(p),g={};try{h.trim()&&(g=(0,sk.parse)(h))}catch{}let v=n.title||g?.title||OA(u,d),y=g?.description||``,b=Array.isArray(g?.tags)?g.tags:[],x={...g};delete x.template,delete x.title;let S=``;Object.keys(x).length>0&&(S=`${(0,sk.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=yj({name:d,body:S,frontmatter:{title:v,description:y,tags:b}});if(!C.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let w=L(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),T=!z(w),E=I(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),ee=qo(f.folderRel,d),{agentId:te,agentName:D,colorSeed:ne,clientName:re}=$n(n),ie=await c.getSession(ee,te,{displayName:D,colorSeed:ne,clientName:re});ie.dc.document.transact(()=>{Fb(ie.dc.document,C.content,`agent`)},ie.origin);let O=await Gt(ee);if(O?.kind===`failure`){Kt(t,O.failure,`template-import`);return}if(O?.kind===`divergence`){qt(t,`template-import`);return}gn(ee,C.content),cr(e,ar(`template`,f.folderRel,d),`template-import: ${E}`),n.deleteSource&&(await wn([i],`deleted-upstream`),Te&&Te.setDeleted(i),Ls(a),_?.({kind:`delete`,path:a,docName:i})),await lr(`template-import`),k?.(`files`),q(t,200,Ue,{path:E,created:T,warnings:C.warnings},{handler:`template-import`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function so(e,t,n){return!e||e.length>64||!Do.test(e)?(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function co(e,t,n){let r=an.safeParse(e??`project`);return r.success?r.data:(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let lo=he??Zu(),fo=k_e({contentDir:l,skillsHome:lo,effectiveInstallMode:jo});function mo(e){return L(e===`global`?lo:l,`.ok`,`skills`)}function ho(e,t,n){let r=L(mo(e),t);if(e===`global`){if(n!==void 0){let e=mL(lo).find(e=>e.name===t&&e.hosts.includes(n));return e?L(lo,e.dir):null}let e=hL(lo,t);return e===null?z(F(r,`SKILL.md`))?r:null:e}let i=pL(l).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?L(l,i.dir):n===void 0&&z(F(r,`SKILL.md`))?r:null}function go(e,t){let n=e.searchParams;return dk({agentId:n.get(`agentId`)??void 0,agentName:n.get(`agentName`)??void 0,colorSeed:n.get(`colorSeed`)??void 0,clientName:n.get(`clientName`)??void 0,clientVersion:n.get(`clientVersion`)??void 0,label:n.get(`label`)??void 0,summary:n.get(`summary`)??void 0},t)}function yo(e,t){let n=e===`project`?A:lo;if(!n)return`symlink`;try{return ks(F(n,...xD)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function xo(e){let t=e===`project`?A:lo;return t?F(t,...xD):null}function So(e,t,n,r={}){let i=xo(e);return i?wJ(i,e=>{let i=e.skills[t];if(!i)return e;let a={...e.skills};return delete a[t],a[n]={...i,...r},{...e,skills:a}}):Promise.resolve()}async function Co(e,t,n){let r=xo(e),i=xo(t);if(!r||!i)return!1;let a=SJ(r).skills[n];if(!a)return!1;let o={...a};return t===`global`&&delete o.baselineRef,await wJ(i,e=>({...e,skills:{...e.skills,[n]:o}})),await wJ(r,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function wo(e,t,n){let r=xo(e);return r?wJ(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function Oo(e,t,n){let[r,i]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[t.code];G(e,r,i,t.error,{handler:n,detail:t.code})}function jo(e,t,n){let r=e===`project`?A:lo;return(r?D_e(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function Mo(e){let t=ho(`project`,e);return t?I(l,t).split(R).join(`/`):`${Tr}/${e}`}let No=YF.project;function Po(e,t,n){let r=[],i=null,a=[...wt.map(e=>({id:e,root:Zo[e]??``})),{id:`agents`,root:Ao}];for(let{id:o,root:s}of a){if(!s)continue;let a=L(e,...s.split(`/`),t);z(L(a,`SKILL.md`))&&(r.push(o),(n===void 0?i===null:o===n)&&(i=a))}if(i===null)return null;let o=L(i,`SKILL.md`);return{dir:i,skillMd:o,hosts:r,relPath:I(e,o).split(/[\\/]/).filter(Boolean).join(`/`)}}function Io(e){let t=jO(e.source,e.pluginProvider);return{source:e.source,...e.publisher===void 0?{}:{publisher:e.publisher},...e.skill===void 0?{}:{skill:e.skill},...t?{marketplaceUrl:t}:{},importedAt:e.importedAt,...e.autoUpdate===void 0?{}:{autoUpdate:e.autoUpdate}}}function Ro(e,t){if(!ZF(t))return null;let n=Po(e,t);if(!n)return null;let r=LD(n.dir)?.contentHash??``,i;try{i=qu(n.skillMd).mtime.toISOString()}catch{i=new Date(0).toISOString()}return{source:za,skill:t,contentHash:r,autoUpdate:!1,importedAt:i}}function zo(e,t,n){let r=Po(e,t);if(!r)return null;let i;try{let{frontmatter:e}=$a(B(r.skillMd,`utf-8`));typeof e.description==`string`&&(i=e.description)}catch{}let a=Ro(e,t);return{name:t,...i===void 0?{}:{description:i},scope:n,path:r.relPath,absolutePath:r.skillMd,installed:r.hosts.length>0,hosts:r.hosts,managed:!0,...a?{origin:Io(a)}:{}}}function Ko(e,t,n){return ZF(e)?(G(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is one of OpenKnowledge's runtime skills — its content is read-only in-app (updates arrive via reimport). Duplicate it under a new name to make your own version.`,{handler:n}),!0):!1}function qo(e,t){return To(e,t)}function Yo(e){return e===`navigation`||e===`relevance`?e:void 0}function Xo(e,t){return I(t===`global`?lo:l,e).split(/[\\/]/).filter(Boolean).join(`/`)}function Qo(e){return e===`global`?lo:A}async function $o(e,t,n,r={}){let i=await CN(e,t),a=n===`project`?l:lo;if(r.purge!==void 0){QI(t,e,wt,BI(n));for(let e of ihe(a,n,t,r.purge.contentHash))Ks(e,{recursive:!0,force:!0});return i!==null}if(!z(L(mo(n),t,`SKILL.md`))){let r=(n===`project`?pL(l):mL(lo)).find(e=>e.name===t);if(r){let a=n===`project`?l:lo,o=L(a,r.dir),s=L(a,`.agents`,`skills`),c=F(s,t);if(z(s)&&!z(F(c,`SKILL.md`))){let e=!1;try{e=V(o)===V(c)}catch{e=!1}e||Gs(o,c,{recursive:!0,dereference:!0})}return ZI({canonicalAbs:z(F(c,`SKILL.md`))?c:o,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...wt],roots:BI(n)}),i!==null}}return QI(t,e,wt,BI(n)),i!==null}function ts(e,t){let n=[];if(!z(e))return{skills:n,truncated:!1};let r;try{r=Hu(e,{withFileTypes:!0})}catch(r){return N(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!Do.test(a.name))continue;if(n.length>=500){i=!0;break}let r=L(e,a.name,`SKILL.md`);if(!z(r))continue;let o;try{let{frontmatter:e}=$a(B(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:Xo(r,t),absolutePath:r})}return{skills:n,truncated:i}}function ns(e){return`!/${P(e).split(R).join(`/`)}/`}let rs=K(at,VB(async(e,t,n)=>{if(!so(n.name,t,`skill-track-in-git`))return;if(n.scope!==`project`){G(t,400,`urn:ok:error:invalid-request`,`Only project skills live in the repository; a global skill is outside any .gitignore.`,{handler:`skill-track-in-git`});return}if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project directory.`,{handler:`skill-track-in-git`});return}let r=pL(l).find(e=>e.name===n.name)?.dir??`.ok/skills/${n.name}`,i=uZ(L(l,r,`SKILL.md`),l)??`${r}/SKILL.md`,a=P(i),o=i,s=ns(a),c=`.gitignore`,u=L(l,c);if(xe&&!xe.isPathIgnored(o)){q(t,200,Sr,{line:s,gitignorePath:c,applied:!1,alreadyTracked:!0},{handler:`skill-track-in-git`});return}if(n.apply!==!0){q(t,200,Sr,{line:s,gitignorePath:c,applied:!1},{handler:`skill-track-in-git`});return}let d=z(u)?B(u,`utf-8`):null;if((d??``).split(`
|
|
1171
1171
|
`).some(e=>e.trim()===s)){G(t,409,`urn:ok:error:invalid-request`,`"${s}" is already in ${c}, but ${o} is still ignored — another rule excludes it.`,{handler:`skill-track-in-git`});return}if(Yu(u,`${d===null||d.endsWith(`
|
|
1172
1172
|
`)||d===``?d??``:`${d}\n`}${s}\n`,`utf-8`),await xe?.rebuildIgnorePatterns(),xe?.isPathIgnored(o)){d===null?Gu(u,{force:!0}):Yu(u,d,`utf-8`),await xe.rebuildIgnorePatterns(),G(t,409,`urn:ok:error:invalid-request`,`Adding "${s}" did not make ${o} trackable — another .gitignore rule excludes a parent directory. ${c} was left unchanged.`,{handler:`skill-track-in-git`});return}k?.(`files`),q(t,200,Sr,{line:s,gitignorePath:c,applied:!0},{handler:`skill-track-in-git`})},{handler:`skill-track-in-git`,title:`Failed to update .gitignore.`}),{handler:`skill-track-in-git`,method:`POST`}),is={lastKey:null},as=K(En,VB(async(e,t)=>{let n=mo(`project`),r=ts(n,`project`),i=ts(mo(`global`),`global`),a=A?Ume(A):[],o=NI(lo).map(e=>e.editorId),s=A?bN(A).skills:{},c=bN(lo).skills,u=A?TD(z(F(A,...xD))?B(F(A,...xD),`utf-8`):``)??null:null,d=Io,f=(e,t,r)=>e.skills.map(e=>{let i=t[e.name]?.hosts??[],a=r?u?.skills[e.name]:void 0,o=a?d(a):void 0,s=a?.localHash!==void 0&&js(n,e.name)!==a.localHash,c=a?.baselineRef!==void 0;return{...e,installed:i.length>0,hosts:i,...o?{origin:o}:{},...s?{modified:!0}:{},...c?{revertable:!0}:{}}}),p=A?pX(A):{},m=(e,t,n)=>{let r=[];for(let i of t??[]){let t=L(e,i.path);if(n!==void 0&&t===L(n))continue;let a=!1;try{a=Fu(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(V(t)===V(n))continue}catch{}r.push(i.path)}}return{drift:r}},h=A?iL(l,`project`):{},g=lL(h,`project`),_=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),v=sL(`project`),y=sL(`global`),b=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),x=new Set,S=A?pL(l).map(e=>{let t=!x.has(e.name);x.add(e.name);let n=t?u?.skills[e.name]??Ro(l,e.name):void 0,r=n?d(n):void 0,i=n?.localHash!==void 0&&e.contentHash!==n.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:L(l,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],size:e.size,installableEditors:a,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(h).length>0?{hostAliases:h}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let n=b(t?p[e.name]:void 0,g).filter(e=>!_(e.path,v));return n.length?{customPlacements:n.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let n=m(A,b(t?p[e.name]:void 0,g),L(l,e.dir));return n.drift.length>0?{driftPaths:n.drift}:{}})(),...jo(`project`,e.name,e)===`link`?{linkMode:!0}:{},...r?{origin:r}:{},...i?{modified:!0}:{},...n?.baselineRef===void 0?{}:{revertable:!0},...ZF(e.name)?{managed:!0}:{}}}):[],C=pX(lo),w=ks(F(lo,...xD)),T=iL(lo,`global`),E=lL(T,`global`),ee=new Set(mL(lo).map(e=>e.name));i.skills=i.skills.filter(e=>!ee.has(e.name));let te=new Set,D=mL(lo).map(e=>{let t=!te.has(e.name);te.add(e.name);let n=t?C[e.name]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:L(lo,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],size:e.size,installableEditors:o,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(T).length>0?{hostAliases:T}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=m(lo,b(n,E),L(lo,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=b(n,E).filter(e=>!_(e.path,y));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...jo(`global`,e.name,e)===`link`?{linkMode:!0}:{},...ZF(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=w.skills[e.name]??Ro(lo,e.name);return n?{origin:d(n),...n.localHash!==void 0&&e.contentHash!==n.localHash?{modified:!0}:{}}:{}})()}}),ne=new Set(S.map(e=>e.name)),re=A&&!r.skills.some(e=>e.name===No)&&!ne.has(No)?zo(A,No,`project`):null,ie=new Set(D.map(e=>e.name)),O=eI.map(e=>YF[e]).filter(e=>!i.skills.some(t=>t.name===e)&&!ie.has(e)).map(e=>zo(lo,e,`global`)).filter(e=>e!==null),k=new Set(S.map(e=>e.name)),ae={skills:[...f(r,s,!0).filter(e=>!k.has(e.name)),...S,...f(i,c,!1),...D,...re?[re]:[],...O].map(e=>{let t=e.scope===`project`&&e.absolutePath?uZ(e.absolutePath,l):null,n=t===null||t===e.path?e:{...e,canonicalPath:t},r=t??e.path;return e.scope===`project`&&xe?.isPathIgnored(r)===!0?{...n,ignored:!0}:n}),truncated:r.truncated||i.truncated};await ave(S.map(e=>e.path),xe??null,is),q(t,200,bn,ae,{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),ss=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!so(r,t,`skill-get`))return;let i=co(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(ZF(r)){let e=i===`global`?lo:A,a=e?Po(e,r,n.searchParams.get(`host`)??void 0):null;if(a){let{frontmatter:e,body:n}=$a(await id(a.skillMd,`utf-8`));q(t,200,ni,{skill:{name:r,scope:i,path:a.relPath,frontmatter:{name:typeof e.name==`string`?e.name:r,description:typeof e.description==`string`?e.description:``},body:n,files:eL(a.dir),managed:!0}},{handler:`skill-get`});return}}let a=n.searchParams.get(`host`)??void 0,o=ho(i,r,a);if(o===null){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:a===void 0?`Skill "${r}" not found in ${i} scope.`:`No skill "${r}" (${i}) in ${a}.`});return}let s=L(o,`SKILL.md`),{frontmatter:c,body:l}=$a(await id(s,`utf-8`));q(t,200,ni,{skill:{name:r,scope:i,path:Xo(s,i),frontmatter:{name:typeof c.name==`string`?c.name:r,description:typeof c.description==`string`?c.description:``},body:l,files:eL(o)}},{handler:`skill-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0});async function cs(e,t){if(!(!O||rS(e))){if(xe)try{await xe.rebuildIgnorePatterns()}catch{}await cn(e,t,`skill-put`)}}let ls=K(uee,async(e,t,n)=>{try{let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!so(n.name,t,`skill-put`)||Ko(n.name,t,`skill-put`))return;let r=nj({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=n.scope===`project`?l:lo,a=ho(n.scope,n.name);if(a===null){let a=uL(i,n.scope);if(a===null){G(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-put`,detail:`NO_USABLE_SKILL_HOME`});return}let o=rj({skillsRoot:L(i,a),name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!o.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:o.error.code,cause:Error(o.error.message)});return}n.scope===`project`&&(cr(e,`${a}/${n.name}/SKILL`,`skill-create: ${a}/${n.name}/SKILL.md`),await lr(`skill-put`)),await cs(n.scope===`project`?`${a}/${n.name}/SKILL`:ji(`global`,n.name),r.content),k?.(`files`),q(t,200,ya,{path:`${a}/${n.name}/SKILL.md`,created:!0,warnings:[...r.warnings,...o.warnings]},{handler:`skill-put`});return}let o=I(i,a).split(R).join(`/`),s=`${o}/SKILL.md`,u=n.scope===`project`?`${o}/SKILL`:ji(n.scope,n.name);if(Xa(u,`skill-put`,t))return;let{agentId:d,agentName:f,colorSeed:p,clientName:m}=$n(n),h=await c.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Fb(h.dc.document,r.content,`agent`)},h.origin);let g=await Gt(u);if(g?.kind===`failure`){Kt(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){qt(t,`skill-put`);return}n.scope===`project`&&(cr(e,ar(`skill`,``,n.name),`skill-edit: ${s}`),await lr(`skill-put`)),await cs(u,r.content),k?.(`files`),q(t,200,ya,{path:s,created:!1,warnings:r.warnings},{handler:`skill-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function us(e,t){let n=e===`project`?l:lo,r=ho(e,t);return{root:r===null?mo(e):P(r),dirRel:r===null?`.ok/skills/${t}`:I(n,r).split(R).join(`/`),realDir:r}}function ds(e,t){let n=e===`project`?l:lo,r=(e===`project`?pL(l):mL(lo)).find(e=>e.name===t);r&&ZI({canonicalAbs:L(n,r.dir),canonicalHash:r.contentHash,name:t,cwd:n,targets:r.hosts.filter(e=>bo(e)),roots:BI(e)})}let ps=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!so(r,t,`skill-delete`))return;let i=co(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let{root:a,dirRel:o}=us(i,r),s=go(n,me);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await wn(i===`project`?[...new Set([`${o}/SKILL`,ji(i,r)])]:[ji(i,r)],`deleted-upstream`),ds(i,r);let c=cj({skillsRoot:a,name:r}),l=mo(i);if(c.ok&&l!==a&&z(L(l,r,`SKILL.md`))){let e=cj({skillsRoot:l,name:r});e.ok||Y.warn({name:r,scope:i,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(cr(s,o,`skill-delete: ${o}`),await lr(`skill-delete`)),k?.(`files`));let u=Qo(i);u&&await $o(u,r,i),q(t,200,di,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),ms=K(ote,async(e,t,n)=>{try{let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!so(n.fromName,t,`skill-move`)||!so(n.toName,t,`skill-move`)||Ko(n.toName,t,`skill-move`))return;let{root:r,dirRel:i}=us(n.scope,n.fromName);if(ho(n.scope,n.toName)!==null){G(t,409,`urn:ok:error:doc-already-exists`,`A skill named "${n.toName}" already exists.`,{handler:`skill-move`});return}let a=Qo(n.scope),o=a?bN(a).skills[n.fromName]:void 0,s=n.scope===`project`?l:lo,c=(n.scope===`project`?pL(l):mL(lo)).find(e=>e.name===n.fromName),u=c?P(c.dir):null,d=u===null?[]:Object.entries(iL(s,n.scope)).filter(([,e])=>e===u).map(([e])=>e),f=[...new Set([...o?II(o.hosts):[],...c?II(c.hosts):[],...II(d)])];await wn(n.scope===`project`?[...new Set([`${i}/SKILL`,ji(n.scope,n.fromName)])]:[ji(n.scope,n.fromName)],`renamed`),ds(n.scope,n.fromName);let p=await vue({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await FZ(A,e,t);return n||PZ(e,t),n}});if(!p.ok){if(p.error.code===`SKILL_NOT_FOUND`){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:p.error.message});return}if(p.error.code===`SKILL_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,p.error.message,{handler:`skill-move`,detail:p.error.code});return}let e=p.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:p.error.code,cause:Error(p.error.message)});return}let m=null,h=L(r,n.toName,`SKILL.md`),g=``,_=``;try{let e=$a(B(h,`utf-8`));g=e.body,typeof e.frontmatter.description==`string`&&(_=e.frontmatter.description)}catch{}let v=typeof n.body==`string`?n.body:g,y=n.frontmatter===void 0?_:n.frontmatter.description,b=rj({skillsRoot:r,name:n.toName,body:v,frontmatter:{name:n.toName,description:y}});b.ok||(m=b.error);let x=[];if(!m)try{x=dhe({base:n.scope===`project`?l:lo,scope:n.scope,fromName:n.fromName,toName:n.toName})}catch(e){N(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored`)}if(n.scope===`project`&&!m)try{await xe?.rebuildIgnorePatterns(),await Cs(r,n.fromName,n.toName),await Ts(x,n.toName)}catch(e){N(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let S=Xo(L(r,n.fromName),n.scope),C=Xo(L(r,n.toName),n.scope);n.scope===`project`&&(cr(e,ar(`skill`,``,n.toName),`skill-rename: ${S} -> ${C}`,[{from:S,to:C}]),await lr(`skill-move`));let w=js(r,n.toName),T=n.scope===`project`?await Ms(Ns(e),C):void 0;if(await So(n.scope,n.fromName,n.toName,{localHash:w,...n.scope===`project`?{baselineRef:T}:{}}),a){await CN(a,n.fromName),QI(n.fromName,a,f,BI(n.scope));let e=L(r,n.toName);if(f.length>0){let t=GI(e,n.toName,a,f,yo(n.scope,n.toName),BI(n.scope));await SN(a,n.toName,{...o,scope:n.scope,hosts:t,scripts:o?.scripts??RI(e,n.toName).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}}if(k?.(`files`),m){let e=m.code===`WRITE_ERROR`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:m.code,cause:Error(m.message)});return}q(t,200,xt,{from:S,to:C,committed:p.committed},{handler:`skill-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),hs=K(Iee,async(e,t,n)=>{let{name:r,home:i}=n;if(!so(r,t,`skill-edit-external`))return;let a;try{a=V(i)}catch{G(t,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!qu(a).isDirectory()||!z(L(a,`SKILL.md`))){G(t,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}az(r,a),q(t,200,Jee,{docName:Sn(r)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`skill-edit-external`})}),gs=K(wee,async(e,t,n)=>{try{let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move-scope`});return}let{name:r,fromScope:i,toScope:a}=n;if(!so(r,t,`skill-move-scope`))return;if(i===a){G(t,400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{handler:`skill-move-scope`});return}if(a===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{handler:`skill-move-scope`,detail:`NO_PROJECT_ROOT`});return}let{root:o,dirRel:s,realDir:c}=us(i,r),u=L(o,r),d=(()=>{try{return V(u)}catch{return u}})(),f=a===`project`?l:lo,p=uL(f,a);if(p===null){G(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available in the destination scope.`,{handler:`skill-move-scope`,detail:`NO_USABLE_SKILL_HOME`});return}let m=L(f,p),h=L(m,r);if(c===null||!z(u)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move-scope`,detail:`Skill "${r}" not found in ${i} scope.`});return}if(L(c)===L(h)||z(h)&&V(c)===V(h)){G(t,409,`urn:ok:error:doc-already-exists`,`The source and destination resolve to the same skill directory.`,{handler:`skill-move-scope`,detail:`SAME_STORAGE`});return}if(ho(a,r)!==null||z(h)){G(t,409,`urn:ok:error:doc-already-exists`,`A ${a} skill named "${r}" already exists.`,{handler:`skill-move-scope`});return}let g=Qo(i),_=Qo(a),v=g?bN(g).skills[r]:void 0,y=i===`project`?l:lo,b=(i===`project`?pL(l):mL(lo)).find(e=>e.name===r),x=b?P(b.dir):null,S=x===null?[]:Object.entries(iL(y,i)).filter(([,e])=>e===x).map(([e])=>e),C=[...new Set([...v?II(v.hosts):[],...b?II(b.hosts):[],...II(S)])];await wn([...new Set([...i===`project`?[`${s}/SKILL`]:[],ji(i,r),ji(a,r)])],`renamed`),Hs(m,{recursive:!0}),Gs(d,h,{recursive:!0,dereference:!0}),ds(i,r);let w=cj({skillsRoot:o,name:r});if(w.ok&&d!==u){let e=I((()=>{try{return V(y)}catch{return y}})(),d);e!==``&&!e.startsWith(`..`)&&!yu(e)&&Ks(d,{recursive:!0,force:!0})}if(!w.ok){cj({skillsRoot:m,name:r}),G(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); rolled back the copy.`,{handler:`skill-move-scope`,detail:w.error.code,cause:Error(w.error.message)});return}let T=await Co(i,a,r);if(g&&await $o(g,r,i,b?{purge:{contentHash:b.contentHash}}:{}),g&&await O_e(g,r),_&&C.length>0){let e=GI(h,r,_,C,yo(a,n.name),BI(a));await SN(_,r,{...v,scope:a,hosts:e,scripts:v?.scripts??RI(h,r).hasScripts,installedAt:v?.installedAt??new Date().toISOString()})}if((i===`project`||a===`project`)&&(cr(e,i===`project`?s:I(l,h).split(R).join(`/`),`skill-move-scope: ${i} -> ${a} ${r}`),await lr(`skill-move-scope`)),T){let t=js(m,r),n=a===`project`?await Ms(Ns(e),I(l,h).split(R).join(`/`)):void 0;await wo(a,r,{localHash:t,...a===`project`?{baselineRef:n}:{}})}if(!z(F(h,`SKILL.md`))){G(t,500,`urn:ok:error:internal-server-error`,`The move did not leave a readable skill at the destination; nothing was reported as moved.`,{handler:`skill-move-scope`,detail:I(f,h).split(R).join(`/`)});return}await xe?.rebuildIgnorePatterns(),k?.(`files`),q(t,200,kt,{scope:a,path:I(f,h).split(R).join(`/`)},{handler:`skill-move-scope`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill across scopes.`,{handler:`skill-move-scope`,cause:e})}},{handler:`skill-move-scope`,method:`POST`}),_s=K(tte,async(e,t,n)=>{try{let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!so(n.name,t,`skill-duplicate`)||!so(n.toName,t,`skill-duplicate`)||Ko(n.toName,t,`skill-duplicate`))return;let r=ho(n.scope,n.name);if(r===null||!z(F(r,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let i=n.scope===`project`?l:lo,a=uL(i,n.scope);if(a===null){G(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-duplicate`,detail:`NO_USABLE_SKILL_HOME`});return}let o=L(i,a),s=L(o,n.toName);if(ho(n.scope,n.toName)!==null||z(s)){G(t,409,`urn:ok:error:doc-already-exists`,`A ${n.scope} skill named "${n.toName}" already exists.`,{handler:`skill-duplicate`});return}let c=LD(r);if(!c){G(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}Hs(o,{recursive:!0}),Gs(r,s,{recursive:!0,dereference:!0});let{fenced:u,body:d}=_o(c.skillMd),f=Wa(u,{name:n.toName});if(!f.ok){cj({skillsRoot:o,name:n.toName}),G(t,400,`urn:ok:error:invalid-request`,`Failed to write duplicated skill.`,{handler:`skill-duplicate`,detail:f.error.kind});return}try{Zs(F(s,`SKILL.md`),`${f.nextFenced}${d}`)}catch(e){throw cj({skillsRoot:o,name:n.toName}),e}if(n.scope===`project`){let t=I(l,s).split(R).join(`/`);cr(e,ar(`skill`,``,n.toName),`skill-duplicate: ${n.name} -> ${t}`),await lr(`skill-duplicate`)}k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,vo,{name:n.toName},{handler:`skill-duplicate`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,cause:e})}},{handler:`skill-duplicate`,method:`POST`}),vs=_W({GET:ss,PUT:ls,POST:ms,DELETE:ps},{handler:`skill`});function ys(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<1||t.some(e=>e===`..`)||t.length===1&&t[0].toLowerCase()===`skill.md`?null:t[0]===`references`&&t.length>=2?`reference`:t[0]===`scripts`&&t.length>=2?`script`:`file`}function bs(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function xs(e,t){let n=t.replace(/\.md$/i,``);return`${hee(e).replace(/\/SKILL$/,``)}/${n}`}function Ss(e,t){let n=L(e,t,`references`);if(!z(n))return[];let r=[],i=(e,t)=>{for(let n of Hu(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(L(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function Cs(e,t,n){if(!O){N(`skill-move`).warn({fromName:t,toName:n},`no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)`);return}let r=[],i=(e,t,n)=>{let i;try{i=B(n,`utf-8`)}catch(i){N(`skill-move`).warn({err:i,absFile:n,oldDocName:e,newDocName:t},`relocated skill file unreadable after move — dropping the old index entry with no replacement`),r.push({kind:`delete`,documentName:e});return}r.push({kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:i})},a=I(l,e).split(R).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),L(e,n,`SKILL.md`));for(let r of Ss(e,n))i(o(t,r),o(n,r),L(e,n,r));await O.recordDirectMutations(r)}async function Ts(e,t){if(!O||e.length===0)return;let n=[];for(let r of e)r.dir.split(`/`).pop()!==t&&n.push({kind:`link-rewrite`,documentName:`${r.dir}/${r.rel.replace(/\.mdx?$/i,``)}`,markdown:r.markdown});n.length>0&&await O.recordDirectMutations(n)}let Es=_W({GET:K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!so(r,t,`skill-file-get`))return;let i=co(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=ZF(r)?i===`global`?lo:A:void 0,s=n.searchParams.get(`host`)??void 0,c=o?Po(o,r,s):null;if(a===``||a.includes(`\0`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let l=(c&&a===`SKILL.md`?`reference`:ys(a))??`reference`,u=s,d=o?c?.dir??null:ho(i,r,u);if(d===null&&u!==void 0){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-get`,detail:`No skill "${r}" (${i}) in ${u}.`});return}let f=d??L(mo(i),r),p=L(f,a);if(p!==f&&!p.startsWith(`${f}${R}`)){G(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let m=p,h=a;if(!z(m)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?Jn.map(t=>`${e[1]}${t}`).find(e=>e!==a&&z(L(f,e))):void 0;if(n===void 0){G(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${a} not found in skill "${r}" (${i}).`});return}h=n,m=L(f,n)}let g=await id(m);if(g.includes(0)){G(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}q(t,200,Ree,{path:h.replace(/\\/g,`/`),kind:l,text:g.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:K(Hee,async(e,t,n)=>{try{let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!so(n.name,t,`skill-file-put`)||Ko(n.name,t,`skill-file-put`))return;let r=ys(n.path);if(r===null){G(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must name a file inside the skill dir, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(n.content,`utf-8`)>262144){G(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=ho(n.scope,n.name);if(i===null||!z(F(i,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${n.name}" before adding bundle files.`});return}let a=I(n.scope===`project`?l:lo,i).split(R).join(`/`),o=n.path.replace(/\\/g,`/`),s=bs(n.scope,r,o),u;if(s){let e=`${a}/${o.replace(/\.mdx?$/i,``)}`;if(Xa(e,`skill-file-put`,t))return;if(u=!z(L(i,o)),u&&aj(i)>=50){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:s,colorSeed:l,clientName:d}=$n(n),f=await c.getSession(e,r,{displayName:s,colorSeed:l,clientName:d});f.dc.document.transact(()=>{Fb(f.dc.document,n.content,`agent`)},f.origin);let p=await Gt(e);if(p?.kind===`failure`){Kt(t,p.failure,`skill-file-put`);return}if(p?.kind===`divergence`){qt(t,`skill-file-put`);return}}else{let e=oj({skillsRoot:P(i),name:n.name,relPath:o,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;G(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}u=e.created}n.scope===`project`&&(cr(e,ar(`skill`,``,n.name),`${u?`skill-file-create`:`skill-file-edit`}: ${a}/${o}`),await lr(`skill-file-put`)),k?.(`files`),q(t,200,nte,{path:o,created:u,kind:r,content:s},{handler:`skill-file-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams,i=r.get(`name`)??``;if(!so(i,t,`skill-file-delete`)||Ko(i,t,`skill-file-delete`))return;let a=co(r.get(`scope`),t,`skill-file-delete`);if(a===null)return;let o=(r.get(`path`)??``).replace(/\\/g,`/`),s=ys(o);if(s===null){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must name a file inside the skill dir).`,{handler:`skill-file-delete`});return}let c=go(n,me);if(c.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let u=ho(a,i),d=u===null?mo(a):P(u);if(z(L(u??F(d,i),o))&&bs(a,s,o)){let e=o.replace(/\.md$/i,``);await wn([u===null?xs(i,o):`${I(l,u).split(R).join(`/`)}/${e}`],`deleted-upstream`)}let f=sj({skillsRoot:d,name:i,relPath:o});if(!f.ok){let e=f.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:f.error.code,cause:Error(f.error.message)});return}f.existed&&a===`project`&&(cr(c,ar(`skill`,``,i),`skill-file-delete: ${u===null?`${i}/${o}`:`${I(l,u).split(R).join(`/`)}/${o}`}`),await lr(`skill-file-delete`)),f.existed&&k?.(`files`),q(t,200,Fo,{path:o,existed:f.existed,kind:s},{handler:`skill-file-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),Ds=K(Xee,async(e,t,n)=>{try{if(!so(n.name,t,`skill-file-rename`)||Ko(n.name,t,`skill-file-rename`))return;let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-rename`});return}let r=n.from.replace(/\\/g,`/`),i=n.to.replace(/\\/g,`/`),a=ys(r),o=ys(i);if(a===null||o===null){G(t,400,`urn:ok:error:invalid-request`,`Both paths must stay inside the skill dir.`,{handler:`skill-file-rename`,detail:a===null?r:i});return}let s=ho(n.scope,n.name);if(s===null){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let c=P(s),u=bs(n.scope,a,r),d=bs(n.scope,o,i),f=I(l,s).split(R).join(`/`),p=u?`${f}/${r.replace(/\.md$/i,``)}`:null,m=d?`${f}/${i.replace(/\.md$/i,``)}`:null;if(p!==null&&Xa(p,`skill-file-rename`,t))return;p!==null&&await wn([p],`deleted-upstream`);let h=_ue({skillsRoot:c,name:n.name,relPath:r,toRelPath:i});if(!h.ok){let e=h.error.code===`RENAME_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,h.error.message,{handler:`skill-file-rename`,detail:h.error.code});return}if(O){let e=[];if(p!==null&&m!==null)try{e.push({kind:`rename`,oldDocumentName:p,newDocumentName:m,markdown:B(L(c,n.name,i),`utf-8`)})}catch{e.push({kind:`delete`,documentName:p})}else if(p!==null)e.push({kind:`delete`,documentName:p});else if(m!==null)try{e.push({kind:`upsert`,documentName:m,markdown:B(L(c,n.name,i),`utf-8`)})}catch{}await tn(e,`skill-file-rename`)}n.scope===`project`&&(cr(e,ar(`skill`,``,n.name),`skill-file-rename: ${n.name}/${r} -> ${i}`),await lr(`skill-file-rename`)),k?.(`files`),q(t,200,Qi,{from:r,to:i,...p===null?{}:{fromDocName:p},...m===null?{}:{toDocName:m}},{handler:`skill-file-rename`})}catch(e){Y.error({err:e},`[skill-file-rename] failed`),t.headersSent||G(t,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`});function Os(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}let ks=SJ;function js(e,t){return LD(L(e,t))?.contentHash}async function Ms(e,t){let n=E?.current;if(!(!n||!e))try{let r=gx(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
|
|
1173
|
-
`).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,`--`,t)).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await lr(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Ns=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Ps(e){try{let t=Qo(e.scope);if(!t)return;let n=zI(t);if(n.length===0)return;let r=GI(L(e.skillsRoot,e.name),e.name,t,n,`copy`,BI(e.scope));if(r.length===0)return;await SN(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){Y.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function Fs(e,t){if(t.ok){q(e,200,fte,t.body,{handler:`skill-import`});return}G(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let Is=x_e({contentDir:l,skillsHome:lo,...A===void 0?{}:{projectDir:A},resolveSkillDirForRead:ho,parseFrontmatterDoc:$a,attributeOkArtifactWrite:cr,commitOkArtifactWrite:lr,shadowHeadSha:Ms,artifactWriterId:Ns,effectiveInstallMode:jo,signalFiles:()=>k?.(`files`)}),Rs=K(Uo,async(e,t,n)=>{let r=()=>{};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l,u=n.source;{let e=n.source;try{let i=await qD(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??vD(d);if(!p){G(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(bX(t,p,`skill-import`))return;let m=await bD(p);r=m.cleanup,s=m.ref;let h=RD(m.dir);if(h.length===0){G(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let g=h[0];if(f){let e=h.find(e=>e.name===f)??h.find(e=>FD(e.dir)?.name===f)??h.find(e=>e.name===ca[f]);if(!e){G(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${f}" not among: ${h.map(e=>e.name).join(`, `)}.`});return}g=e}else if(h.length>1){G(t,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:h.map(e=>e.name).join(`, `)});return}a=g.dir,l=g.name,o=e,c=i?.publisher??Os(d)}catch(e){if(e instanceof rD){G(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){G(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await Is.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||Ka(u))&&AI({source:u,skills:[d.body.name]},lI()),await xe?.rebuildIgnorePatterns(),Fs(t,d)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),zs=K(Dee,async(e,t,n)=>{let r=()=>{};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l,u=i;try{let e=await qD(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??vD(d);if(!f){G(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(bX(t,f,`skills-import-bulk`))return;if(l=e?.publisher??Os(d),f.kind===`well-known`)a=f,o=await pD(f.origin);else{let e=await bD(f);r=e.cleanup,c=e.ref,s=RD(e.dir)}}catch(e){if(e instanceof rD){G(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){G(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let d=[];for(let t of new Set(n.skills)){let r,u,f=()=>{};if(a!==null)try{let e=await bD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof rD?`not-found`:`failed`,warnings:[],...e instanceof rD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>LD(e.dir)?.name===t)??s.find(e=>e.name===ca[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await Is.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){N(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}d.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings})}catch(e){N(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}if(n.marketplace===!0||Ka(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&AI({source:u,skills:e},lI())}await xe?.rebuildIgnorePatterns(),q(t,200,Ut,{results:d,imported:d.filter(e=>e.status===`imported`).length,alreadyImported:d.filter(e=>e.status===`already-imported`).length,failed:d.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),Bs=8*1024*1024,Vs=32*1024*1024;function Us(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=L(e,n);return r!==e&&!r.startsWith(e+R)?null:r}function qs(e){return new Promise((t,n)=>{let r;try{r=Oq(e,{files:200,fields:10,fieldSize:2*1024,fileSize:Bs})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>Vs){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function Js(e,t){return new Promise((n,r)=>{(0,tle.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=Us(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){Hs(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>Bs){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>Vs){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{Hs(P(n),{recursive:!0}),Zs(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function Xs(e,t){let n=Lu(F(ed(),`ok-skill-upload-`)),r=()=>{try{Ks(n,{recursive:!0,force:!0})}catch{}};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){G(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=co(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=dk({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},me);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await qs(e)}catch(e){G(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){G(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await Js(c.data,n)}catch(e){G(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=Us(n,e.relPath);if(!r){G(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}Hs(P(r),{recursive:!0}),Zs(r,e.data)}let u=RD(n);if(u.length===0){G(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){G(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];Fs(t,await Is.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let Qs=K(Nee,async(e,t,n)=>{try{let e=mo(n.scope);if(!so(n.name,t,`skill-install`))return;if(n.scope===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=Qo(n.scope),i=L(e,n.name),a=n.scope===`project`?l:lo,o=(n.scope===`project`?pL(l):mL(lo)).find(e=>e.name===n.name),s=o?L(a,o.dir):i;if(!z(s)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await Gt(n.scope===`project`?`${I(a,s).split(R).join(`/`)}/SKILL`:ji(n.scope,n.name));let c=RI(s,n.name);if(!c.ok){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${c.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){G(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=fo.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:G(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:G(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:G(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:G(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:G(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,sr,{name:n.name,hosts:o.hosts.filter(bo),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){G(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await fo.applyAddRemove({scope:n.scope,name:n.name,inPlaceEntry:o,...n.add===void 0?{}:{add:n.add},...n.remove===void 0?{}:{remove:n.remove}});if(!e.ok){e.kind===`remove-source`?G(t,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`}):G(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(bo),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await fo.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:s,newSource:u});if(!e.ok){G(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,sr,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?A:lo;if(!e){G(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Mr.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:s,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?G(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):G(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in r||k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,sr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?A:lo;if(!e){G(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Mr.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:s});if(!r.ok)switch(r.kind){case`not-recorded`:G(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:G(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:G(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r.path});return;case`canonical-dir`:G(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r.path});return;default:throw Error(`Unhandled unplace outcome: ${String(r.kind)}`)}k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,sr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){G(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?A:lo,l=await Mr.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:s,canonicalHash:o.contentHash});if(!l.ok)switch(l.kind){case`invalid-location`:G(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:G(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:G(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:G(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(l.kind)}`)}k?.(`files`),q(t,200,sr,{name:n.name,hosts:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f===void 0?NI(lo).map(e=>e.editorId).filter(e=>wt.includes(e)):wt.filter(e=>f?.some(t=>t===e)):f===void 0?zI(r):wt.filter(e=>f?.some(t=>t===e)),g=[],_=[];if(h.length===0&&f===void 0&&(g.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),c.hasScripts&&(g.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),c.warnings.length>0&&(g.push(c.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=(f===void 0?n.scope===`global`&&z(F(lo,`.agents`)):f.includes(`agents`))?[...h,`agents`]:[...h],a=n.scope===`project`?A:lo,l=d===void 0?jo(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await fo.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,newSource:u});if(!e.ok){e.kind===`invalid-target`?G(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):G(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}k?.(`files`),q(t,200,sr,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await fo.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:f!==void 0,installMode:l,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){G(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),k?.(`files`),q(t,200,sr,{name:n.name,hosts:v.hosts,scripts:c.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=II(bN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&QI(n.name,r,v,BI(n.scope));let y=F(r,...xD),b=z(y)?B(y,`utf-8`):null,x=b===null?null:TD(b);b!==null&&x===null&&Y.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=GI(s,n.name,r,h,C,BI(n.scope));w.length===0?await CN(r,n.name):await SN(r,n.name,{hosts:w,scope:n.scope,scripts:c.hasScripts,installedAt:new Date().toISOString(),projection:C}),k?.(`files`),q(t,200,sr,{name:n.name,hosts:w,scripts:c.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),$s=K(Xt,async(e,t,n)=>{try{if(!so(n.name,t,`skill-uninstall`))return;let e=Qo(n.scope);if(!e){G(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await $o(e,n.name,n.scope);k?.(`files`),q(t,200,gr,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),ec=_W({GET:K(En,async(e,t)=>{try{let e=zI(A??``),n=(e,t)=>{let n=T_e(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};q(t,200,nee,{targets:e,configured:!1,folders:[...A?sX(l,oL(l,`project`)).filter(e=>cL(l,`project`,e.root)).map(e=>({...e,scope:`project`,...n(l,e)})):[],...sX(lo,oL(lo,`global`)).filter(e=>cL(lo,`global`,e.root)).map(e=>({...e,scope:`global`,...n(lo,e)}))]},{handler:`skill-targets-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:K(vee,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?l:lo;if(e.scope===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await E_e(r,i.join(`/`)),k?.(`files`),q(t,200,fs,{targets:zI(A??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(oL(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){G(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?w_e({base:r,folderRel:e.root,targetRootRel:a}):lX({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){G(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await fX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),k?.(`files`),q(t,200,fs,{targets:zI(A??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),tc=K(aee,async(e,t,n)=>{try{let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!so(n.name,t,`skill-restore`)||Ko(n.name,t,`skill-restore`))return;if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=E?.current;if(!r){G(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await SX({shadow:r,contentDir:l,contentRoot:ie??`.`,name:n.name,version:n.version,skillDirRel:Mo(n.name)});if(!i.ok){Oo(t,i,`skill-restore`);return}let a=[],o=RI(L(l,Mo(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),cr(e,ar(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await lr(`skill-restore`),k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,Fn,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),nc=K(Ze,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!so(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?lo:l,{root:a,dirRel:o,realDir:s}=us(n.scope,n.name),c=!o.startsWith(`${Tr}/`);if(s===null||!z(L(i,o,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=F(n.scope===`global`?lo:A,...xD),d=ks(u).skills[n.name];if(!d){let e=OD(n.name,LD(L(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:$_e(L(a,n.name))})??Ro(i,n.name);e&&(d=e)}if(!d){G(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await wJ(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),await xe?.rebuildIgnorePatterns(),q(t,200,fa,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=d.skill??n.name,i=ca[e],a=await qD(d.source,e).catch(async e=>{if(i===void 0)throw e;return qD(d.source,i)}),o=a?.source??MO(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??vD(o);if(!c){G(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if(bX(t,c,`skill-reimport`))return;let l=await bD(c);r=l.cleanup,f=l.ref;let u=RD(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>LD(e.dir)?.name===n.name)??u.find(e=>e.name===ca[s??n.name])??(u.length===1?u[0]:void 0);if(!m){G(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=ID(m.dir);if(h){G(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=LD(m.dir)}catch(e){if(e instanceof rD){G(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){G(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=oX(p);if(h){G(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=LD(L(a,n.name)),_=new Set(p.files.map(e=>e.relPath)),v=new Set((g?.files??[]).map(e=>e.relPath)),y=(d.files??(d.localHash!==void 0&&g?.contentHash===d.localHash?g.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(p.contentHash===d.contentHash&&y.length===0){await xe?.rebuildIgnorePatterns(),q(t,200,fa,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=$a(p.skillMd).body;if(n.dryRun){let e=LD(L(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&A)try{let e=fc({baseDir:A,timeout:{block:15e3}}),t=I(A,L(a,n.name)).split(R).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}await xe?.rebuildIgnorePatterns(),q(t,200,fa,{name:n.name,updated:!0,source:d.source,localBody:$a(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await wn(e,`deleted-upstream`)}let x=rj({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){G(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=oj({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:aX});if(!r.ok){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=sj({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){G(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(cr(e,ar(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await lr(`skill-reimport`));let C=js(a,n.name),w=n.scope===`project`?await Ms(Ns(e),o):void 0;await wJ(u,e=>ED(e,n.name,{...e.skills[n.name]??d,contentHash:p.contentHash,files:p.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:f,importedAt:new Date().toISOString()})),!c&&n.scope===`project`&&await Ps({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,fa,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),rc=K(Gn,async(e,t,n)=>{try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!so(n.name,t,`skill-revert`)||Ko(n.name,t,`skill-revert`))return;if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=F(A,...xD),i=ks(r).skills[n.name];if(!i?.baselineRef){G(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=E?.current;if(!a){G(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await SX({shadow:a,contentDir:l,contentRoot:ie??`.`,name:n.name,version:i.baselineRef,skillDirRel:Mo(n.name)});if(!o.ok){Oo(t,o,`skill-revert`);return}cr(e,ar(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await lr(`skill-revert`);let s=L(l,Mo(n.name),`..`),c=js(s,n.name);await wJ(r,e=>ED(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===mo(`project`)&&await Ps({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),k?.(`files`),q(t,200,It,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function ic(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function ac(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let n=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return n.length>0?n:void 0}function oc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function sc(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let cc=y_e({contentDir:l,projectDir:A,getAllFilesIndex:g,getFileIndexGeneration:v,getSearchMaxEntries:sve,semanticSearch:Oe,getSemanticSimilarityFloor:ke,ready:we,getProjectSkillsRoot:()=>mo(`project`),parseFrontmatterDoc:$a});cc.prewarm();let lc=_W({GET:K(En,VB(async(e,t)=>{let n=Nc(e),r=n.get(`limit`),i=n.get(`query`)??``,a=ic(n.get(`intent`)),o=Yo(n.get(`ranking`)),s=ac(n.get(`scope`)??n.get(`scopes`)),c=oc(n.get(`semantic`)),l=sc(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}q(t,200,uo,await cc.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:K($ee,VB(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=ic(n.intent),a=Yo(n.ranking),o=ac(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=oc(n.semantic),l=sc(n.source);if(r.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}q(t,200,uo,await cc.buildSearchResponse({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),uc=K(En,VB(async(e,t)=>{q(t,200,lte,{...await DI(Zu())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function dc(e,t){if(r(e,t,{handler:`handoff`}))try{await cfe(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:nt.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:cS(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function mc(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await nN(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:cS(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let hc=K(dee,async(e,t,n)=>{try{if(!A){MF(`no-remote`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`no-remote`},{handler:jF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!tme(e,n.kind)){MF(`invalid-path`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`invalid-path`},{handler:jF});return}let r=ome(A);if(r===null){if(IF(A).kind===`no-remote`){MF(`no-remote`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`no-remote`},{handler:jF});return}MF(`detached-head`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`detached-head`},{handler:jF});return}let i=IF(A);if(i.kind===`no-remote`){MF(`no-remote`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`no-remote`},{handler:jF});return}if(i.kind===`non-github`){MF(`non-github-remote`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`non-github-remote`},{handler:jF});return}if(!dme(A,r)){MF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,ba,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:jF});return}let a=kZ(A,l);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&N(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let s;if(n.kind===`doc`)s=nme(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=rme(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${Bt(s)}`,u=await ime(A,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);MF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,ba,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:jF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:jF,cause:e})}},{handler:jF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:jF})}),gc=K(En,async(e,t)=>{try{if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:iB});return}let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`branch`),i=n.searchParams.get(`path`),a=n.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!ot(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:iB});return}if(!nB(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:iB});return}q(t,200,Tee,await rB(A,r,i,a),{handler:iB})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:iB,cause:e})}},{handler:iB,method:`GET`,skipBodyParse:!0});function _c(e,t,n){let r=e.split(`/`),i=t.split(`/`);if(n>=r.length||n>=i.length)return{verdict:`unknown`};for(let e=0;e<n;e+=1)if(r[e]!==i[e])return{verdict:`unknown`};return{verdict:`renamed`,renamedTo:i.slice(n).join(`/`)}}let vc=K(Lt,async(e,t,n)=>{try{if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:JF});return}if(!nB(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:JF});return}let e=await yme(A,n.branch,n.path,n.kind);q(t,200,on,e.verdict!==`renamed`||n.contentRootDepth===void 0?e:_c(n.path,e.renamedTo,n.contentRootDepth),{handler:JF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:JF,cause:e})}},{handler:JF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:JF})}),yc=K(At,async(e,t,n)=>{if(dk(n,me).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:lB});return}if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:lB});return}try{q(t,200,St,await pc(()=>dB(A,n.branch,{fastForward:n.fastForward===!0})),{handler:lB})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:lB,cause:e})}},{handler:lB,method:`POST`});async function bc(e){let[t,...n]=le,r=[...n,...e];return await new Promise((e,n)=>{let i=pu(t,r,JM({...hi,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},VF),s=[],c=[];i.stdout.on(`data`,e=>s.push(e)),i.stderr.on(`data`,e=>c.push(e)),i.on(`close`,t=>{if(clearTimeout(o),a){n(Error(`share subprocess timed out after ${VF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=qF(Buffer.concat(c).toString(`utf-8`)).slice(0,500);Y.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let xc=K(En,async(e,t)=>{if(!ze.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:RF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await bc([`share`,`owners`,`--json`]),n=fme(WF(e));KF(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,oee,n,{handler:RF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:RF,cause:e})}finally{ze.release(`/api/share/publish/owners`)}},{handler:RF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:RF})}),Cc=K(En,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!UF(r)||!HF(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:zF});return}if(!ze.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:zF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await bc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=pme(WF(e));KF(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,pa,n,{handler:zF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:zF,cause:e})}finally{ze.release(`/api/share/publish/name-check`)}},{handler:zF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:zF})}),wc=K(cee,async(e,t,n)=>{if(!A){KF(`publish-create`,`no-project`),q(t,200,Kn,{ok:!1,error:`no-project`},{handler:BF});return}if(!UF(n.owner)||!HF(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:BF});return}if(!ze.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:BF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,A,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await bc(e),i=gme(WF(r));KF(`publish-create`,i.ok?`ok`:i.error),i.ok&&ce?.()?.refreshRemote().catch(()=>{}),q(t,200,Kn,i,{handler:BF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BF,cause:e})}finally{ze.release(`/api/share/publish`)}},{handler:BF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:BF})}),Tc=K(Qn,async(e,t,n)=>{try{let e=N(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}q(t,200,He,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),Ec=A?zk(A):null;async function Oc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:cle(e.headers),previewUrl:null,port:Ec?Dc(Ec)?.port??0:0,singleFile:Fe};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,Gee,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function kc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Re?.()??{diagnostics:[]};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,fe,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let Ac=`local-op-embeddings-set-key`,jc=`local-op-embeddings-clear-key`,Mc=`/api/local-op/embeddings`;function Pc(){let e=je?.();return{projectDir:A??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let Fc=K(Mee,async(e,t,n)=>{if(!ze.tryAcquire(Mc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Ac,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=Pc();await new Qj(Ae).setForProject(e,r,n.key),Oe?.reloadCredential(),q(t,200,os,{keyPresent:!0},{handler:Ac,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Ac,cause:e})}finally{ze.release(Mc)}},{handler:Ac,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ac})}),Ic=K(En,async(e,t)=>{if(!ze.tryAcquire(Mc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:jc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=Pc();await new Qj(Ae).clearForProject(e,n),Oe?.reloadCredential(),q(t,200,os,{keyPresent:!1},{handler:jc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:jc,cause:e})}finally{ze.release(Mc)}},{handler:jc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:jc})}),Lc=`local-op-embeddings-test`,Rc=`/api/local-op/embeddings/test`,zc=K(En,async(e,t)=>{if(!ze.tryAcquire(Rc)){G(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Lc,extraHeaders:{"Retry-After":`5`}});return}try{let e=je?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await Gj(new Qj(Ae),A??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await ide({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};q(t,200,cte,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Lc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Lc,cause:e})}finally{ze.release(Rc)}},{handler:Lc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Lc})}),Bc=K(En,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Oe){let t=Oe.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=je?.()?.baseUrl??`https://api.openai.com/v1`,o=await Gj(new Qj(Ae),A??l,a),s=o.apiKey!==null,c=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,f=0;for(let[e]of m())!Zx(e)&&!Qx(e)&&!Cr(e)&&(f+=1);q(t,200,aa,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Vc=0;function Hc(){Vc+=1,k?.(`lint-config`)}let Uc=()=>`${Vc} ${t.getActiveBranch()} ${O?.readLocalTargetGeneration?.()??0}`;async function Wc(e,t){let n=Me?.()??Vt;try{let r=await Ha(e,RP(l,n,{docName:t,projectDir:A??l,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Pe?.()??`warning`;if(O&&a!==`off`&&!rS(t)){await ln(t,e,`lint-validation`);let r=pF({projectDir:A??l,contentDir:l,baseConfig:n,derivedDocumentIndex:O,linksValidation:a,admittedDocNames:en,docFilePathFor:e=>EZ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:EZ(l,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Gc(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=VP({projectDir:A??l,contentDir:l});return uP(t.schemas,n)}let Kc=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!RZ(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Me?.()??Vt,i=[],a=FP(l,n??void 0,e=>i.push(e)),o=LP(A??l,IP(r,a),e=>i.push(e));n===null&&i.push(...Gc(o)),q(t,200,es,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),qc=K(Cee,async(e,t,n)=>{let r;try{r=ZP(L(l),n.ruleId,n.value)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){G(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}Hc();try{let e=Me?.()??Vt,n=[],r=FP(l,void 0,e=>n.push(e)),i=LP(A??l,IP(e,r),e=>n.push(e));n.push(...Gc(i)),q(t,200,es,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),Jc=K(Vo,async(e,t,n)=>{let r;try{let e=L(A??l),t=n.parentPath??[];r=n.delete?cpe(e,n.file):n.field!==void 0&&n.removeField?ope(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?spe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?ipe(e,n.file,n.field,n.constraint,t):ape(e,n.file)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){G(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&k?.(`files`),Hc();try{let e=Me?.()??Vt,n=[],r=FP(l,void 0,e=>n.push(e)),i=LP(A??l,IP(e,r),e=>n.push(e));n.push(...Gc(i)),q(t,200,es,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),Yc=K(En,async(e,t)=>{try{let e=L(A??l),{schemas:n,truncated:r}=Pfe(e),i=new Set(n),a=!1;if(xe!==void 0){let t=gZ({contentDir:l,contentFilter:xe,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&Yi(a)){let t=I(e,L(l,a));!t.startsWith(`..`)&&!yu(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));q(t,200,dte,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),Xc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=s.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},Zc=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!RZ(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=EZ(l,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Me?.()??Vt,a=[],o=await BP({projectDir:A??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:Xc});q(t,200,yee,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof LM){G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),Qc=new oP,$c=yX();function el(e,t,n){let r=`${n} ${Uc()} ${t??``}`;return $c.run(r,()=>Dpe(e,{targetPath:t})).promise}function tl(e,t){G(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let nl=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!_Z(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Me?.()??Vt;q(t,200,jee,await HP({projectDir:A??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:Xc,cache:Qc,auditGeneration:Uc}),{handler:`lint-audit`})}catch(e){if(e instanceof zP){tl(t,`lint-audit`);return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),rl=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!_Z(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!_Z(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=EZ(l,o)??`${o}.md`}let s=Me?.()??Vt,c=await el(pF({projectDir:A??l,contentDir:l,baseConfig:s,liveSourceFor:Xc,derivedDocumentIndex:O??null,linksValidation:Pe?.(),admittedDocNames:en,docFilePathFor:e=>EZ(l,e),cache:Qc,auditGeneration:Uc}),i,oP.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){q(t,200,Dt,Epe(c),{handler:`audit`});return}q(t,200,yt,c,{handler:`audit`})}catch(e){if(e instanceof zP){tl(t,`audit`);return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),il=K(dt,async(t,n,r)=>{try{let t=yZ(r.docName,n,`lint-fix`);if(t===null)return;let i=Tt(t),a=dk(r,me);if(a.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,s=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Zx(i)||Qx(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=EZ(l,i);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}KM(L(l,f),l);let p=Me?.()??Vt,{stored:m}=tr(a.summary),h=await c.getSession(i,o,{displayName:s,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await tpe({projectDir:A??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Bo(d),n=Oa[t]??Vi(u??o);oe?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{lw(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,sw(h))},h.origin),a.kind!==`anonymous`&&Ej(i,o,s,u,void 0,a.kind===`agent`?er({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{oe?.touchMode(o,`idle`)}let t=await Gt(i);if(t?.kind===`failure`){Kt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){qt(n,`lint-fix`);return}Ht(i,`lint-fix`);try{b=await Ha(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,Y.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;q(n,200,Jo,{file:f,fixedCount:Math.max(0,v.length-b.length),diagnostics:b,errorCount:S,warningCount:C,...x?{warning:x}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof LM){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof gS){_S(n,e,`lint-fix`);return}if(e instanceof xS){wS(n,e,`lint-fix`);return}if(e instanceof yw){G(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Y.error({err:e},`[lint-fix] handler failed`),G(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),al=`link-preview`,ol=new TG({cacheDir:Fe?null:L(A??l,`.ok`,`local`,`link-previews`)}),sl=null,cl=()=>(sl??=ol.init(),sl),ll=Ie??gG;async function ul(e){let t=await ll(e);return t.ok?{ok:!0,metadata:await xG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:ll})}:{ok:!1,reason:t.reason}}let dl=()=>{try{return Le?.()===!0}catch{return!1}},fl=K(Kee,async(e,t,n)=>{try{if(!dl()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,Xe,{ok:!1,reason:`disabled`},{handler:al});return}await cl();let e=!1,r=await ol.load(n.url,()=>(e=!0,ul(n.url)));ol.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Y.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),q(t,200,Xe,i,{handler:al})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:al,cause:e})}},{handler:al,method:`POST`,preBodyGate:(e,t)=>{let n=OG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:al}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:al}),!1)}}),pl=vle({service:ct,getPrincipal:me,onChanged:()=>k?.(`comments`)}),ml=_W({GET:pl.list,POST:pl.create},{handler:`comments`}),hl=_W({GET:pl.read,POST:pl.mutate,DELETE:pl.remove},{handler:`comment`}),{handleSkillsSearch:gl,handleSkillsPopular:_l,handleSkillsPublisher:vl,handleSkillsDetail:yl,handleSkillsPreview:bl,handleSkillsDiscover:xl,handleSkillsResolveRef:Sl}=L_e({log:Y,skillsHome:lo,projectDir:A,contentDir:l,resolveSkillDirForRead:ho}),Cl={"/api/config":Oc,"/api/config/diagnostics":kc,"/api/generated-index/settings":_W({GET:K(En,async(e,t)=>{if(!d){G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-get`});return}q(t,200,IZ,d(),{handler:`generated-index-settings-get`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-get`,method:`GET`,skipBodyParse:!0}),POST:K(xve,async(e,t,n)=>{if(!f){G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-set`});return}q(t,200,IZ,await f(n.enabled),{handler:`generated-index-settings-set`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-set`,method:`POST`})},{handler:`generated-index-settings`}),"/api/comments":ml,"/api/comment":hl,"/api/asset":qr,"/api/asset-text":Yr,"/api/comment-counts":hr,"/api/link-preview":fl,"/api/folder-config":Va,"/api/saved-themes":Ua,"/api/saved-theme":Ja,"/api/template":ro,"/api/template/import":ao,"/api/templates":Qa,"/api/skill":vs,"/api/skill-file":Es,"/api/skill-file/rename":Ds,"/api/skills":as,"/api/skills/installed":mr,"/api/skills/search":gl,"/api/skills/popular":_l,"/api/skills/publisher":vl,"/api/skills/detail":yl,"/api/skills/preview":bl,"/api/skills/discover":xl,"/api/skills/resolve-ref":Sl,"/api/skill/import":Rs,"/api/skills/import-bulk":zs,"/api/skill/edit-external":hs,"/api/skill/duplicate":_s,"/api/skill/move-scope":gs,"/api/skill-upload":Xs,"/api/skill/install":Qs,"/api/skill/uninstall":$s,"/api/skill/restore":tc,"/api/skill/reimport":nc,"/api/skill/revert":rc,"/api/skill/track-in-git":rs,"/api/skill-targets":ec,"/api/search":lc,"/api/semantic-status":Bc,"/api/lint/config":Kc,"/api/lint/markdownlint-config":qc,"/api/lint/frontmatter-schema":Jc,"/api/lint/frontmatter-schemas":Yc,"/api/lint":Zc,"/api/lint/audit":nl,"/api/lint/fix":il,"/api/audit":rl,"/api/create-page":Zr,"/api/create-folder":ei,"/api/duplicate-path":ai,"/api/rename-path":oi,"/api/delete-path":si,"/api/trash/cleanup":ci,"/api/upload":li,"/api/agent-write":ur,"/api/agent-write-md":dr,"/api/agent-write-batch":fr,"/api/frontmatter-patch":pr,"/api/agent-patch":vr,"/api/agent-undo":yr,"/api/agent-activity":xr,"/api/agent-burst-diff":Er,"/api/save-version":Nr,"/api/history":Pr,"/api/rollback":Lr,"/api/__embed-detect":Hr,"/api/server-info":Rr,"/api/acp/catalog":Br,"/api/share/construct-url":hc,"/api/share/target-status":vc,"/api/git/branch-info":gc,"/api/git/checkout":yc,"/api/share/publish/owners":xc,"/api/share/publish/name-check":Cc,"/api/share/publish":wc,"/api/principal":Vr,"/api/rescue":Xr,"/api/workspace":Wr,"/api/sync/status":xa,"/api/sync/trigger":Sa,"/api/sync/conflicts":Ca,"/api/sync/conflict-content":Ta,"/api/sync/resolve-conflict":wa,"/api/local-op/clone":yi,"/api/local-op/ok-init":wi,"/api/local-op/auth/login":zi,"/api/local-op/auth/status":Ji,"/api/local-op/auth/pat":ea,"/api/local-op/auth/gh-login":Ui,"/api/local-op/auth/cancel":Ki,"/api/local-op/auth/repos":na,"/api/local-op/auth/signout":la,"/api/local-op/auth/set-identity":va,"/api/local-op/embeddings/set-key":Fc,"/api/local-op/embeddings/clear-key":Ic,"/api/local-op/embeddings/test":zc,"/api/installed-agents":Na,"/api/spawn-cursor":mc,"/api/handoff":dc,"/api/install-skill":Ma,"/api/skill/install-state":uc,"/api/seed/plan":Ea,"/api/seed/apply":Da,"/api/seed/install-pack-skill":ka,"/api/seed/packs":Aa,"/api/client-logs":Tc};T&&(Cl[`/api/test-reset`]=Or,Cl[`/api/test-flush-git`]=Dr,Cl[`/api/test-rescan-backlinks`]=kr,Cl[`/api/test-rescan-files`]=Ar);let wl=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/generated-index/settings./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/saved-theme./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skill/track-in-git./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/seed/install-pack-skill./api/client-logs`.split(`.`)),Tl=[`/api/local-op/`],El=BB({log:Y,policy:n,ephemeral:Fe,table:{resolve(e){let t=Cl[e];if(t)return{template:e,dispatch:(e,n)=>t(e,n)};if(e.startsWith(`/api/history/`)){let t=e.slice(13);return{template:`/api/history/:sha`,dispatch:t?async(e,n)=>{await Ir(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>wl.has(e)||Tl.some(t=>e.startsWith(t))}}),Dl=pW({hocuspocus:s,derivedDocumentIndex:O,getFileIndex:m,isSafeDocName:RZ,readPageTitleForDocName:lt,readPageTitleForLinkedDocName:pt,readFrontmatterMetadataForLinkedDocName:vt,collectAdmittedDocNames:en,resolveAlias:Tt,respondToDerivedIndexQueryFailure:dn}),Ol=[Dl,vW({hocuspocus:s,agentPresenceBroadcaster:oe,isAllowedWorkspaceHostHeader:a,log:Y}),Ve],kl=Ol.flatMap(e=>[...e.paths]);BU(kl,Cl);let Al=Ol.map(e=>BB({log:Y,policy:n,ephemeral:Fe,table:e.table})),jl={paths:kl,dispatch:async(e,t)=>{for(let n of Al)if(await n(e,t))return!0;return!1}},Ml=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]);for(let e of Ml)if(Cl[e]===void 0&&Dl.table.resolve(e)?.dispatch===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await El(e,t)},nativeApi:jl,localApi:gW({resolve:e=>{if(!Ml.has(e))return;let t=Cl[e];return t===void 0?Dl.table.resolve(e)?.dispatch:t}})}}function BZ(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a,ingressPolicy:o}=e;return(e,s,c)=>{let l;try{l=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return c()}let u=vu(l).slice(1).toLowerCase(),d=u===`md`||u===`mdx`;if(!l||t.isPathIgnored(l)||!d&&!i.has(u))return c();let f=e.socket?.remoteAddress;if(f!==void 0&&!AB(f,o)){G(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!MB(e.headers.host,o)){G(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:TB});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=XY(u,r);d||s.setHeader(`Content-Disposition`,p.disposition),p.csp!==null&&s.setHeader(`Content-Security-Policy`,p.csp),p.sandboxedHtml&&s.setHeader(`Cache-Control`,`no-store`),n(e,s,()=>{if(s.headersSent)return;let e=Oe.has(u);if(!e&&(i.has(u)||a.has(u))){s.statusCode=404,s.end();return}e&&(s.removeHeader(`Content-Security-Policy`),s.removeHeader(`Content-Disposition`),s.removeHeader(`X-Content-Type-Options`),s.removeHeader(`Cache-Control`)),c()})}}function VZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function Cve(e){let t;try{t=Hu(e.contentDir,{withFileTypes:!0})}catch(t){let n=VZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Bx(n.name,w)&&e.basenameIndex.add(n.name)}async function HZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await ad(i,{withFileTypes:!0})}catch(t){let n=VZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=F(i,o.name),s=HM(I(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await rd(a)}catch(t){let n=VZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await od(a)}catch(t){let n=VZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!UM(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await sd(i)}catch(t){let n=VZ(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(o.ino))continue;n.add(o.ino),o.isDirectory()?await r(i):o.isFile()&&Bx(a,de)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(c.ino))continue;n.add(c.ino),await r(a);continue}c.isFile()&&Bx(a,de)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const UZ=j({principalId:u().optional(),tabSessionId:u().optional(),expectedServerInstanceId:u().optional(),expectedBranch:u().optional(),expectedDocLineageEpoch:u().optional(),clientProtocolVersion:i().optional(),clientRuntimeVersion:u().optional(),clientKind:u().optional()}).loose(),WZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function GZ(e){return WZ.includes(e)}function KZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function wve(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!GZ(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var qZ=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=KZ(e,this.payload)}};function JZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=UZ.safeParse(t);return n.success?n.data:void 0}var YZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const XZ=N(`conflict-storage`);var ZZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=F(zk(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!z(this.storePath)){this.conflicts=[];return}try{let e=B(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){XZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){XZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=P(this.storePath);z(e)||Iu(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return Yu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return XZ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-B0ZVs8y7.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=L(this.projectDir),r=L(t,e);if(!UM(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);_L(r,t),Zs(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),XZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Wb(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){XZ.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),XZ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=L(this.projectDir),a=L(i,e.file);if(!UM(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(_L(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-B0ZVs8y7.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);_L(a,i),Zs(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);Zs(a,n,`utf-8`);break;case`delete`:z(a)&&Ls(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function Tve(e,t){let n=e instanceof Error?{name:e.name,message:e.message,stack:e.stack??null}:{name:`NonError`,message:String(e),stack:null};return{timestamp:new Date().toISOString(),origin:t,error:n,pid:process.pid,uptimeSec:Math.round(process.uptime()*1e3)/1e3}}function Eve(e,t){let n=zk(e);try{Iu(n,{recursive:!0}),Yu(F(n,mo),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=sc(e);Iu(P(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};Yu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const QZ=new Map;let $Z=!1;function Dve(e,t){try{let n=Tve(e,t);for(let e of QZ.keys())Eve(e,n)}catch{}}function Ove(e){QZ.set(e,(QZ.get(e)??0)+1),$Z||($Z=!0,process.on(`uncaughtExceptionMonitor`,Dve));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=QZ.get(e)??0;n<=1?QZ.delete(e):QZ.set(e,n-1)}}}function eQ(e){let t=e.scheduler??Bi,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function tQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nQ(e){if(!z(e))return{};let t;try{t=(0,sk.parse)(B(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!tQ(t))return{};let n=t.telemetry;if(!tQ(n))return{};let r=n.localSink;return tQ(r)?r:{}}function rQ(e){return typeof e==`boolean`?e:void 0}function kve(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function iQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function aQ(e){if(tQ(e))return kve(e.maxBytes)}function Ave(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=nQ(Vs(`project`,e.projectDir)),n=nQ(Vs(`project-local`,e.projectDir));if((rQ(n.enabled)??rQ(t.enabled)??!0)===!1)return null;let r=aQ(n.spans)??aQ(t.spans)??52428800,i=aQ(n.logs)??aQ(t.logs)??26214400,a=iQ(n.attributeDenylist)??iQ(t.attributeDenylist)??ve;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var oQ;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(oQ||={});var jve;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(jve||={});const sQ=oQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),cQ=e=>{switch(typeof e){case`undefined`:return sQ.undefined;case`string`:return sQ.string;case`number`:return Number.isNaN(e)?sQ.nan:sQ.number;case`boolean`:return sQ.boolean;case`function`:return sQ.function;case`bigint`:return sQ.bigint;case`symbol`:return sQ.symbol;case`object`:return Array.isArray(e)?sQ.array:e===null?sQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?sQ.promise:typeof Map<`u`&&e instanceof Map?sQ.map:typeof Set<`u`&&e instanceof Set?sQ.set:typeof Date<`u`&&e instanceof Date?sQ.date:sQ.object;default:return sQ.unknown}},X=oQ.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var lQ=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,oQ.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};lQ.create=e=>new lQ(e);const uQ=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===sQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,oQ.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${oQ.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${oQ.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${oQ.joinValues(e.options)}, received '${e.received}'`;break;case X.invalid_arguments:n=`Invalid function arguments`;break;case X.invalid_return_type:n=`Invalid function return type`;break;case X.invalid_date:n=`Invalid date`;break;case X.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:oQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case X.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case X.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case X.custom:n=`Invalid input`;break;case X.invalid_intersection_types:n=`Intersection results could not be merged`;break;case X.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case X.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,oQ.assertNever(e)}return{message:n}};let Mve=uQ;function dQ(){return Mve}const fQ=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function pQ(e,t){let n=dQ(),r=fQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===uQ?void 0:uQ].filter(e=>!!e)});e.common.issues.push(r)}var mQ=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return hQ;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return hQ;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const hQ=Object.freeze({status:`aborted`}),gQ=e=>({status:`dirty`,value:e}),_Q=e=>({status:`valid`,value:e}),vQ=e=>e.status===`aborted`,yQ=e=>e.status===`dirty`,bQ=e=>e.status===`valid`,xQ=e=>typeof Promise<`u`&&e instanceof Promise;var SQ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(SQ||={});var CQ=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const wQ=(e,t)=>{if(bQ(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new lQ(e.common.issues);return this._error=t,this._error}}};function TQ(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var EQ=class{get description(){return this._def.description}_getType(e){return cQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:cQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new mQ,ctx:{common:e.parent.common,data:e.data,parsedType:cQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(xQ(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:cQ(e)};return wQ(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:cQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return bQ(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>bQ(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:cQ(e)},r=this._parse({data:e,path:n.path,parent:n});return wQ(n,await(xQ(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:X.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new i$({schema:this,typeName:Z.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return a$.create(this,this._def)}nullable(){return o$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return HQ.create(this)}promise(){return r$.create(this,this._def)}or(e){return GQ.create([this,e],this._def)}and(e){return JQ.create(this,e,this._def)}transform(e){return new i$({...TQ(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new s$({...TQ(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new u$({typeName:Z.ZodBranded,type:this,...TQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new c$({...TQ(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return d$.create(this,e)}readonly(){return f$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Nve=/^c[^\s-]{8,}$/i,Pve=/^[0-9a-z]+$/,Fve=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ive=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Lve=/^[a-z0-9_-]{21}$/i,Rve=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zve=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Bve=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let DQ;const Vve=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Hve=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Uve=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Wve=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Gve=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Kve=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,OQ=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,qve=RegExp(`^${OQ}$`);function kQ(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Jve(e){return RegExp(`^${kQ(e)}$`)}function Yve(e){let t=`${OQ}T${kQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Xve(e,t){return!!((t===`v4`||!t)&&Vve.test(e)||(t===`v6`||!t)&&Uve.test(e))}function Zve(e,t){if(!Rve.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Qve(e,t){return!!((t===`v4`||!t)&&Hve.test(e)||(t===`v6`||!t)&&Wve.test(e))}var AQ=class e extends EQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==sQ.string){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.string,received:t.parsedType}),hQ}let t=new mQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?pQ(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&pQ(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Bve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)DQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),DQ.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Ive.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Lve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Nve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Pve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Fve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`ulid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),pQ(n,{validation:`url`,code:X.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`regex`,code:X.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Yve(r).test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?qve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Jve(r).test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?zve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Xve(e.data,r.version)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Zve(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Qve(e.data,r.version)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Gve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Kve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):oQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:X.invalid_string,...SQ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...SQ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...SQ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...SQ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...SQ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...SQ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...SQ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...SQ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...SQ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...SQ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...SQ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...SQ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...SQ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...SQ.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...SQ.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...SQ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...SQ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...SQ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...SQ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...SQ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...SQ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...SQ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...SQ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...SQ.errToObj(t)})}nonempty(e){return this.min(1,SQ.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};AQ.create=e=>new AQ({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...TQ(e)});function $ve(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var jQ=class e extends EQ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==sQ.number){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.number,received:t.parsedType}),hQ}let t,n=new mQ;for(let r of this._def.checks)r.kind===`int`?oQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?$ve(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.not_finite,message:r.message}),n.dirty()):oQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,SQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,SQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,SQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,SQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:SQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:SQ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:SQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:SQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:SQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:SQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:SQ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:SQ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:SQ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:SQ.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&oQ.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};jQ.create=e=>new jQ({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...TQ(e)});var MQ=class e extends EQ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==sQ.bigint)return this._getInvalidInput(e);let t,n=new mQ;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):oQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.bigint,received:t.parsedType}),hQ}gte(e,t){return this.setLimit(`min`,e,!0,SQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,SQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,SQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,SQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:SQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:SQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:SQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:SQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:SQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:SQ.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};MQ.create=e=>new MQ({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...TQ(e)});var NQ=class extends EQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==sQ.boolean){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.boolean,received:t.parsedType}),hQ}return _Q(e.data)}};NQ.create=e=>new NQ({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...TQ(e)});var PQ=class e extends EQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==sQ.date){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.date,received:t.parsedType}),hQ}if(Number.isNaN(e.data.getTime()))return pQ(this._getOrReturnCtx(e),{code:X.invalid_date}),hQ;let t=new mQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):oQ.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:SQ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:SQ.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};PQ.create=e=>new PQ({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...TQ(e)});var FQ=class extends EQ{_parse(e){if(this._getType(e)!==sQ.symbol){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.symbol,received:t.parsedType}),hQ}return _Q(e.data)}};FQ.create=e=>new FQ({typeName:Z.ZodSymbol,...TQ(e)});var IQ=class extends EQ{_parse(e){if(this._getType(e)!==sQ.undefined){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.undefined,received:t.parsedType}),hQ}return _Q(e.data)}};IQ.create=e=>new IQ({typeName:Z.ZodUndefined,...TQ(e)});var LQ=class extends EQ{_parse(e){if(this._getType(e)!==sQ.null){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.null,received:t.parsedType}),hQ}return _Q(e.data)}};LQ.create=e=>new LQ({typeName:Z.ZodNull,...TQ(e)});var RQ=class extends EQ{constructor(){super(...arguments),this._any=!0}_parse(e){return _Q(e.data)}};RQ.create=e=>new RQ({typeName:Z.ZodAny,...TQ(e)});var zQ=class extends EQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _Q(e.data)}};zQ.create=e=>new zQ({typeName:Z.ZodUnknown,...TQ(e)});var BQ=class extends EQ{_parse(e){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.never,received:t.parsedType}),hQ}};BQ.create=e=>new BQ({typeName:Z.ZodNever,...TQ(e)});var VQ=class extends EQ{_parse(e){if(this._getType(e)!==sQ.undefined){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.void,received:t.parsedType}),hQ}return _Q(e.data)}};VQ.create=e=>new VQ({typeName:Z.ZodVoid,...TQ(e)});var HQ=class e extends EQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==sQ.array)return pQ(t,{code:X.invalid_type,expected:sQ.array,received:t.parsedType}),hQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(pQ(t,{code:e?X.too_big:X.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(pQ(t,{code:X.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(pQ(t,{code:X.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new CQ(t,e,t.path,n)))).then(e=>mQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new CQ(t,e,t.path,n)));return mQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:SQ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:SQ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:SQ.toString(n)}})}nonempty(e){return this.min(1,e)}};HQ.create=(e,t)=>new HQ({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...TQ(t)});function UQ(e){if(e instanceof WQ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=a$.create(UQ(r))}return new WQ({...e._def,shape:()=>t})}else if(e instanceof HQ)return new HQ({...e._def,type:UQ(e.element)});else if(e instanceof a$)return a$.create(UQ(e.unwrap()));else if(e instanceof o$)return o$.create(UQ(e.unwrap()));else if(e instanceof YQ)return YQ.create(e.items.map(e=>UQ(e)));else return e}var WQ=class e extends EQ{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=oQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==sQ.object){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.object,received:t.parsedType}),hQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof BQ&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new CQ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof BQ){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(pQ(n,{code:X.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new CQ(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>mQ.mergeObjectSync(t,e)):mQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return SQ.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:SQ.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of oQ.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of oQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return UQ(this)}partial(t){let n={};for(let e of oQ.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of oQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof a$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return e$(oQ.objectKeys(this.shape))}};WQ.create=(e,t)=>new WQ({shape:()=>e,unknownKeys:`strip`,catchall:BQ.create(),typeName:Z.ZodObject,...TQ(t)}),WQ.strictCreate=(e,t)=>new WQ({shape:()=>e,unknownKeys:`strict`,catchall:BQ.create(),typeName:Z.ZodObject,...TQ(t)}),WQ.lazycreate=(e,t)=>new WQ({shape:e,unknownKeys:`strip`,catchall:BQ.create(),typeName:Z.ZodObject,...TQ(t)});var GQ=class extends EQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new lQ(e.ctx.common.issues));return pQ(t,{code:X.invalid_union,unionErrors:n}),hQ}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new lQ(e));return pQ(t,{code:X.invalid_union,unionErrors:i}),hQ}}get options(){return this._def.options}};GQ.create=(e,t)=>new GQ({options:e,typeName:Z.ZodUnion,...TQ(t)});const KQ=e=>e instanceof QQ?KQ(e.schema):e instanceof i$?KQ(e.innerType()):e instanceof $Q?[e.value]:e instanceof t$?e.options:e instanceof n$?oQ.objectValues(e.enum):e instanceof s$?KQ(e._def.innerType):e instanceof IQ?[void 0]:e instanceof LQ?[null]:e instanceof a$?[void 0,...KQ(e.unwrap())]:e instanceof o$?[null,...KQ(e.unwrap())]:e instanceof u$||e instanceof f$?KQ(e.unwrap()):e instanceof c$?KQ(e._def.innerType):[];var eye=class e extends EQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==sQ.object)return pQ(t,{code:X.invalid_type,expected:sQ.object,received:t.parsedType}),hQ;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(pQ(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),hQ)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=KQ(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...TQ(r)})}};function qQ(e,t){let n=cQ(e),r=cQ(t);if(e===t)return{valid:!0,data:e};if(n===sQ.object&&r===sQ.object){let n=oQ.objectKeys(t),r=oQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=qQ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===sQ.array&&r===sQ.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=qQ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===sQ.date&&r===sQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var JQ=class extends EQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(vQ(e)||vQ(r))return hQ;let i=qQ(e.value,r.value);return i.valid?((yQ(e)||yQ(r))&&t.dirty(),{status:t.value,value:i.data}):(pQ(n,{code:X.invalid_intersection_types}),hQ)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};JQ.create=(e,t,n)=>new JQ({left:e,right:t,typeName:Z.ZodIntersection,...TQ(n)});var YQ=class e extends EQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.array)return pQ(n,{code:X.invalid_type,expected:sQ.array,received:n.parsedType}),hQ;if(n.data.length<this._def.items.length)return pQ(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),hQ;!this._def.rest&&n.data.length>this._def.items.length&&(pQ(n,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new CQ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>mQ.mergeArray(t,e)):mQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};YQ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new YQ({items:e,typeName:Z.ZodTuple,rest:null,...TQ(t)})};var tye=class e extends EQ{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.object)return pQ(n,{code:X.invalid_type,expected:sQ.object,received:n.parsedType}),hQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new CQ(n,e,n.path,e)),value:a._parse(new CQ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?mQ.mergeObjectAsync(t,r):mQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof EQ?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...TQ(r)}):new e({keyType:AQ.create(),valueType:t,typeName:Z.ZodRecord,...TQ(n)})}},XQ=class extends EQ{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.map)return pQ(n,{code:X.invalid_type,expected:sQ.map,received:n.parsedType}),hQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new CQ(n,e,n.path,[a,`key`])),value:i._parse(new CQ(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return hQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return hQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};XQ.create=(e,t,n)=>new XQ({valueType:t,keyType:e,typeName:Z.ZodMap,...TQ(n)});var ZQ=class e extends EQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.set)return pQ(n,{code:X.invalid_type,expected:sQ.set,received:n.parsedType}),hQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(pQ(n,{code:X.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(pQ(n,{code:X.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return hQ;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new CQ(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:SQ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:SQ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZQ.create=(e,t)=>new ZQ({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...TQ(t)});var nye=class e extends EQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==sQ.function)return pQ(t,{code:X.invalid_type,expected:sQ.function,received:t.parsedType}),hQ;function n(e,n){return fQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,dQ(),uQ].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return fQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,dQ(),uQ].filter(e=>!!e),issueData:{code:X.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof r$){let e=this;return _Q(async function(...t){let o=new lQ([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return _Q(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new lQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new lQ([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:YQ.create(t).rest(zQ.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||YQ.create([]).rest(zQ.create()),returns:n||zQ.create(),typeName:Z.ZodFunction,...TQ(r)})}},QQ=class extends EQ{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};QQ.create=(e,t)=>new QQ({getter:e,typeName:Z.ZodLazy,...TQ(t)});var $Q=class extends EQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return pQ(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),hQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};$Q.create=(e,t)=>new $Q({value:e,typeName:Z.ZodLiteral,...TQ(t)});function e$(e,t){return new t$({values:e,typeName:Z.ZodEnum,...TQ(t)})}var t$=class e extends EQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return pQ(t,{expected:oQ.joinValues(n),received:t.parsedType,code:X.invalid_type}),hQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return pQ(t,{received:t.data,code:X.invalid_enum_value,options:n}),hQ}return _Q(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};t$.create=e$;var n$=class extends EQ{_parse(e){let t=oQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==sQ.string&&n.parsedType!==sQ.number){let e=oQ.objectValues(t);return pQ(n,{expected:oQ.joinValues(e),received:n.parsedType,code:X.invalid_type}),hQ}if(this._cache||=new Set(oQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=oQ.objectValues(t);return pQ(n,{received:n.data,code:X.invalid_enum_value,options:e}),hQ}return _Q(e.data)}get enum(){return this._def.values}};n$.create=(e,t)=>new n$({values:e,typeName:Z.ZodNativeEnum,...TQ(t)});var r$=class extends EQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==sQ.promise&&t.common.async===!1?(pQ(t,{code:X.invalid_type,expected:sQ.promise,received:t.parsedType}),hQ):_Q((t.parsedType===sQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};r$.create=(e,t)=>new r$({type:e,typeName:Z.ZodPromise,...TQ(t)});var i$=class extends EQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{pQ(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return hQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?hQ:r.status===`dirty`||t.value===`dirty`?gQ(r.value):r});{if(t.value===`aborted`)return hQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?hQ:r.status===`dirty`||t.value===`dirty`?gQ(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?hQ:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?hQ:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!bQ(e))return hQ;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>bQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):hQ);oQ.assertNever(r)}};i$.create=(e,t,n)=>new i$({schema:e,typeName:Z.ZodEffects,effect:t,...TQ(n)}),i$.createWithPreprocess=(e,t,n)=>new i$({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...TQ(n)});var a$=class extends EQ{_parse(e){return this._getType(e)===sQ.undefined?_Q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};a$.create=(e,t)=>new a$({innerType:e,typeName:Z.ZodOptional,...TQ(t)});var o$=class extends EQ{_parse(e){return this._getType(e)===sQ.null?_Q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};o$.create=(e,t)=>new o$({innerType:e,typeName:Z.ZodNullable,...TQ(t)});var s$=class extends EQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===sQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};s$.create=(e,t)=>new s$({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...TQ(t)});var c$=class extends EQ{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return xQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new lQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new lQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};c$.create=(e,t)=>new c$({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...TQ(t)});var l$=class extends EQ{_parse(e){if(this._getType(e)!==sQ.nan){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.nan,received:t.parsedType}),hQ}return{status:`valid`,value:e.data}}};l$.create=e=>new l$({typeName:Z.ZodNaN,...TQ(e)});var u$=class extends EQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},d$=class e extends EQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?hQ:e.status===`dirty`?(t.dirty(),gQ(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?hQ:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Z.ZodPipeline})}},f$=class extends EQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(bQ(e)&&(e.value=Object.freeze(e.value)),e);return xQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};f$.create=(e,t)=>new f$({innerType:e,typeName:Z.ZodReadonly,...TQ(t)}),WQ.lazycreate;var Z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Z||={}),AQ.create,jQ.create,l$.create,MQ.create,NQ.create,PQ.create,FQ.create,IQ.create,LQ.create,RQ.create,zQ.create,BQ.create,VQ.create,HQ.create;const rye=WQ.create;WQ.strictCreate,GQ.create,eye.create,JQ.create,YQ.create,tye.create,XQ.create,ZQ.create,nye.create,QQ.create,$Q.create,t$.create,n$.create,r$.create,i$.create,a$.create,o$.create,i$.createWithPreprocess,d$.create;const iye=pe(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);d.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>h(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>m(e,t,n),e.parseAsync=async(t,n)=>Ee(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>se(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>ce(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),aye=pe(`ZodMiniObject`,(e,t)=>{ae.init(e,t),iye.init(e,t),T(e,`shape`,()=>t.shape)});function p$(e,t){return new aye({type:`object`,shape:e??{},...r(t)})}function m$(e){return!!e._zod}function h$(e){let t=Object.values(e);if(t.length===0)return p$({});let n=t.every(m$),r=t.every(e=>!m$(e));if(n)return p$(e);if(r)return rye(e);throw Error(`Mixed Zod versions detected in object shape.`)}function g$(e,t){return m$(e)?m(e,t):e.safeParse(t)}async function _$(e,t){return m$(e)?await se(e,t):await e.safeParseAsync(t)}function v$(e){if(!e)return;let t;if(t=m$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function y$(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return h$(e)}}if(m$(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function b$(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function oye(e){return e.description}function sye(e){if(m$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function x$(e){if(m$(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const S$=`2025-11-25`,C$=[S$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],w$=`io.modelcontextprotocol/related-task`,T$=s(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),E$=p([u(),i().int()]),D$=u();ye({ttl:i().optional(),pollInterval:i().optional()});const cye=j({ttl:i().optional()}),lye=j({taskId:u()}),O$=ye({progressToken:E$.optional(),[w$]:lye.optional()}),k$=j({_meta:O$.optional()}),A$=k$.extend({task:cye.optional()}),uye=e=>A$.safeParse(e).success,j$=j({method:u(),params:k$.loose().optional()}),M$=j({_meta:O$.optional()}),N$=j({method:u(),params:M$.loose().optional()}),P$=ye({_meta:O$.optional()}),F$=p([u(),i().int()]),I$=j({jsonrpc:x(`2.0`),id:F$,...j$.shape}).strict(),L$=e=>I$.safeParse(e).success,R$=j({jsonrpc:x(`2.0`),...N$.shape}).strict(),dye=e=>R$.safeParse(e).success,z$=j({jsonrpc:x(`2.0`),id:F$,result:P$}).strict(),B$=e=>z$.safeParse(e).success;var V$;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(V$||={});const H$=j({jsonrpc:x(`2.0`),id:F$.optional(),error:j({code:i().int(),message:u(),data:_().optional()})}).strict(),U$=e=>H$.safeParse(e).success,W$=p([I$,R$,z$,H$]);p([z$,H$]);const G$=P$.strict(),fye=M$.extend({requestId:F$.optional(),reason:u().optional()}),K$=N$.extend({method:x(`notifications/cancelled`),params:fye}),q$=j({icons:M(j({src:u(),mimeType:u().optional(),sizes:M(u()).optional(),theme:Ne([`light`,`dark`]).optional()})).optional()}),J$=j({name:u(),title:u().optional()}),Y$=J$.extend({...J$.shape,...q$.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),pye=b(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,c(j({form:c(j({applyDefaults:D().optional()}),C(u(),_())).optional(),url:T$.optional()}),C(u(),_()).optional())),mye=ye({list:T$.optional(),cancel:T$.optional(),requests:ye({sampling:ye({createMessage:T$.optional()}).optional(),elicitation:ye({create:T$.optional()}).optional()}).optional()}),hye=ye({list:T$.optional(),cancel:T$.optional(),requests:ye({tools:ye({call:T$.optional()}).optional()}).optional()}),gye=j({experimental:C(u(),T$).optional(),sampling:j({context:T$.optional(),tools:T$.optional()}).optional(),elicitation:pye.optional(),roots:j({listChanged:D().optional()}).optional(),tasks:mye.optional(),extensions:C(u(),T$).optional()}),_ye=k$.extend({protocolVersion:u(),capabilities:gye,clientInfo:Y$}),X$=j$.extend({method:x(`initialize`),params:_ye}),Z$=e=>X$.safeParse(e).success,vye=j({experimental:C(u(),T$).optional(),logging:T$.optional(),completions:T$.optional(),prompts:j({listChanged:D().optional()}).optional(),resources:j({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:j({listChanged:D().optional()}).optional(),tasks:hye.optional(),extensions:C(u(),T$).optional()}),yye=P$.extend({protocolVersion:u(),capabilities:vye,serverInfo:Y$,instructions:u().optional()}),Q$=N$.extend({method:x(`notifications/initialized`),params:M$.optional()}),bye=e=>Q$.safeParse(e).success,$$=j$.extend({method:x(`ping`),params:k$.optional()}),xye=j({progress:i(),total:v(i()),message:v(u())}),Sye=j({...M$.shape,...xye.shape,progressToken:E$}),e1=N$.extend({method:x(`notifications/progress`),params:Sye}),Cye=k$.extend({cursor:D$.optional()}),t1=j$.extend({params:Cye.optional()}),n1=P$.extend({nextCursor:D$.optional()}),wye=Ne([`working`,`input_required`,`completed`,`failed`,`cancelled`]),r1=j({taskId:u(),status:wye,ttl:p([i(),Le()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:v(i()),statusMessage:v(u())}),i1=P$.extend({task:r1}),Tye=M$.merge(r1),a1=N$.extend({method:x(`notifications/tasks/status`),params:Tye}),o1=j$.extend({method:x(`tasks/get`),params:k$.extend({taskId:u()})}),s1=P$.merge(r1),c1=j$.extend({method:x(`tasks/result`),params:k$.extend({taskId:u()})});P$.loose();const l1=t1.extend({method:x(`tasks/list`)}),u1=n1.extend({tasks:M(r1)}),d1=j$.extend({method:x(`tasks/cancel`),params:k$.extend({taskId:u()})}),Eye=P$.merge(r1),f1=j({uri:u(),mimeType:v(u()),_meta:C(u(),_()).optional()}),p1=f1.extend({text:u()}),m1=u().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),h1=f1.extend({blob:m1}),g1=Ne([`user`,`assistant`]),_1=j({audience:M(g1).optional(),priority:i().min(0).max(1).optional(),lastModified:a({offset:!0}).optional()}),v1=j({...J$.shape,...q$.shape,uri:u(),description:v(u()),mimeType:v(u()),size:v(i()),annotations:_1.optional(),_meta:v(ye({}))}),Dye=j({...J$.shape,...q$.shape,uriTemplate:u(),description:v(u()),mimeType:v(u()),annotations:_1.optional(),_meta:v(ye({}))}),y1=t1.extend({method:x(`resources/list`)}),Oye=n1.extend({resources:M(v1)}),b1=t1.extend({method:x(`resources/templates/list`)}),kye=n1.extend({resourceTemplates:M(Dye)}),x1=k$.extend({uri:u()}),Aye=x1,S1=j$.extend({method:x(`resources/read`),params:Aye}),jye=P$.extend({contents:M(p([p1,h1]))}),Mye=N$.extend({method:x(`notifications/resources/list_changed`),params:M$.optional()}),Nye=x1,Pye=j$.extend({method:x(`resources/subscribe`),params:Nye}),Fye=x1,Iye=j$.extend({method:x(`resources/unsubscribe`),params:Fye}),Lye=M$.extend({uri:u()}),Rye=N$.extend({method:x(`notifications/resources/updated`),params:Lye}),zye=j({name:u(),description:v(u()),required:v(D())}),Bye=j({...J$.shape,...q$.shape,description:v(u()),arguments:v(M(zye)),_meta:v(ye({}))}),C1=t1.extend({method:x(`prompts/list`)}),Vye=n1.extend({prompts:M(Bye)}),Hye=k$.extend({name:u(),arguments:C(u(),u()).optional()}),w1=j$.extend({method:x(`prompts/get`),params:Hye}),T1=j({type:x(`text`),text:u(),annotations:_1.optional(),_meta:C(u(),_()).optional()}),E1=j({type:x(`image`),data:m1,mimeType:u(),annotations:_1.optional(),_meta:C(u(),_()).optional()}),D1=j({type:x(`audio`),data:m1,mimeType:u(),annotations:_1.optional(),_meta:C(u(),_()).optional()}),Uye=j({type:x(`tool_use`),name:u(),id:u(),input:C(u(),_()),_meta:C(u(),_()).optional()}),Wye=j({type:x(`resource`),resource:p([p1,h1]),annotations:_1.optional(),_meta:C(u(),_()).optional()}),O1=p([T1,E1,D1,v1.extend({type:x(`resource_link`)}),Wye]),Gye=j({role:g1,content:O1}),Kye=P$.extend({description:u().optional(),messages:M(Gye)}),qye=N$.extend({method:x(`notifications/prompts/list_changed`),params:M$.optional()}),Jye=j({title:u().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),Yye=j({taskSupport:Ne([`required`,`optional`,`forbidden`]).optional()}),k1=j({...J$.shape,...q$.shape,description:u().optional(),inputSchema:j({type:x(`object`),properties:C(u(),T$).optional(),required:M(u()).optional()}).catchall(_()),outputSchema:j({type:x(`object`),properties:C(u(),T$).optional(),required:M(u()).optional()}).catchall(_()).optional(),annotations:Jye.optional(),execution:Yye.optional(),_meta:C(u(),_()).optional()}),A1=t1.extend({method:x(`tools/list`)}),Xye=n1.extend({tools:M(k1)}),j1=P$.extend({content:M(O1).default([]),structuredContent:C(u(),_()).optional(),isError:D().optional()});j1.or(P$.extend({toolResult:_()}));const Zye=A$.extend({name:u(),arguments:C(u(),_()).optional()}),M1=j$.extend({method:x(`tools/call`),params:Zye}),Qye=N$.extend({method:x(`notifications/tools/list_changed`),params:M$.optional()});j({autoRefresh:D().default(!0),debounceMs:i().int().nonnegative().default(300)});const N1=Ne([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),$ye=k$.extend({level:N1}),P1=j$.extend({method:x(`logging/setLevel`),params:$ye}),ebe=M$.extend({level:N1,logger:u().optional(),data:_()}),tbe=N$.extend({method:x(`notifications/message`),params:ebe}),nbe=j({hints:M(j({name:u().optional()})).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),rbe=j({mode:Ne([`auto`,`required`,`none`]).optional()}),ibe=j({type:x(`tool_result`),toolUseId:u().describe(`The unique identifier for the corresponding tool call.`),content:M(O1).default([]),structuredContent:j({}).loose().optional(),isError:D().optional(),_meta:C(u(),_()).optional()}),abe=Fe(`type`,[T1,E1,D1]),F1=Fe(`type`,[T1,E1,D1,Uye,ibe]),obe=j({role:g1,content:p([F1,M(F1)]),_meta:C(u(),_()).optional()}),sbe=A$.extend({messages:M(obe),modelPreferences:nbe.optional(),systemPrompt:u().optional(),includeContext:Ne([`none`,`thisServer`,`allServers`]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:M(u()).optional(),metadata:T$.optional(),tools:M(k1).optional(),toolChoice:rbe.optional()}),cbe=j$.extend({method:x(`sampling/createMessage`),params:sbe}),I1=P$.extend({model:u(),stopReason:v(Ne([`endTurn`,`stopSequence`,`maxTokens`]).or(u())),role:g1,content:abe}),L1=P$.extend({model:u(),stopReason:v(Ne([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(u())),role:g1,content:p([F1,M(F1)])}),lbe=j({type:x(`boolean`),title:u().optional(),description:u().optional(),default:D().optional()}),ube=j({type:x(`string`),title:u().optional(),description:u().optional(),minLength:i().optional(),maxLength:i().optional(),format:Ne([`email`,`uri`,`date`,`date-time`]).optional(),default:u().optional()}),dbe=j({type:Ne([`number`,`integer`]),title:u().optional(),description:u().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),fbe=j({type:x(`string`),title:u().optional(),description:u().optional(),enum:M(u()),default:u().optional()}),pbe=j({type:x(`string`),title:u().optional(),description:u().optional(),oneOf:M(j({const:u(),title:u()})),default:u().optional()}),mbe=p([p([j({type:x(`string`),title:u().optional(),description:u().optional(),enum:M(u()),enumNames:M(u()).optional(),default:u().optional()}),p([fbe,pbe]),p([j({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:j({type:x(`string`),enum:M(u())}),default:M(u()).optional()}),j({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:j({anyOf:M(j({const:u(),title:u()}))}),default:M(u()).optional()})])]),lbe,ube,dbe]),hbe=p([A$.extend({mode:x(`form`).optional(),message:u(),requestedSchema:j({type:x(`object`),properties:C(u(),mbe),required:M(u()).optional()})}),A$.extend({mode:x(`url`),message:u(),elicitationId:u(),url:u().url()})]),gbe=j$.extend({method:x(`elicitation/create`),params:hbe}),_be=M$.extend({elicitationId:u()}),vbe=N$.extend({method:x(`notifications/elicitation/complete`),params:_be}),R1=P$.extend({action:Ne([`accept`,`decline`,`cancel`]),content:b(e=>e===null?void 0:e,C(u(),p([u(),i(),D(),M(u())])).optional())}),ybe=j({type:x(`ref/resource`),uri:u()}),bbe=j({type:x(`ref/prompt`),name:u()}),xbe=k$.extend({ref:p([bbe,ybe]),argument:j({name:u(),value:u()}),context:j({arguments:C(u(),u()).optional()}).optional()}),z1=j$.extend({method:x(`completion/complete`),params:xbe});function Sbe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Cbe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const wbe=P$.extend({completion:ye({values:M(u()).max(100),total:v(i().int()),hasMore:v(D())})}),Tbe=j({uri:u().startsWith(`file://`),name:u().optional(),_meta:C(u(),_()).optional()}),Ebe=j$.extend({method:x(`roots/list`),params:k$.optional()}),B1=P$.extend({roots:M(Tbe)}),Dbe=N$.extend({method:x(`notifications/roots/list_changed`),params:M$.optional()});p([$$,X$,z1,P1,w1,C1,y1,b1,S1,Pye,Iye,M1,A1,o1,c1,l1,d1]),p([K$,e1,Q$,Dbe,a1]),p([G$,I1,L1,R1,B1,s1,u1,i1]),p([$$,cbe,gbe,Ebe,o1,c1,l1,d1]),p([K$,e1,tbe,Rye,Mye,Qye,qye,a1,vbe]),p([G$,yye,wbe,Kye,Vye,Oye,kye,jye,j1,Xye,s1,u1,i1]);var V1=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===V$.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Obe(e.elicitations,n)}return new e(t,n,r)}},Obe=class extends V1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(V$.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function H1(e){return e===`completed`||e===`failed`||e===`cancelled`}const kbe=Symbol(`Let zodToJsonSchema decide on which parser to use`),U1={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},Abe=e=>typeof e==`string`?{...U1,name:e}:{...U1,...e},jbe=e=>{let t=Abe(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function W1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function G1(e,t,n,r,i){e[t]=n,W1(e,t,r,i)}const K1=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function q1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?K1(t,e.currentPath):t.join(`/`)}}function Mbe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=o0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&G1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&G1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(G1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),G1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Nbe(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?G1(n,`minimum`,r.value,r.message,t):G1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),G1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?G1(n,`maximum`,r.value,r.message,t):G1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),G1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:G1(n,`multipleOf`,r.value,r.message,t);break}return n}function Pbe(){return{type:`boolean`}}function J1(e,t){return o0(e.type._def,t)}const Fbe=(e,t)=>o0(e.innerType._def,t);function Y1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Y1(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Ibe(e,t)}}const Ibe=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:G1(n,`minimum`,r.value,r.message,t);break;case`max`:G1(n,`maximum`,r.value,r.message,t);break}return n};function Lbe(e,t){return{...o0(e.innerType._def,t),default:e.defaultValue()}}function Rbe(e,t){return t.effectStrategy===`input`?o0(e.schema._def,t):q1(t)}function zbe(e){return{type:`string`,enum:Array.from(e.values)}}const Bbe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Vbe(e,t){let n=[o0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),o0(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Bbe(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Hbe(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let X1;const Z1={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(X1===void 0&&(X1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),X1),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Q1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:G1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:G1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:e0(n,`email`,r.message,t);break;case`format:idn-email`:e0(n,`idn-email`,r.message,t);break;case`pattern:zod`:t0(n,Z1.email,r.message,t);break}break;case`url`:e0(n,`uri`,r.message,t);break;case`uuid`:e0(n,`uuid`,r.message,t);break;case`regex`:t0(n,r.regex,r.message,t);break;case`cuid`:t0(n,Z1.cuid,r.message,t);break;case`cuid2`:t0(n,Z1.cuid2,r.message,t);break;case`startsWith`:t0(n,RegExp(`^${$1(r.value,t)}`),r.message,t);break;case`endsWith`:t0(n,RegExp(`${$1(r.value,t)}$`),r.message,t);break;case`datetime`:e0(n,`date-time`,r.message,t);break;case`date`:e0(n,`date`,r.message,t);break;case`time`:e0(n,`time`,r.message,t);break;case`duration`:e0(n,`duration`,r.message,t);break;case`length`:G1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),G1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:t0(n,RegExp($1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&e0(n,`ipv4`,r.message,t),r.version!==`v4`&&e0(n,`ipv6`,r.message,t);break;case`base64url`:t0(n,Z1.base64url,r.message,t);break;case`jwt`:t0(n,Z1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&t0(n,Z1.ipv4Cidr,r.message,t),r.version!==`v4`&&t0(n,Z1.ipv6Cidr,r.message,t);break;case`emoji`:t0(n,Z1.emoji(),r.message,t);break;case`ulid`:t0(n,Z1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:e0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:G1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:t0(n,Z1.base64,r.message,t);break}break;case`nanoid`:t0(n,Z1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function $1(e,t){return t.patternStrategy===`escape`?Wbe(e):e}const Ube=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Wbe(e){let t=``;for(let n=0;n<e.length;n++)Ube.has(e[n])||(t+=`\\`),t+=e[n];return t}function e0(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):G1(e,`format`,t,n,r)}function t0(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:n0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):G1(e,`pattern`,n0(t,r),n,r)}function n0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
1173
|
+
`).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,`--`,t)).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await lr(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Ns=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Ps(e){try{let t=Qo(e.scope);if(!t)return;let n=zI(t);if(n.length===0)return;let r=GI(L(e.skillsRoot,e.name),e.name,t,n,`copy`,BI(e.scope));if(r.length===0)return;await SN(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){Y.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function Fs(e,t){if(t.ok){q(e,200,fte,t.body,{handler:`skill-import`});return}G(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let Is=x_e({contentDir:l,skillsHome:lo,...A===void 0?{}:{projectDir:A},resolveSkillDirForRead:ho,parseFrontmatterDoc:$a,attributeOkArtifactWrite:cr,commitOkArtifactWrite:lr,shadowHeadSha:Ms,artifactWriterId:Ns,effectiveInstallMode:jo,signalFiles:()=>k?.(`files`)}),Rs=K(Uo,async(e,t,n)=>{let r=()=>{};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l,u=n.source;{let e=n.source;try{let i=await qD(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??vD(d);if(!p){G(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(bX(t,p,`skill-import`))return;let m=await bD(p);r=m.cleanup,s=m.ref;let h=RD(m.dir);if(h.length===0){G(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let g=h[0];if(f){let e=h.find(e=>e.name===f)??h.find(e=>FD(e.dir)?.name===f)??h.find(e=>e.name===ca[f]);if(!e){G(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${f}" not among: ${h.map(e=>e.name).join(`, `)}.`});return}g=e}else if(h.length>1){G(t,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:h.map(e=>e.name).join(`, `)});return}a=g.dir,l=g.name,o=e,c=i?.publisher??Os(d)}catch(e){if(e instanceof rD){G(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){G(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await Is.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||Ka(u))&&AI({source:u,skills:[d.body.name]},lI()),await xe?.rebuildIgnorePatterns(),Fs(t,d)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),zs=K(Dee,async(e,t,n)=>{let r=()=>{};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l,u=i;try{let e=await qD(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??vD(d);if(!f){G(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(bX(t,f,`skills-import-bulk`))return;if(l=e?.publisher??Os(d),f.kind===`well-known`)a=f,o=await pD(f.origin);else{let e=await bD(f);r=e.cleanup,c=e.ref,s=RD(e.dir)}}catch(e){if(e instanceof rD){G(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){G(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let d=[];for(let t of new Set(n.skills)){let r,u,f=()=>{};if(a!==null)try{let e=await bD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof rD?`not-found`:`failed`,warnings:[],...e instanceof rD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>LD(e.dir)?.name===t)??s.find(e=>e.name===ca[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await Is.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){N(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}d.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings})}catch(e){N(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}if(n.marketplace===!0||Ka(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&AI({source:u,skills:e},lI())}await xe?.rebuildIgnorePatterns(),q(t,200,Ut,{results:d,imported:d.filter(e=>e.status===`imported`).length,alreadyImported:d.filter(e=>e.status===`already-imported`).length,failed:d.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),Bs=8*1024*1024,Vs=32*1024*1024;function Us(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=L(e,n);return r!==e&&!r.startsWith(e+R)?null:r}function qs(e){return new Promise((t,n)=>{let r;try{r=Oq(e,{files:200,fields:10,fieldSize:2*1024,fileSize:Bs})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>Vs){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function Js(e,t){return new Promise((n,r)=>{(0,tle.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=Us(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){Hs(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>Bs){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>Vs){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{Hs(P(n),{recursive:!0}),Zs(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function Xs(e,t){let n=Lu(F(ed(),`ok-skill-upload-`)),r=()=>{try{Ks(n,{recursive:!0,force:!0})}catch{}};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){G(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=co(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=dk({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},me);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await qs(e)}catch(e){G(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){G(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await Js(c.data,n)}catch(e){G(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=Us(n,e.relPath);if(!r){G(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}Hs(P(r),{recursive:!0}),Zs(r,e.data)}let u=RD(n);if(u.length===0){G(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){G(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];Fs(t,await Is.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let Qs=K(Nee,async(e,t,n)=>{try{let e=mo(n.scope);if(!so(n.name,t,`skill-install`))return;if(n.scope===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=Qo(n.scope),i=L(e,n.name),a=n.scope===`project`?l:lo,o=(n.scope===`project`?pL(l):mL(lo)).find(e=>e.name===n.name),s=o?L(a,o.dir):i;if(!z(s)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await Gt(n.scope===`project`?`${I(a,s).split(R).join(`/`)}/SKILL`:ji(n.scope,n.name));let c=RI(s,n.name,{allowReservedName:ZF(n.name)});if(!c.ok){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${c.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){G(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=fo.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:G(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:G(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:G(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:G(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:G(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,sr,{name:n.name,hosts:o.hosts.filter(bo),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){G(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await fo.applyAddRemove({scope:n.scope,name:n.name,inPlaceEntry:o,...n.add===void 0?{}:{add:n.add},...n.remove===void 0?{}:{remove:n.remove}});if(!e.ok){e.kind===`remove-source`?G(t,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`}):G(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(bo),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await fo.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:s,newSource:u});if(!e.ok){G(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,sr,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?A:lo;if(!e){G(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Mr.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:s,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?G(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):G(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in r||k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,sr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?A:lo;if(!e){G(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Mr.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:s});if(!r.ok)switch(r.kind){case`not-recorded`:G(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:G(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:G(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r.path});return;case`canonical-dir`:G(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r.path});return;default:throw Error(`Unhandled unplace outcome: ${String(r.kind)}`)}k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,sr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){G(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?A:lo,l=await Mr.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:s,canonicalHash:o.contentHash});if(!l.ok)switch(l.kind){case`invalid-location`:G(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:G(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:G(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:G(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(l.kind)}`)}k?.(`files`),q(t,200,sr,{name:n.name,hosts:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f===void 0?NI(lo).map(e=>e.editorId).filter(e=>wt.includes(e)):wt.filter(e=>f?.some(t=>t===e)):f===void 0?zI(r):wt.filter(e=>f?.some(t=>t===e)),g=[],_=[];if(h.length===0&&f===void 0&&(g.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),c.hasScripts&&(g.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),c.warnings.length>0&&(g.push(c.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=(f===void 0?n.scope===`global`&&z(F(lo,`.agents`)):f.includes(`agents`))?[...h,`agents`]:[...h],a=n.scope===`project`?A:lo,l=d===void 0?jo(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await fo.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,newSource:u});if(!e.ok){e.kind===`invalid-target`?G(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):G(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}k?.(`files`),q(t,200,sr,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await fo.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:f!==void 0,installMode:l,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){G(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),k?.(`files`),q(t,200,sr,{name:n.name,hosts:v.hosts,scripts:c.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=II(bN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&QI(n.name,r,v,BI(n.scope));let y=F(r,...xD),b=z(y)?B(y,`utf-8`):null,x=b===null?null:TD(b);b!==null&&x===null&&Y.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=GI(s,n.name,r,h,C,BI(n.scope));w.length===0?await CN(r,n.name):await SN(r,n.name,{hosts:w,scope:n.scope,scripts:c.hasScripts,installedAt:new Date().toISOString(),projection:C}),k?.(`files`),q(t,200,sr,{name:n.name,hosts:w,scripts:c.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),$s=K(Xt,async(e,t,n)=>{try{if(!so(n.name,t,`skill-uninstall`))return;let e=Qo(n.scope);if(!e){G(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await $o(e,n.name,n.scope);k?.(`files`),q(t,200,gr,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),ec=_W({GET:K(En,async(e,t)=>{try{let e=zI(A??``),n=(e,t)=>{let n=T_e(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};q(t,200,nee,{targets:e,configured:!1,folders:[...A?sX(l,oL(l,`project`)).filter(e=>cL(l,`project`,e.root)).map(e=>({...e,scope:`project`,...n(l,e)})):[],...sX(lo,oL(lo,`global`)).filter(e=>cL(lo,`global`,e.root)).map(e=>({...e,scope:`global`,...n(lo,e)}))]},{handler:`skill-targets-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:K(vee,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?l:lo;if(e.scope===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await E_e(r,i.join(`/`)),k?.(`files`),q(t,200,fs,{targets:zI(A??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(oL(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){G(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?w_e({base:r,folderRel:e.root,targetRootRel:a}):lX({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){G(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await fX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),k?.(`files`),q(t,200,fs,{targets:zI(A??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),tc=K(aee,async(e,t,n)=>{try{let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!so(n.name,t,`skill-restore`)||Ko(n.name,t,`skill-restore`))return;if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=E?.current;if(!r){G(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await SX({shadow:r,contentDir:l,contentRoot:ie??`.`,name:n.name,version:n.version,skillDirRel:Mo(n.name)});if(!i.ok){Oo(t,i,`skill-restore`);return}let a=[],o=RI(L(l,Mo(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),cr(e,ar(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await lr(`skill-restore`),k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,Fn,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),nc=K(Ze,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!so(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?lo:l,{root:a,dirRel:o,realDir:s}=us(n.scope,n.name),c=!o.startsWith(`${Tr}/`);if(s===null||!z(L(i,o,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=F(n.scope===`global`?lo:A,...xD),d=ks(u).skills[n.name];if(!d){let e=OD(n.name,LD(L(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:$_e(L(a,n.name))})??Ro(i,n.name);e&&(d=e)}if(!d){G(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await wJ(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),await xe?.rebuildIgnorePatterns(),q(t,200,fa,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=d.skill??n.name,i=ca[e],a=await qD(d.source,e).catch(async e=>{if(i===void 0)throw e;return qD(d.source,i)}),o=a?.source??MO(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??vD(o);if(!c){G(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if(bX(t,c,`skill-reimport`))return;let l=await bD(c);r=l.cleanup,f=l.ref;let u=RD(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>LD(e.dir)?.name===n.name)??u.find(e=>e.name===ca[s??n.name])??(u.length===1?u[0]:void 0);if(!m){G(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=ID(m.dir);if(h){G(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=LD(m.dir)}catch(e){if(e instanceof rD){G(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){G(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=oX(p);if(h){G(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=LD(L(a,n.name)),_=new Set(p.files.map(e=>e.relPath)),v=new Set((g?.files??[]).map(e=>e.relPath)),y=(d.files??(d.localHash!==void 0&&g?.contentHash===d.localHash?g.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(p.contentHash===d.contentHash&&y.length===0){await xe?.rebuildIgnorePatterns(),q(t,200,fa,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=$a(p.skillMd).body;if(n.dryRun){let e=LD(L(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&A)try{let e=fc({baseDir:A,timeout:{block:15e3}}),t=I(A,L(a,n.name)).split(R).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}await xe?.rebuildIgnorePatterns(),q(t,200,fa,{name:n.name,updated:!0,source:d.source,localBody:$a(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await wn(e,`deleted-upstream`)}let x=rj({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){G(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=oj({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:aX});if(!r.ok){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=sj({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){G(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(cr(e,ar(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await lr(`skill-reimport`));let C=js(a,n.name),w=n.scope===`project`?await Ms(Ns(e),o):void 0;await wJ(u,e=>ED(e,n.name,{...e.skills[n.name]??d,contentHash:p.contentHash,files:p.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:f,importedAt:new Date().toISOString()})),!c&&n.scope===`project`&&await Ps({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),k?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,fa,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),rc=K(Gn,async(e,t,n)=>{try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=dk(n,me);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!so(n.name,t,`skill-revert`)||Ko(n.name,t,`skill-revert`))return;if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=F(A,...xD),i=ks(r).skills[n.name];if(!i?.baselineRef){G(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=E?.current;if(!a){G(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await SX({shadow:a,contentDir:l,contentRoot:ie??`.`,name:n.name,version:i.baselineRef,skillDirRel:Mo(n.name)});if(!o.ok){Oo(t,o,`skill-revert`);return}cr(e,ar(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await lr(`skill-revert`);let s=L(l,Mo(n.name),`..`),c=js(s,n.name);await wJ(r,e=>ED(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===mo(`project`)&&await Ps({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),k?.(`files`),q(t,200,It,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function ic(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function ac(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let n=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return n.length>0?n:void 0}function oc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function sc(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let cc=y_e({contentDir:l,projectDir:A,getAllFilesIndex:g,getFileIndexGeneration:v,getSearchMaxEntries:sve,semanticSearch:Oe,getSemanticSimilarityFloor:ke,ready:we,getProjectSkillsRoot:()=>mo(`project`),parseFrontmatterDoc:$a});cc.prewarm();let lc=_W({GET:K(En,VB(async(e,t)=>{let n=Nc(e),r=n.get(`limit`),i=n.get(`query`)??``,a=ic(n.get(`intent`)),o=Yo(n.get(`ranking`)),s=ac(n.get(`scope`)??n.get(`scopes`)),c=oc(n.get(`semantic`)),l=sc(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}q(t,200,uo,await cc.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:K($ee,VB(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=ic(n.intent),a=Yo(n.ranking),o=ac(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=oc(n.semantic),l=sc(n.source);if(r.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}q(t,200,uo,await cc.buildSearchResponse({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),uc=K(En,VB(async(e,t)=>{q(t,200,lte,{...await DI(Zu())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function dc(e,t){if(r(e,t,{handler:`handoff`}))try{await cfe(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:nt.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:cS(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function mc(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await nN(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:cS(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let hc=K(dee,async(e,t,n)=>{try{if(!A){MF(`no-remote`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`no-remote`},{handler:jF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!tme(e,n.kind)){MF(`invalid-path`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`invalid-path`},{handler:jF});return}let r=ome(A);if(r===null){if(IF(A).kind===`no-remote`){MF(`no-remote`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`no-remote`},{handler:jF});return}MF(`detached-head`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`detached-head`},{handler:jF});return}let i=IF(A);if(i.kind===`no-remote`){MF(`no-remote`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`no-remote`},{handler:jF});return}if(i.kind===`non-github`){MF(`non-github-remote`,{kind:n.kind}),q(t,200,ba,{ok:!1,error:`non-github-remote`},{handler:jF});return}if(!dme(A,r)){MF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,ba,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:jF});return}let a=kZ(A,l);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&N(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let s;if(n.kind===`doc`)s=nme(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=rme(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${Bt(s)}`,u=await ime(A,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);MF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,ba,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:jF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:jF,cause:e})}},{handler:jF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:jF})}),gc=K(En,async(e,t)=>{try{if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:iB});return}let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`branch`),i=n.searchParams.get(`path`),a=n.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!ot(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:iB});return}if(!nB(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:iB});return}q(t,200,Tee,await rB(A,r,i,a),{handler:iB})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:iB,cause:e})}},{handler:iB,method:`GET`,skipBodyParse:!0});function _c(e,t,n){let r=e.split(`/`),i=t.split(`/`);if(n>=r.length||n>=i.length)return{verdict:`unknown`};for(let e=0;e<n;e+=1)if(r[e]!==i[e])return{verdict:`unknown`};return{verdict:`renamed`,renamedTo:i.slice(n).join(`/`)}}let vc=K(Lt,async(e,t,n)=>{try{if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:JF});return}if(!nB(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:JF});return}let e=await yme(A,n.branch,n.path,n.kind);q(t,200,on,e.verdict!==`renamed`||n.contentRootDepth===void 0?e:_c(n.path,e.renamedTo,n.contentRootDepth),{handler:JF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:JF,cause:e})}},{handler:JF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:JF})}),yc=K(At,async(e,t,n)=>{if(dk(n,me).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:lB});return}if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:lB});return}try{q(t,200,St,await pc(()=>dB(A,n.branch,{fastForward:n.fastForward===!0})),{handler:lB})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:lB,cause:e})}},{handler:lB,method:`POST`});async function bc(e){let[t,...n]=le,r=[...n,...e];return await new Promise((e,n)=>{let i=pu(t,r,JM({...hi,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},VF),s=[],c=[];i.stdout.on(`data`,e=>s.push(e)),i.stderr.on(`data`,e=>c.push(e)),i.on(`close`,t=>{if(clearTimeout(o),a){n(Error(`share subprocess timed out after ${VF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=qF(Buffer.concat(c).toString(`utf-8`)).slice(0,500);Y.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let xc=K(En,async(e,t)=>{if(!ze.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:RF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await bc([`share`,`owners`,`--json`]),n=fme(WF(e));KF(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,oee,n,{handler:RF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:RF,cause:e})}finally{ze.release(`/api/share/publish/owners`)}},{handler:RF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:RF})}),Cc=K(En,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!UF(r)||!HF(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:zF});return}if(!ze.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:zF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await bc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=pme(WF(e));KF(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,pa,n,{handler:zF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:zF,cause:e})}finally{ze.release(`/api/share/publish/name-check`)}},{handler:zF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:zF})}),wc=K(cee,async(e,t,n)=>{if(!A){KF(`publish-create`,`no-project`),q(t,200,Kn,{ok:!1,error:`no-project`},{handler:BF});return}if(!UF(n.owner)||!HF(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:BF});return}if(!ze.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:BF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,A,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await bc(e),i=gme(WF(r));KF(`publish-create`,i.ok?`ok`:i.error),i.ok&&ce?.()?.refreshRemote().catch(()=>{}),q(t,200,Kn,i,{handler:BF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BF,cause:e})}finally{ze.release(`/api/share/publish`)}},{handler:BF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:BF})}),Tc=K(Qn,async(e,t,n)=>{try{let e=N(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}q(t,200,He,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),Ec=A?zk(A):null;async function Oc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:cle(e.headers),previewUrl:null,port:Ec?Dc(Ec)?.port??0:0,singleFile:Fe};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,Gee,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function kc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Re?.()??{diagnostics:[]};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,fe,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let Ac=`local-op-embeddings-set-key`,jc=`local-op-embeddings-clear-key`,Mc=`/api/local-op/embeddings`;function Pc(){let e=je?.();return{projectDir:A??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let Fc=K(Mee,async(e,t,n)=>{if(!ze.tryAcquire(Mc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Ac,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=Pc();await new Qj(Ae).setForProject(e,r,n.key),Oe?.reloadCredential(),q(t,200,os,{keyPresent:!0},{handler:Ac,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Ac,cause:e})}finally{ze.release(Mc)}},{handler:Ac,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ac})}),Ic=K(En,async(e,t)=>{if(!ze.tryAcquire(Mc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:jc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=Pc();await new Qj(Ae).clearForProject(e,n),Oe?.reloadCredential(),q(t,200,os,{keyPresent:!1},{handler:jc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:jc,cause:e})}finally{ze.release(Mc)}},{handler:jc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:jc})}),Lc=`local-op-embeddings-test`,Rc=`/api/local-op/embeddings/test`,zc=K(En,async(e,t)=>{if(!ze.tryAcquire(Rc)){G(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Lc,extraHeaders:{"Retry-After":`5`}});return}try{let e=je?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await Gj(new Qj(Ae),A??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await ide({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};q(t,200,cte,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Lc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Lc,cause:e})}finally{ze.release(Rc)}},{handler:Lc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Lc})}),Bc=K(En,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Oe){let t=Oe.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=je?.()?.baseUrl??`https://api.openai.com/v1`,o=await Gj(new Qj(Ae),A??l,a),s=o.apiKey!==null,c=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,f=0;for(let[e]of m())!Zx(e)&&!Qx(e)&&!Cr(e)&&(f+=1);q(t,200,aa,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Vc=0;function Hc(){Vc+=1,k?.(`lint-config`)}let Uc=()=>`${Vc} ${t.getActiveBranch()} ${O?.readLocalTargetGeneration?.()??0}`;async function Wc(e,t){let n=Me?.()??Vt;try{let r=await Ha(e,RP(l,n,{docName:t,projectDir:A??l,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Pe?.()??`warning`;if(O&&a!==`off`&&!rS(t)){await ln(t,e,`lint-validation`);let r=pF({projectDir:A??l,contentDir:l,baseConfig:n,derivedDocumentIndex:O,linksValidation:a,admittedDocNames:en,docFilePathFor:e=>EZ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:EZ(l,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Gc(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=VP({projectDir:A??l,contentDir:l});return uP(t.schemas,n)}let Kc=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!RZ(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Me?.()??Vt,i=[],a=FP(l,n??void 0,e=>i.push(e)),o=LP(A??l,IP(r,a),e=>i.push(e));n===null&&i.push(...Gc(o)),q(t,200,es,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),qc=K(Cee,async(e,t,n)=>{let r;try{r=ZP(L(l),n.ruleId,n.value)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){G(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}Hc();try{let e=Me?.()??Vt,n=[],r=FP(l,void 0,e=>n.push(e)),i=LP(A??l,IP(e,r),e=>n.push(e));n.push(...Gc(i)),q(t,200,es,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),Jc=K(Vo,async(e,t,n)=>{let r;try{let e=L(A??l),t=n.parentPath??[];r=n.delete?cpe(e,n.file):n.field!==void 0&&n.removeField?ope(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?spe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?ipe(e,n.file,n.field,n.constraint,t):ape(e,n.file)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){G(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&k?.(`files`),Hc();try{let e=Me?.()??Vt,n=[],r=FP(l,void 0,e=>n.push(e)),i=LP(A??l,IP(e,r),e=>n.push(e));n.push(...Gc(i)),q(t,200,es,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),Yc=K(En,async(e,t)=>{try{let e=L(A??l),{schemas:n,truncated:r}=Pfe(e),i=new Set(n),a=!1;if(xe!==void 0){let t=gZ({contentDir:l,contentFilter:xe,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&Yi(a)){let t=I(e,L(l,a));!t.startsWith(`..`)&&!yu(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));q(t,200,dte,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),Xc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=s.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},Zc=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!RZ(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=EZ(l,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Me?.()??Vt,a=[],o=await BP({projectDir:A??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:Xc});q(t,200,yee,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof LM){G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),Qc=new oP,$c=yX();function el(e,t,n){let r=`${n} ${Uc()} ${t??``}`;return $c.run(r,()=>Dpe(e,{targetPath:t})).promise}function tl(e,t){G(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let nl=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!_Z(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Me?.()??Vt;q(t,200,jee,await HP({projectDir:A??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:Xc,cache:Qc,auditGeneration:Uc}),{handler:`lint-audit`})}catch(e){if(e instanceof zP){tl(t,`lint-audit`);return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),rl=K(En,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!_Z(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!_Z(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=EZ(l,o)??`${o}.md`}let s=Me?.()??Vt,c=await el(pF({projectDir:A??l,contentDir:l,baseConfig:s,liveSourceFor:Xc,derivedDocumentIndex:O??null,linksValidation:Pe?.(),admittedDocNames:en,docFilePathFor:e=>EZ(l,e),cache:Qc,auditGeneration:Uc}),i,oP.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){q(t,200,Dt,Epe(c),{handler:`audit`});return}q(t,200,yt,c,{handler:`audit`})}catch(e){if(e instanceof zP){tl(t,`audit`);return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),il=K(dt,async(t,n,r)=>{try{let t=yZ(r.docName,n,`lint-fix`);if(t===null)return;let i=Tt(t),a=dk(r,me);if(a.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,s=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Zx(i)||Qx(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=EZ(l,i);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}KM(L(l,f),l);let p=Me?.()??Vt,{stored:m}=tr(a.summary),h=await c.getSession(i,o,{displayName:s,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await tpe({projectDir:A??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Bo(d),n=Oa[t]??Vi(u??o);oe?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{lw(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,sw(h))},h.origin),a.kind!==`anonymous`&&Ej(i,o,s,u,void 0,a.kind===`agent`?er({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{oe?.touchMode(o,`idle`)}let t=await Gt(i);if(t?.kind===`failure`){Kt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){qt(n,`lint-fix`);return}Ht(i,`lint-fix`);try{b=await Ha(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,Y.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;q(n,200,Jo,{file:f,fixedCount:Math.max(0,v.length-b.length),diagnostics:b,errorCount:S,warningCount:C,...x?{warning:x}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof LM){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof gS){_S(n,e,`lint-fix`);return}if(e instanceof xS){wS(n,e,`lint-fix`);return}if(e instanceof yw){G(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Y.error({err:e},`[lint-fix] handler failed`),G(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),al=`link-preview`,ol=new TG({cacheDir:Fe?null:L(A??l,`.ok`,`local`,`link-previews`)}),sl=null,cl=()=>(sl??=ol.init(),sl),ll=Ie??gG;async function ul(e){let t=await ll(e);return t.ok?{ok:!0,metadata:await xG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:ll})}:{ok:!1,reason:t.reason}}let dl=()=>{try{return Le?.()===!0}catch{return!1}},fl=K(Kee,async(e,t,n)=>{try{if(!dl()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,Xe,{ok:!1,reason:`disabled`},{handler:al});return}await cl();let e=!1,r=await ol.load(n.url,()=>(e=!0,ul(n.url)));ol.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Y.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),q(t,200,Xe,i,{handler:al})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:al,cause:e})}},{handler:al,method:`POST`,preBodyGate:(e,t)=>{let n=OG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:al}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:al}),!1)}}),pl=vle({service:ct,getPrincipal:me,onChanged:()=>k?.(`comments`)}),ml=_W({GET:pl.list,POST:pl.create},{handler:`comments`}),hl=_W({GET:pl.read,POST:pl.mutate,DELETE:pl.remove},{handler:`comment`}),{handleSkillsSearch:gl,handleSkillsPopular:_l,handleSkillsPublisher:vl,handleSkillsDetail:yl,handleSkillsPreview:bl,handleSkillsDiscover:xl,handleSkillsResolveRef:Sl}=L_e({log:Y,skillsHome:lo,projectDir:A,contentDir:l,resolveSkillDirForRead:ho}),Cl={"/api/config":Oc,"/api/config/diagnostics":kc,"/api/generated-index/settings":_W({GET:K(En,async(e,t)=>{if(!d){G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-get`});return}q(t,200,IZ,d(),{handler:`generated-index-settings-get`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-get`,method:`GET`,skipBodyParse:!0}),POST:K(xve,async(e,t,n)=>{if(!f){G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-set`});return}q(t,200,IZ,await f(n.enabled),{handler:`generated-index-settings-set`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-set`,method:`POST`})},{handler:`generated-index-settings`}),"/api/comments":ml,"/api/comment":hl,"/api/asset":qr,"/api/asset-text":Yr,"/api/comment-counts":hr,"/api/link-preview":fl,"/api/folder-config":Va,"/api/saved-themes":Ua,"/api/saved-theme":Ja,"/api/template":ro,"/api/template/import":ao,"/api/templates":Qa,"/api/skill":vs,"/api/skill-file":Es,"/api/skill-file/rename":Ds,"/api/skills":as,"/api/skills/installed":mr,"/api/skills/search":gl,"/api/skills/popular":_l,"/api/skills/publisher":vl,"/api/skills/detail":yl,"/api/skills/preview":bl,"/api/skills/discover":xl,"/api/skills/resolve-ref":Sl,"/api/skill/import":Rs,"/api/skills/import-bulk":zs,"/api/skill/edit-external":hs,"/api/skill/duplicate":_s,"/api/skill/move-scope":gs,"/api/skill-upload":Xs,"/api/skill/install":Qs,"/api/skill/uninstall":$s,"/api/skill/restore":tc,"/api/skill/reimport":nc,"/api/skill/revert":rc,"/api/skill/track-in-git":rs,"/api/skill-targets":ec,"/api/search":lc,"/api/semantic-status":Bc,"/api/lint/config":Kc,"/api/lint/markdownlint-config":qc,"/api/lint/frontmatter-schema":Jc,"/api/lint/frontmatter-schemas":Yc,"/api/lint":Zc,"/api/lint/audit":nl,"/api/lint/fix":il,"/api/audit":rl,"/api/create-page":Zr,"/api/create-folder":ei,"/api/duplicate-path":ai,"/api/rename-path":oi,"/api/delete-path":si,"/api/trash/cleanup":ci,"/api/upload":li,"/api/agent-write":ur,"/api/agent-write-md":dr,"/api/agent-write-batch":fr,"/api/frontmatter-patch":pr,"/api/agent-patch":vr,"/api/agent-undo":yr,"/api/agent-activity":xr,"/api/agent-burst-diff":Er,"/api/save-version":Nr,"/api/history":Pr,"/api/rollback":Lr,"/api/__embed-detect":Hr,"/api/server-info":Rr,"/api/acp/catalog":Br,"/api/share/construct-url":hc,"/api/share/target-status":vc,"/api/git/branch-info":gc,"/api/git/checkout":yc,"/api/share/publish/owners":xc,"/api/share/publish/name-check":Cc,"/api/share/publish":wc,"/api/principal":Vr,"/api/rescue":Xr,"/api/workspace":Wr,"/api/sync/status":xa,"/api/sync/trigger":Sa,"/api/sync/conflicts":Ca,"/api/sync/conflict-content":Ta,"/api/sync/resolve-conflict":wa,"/api/local-op/clone":yi,"/api/local-op/ok-init":wi,"/api/local-op/auth/login":zi,"/api/local-op/auth/status":Ji,"/api/local-op/auth/pat":ea,"/api/local-op/auth/gh-login":Ui,"/api/local-op/auth/cancel":Ki,"/api/local-op/auth/repos":na,"/api/local-op/auth/signout":la,"/api/local-op/auth/set-identity":va,"/api/local-op/embeddings/set-key":Fc,"/api/local-op/embeddings/clear-key":Ic,"/api/local-op/embeddings/test":zc,"/api/installed-agents":Na,"/api/spawn-cursor":mc,"/api/handoff":dc,"/api/install-skill":Ma,"/api/skill/install-state":uc,"/api/seed/plan":Ea,"/api/seed/apply":Da,"/api/seed/install-pack-skill":ka,"/api/seed/packs":Aa,"/api/client-logs":Tc};T&&(Cl[`/api/test-reset`]=Or,Cl[`/api/test-flush-git`]=Dr,Cl[`/api/test-rescan-backlinks`]=kr,Cl[`/api/test-rescan-files`]=Ar);let wl=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/generated-index/settings./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/saved-theme./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skill/track-in-git./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/seed/install-pack-skill./api/client-logs`.split(`.`)),Tl=[`/api/local-op/`],El=BB({log:Y,policy:n,ephemeral:Fe,table:{resolve(e){let t=Cl[e];if(t)return{template:e,dispatch:(e,n)=>t(e,n)};if(e.startsWith(`/api/history/`)){let t=e.slice(13);return{template:`/api/history/:sha`,dispatch:t?async(e,n)=>{await Ir(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>wl.has(e)||Tl.some(t=>e.startsWith(t))}}),Dl=pW({hocuspocus:s,derivedDocumentIndex:O,getFileIndex:m,isSafeDocName:RZ,readPageTitleForDocName:lt,readPageTitleForLinkedDocName:pt,readFrontmatterMetadataForLinkedDocName:vt,collectAdmittedDocNames:en,resolveAlias:Tt,respondToDerivedIndexQueryFailure:dn}),Ol=[Dl,vW({hocuspocus:s,agentPresenceBroadcaster:oe,isAllowedWorkspaceHostHeader:a,log:Y}),Ve],kl=Ol.flatMap(e=>[...e.paths]);BU(kl,Cl);let Al=Ol.map(e=>BB({log:Y,policy:n,ephemeral:Fe,table:e.table})),jl={paths:kl,dispatch:async(e,t)=>{for(let n of Al)if(await n(e,t))return!0;return!1}},Ml=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]);for(let e of Ml)if(Cl[e]===void 0&&Dl.table.resolve(e)?.dispatch===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await El(e,t)},nativeApi:jl,localApi:gW({resolve:e=>{if(!Ml.has(e))return;let t=Cl[e];return t===void 0?Dl.table.resolve(e)?.dispatch:t}})}}function BZ(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a,ingressPolicy:o}=e;return(e,s,c)=>{let l;try{l=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return c()}let u=vu(l).slice(1).toLowerCase(),d=u===`md`||u===`mdx`;if(!l||t.isPathIgnored(l)||!d&&!i.has(u))return c();let f=e.socket?.remoteAddress;if(f!==void 0&&!AB(f,o)){G(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!MB(e.headers.host,o)){G(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:TB});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=XY(u,r);d||s.setHeader(`Content-Disposition`,p.disposition),p.csp!==null&&s.setHeader(`Content-Security-Policy`,p.csp),p.sandboxedHtml&&s.setHeader(`Cache-Control`,`no-store`),n(e,s,()=>{if(s.headersSent)return;let e=Oe.has(u);if(!e&&(i.has(u)||a.has(u))){s.statusCode=404,s.end();return}e&&(s.removeHeader(`Content-Security-Policy`),s.removeHeader(`Content-Disposition`),s.removeHeader(`X-Content-Type-Options`),s.removeHeader(`Cache-Control`)),c()})}}function VZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function Cve(e){let t;try{t=Hu(e.contentDir,{withFileTypes:!0})}catch(t){let n=VZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Bx(n.name,w)&&e.basenameIndex.add(n.name)}async function HZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await ad(i,{withFileTypes:!0})}catch(t){let n=VZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=F(i,o.name),s=HM(I(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await rd(a)}catch(t){let n=VZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await od(a)}catch(t){let n=VZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!UM(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await sd(i)}catch(t){let n=VZ(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(o.ino))continue;n.add(o.ino),o.isDirectory()?await r(i):o.isFile()&&Bx(a,de)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(c.ino))continue;n.add(c.ino),await r(a);continue}c.isFile()&&Bx(a,de)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const UZ=j({principalId:u().optional(),tabSessionId:u().optional(),expectedServerInstanceId:u().optional(),expectedBranch:u().optional(),expectedDocLineageEpoch:u().optional(),clientProtocolVersion:i().optional(),clientRuntimeVersion:u().optional(),clientKind:u().optional()}).loose(),WZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function GZ(e){return WZ.includes(e)}function KZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function wve(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!GZ(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var qZ=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=KZ(e,this.payload)}};function JZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=UZ.safeParse(t);return n.success?n.data:void 0}var YZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const XZ=N(`conflict-storage`);var ZZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=F(zk(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!z(this.storePath)){this.conflicts=[];return}try{let e=B(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){XZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){XZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=P(this.storePath);z(e)||Iu(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return Yu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return XZ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-B0ZVs8y7.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=L(this.projectDir),r=L(t,e);if(!UM(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);_L(r,t),Zs(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),XZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Wb(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){XZ.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),XZ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=L(this.projectDir),a=L(i,e.file);if(!UM(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(_L(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-B0ZVs8y7.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);_L(a,i),Zs(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);Zs(a,n,`utf-8`);break;case`delete`:z(a)&&Ls(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function Tve(e,t){let n=e instanceof Error?{name:e.name,message:e.message,stack:e.stack??null}:{name:`NonError`,message:String(e),stack:null};return{timestamp:new Date().toISOString(),origin:t,error:n,pid:process.pid,uptimeSec:Math.round(process.uptime()*1e3)/1e3}}function Eve(e,t){let n=zk(e);try{Iu(n,{recursive:!0}),Yu(F(n,mo),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=sc(e);Iu(P(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};Yu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const QZ=new Map;let $Z=!1;function Dve(e,t){try{let n=Tve(e,t);for(let e of QZ.keys())Eve(e,n)}catch{}}function Ove(e){QZ.set(e,(QZ.get(e)??0)+1),$Z||($Z=!0,process.on(`uncaughtExceptionMonitor`,Dve));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=QZ.get(e)??0;n<=1?QZ.delete(e):QZ.set(e,n-1)}}}function eQ(e){let t=e.scheduler??Bi,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function tQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nQ(e){if(!z(e))return{};let t;try{t=(0,sk.parse)(B(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!tQ(t))return{};let n=t.telemetry;if(!tQ(n))return{};let r=n.localSink;return tQ(r)?r:{}}function rQ(e){return typeof e==`boolean`?e:void 0}function kve(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function iQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function aQ(e){if(tQ(e))return kve(e.maxBytes)}function Ave(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=nQ(Vs(`project`,e.projectDir)),n=nQ(Vs(`project-local`,e.projectDir));if((rQ(n.enabled)??rQ(t.enabled)??!0)===!1)return null;let r=aQ(n.spans)??aQ(t.spans)??52428800,i=aQ(n.logs)??aQ(t.logs)??26214400,a=iQ(n.attributeDenylist)??iQ(t.attributeDenylist)??ve;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var oQ;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(oQ||={});var jve;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(jve||={});const sQ=oQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),cQ=e=>{switch(typeof e){case`undefined`:return sQ.undefined;case`string`:return sQ.string;case`number`:return Number.isNaN(e)?sQ.nan:sQ.number;case`boolean`:return sQ.boolean;case`function`:return sQ.function;case`bigint`:return sQ.bigint;case`symbol`:return sQ.symbol;case`object`:return Array.isArray(e)?sQ.array:e===null?sQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?sQ.promise:typeof Map<`u`&&e instanceof Map?sQ.map:typeof Set<`u`&&e instanceof Set?sQ.set:typeof Date<`u`&&e instanceof Date?sQ.date:sQ.object;default:return sQ.unknown}},X=oQ.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var lQ=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,oQ.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};lQ.create=e=>new lQ(e);const uQ=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===sQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,oQ.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${oQ.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${oQ.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${oQ.joinValues(e.options)}, received '${e.received}'`;break;case X.invalid_arguments:n=`Invalid function arguments`;break;case X.invalid_return_type:n=`Invalid function return type`;break;case X.invalid_date:n=`Invalid date`;break;case X.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:oQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case X.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case X.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case X.custom:n=`Invalid input`;break;case X.invalid_intersection_types:n=`Intersection results could not be merged`;break;case X.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case X.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,oQ.assertNever(e)}return{message:n}};let Mve=uQ;function dQ(){return Mve}const fQ=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function pQ(e,t){let n=dQ(),r=fQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===uQ?void 0:uQ].filter(e=>!!e)});e.common.issues.push(r)}var mQ=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return hQ;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return hQ;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const hQ=Object.freeze({status:`aborted`}),gQ=e=>({status:`dirty`,value:e}),_Q=e=>({status:`valid`,value:e}),vQ=e=>e.status===`aborted`,yQ=e=>e.status===`dirty`,bQ=e=>e.status===`valid`,xQ=e=>typeof Promise<`u`&&e instanceof Promise;var SQ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(SQ||={});var CQ=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const wQ=(e,t)=>{if(bQ(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new lQ(e.common.issues);return this._error=t,this._error}}};function TQ(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var EQ=class{get description(){return this._def.description}_getType(e){return cQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:cQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new mQ,ctx:{common:e.parent.common,data:e.data,parsedType:cQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(xQ(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:cQ(e)};return wQ(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:cQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return bQ(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>bQ(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:cQ(e)},r=this._parse({data:e,path:n.path,parent:n});return wQ(n,await(xQ(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:X.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new i$({schema:this,typeName:Z.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return a$.create(this,this._def)}nullable(){return o$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return HQ.create(this)}promise(){return r$.create(this,this._def)}or(e){return GQ.create([this,e],this._def)}and(e){return JQ.create(this,e,this._def)}transform(e){return new i$({...TQ(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new s$({...TQ(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new u$({typeName:Z.ZodBranded,type:this,...TQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new c$({...TQ(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return d$.create(this,e)}readonly(){return f$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Nve=/^c[^\s-]{8,}$/i,Pve=/^[0-9a-z]+$/,Fve=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ive=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Lve=/^[a-z0-9_-]{21}$/i,Rve=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zve=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Bve=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let DQ;const Vve=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Hve=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Uve=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Wve=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Gve=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Kve=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,OQ=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,qve=RegExp(`^${OQ}$`);function kQ(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Jve(e){return RegExp(`^${kQ(e)}$`)}function Yve(e){let t=`${OQ}T${kQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Xve(e,t){return!!((t===`v4`||!t)&&Vve.test(e)||(t===`v6`||!t)&&Uve.test(e))}function Zve(e,t){if(!Rve.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Qve(e,t){return!!((t===`v4`||!t)&&Hve.test(e)||(t===`v6`||!t)&&Wve.test(e))}var AQ=class e extends EQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==sQ.string){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.string,received:t.parsedType}),hQ}let t=new mQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?pQ(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&pQ(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Bve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)DQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),DQ.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Ive.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Lve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Nve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Pve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Fve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`ulid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),pQ(n,{validation:`url`,code:X.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`regex`,code:X.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Yve(r).test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?qve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Jve(r).test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?zve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Xve(e.data,r.version)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Zve(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Qve(e.data,r.version)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Gve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Kve.test(e.data)||(n=this._getOrReturnCtx(e,n),pQ(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):oQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:X.invalid_string,...SQ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...SQ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...SQ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...SQ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...SQ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...SQ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...SQ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...SQ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...SQ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...SQ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...SQ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...SQ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...SQ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...SQ.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...SQ.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...SQ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...SQ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...SQ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...SQ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...SQ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...SQ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...SQ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...SQ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...SQ.errToObj(t)})}nonempty(e){return this.min(1,SQ.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};AQ.create=e=>new AQ({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...TQ(e)});function $ve(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var jQ=class e extends EQ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==sQ.number){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.number,received:t.parsedType}),hQ}let t,n=new mQ;for(let r of this._def.checks)r.kind===`int`?oQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?$ve(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.not_finite,message:r.message}),n.dirty()):oQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,SQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,SQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,SQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,SQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:SQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:SQ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:SQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:SQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:SQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:SQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:SQ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:SQ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:SQ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:SQ.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&oQ.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};jQ.create=e=>new jQ({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...TQ(e)});var MQ=class e extends EQ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==sQ.bigint)return this._getInvalidInput(e);let t,n=new mQ;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),pQ(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):oQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.bigint,received:t.parsedType}),hQ}gte(e,t){return this.setLimit(`min`,e,!0,SQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,SQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,SQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,SQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:SQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:SQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:SQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:SQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:SQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:SQ.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};MQ.create=e=>new MQ({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...TQ(e)});var NQ=class extends EQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==sQ.boolean){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.boolean,received:t.parsedType}),hQ}return _Q(e.data)}};NQ.create=e=>new NQ({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...TQ(e)});var PQ=class e extends EQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==sQ.date){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.date,received:t.parsedType}),hQ}if(Number.isNaN(e.data.getTime()))return pQ(this._getOrReturnCtx(e),{code:X.invalid_date}),hQ;let t=new mQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),pQ(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):oQ.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:SQ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:SQ.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};PQ.create=e=>new PQ({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...TQ(e)});var FQ=class extends EQ{_parse(e){if(this._getType(e)!==sQ.symbol){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.symbol,received:t.parsedType}),hQ}return _Q(e.data)}};FQ.create=e=>new FQ({typeName:Z.ZodSymbol,...TQ(e)});var IQ=class extends EQ{_parse(e){if(this._getType(e)!==sQ.undefined){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.undefined,received:t.parsedType}),hQ}return _Q(e.data)}};IQ.create=e=>new IQ({typeName:Z.ZodUndefined,...TQ(e)});var LQ=class extends EQ{_parse(e){if(this._getType(e)!==sQ.null){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.null,received:t.parsedType}),hQ}return _Q(e.data)}};LQ.create=e=>new LQ({typeName:Z.ZodNull,...TQ(e)});var RQ=class extends EQ{constructor(){super(...arguments),this._any=!0}_parse(e){return _Q(e.data)}};RQ.create=e=>new RQ({typeName:Z.ZodAny,...TQ(e)});var zQ=class extends EQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _Q(e.data)}};zQ.create=e=>new zQ({typeName:Z.ZodUnknown,...TQ(e)});var BQ=class extends EQ{_parse(e){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.never,received:t.parsedType}),hQ}};BQ.create=e=>new BQ({typeName:Z.ZodNever,...TQ(e)});var VQ=class extends EQ{_parse(e){if(this._getType(e)!==sQ.undefined){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.void,received:t.parsedType}),hQ}return _Q(e.data)}};VQ.create=e=>new VQ({typeName:Z.ZodVoid,...TQ(e)});var HQ=class e extends EQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==sQ.array)return pQ(t,{code:X.invalid_type,expected:sQ.array,received:t.parsedType}),hQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(pQ(t,{code:e?X.too_big:X.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(pQ(t,{code:X.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(pQ(t,{code:X.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new CQ(t,e,t.path,n)))).then(e=>mQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new CQ(t,e,t.path,n)));return mQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:SQ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:SQ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:SQ.toString(n)}})}nonempty(e){return this.min(1,e)}};HQ.create=(e,t)=>new HQ({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...TQ(t)});function UQ(e){if(e instanceof WQ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=a$.create(UQ(r))}return new WQ({...e._def,shape:()=>t})}else if(e instanceof HQ)return new HQ({...e._def,type:UQ(e.element)});else if(e instanceof a$)return a$.create(UQ(e.unwrap()));else if(e instanceof o$)return o$.create(UQ(e.unwrap()));else if(e instanceof YQ)return YQ.create(e.items.map(e=>UQ(e)));else return e}var WQ=class e extends EQ{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=oQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==sQ.object){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.object,received:t.parsedType}),hQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof BQ&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new CQ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof BQ){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(pQ(n,{code:X.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new CQ(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>mQ.mergeObjectSync(t,e)):mQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return SQ.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:SQ.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of oQ.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of oQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return UQ(this)}partial(t){let n={};for(let e of oQ.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of oQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof a$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return e$(oQ.objectKeys(this.shape))}};WQ.create=(e,t)=>new WQ({shape:()=>e,unknownKeys:`strip`,catchall:BQ.create(),typeName:Z.ZodObject,...TQ(t)}),WQ.strictCreate=(e,t)=>new WQ({shape:()=>e,unknownKeys:`strict`,catchall:BQ.create(),typeName:Z.ZodObject,...TQ(t)}),WQ.lazycreate=(e,t)=>new WQ({shape:e,unknownKeys:`strip`,catchall:BQ.create(),typeName:Z.ZodObject,...TQ(t)});var GQ=class extends EQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new lQ(e.ctx.common.issues));return pQ(t,{code:X.invalid_union,unionErrors:n}),hQ}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new lQ(e));return pQ(t,{code:X.invalid_union,unionErrors:i}),hQ}}get options(){return this._def.options}};GQ.create=(e,t)=>new GQ({options:e,typeName:Z.ZodUnion,...TQ(t)});const KQ=e=>e instanceof QQ?KQ(e.schema):e instanceof i$?KQ(e.innerType()):e instanceof $Q?[e.value]:e instanceof t$?e.options:e instanceof n$?oQ.objectValues(e.enum):e instanceof s$?KQ(e._def.innerType):e instanceof IQ?[void 0]:e instanceof LQ?[null]:e instanceof a$?[void 0,...KQ(e.unwrap())]:e instanceof o$?[null,...KQ(e.unwrap())]:e instanceof u$||e instanceof f$?KQ(e.unwrap()):e instanceof c$?KQ(e._def.innerType):[];var eye=class e extends EQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==sQ.object)return pQ(t,{code:X.invalid_type,expected:sQ.object,received:t.parsedType}),hQ;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(pQ(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),hQ)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=KQ(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...TQ(r)})}};function qQ(e,t){let n=cQ(e),r=cQ(t);if(e===t)return{valid:!0,data:e};if(n===sQ.object&&r===sQ.object){let n=oQ.objectKeys(t),r=oQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=qQ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===sQ.array&&r===sQ.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=qQ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===sQ.date&&r===sQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var JQ=class extends EQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(vQ(e)||vQ(r))return hQ;let i=qQ(e.value,r.value);return i.valid?((yQ(e)||yQ(r))&&t.dirty(),{status:t.value,value:i.data}):(pQ(n,{code:X.invalid_intersection_types}),hQ)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};JQ.create=(e,t,n)=>new JQ({left:e,right:t,typeName:Z.ZodIntersection,...TQ(n)});var YQ=class e extends EQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.array)return pQ(n,{code:X.invalid_type,expected:sQ.array,received:n.parsedType}),hQ;if(n.data.length<this._def.items.length)return pQ(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),hQ;!this._def.rest&&n.data.length>this._def.items.length&&(pQ(n,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new CQ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>mQ.mergeArray(t,e)):mQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};YQ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new YQ({items:e,typeName:Z.ZodTuple,rest:null,...TQ(t)})};var tye=class e extends EQ{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.object)return pQ(n,{code:X.invalid_type,expected:sQ.object,received:n.parsedType}),hQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new CQ(n,e,n.path,e)),value:a._parse(new CQ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?mQ.mergeObjectAsync(t,r):mQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof EQ?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...TQ(r)}):new e({keyType:AQ.create(),valueType:t,typeName:Z.ZodRecord,...TQ(n)})}},XQ=class extends EQ{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.map)return pQ(n,{code:X.invalid_type,expected:sQ.map,received:n.parsedType}),hQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new CQ(n,e,n.path,[a,`key`])),value:i._parse(new CQ(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return hQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return hQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};XQ.create=(e,t,n)=>new XQ({valueType:t,keyType:e,typeName:Z.ZodMap,...TQ(n)});var ZQ=class e extends EQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.set)return pQ(n,{code:X.invalid_type,expected:sQ.set,received:n.parsedType}),hQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(pQ(n,{code:X.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(pQ(n,{code:X.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return hQ;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new CQ(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:SQ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:SQ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZQ.create=(e,t)=>new ZQ({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...TQ(t)});var nye=class e extends EQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==sQ.function)return pQ(t,{code:X.invalid_type,expected:sQ.function,received:t.parsedType}),hQ;function n(e,n){return fQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,dQ(),uQ].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return fQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,dQ(),uQ].filter(e=>!!e),issueData:{code:X.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof r$){let e=this;return _Q(async function(...t){let o=new lQ([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return _Q(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new lQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new lQ([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:YQ.create(t).rest(zQ.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||YQ.create([]).rest(zQ.create()),returns:n||zQ.create(),typeName:Z.ZodFunction,...TQ(r)})}},QQ=class extends EQ{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};QQ.create=(e,t)=>new QQ({getter:e,typeName:Z.ZodLazy,...TQ(t)});var $Q=class extends EQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return pQ(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),hQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};$Q.create=(e,t)=>new $Q({value:e,typeName:Z.ZodLiteral,...TQ(t)});function e$(e,t){return new t$({values:e,typeName:Z.ZodEnum,...TQ(t)})}var t$=class e extends EQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return pQ(t,{expected:oQ.joinValues(n),received:t.parsedType,code:X.invalid_type}),hQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return pQ(t,{received:t.data,code:X.invalid_enum_value,options:n}),hQ}return _Q(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};t$.create=e$;var n$=class extends EQ{_parse(e){let t=oQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==sQ.string&&n.parsedType!==sQ.number){let e=oQ.objectValues(t);return pQ(n,{expected:oQ.joinValues(e),received:n.parsedType,code:X.invalid_type}),hQ}if(this._cache||=new Set(oQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=oQ.objectValues(t);return pQ(n,{received:n.data,code:X.invalid_enum_value,options:e}),hQ}return _Q(e.data)}get enum(){return this._def.values}};n$.create=(e,t)=>new n$({values:e,typeName:Z.ZodNativeEnum,...TQ(t)});var r$=class extends EQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==sQ.promise&&t.common.async===!1?(pQ(t,{code:X.invalid_type,expected:sQ.promise,received:t.parsedType}),hQ):_Q((t.parsedType===sQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};r$.create=(e,t)=>new r$({type:e,typeName:Z.ZodPromise,...TQ(t)});var i$=class extends EQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{pQ(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return hQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?hQ:r.status===`dirty`||t.value===`dirty`?gQ(r.value):r});{if(t.value===`aborted`)return hQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?hQ:r.status===`dirty`||t.value===`dirty`?gQ(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?hQ:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?hQ:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!bQ(e))return hQ;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>bQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):hQ);oQ.assertNever(r)}};i$.create=(e,t,n)=>new i$({schema:e,typeName:Z.ZodEffects,effect:t,...TQ(n)}),i$.createWithPreprocess=(e,t,n)=>new i$({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...TQ(n)});var a$=class extends EQ{_parse(e){return this._getType(e)===sQ.undefined?_Q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};a$.create=(e,t)=>new a$({innerType:e,typeName:Z.ZodOptional,...TQ(t)});var o$=class extends EQ{_parse(e){return this._getType(e)===sQ.null?_Q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};o$.create=(e,t)=>new o$({innerType:e,typeName:Z.ZodNullable,...TQ(t)});var s$=class extends EQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===sQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};s$.create=(e,t)=>new s$({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...TQ(t)});var c$=class extends EQ{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return xQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new lQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new lQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};c$.create=(e,t)=>new c$({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...TQ(t)});var l$=class extends EQ{_parse(e){if(this._getType(e)!==sQ.nan){let t=this._getOrReturnCtx(e);return pQ(t,{code:X.invalid_type,expected:sQ.nan,received:t.parsedType}),hQ}return{status:`valid`,value:e.data}}};l$.create=e=>new l$({typeName:Z.ZodNaN,...TQ(e)});var u$=class extends EQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},d$=class e extends EQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?hQ:e.status===`dirty`?(t.dirty(),gQ(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?hQ:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Z.ZodPipeline})}},f$=class extends EQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(bQ(e)&&(e.value=Object.freeze(e.value)),e);return xQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};f$.create=(e,t)=>new f$({innerType:e,typeName:Z.ZodReadonly,...TQ(t)}),WQ.lazycreate;var Z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Z||={}),AQ.create,jQ.create,l$.create,MQ.create,NQ.create,PQ.create,FQ.create,IQ.create,LQ.create,RQ.create,zQ.create,BQ.create,VQ.create,HQ.create;const rye=WQ.create;WQ.strictCreate,GQ.create,eye.create,JQ.create,YQ.create,tye.create,XQ.create,ZQ.create,nye.create,QQ.create,$Q.create,t$.create,n$.create,r$.create,i$.create,a$.create,o$.create,i$.createWithPreprocess,d$.create;const iye=pe(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);d.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>h(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>m(e,t,n),e.parseAsync=async(t,n)=>Ee(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>se(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>ce(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),aye=pe(`ZodMiniObject`,(e,t)=>{ae.init(e,t),iye.init(e,t),T(e,`shape`,()=>t.shape)});function p$(e,t){return new aye({type:`object`,shape:e??{},...r(t)})}function m$(e){return!!e._zod}function h$(e){let t=Object.values(e);if(t.length===0)return p$({});let n=t.every(m$),r=t.every(e=>!m$(e));if(n)return p$(e);if(r)return rye(e);throw Error(`Mixed Zod versions detected in object shape.`)}function g$(e,t){return m$(e)?m(e,t):e.safeParse(t)}async function _$(e,t){return m$(e)?await se(e,t):await e.safeParseAsync(t)}function v$(e){if(!e)return;let t;if(t=m$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function y$(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return h$(e)}}if(m$(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function b$(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function oye(e){return e.description}function sye(e){if(m$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function x$(e){if(m$(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const S$=`2025-11-25`,C$=[S$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],w$=`io.modelcontextprotocol/related-task`,T$=s(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),E$=p([u(),i().int()]),D$=u();ye({ttl:i().optional(),pollInterval:i().optional()});const cye=j({ttl:i().optional()}),lye=j({taskId:u()}),O$=ye({progressToken:E$.optional(),[w$]:lye.optional()}),k$=j({_meta:O$.optional()}),A$=k$.extend({task:cye.optional()}),uye=e=>A$.safeParse(e).success,j$=j({method:u(),params:k$.loose().optional()}),M$=j({_meta:O$.optional()}),N$=j({method:u(),params:M$.loose().optional()}),P$=ye({_meta:O$.optional()}),F$=p([u(),i().int()]),I$=j({jsonrpc:x(`2.0`),id:F$,...j$.shape}).strict(),L$=e=>I$.safeParse(e).success,R$=j({jsonrpc:x(`2.0`),...N$.shape}).strict(),dye=e=>R$.safeParse(e).success,z$=j({jsonrpc:x(`2.0`),id:F$,result:P$}).strict(),B$=e=>z$.safeParse(e).success;var V$;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(V$||={});const H$=j({jsonrpc:x(`2.0`),id:F$.optional(),error:j({code:i().int(),message:u(),data:_().optional()})}).strict(),U$=e=>H$.safeParse(e).success,W$=p([I$,R$,z$,H$]);p([z$,H$]);const G$=P$.strict(),fye=M$.extend({requestId:F$.optional(),reason:u().optional()}),K$=N$.extend({method:x(`notifications/cancelled`),params:fye}),q$=j({icons:M(j({src:u(),mimeType:u().optional(),sizes:M(u()).optional(),theme:Ne([`light`,`dark`]).optional()})).optional()}),J$=j({name:u(),title:u().optional()}),Y$=J$.extend({...J$.shape,...q$.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),pye=b(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,c(j({form:c(j({applyDefaults:D().optional()}),C(u(),_())).optional(),url:T$.optional()}),C(u(),_()).optional())),mye=ye({list:T$.optional(),cancel:T$.optional(),requests:ye({sampling:ye({createMessage:T$.optional()}).optional(),elicitation:ye({create:T$.optional()}).optional()}).optional()}),hye=ye({list:T$.optional(),cancel:T$.optional(),requests:ye({tools:ye({call:T$.optional()}).optional()}).optional()}),gye=j({experimental:C(u(),T$).optional(),sampling:j({context:T$.optional(),tools:T$.optional()}).optional(),elicitation:pye.optional(),roots:j({listChanged:D().optional()}).optional(),tasks:mye.optional(),extensions:C(u(),T$).optional()}),_ye=k$.extend({protocolVersion:u(),capabilities:gye,clientInfo:Y$}),X$=j$.extend({method:x(`initialize`),params:_ye}),Z$=e=>X$.safeParse(e).success,vye=j({experimental:C(u(),T$).optional(),logging:T$.optional(),completions:T$.optional(),prompts:j({listChanged:D().optional()}).optional(),resources:j({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:j({listChanged:D().optional()}).optional(),tasks:hye.optional(),extensions:C(u(),T$).optional()}),yye=P$.extend({protocolVersion:u(),capabilities:vye,serverInfo:Y$,instructions:u().optional()}),Q$=N$.extend({method:x(`notifications/initialized`),params:M$.optional()}),bye=e=>Q$.safeParse(e).success,$$=j$.extend({method:x(`ping`),params:k$.optional()}),xye=j({progress:i(),total:v(i()),message:v(u())}),Sye=j({...M$.shape,...xye.shape,progressToken:E$}),e1=N$.extend({method:x(`notifications/progress`),params:Sye}),Cye=k$.extend({cursor:D$.optional()}),t1=j$.extend({params:Cye.optional()}),n1=P$.extend({nextCursor:D$.optional()}),wye=Ne([`working`,`input_required`,`completed`,`failed`,`cancelled`]),r1=j({taskId:u(),status:wye,ttl:p([i(),Le()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:v(i()),statusMessage:v(u())}),i1=P$.extend({task:r1}),Tye=M$.merge(r1),a1=N$.extend({method:x(`notifications/tasks/status`),params:Tye}),o1=j$.extend({method:x(`tasks/get`),params:k$.extend({taskId:u()})}),s1=P$.merge(r1),c1=j$.extend({method:x(`tasks/result`),params:k$.extend({taskId:u()})});P$.loose();const l1=t1.extend({method:x(`tasks/list`)}),u1=n1.extend({tasks:M(r1)}),d1=j$.extend({method:x(`tasks/cancel`),params:k$.extend({taskId:u()})}),Eye=P$.merge(r1),f1=j({uri:u(),mimeType:v(u()),_meta:C(u(),_()).optional()}),p1=f1.extend({text:u()}),m1=u().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),h1=f1.extend({blob:m1}),g1=Ne([`user`,`assistant`]),_1=j({audience:M(g1).optional(),priority:i().min(0).max(1).optional(),lastModified:a({offset:!0}).optional()}),v1=j({...J$.shape,...q$.shape,uri:u(),description:v(u()),mimeType:v(u()),size:v(i()),annotations:_1.optional(),_meta:v(ye({}))}),Dye=j({...J$.shape,...q$.shape,uriTemplate:u(),description:v(u()),mimeType:v(u()),annotations:_1.optional(),_meta:v(ye({}))}),y1=t1.extend({method:x(`resources/list`)}),Oye=n1.extend({resources:M(v1)}),b1=t1.extend({method:x(`resources/templates/list`)}),kye=n1.extend({resourceTemplates:M(Dye)}),x1=k$.extend({uri:u()}),Aye=x1,S1=j$.extend({method:x(`resources/read`),params:Aye}),jye=P$.extend({contents:M(p([p1,h1]))}),Mye=N$.extend({method:x(`notifications/resources/list_changed`),params:M$.optional()}),Nye=x1,Pye=j$.extend({method:x(`resources/subscribe`),params:Nye}),Fye=x1,Iye=j$.extend({method:x(`resources/unsubscribe`),params:Fye}),Lye=M$.extend({uri:u()}),Rye=N$.extend({method:x(`notifications/resources/updated`),params:Lye}),zye=j({name:u(),description:v(u()),required:v(D())}),Bye=j({...J$.shape,...q$.shape,description:v(u()),arguments:v(M(zye)),_meta:v(ye({}))}),C1=t1.extend({method:x(`prompts/list`)}),Vye=n1.extend({prompts:M(Bye)}),Hye=k$.extend({name:u(),arguments:C(u(),u()).optional()}),w1=j$.extend({method:x(`prompts/get`),params:Hye}),T1=j({type:x(`text`),text:u(),annotations:_1.optional(),_meta:C(u(),_()).optional()}),E1=j({type:x(`image`),data:m1,mimeType:u(),annotations:_1.optional(),_meta:C(u(),_()).optional()}),D1=j({type:x(`audio`),data:m1,mimeType:u(),annotations:_1.optional(),_meta:C(u(),_()).optional()}),Uye=j({type:x(`tool_use`),name:u(),id:u(),input:C(u(),_()),_meta:C(u(),_()).optional()}),Wye=j({type:x(`resource`),resource:p([p1,h1]),annotations:_1.optional(),_meta:C(u(),_()).optional()}),O1=p([T1,E1,D1,v1.extend({type:x(`resource_link`)}),Wye]),Gye=j({role:g1,content:O1}),Kye=P$.extend({description:u().optional(),messages:M(Gye)}),qye=N$.extend({method:x(`notifications/prompts/list_changed`),params:M$.optional()}),Jye=j({title:u().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),Yye=j({taskSupport:Ne([`required`,`optional`,`forbidden`]).optional()}),k1=j({...J$.shape,...q$.shape,description:u().optional(),inputSchema:j({type:x(`object`),properties:C(u(),T$).optional(),required:M(u()).optional()}).catchall(_()),outputSchema:j({type:x(`object`),properties:C(u(),T$).optional(),required:M(u()).optional()}).catchall(_()).optional(),annotations:Jye.optional(),execution:Yye.optional(),_meta:C(u(),_()).optional()}),A1=t1.extend({method:x(`tools/list`)}),Xye=n1.extend({tools:M(k1)}),j1=P$.extend({content:M(O1).default([]),structuredContent:C(u(),_()).optional(),isError:D().optional()});j1.or(P$.extend({toolResult:_()}));const Zye=A$.extend({name:u(),arguments:C(u(),_()).optional()}),M1=j$.extend({method:x(`tools/call`),params:Zye}),Qye=N$.extend({method:x(`notifications/tools/list_changed`),params:M$.optional()});j({autoRefresh:D().default(!0),debounceMs:i().int().nonnegative().default(300)});const N1=Ne([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),$ye=k$.extend({level:N1}),P1=j$.extend({method:x(`logging/setLevel`),params:$ye}),ebe=M$.extend({level:N1,logger:u().optional(),data:_()}),tbe=N$.extend({method:x(`notifications/message`),params:ebe}),nbe=j({hints:M(j({name:u().optional()})).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),rbe=j({mode:Ne([`auto`,`required`,`none`]).optional()}),ibe=j({type:x(`tool_result`),toolUseId:u().describe(`The unique identifier for the corresponding tool call.`),content:M(O1).default([]),structuredContent:j({}).loose().optional(),isError:D().optional(),_meta:C(u(),_()).optional()}),abe=Fe(`type`,[T1,E1,D1]),F1=Fe(`type`,[T1,E1,D1,Uye,ibe]),obe=j({role:g1,content:p([F1,M(F1)]),_meta:C(u(),_()).optional()}),sbe=A$.extend({messages:M(obe),modelPreferences:nbe.optional(),systemPrompt:u().optional(),includeContext:Ne([`none`,`thisServer`,`allServers`]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:M(u()).optional(),metadata:T$.optional(),tools:M(k1).optional(),toolChoice:rbe.optional()}),cbe=j$.extend({method:x(`sampling/createMessage`),params:sbe}),I1=P$.extend({model:u(),stopReason:v(Ne([`endTurn`,`stopSequence`,`maxTokens`]).or(u())),role:g1,content:abe}),L1=P$.extend({model:u(),stopReason:v(Ne([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(u())),role:g1,content:p([F1,M(F1)])}),lbe=j({type:x(`boolean`),title:u().optional(),description:u().optional(),default:D().optional()}),ube=j({type:x(`string`),title:u().optional(),description:u().optional(),minLength:i().optional(),maxLength:i().optional(),format:Ne([`email`,`uri`,`date`,`date-time`]).optional(),default:u().optional()}),dbe=j({type:Ne([`number`,`integer`]),title:u().optional(),description:u().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),fbe=j({type:x(`string`),title:u().optional(),description:u().optional(),enum:M(u()),default:u().optional()}),pbe=j({type:x(`string`),title:u().optional(),description:u().optional(),oneOf:M(j({const:u(),title:u()})),default:u().optional()}),mbe=p([p([j({type:x(`string`),title:u().optional(),description:u().optional(),enum:M(u()),enumNames:M(u()).optional(),default:u().optional()}),p([fbe,pbe]),p([j({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:j({type:x(`string`),enum:M(u())}),default:M(u()).optional()}),j({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:j({anyOf:M(j({const:u(),title:u()}))}),default:M(u()).optional()})])]),lbe,ube,dbe]),hbe=p([A$.extend({mode:x(`form`).optional(),message:u(),requestedSchema:j({type:x(`object`),properties:C(u(),mbe),required:M(u()).optional()})}),A$.extend({mode:x(`url`),message:u(),elicitationId:u(),url:u().url()})]),gbe=j$.extend({method:x(`elicitation/create`),params:hbe}),_be=M$.extend({elicitationId:u()}),vbe=N$.extend({method:x(`notifications/elicitation/complete`),params:_be}),R1=P$.extend({action:Ne([`accept`,`decline`,`cancel`]),content:b(e=>e===null?void 0:e,C(u(),p([u(),i(),D(),M(u())])).optional())}),ybe=j({type:x(`ref/resource`),uri:u()}),bbe=j({type:x(`ref/prompt`),name:u()}),xbe=k$.extend({ref:p([bbe,ybe]),argument:j({name:u(),value:u()}),context:j({arguments:C(u(),u()).optional()}).optional()}),z1=j$.extend({method:x(`completion/complete`),params:xbe});function Sbe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Cbe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const wbe=P$.extend({completion:ye({values:M(u()).max(100),total:v(i().int()),hasMore:v(D())})}),Tbe=j({uri:u().startsWith(`file://`),name:u().optional(),_meta:C(u(),_()).optional()}),Ebe=j$.extend({method:x(`roots/list`),params:k$.optional()}),B1=P$.extend({roots:M(Tbe)}),Dbe=N$.extend({method:x(`notifications/roots/list_changed`),params:M$.optional()});p([$$,X$,z1,P1,w1,C1,y1,b1,S1,Pye,Iye,M1,A1,o1,c1,l1,d1]),p([K$,e1,Q$,Dbe,a1]),p([G$,I1,L1,R1,B1,s1,u1,i1]),p([$$,cbe,gbe,Ebe,o1,c1,l1,d1]),p([K$,e1,tbe,Rye,Mye,Qye,qye,a1,vbe]),p([G$,yye,wbe,Kye,Vye,Oye,kye,jye,j1,Xye,s1,u1,i1]);var V1=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===V$.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Obe(e.elicitations,n)}return new e(t,n,r)}},Obe=class extends V1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(V$.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function H1(e){return e===`completed`||e===`failed`||e===`cancelled`}const kbe=Symbol(`Let zodToJsonSchema decide on which parser to use`),U1={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},Abe=e=>typeof e==`string`?{...U1,name:e}:{...U1,...e},jbe=e=>{let t=Abe(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function W1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function G1(e,t,n,r,i){e[t]=n,W1(e,t,r,i)}const K1=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function q1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?K1(t,e.currentPath):t.join(`/`)}}function Mbe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=o0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&G1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&G1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(G1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),G1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Nbe(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?G1(n,`minimum`,r.value,r.message,t):G1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),G1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?G1(n,`maximum`,r.value,r.message,t):G1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),G1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:G1(n,`multipleOf`,r.value,r.message,t);break}return n}function Pbe(){return{type:`boolean`}}function J1(e,t){return o0(e.type._def,t)}const Fbe=(e,t)=>o0(e.innerType._def,t);function Y1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Y1(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Ibe(e,t)}}const Ibe=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:G1(n,`minimum`,r.value,r.message,t);break;case`max`:G1(n,`maximum`,r.value,r.message,t);break}return n};function Lbe(e,t){return{...o0(e.innerType._def,t),default:e.defaultValue()}}function Rbe(e,t){return t.effectStrategy===`input`?o0(e.schema._def,t):q1(t)}function zbe(e){return{type:`string`,enum:Array.from(e.values)}}const Bbe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Vbe(e,t){let n=[o0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),o0(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Bbe(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Hbe(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let X1;const Z1={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(X1===void 0&&(X1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),X1),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Q1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:G1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:G1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:e0(n,`email`,r.message,t);break;case`format:idn-email`:e0(n,`idn-email`,r.message,t);break;case`pattern:zod`:t0(n,Z1.email,r.message,t);break}break;case`url`:e0(n,`uri`,r.message,t);break;case`uuid`:e0(n,`uuid`,r.message,t);break;case`regex`:t0(n,r.regex,r.message,t);break;case`cuid`:t0(n,Z1.cuid,r.message,t);break;case`cuid2`:t0(n,Z1.cuid2,r.message,t);break;case`startsWith`:t0(n,RegExp(`^${$1(r.value,t)}`),r.message,t);break;case`endsWith`:t0(n,RegExp(`${$1(r.value,t)}$`),r.message,t);break;case`datetime`:e0(n,`date-time`,r.message,t);break;case`date`:e0(n,`date`,r.message,t);break;case`time`:e0(n,`time`,r.message,t);break;case`duration`:e0(n,`duration`,r.message,t);break;case`length`:G1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),G1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:t0(n,RegExp($1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&e0(n,`ipv4`,r.message,t),r.version!==`v4`&&e0(n,`ipv6`,r.message,t);break;case`base64url`:t0(n,Z1.base64url,r.message,t);break;case`jwt`:t0(n,Z1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&t0(n,Z1.ipv4Cidr,r.message,t),r.version!==`v4`&&t0(n,Z1.ipv6Cidr,r.message,t);break;case`emoji`:t0(n,Z1.emoji(),r.message,t);break;case`ulid`:t0(n,Z1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:e0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:G1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:t0(n,Z1.base64,r.message,t);break}break;case`nanoid`:t0(n,Z1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function $1(e,t){return t.patternStrategy===`escape`?Wbe(e):e}const Ube=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Wbe(e){let t=``;for(let n=0;n<e.length;n++)Ube.has(e[n])||(t+=`\\`),t+=e[n];return t}function e0(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):G1(e,`format`,t,n,r)}function t0(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:n0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):G1(e,`pattern`,n0(t,r),n,r)}function n0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
1174
1174
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
1175
1175
|
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function r0(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===Z.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:o0(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??q1(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:o0(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===Z.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Q1(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===Z.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===Z.ZodBranded&&e.keyType._def.type._def.typeName===Z.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=J1(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Gbe(e,t){return t.mapStrategy===`record`?r0(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[o0(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||q1(t),o0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||q1(t)],minItems:2,maxItems:2}}}function Kbe(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function qbe(e){return e.target===`openAi`?void 0:{not:q1({...e,currentPath:[...e.currentPath,`not`]})}}function Jbe(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const i0={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Ybe(e,t){if(t.target===`openApi3`)return a0(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in i0&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=i0[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return a0(e,t)}const a0=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>o0(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Xbe(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:i0[e.innerType._def.typeName],nullable:!0}:{type:[i0[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=o0(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=o0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Zbe(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,W1(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?G1(n,`minimum`,r.value,r.message,t):G1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),G1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?G1(n,`maximum`,r.value,r.message,t):G1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),G1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:G1(n,`multipleOf`,r.value,r.message,t);break}return n}function Qbe(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=exe(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=o0(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=$be(e,t);return o!==void 0&&(r.additionalProperties=o),r}function $be(e,t){if(e.catchall._def.typeName!==`ZodNever`)return o0(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function exe(e){try{return e.isOptional()}catch{return!0}}const txe=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return o0(e.innerType._def,t);let n=o0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:q1(t)},n]}:q1(t)},nxe=(e,t)=>{if(t.pipeStrategy===`input`)return o0(e.in._def,t);if(t.pipeStrategy===`output`)return o0(e.out._def,t);let n=o0(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,o0(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function rxe(e,t){return o0(e.type._def,t)}function ixe(e,t){let n={type:`array`,uniqueItems:!0,items:o0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&G1(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&G1(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function axe(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>o0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:o0(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>o0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function oxe(e){return{not:q1(e)}}function sxe(e){return q1(e)}const cxe=(e,t)=>o0(e.innerType._def,t),lxe=(e,t,n)=>{switch(t){case Z.ZodString:return Q1(e,n);case Z.ZodNumber:return Zbe(e,n);case Z.ZodObject:return Qbe(e,n);case Z.ZodBigInt:return Nbe(e,n);case Z.ZodBoolean:return Pbe();case Z.ZodDate:return Y1(e,n);case Z.ZodUndefined:return oxe(n);case Z.ZodNull:return Jbe(n);case Z.ZodArray:return Mbe(e,n);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return Ybe(e,n);case Z.ZodIntersection:return Vbe(e,n);case Z.ZodTuple:return axe(e,n);case Z.ZodRecord:return r0(e,n);case Z.ZodLiteral:return Hbe(e,n);case Z.ZodEnum:return zbe(e);case Z.ZodNativeEnum:return Kbe(e);case Z.ZodNullable:return Xbe(e,n);case Z.ZodOptional:return txe(e,n);case Z.ZodMap:return Gbe(e,n);case Z.ZodSet:return ixe(e,n);case Z.ZodLazy:return()=>e.getter()._def;case Z.ZodPromise:return rxe(e,n);case Z.ZodNaN:case Z.ZodNever:return qbe(n);case Z.ZodEffects:return Rbe(e,n);case Z.ZodAny:return q1(n);case Z.ZodUnknown:return sxe(n);case Z.ZodDefault:return Lbe(e,n);case Z.ZodBranded:return J1(e,n);case Z.ZodReadonly:return cxe(e,n);case Z.ZodCatch:return Fbe(e,n);case Z.ZodPipeline:return nxe(e,n);case Z.ZodFunction:case Z.ZodVoid:case Z.ZodSymbol:return;default:return(e=>void 0)(t)}};function o0(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==kbe)return i}if(r&&!n){let e=uxe(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=lxe(e,e.typeName,t),o=typeof a==`function`?o0(a(),t):a;if(o&&dxe(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const uxe=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:K1(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),q1(t)):t.$refStrategy===`seen`?q1(t):void 0}},dxe=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),fxe=(e,t)=>{let n=jbe(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:o0(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??q1(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=o0(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??q1(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function pxe(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function s0(e,t){return m$(e)?k(e,{target:pxe(t?.target),io:t?.pipeStrategy??`input`}):fxe(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function c0(e){let t=v$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=x$(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function l0(e,t){let n=g$(e,t);if(!n.success)throw n.error;return n.data}var mxe=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(K$,e=>{this._oncancel(e)}),this.setNotificationHandler(e1,e=>{this._onprogress(e)}),this.setRequestHandler($$,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(o1,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new V1(V$.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(c1,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new V1(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new V1(V$.InvalidParams,`Task not found: ${r}`);if(!H1(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(H1(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[w$]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(l1,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new V1(V$.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(d1,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new V1(V$.InvalidParams,`Task not found: ${e.params.taskId}`);if(H1(n.status))throw new V1(V$.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new V1(V$.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof V1?e:new V1(V$.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),V1.fromError(V$.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),B$(e)||U$(e)?this._onresponse(e):L$(e)?this._onrequest(e,t):dye(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=V1.fromError(V$.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[w$]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:V$.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=uye(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new V1(V$.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:V$.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),B$(e)?n(e):n(new V1(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(B$(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),B$(e)?r(e):r(V1.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof V1?e:new V1(V$.InternalError,String(e))}}return}let i;try{let r=await this.request(e,i1,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new V1(V$.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},H1(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new V1(V$.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new V1(V$.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof V1?e:new V1(V$.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[w$]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof V1?e:new V1(V$.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=g$(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(V1.fromError(V$.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},s1,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},u1,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Eye,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[w$]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[w$]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[w$]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=c0(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=l0(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=c0(e);this._notificationHandlers.set(n,n=>{let r=l0(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&L$(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new V1(V$.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new V1(V$.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new V1(V$.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new V1(V$.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=a1.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),H1(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new V1(V$.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(H1(a.status))throw new V1(V$.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=a1.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),H1(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function u0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hxe(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];u0(a)&&u0(i)?n[r]={...a,...i}:n[r]=i}return n}var gxe=t(oa(),1),_xe=t(fo(),1);function vxe(){let e=new gxe.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,_xe.default)(e),e}var yxe=class{constructor(e){this._ajv=e??vxe()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},bxe=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},I1,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},R1,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function xxe(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Sxe(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Cxe=class extends mxe{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(N1.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new yxe,this.setRequestHandler(X$,e=>this._oninitialize(e)),this.setNotificationHandler(Q$,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(P1,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=N1.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new bxe(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=hxe(this._capabilities,e)}setRequestHandler(e,t){let n=v$(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(m$(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=g$(M1,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new V1(V$.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=g$(i1,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new V1(V$.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=g$(j1,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new V1(V$.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){Sxe(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&xxe(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:C$.includes(t)?t:S$,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},G$)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},L1,t):this.request({method:`sampling/createMessage`,params:e},I1,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},R1,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},R1,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new V1(V$.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof V1?e:new V1(V$.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},B1,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const d0=Symbol.for(`mcp.completable`);function f0(e){return!!e&&typeof e==`object`&&d0 in e}function wxe(e){return e[d0]?.complete}var Txe;(function(e){e.Completable=`McpCompletable`})(Txe||={});const Exe=/^[A-Za-z0-9._-]{1,128}$/;function Dxe(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Exe.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Oxe(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function p0(e){let t=Dxe(e);return Oxe(e,t.warnings),t.isValid}var kxe=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},m0=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Cxe(e,t)}get experimental(){return this._experimental||={tasks:new kxe(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(y0(A1)),this.server.assertCanSetRequestHandler(y0(M1)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(A1,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=y$(t.inputSchema);return e?s0(e,{strictUnions:!0,pipeStrategy:`input`}):Axe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=y$(t.outputSchema);e&&(n.outputSchema=s0(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(M1,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new V1(V$.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new V1(V$.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new V1(V$.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new V1(V$.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof V1&&e.code===V$.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await _$(y$(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=b$(`error`in r?r.error:`Unknown error`);throw new V1(V$.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new V1(V$.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await _$(y$(e.outputSchema),t.structuredContent);if(!r.success){let e=b$(`error`in r?r.error:`Unknown error`);throw new V1(V$.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new V1(V$.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(y0(z1)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(z1,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Sbe(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Cbe(e),this.handleResourceCompletion(e,e.params.ref);default:throw new V1(V$.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new V1(V$.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new V1(V$.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return x0;let r=v$(n.argsSchema)?.[e.params.argument.name];if(!f0(r))return x0;let i=wxe(r);return i?b0(await i(e.params.argument.value,e.params.context)):x0}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return x0;throw new V1(V$.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?b0(await r(e.params.argument.value,e.params.context)):x0}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(y0(y1)),this.server.assertCanSetRequestHandler(y0(b1)),this.server.assertCanSetRequestHandler(y0(S1)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(y1,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(b1,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(S1,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new V1(V$.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new V1(V$.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(y0(C1)),this.server.assertCanSetRequestHandler(y0(w1)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(C1,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?jxe(t.argsSchema):void 0}))})),this.server.setRequestHandler(w1,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new V1(V$.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new V1(V$.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await _$(y$(n.argsSchema),e.params.arguments);if(!r.success){let t=b$(`error`in r?r.error:`Unknown error`);throw new V1(V$.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:h$(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=h$(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>f0(e instanceof le?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){p0(e);let l={title:t,description:n,inputSchema:v0(r),outputSchema:v0(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&p0(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=h$(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=h$(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(_0(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!_0(t[0])&&(i=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const Axe={type:`object`,properties:{}};function h0(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function g0(e){return`_def`in e||`_zod`in e||h0(e)}function _0(e){return typeof e!=`object`||!e||g0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(h0)}function v0(e){if(e){if(_0(e))return h$(e);if(!g0(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function jxe(e){let t=v$(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:oye(t),required:!sye(t)})):[]}function y0(e){let t=v$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=x$(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function b0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const x0={completion:{values:[],hasMore:!1}};var S0=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Mxe=e=>e instanceof S0?e:new S0(e.message,{cause:e}),Nxe=global.Request,C0=class extends Nxe{constructor(e,t){typeof e==`object`&&T0 in e&&(e=e[T0]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Pxe=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},w0=Symbol(`wrapBodyStream`),Fxe=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new C0(t,a);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[w0]){let e;a.body=new ReadableStream({async pull(t){try{e||=pd.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=pd.toWeb(r);return new C0(t,a)},T0=Symbol(`getRequestCache`),E0=Symbol(`requestCache`),D0=Symbol(`incomingKey`),O0=Symbol(`urlKey`),Ixe=Symbol(`headersKey`),k0=Symbol(`abortControllerKey`),A0={get method(){return this[D0].method||`GET`},get url(){return this[O0]},get headers(){return this[Ixe]||=Pxe(this[D0])},[Symbol(`getAbortController`)](){return this[T0](),this[k0]},[T0](){return this[k0]||=new AbortController,this[E0]||=Fxe(this.method,this[O0],this.headers,this[D0],this[k0])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(A0,e,{get(){return this[T0]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(A0,e,{value:function(){return this[T0]()[e]()}})}),Object.defineProperty(A0,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[E0]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(A0,C0.prototype);var Lxe=(e,t)=>{let n=Object.create(A0);n[D0]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof yd)throw new S0(`Absolute URL for :path is not allowed in HTTP/2`);try{n[O0]=new URL(r).href}catch(e){throw new S0(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof yd?e.authority:e.headers.host)||t;if(!i)throw new S0(`Missing host header`);let a;if(e instanceof yd){if(a=e.scheme,!(a===`http`||a===`https`))throw new S0(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;let o=new URL(`${a}://${i}${r}`);if(o.hostname.length!==i.length&&o.hostname!==i.replace(/:\d+$/,``))throw new S0(`Invalid host header`);return n[O0]=o.href,n},j0=Symbol(`responseCache`),M0=Symbol(`getResponseCache`),N0=Symbol(`cache`),P0=global.Response,F0=class e{#e;#t;[M0](){return delete this[N0],this[j0]||=new P0(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[j0];if(e){this.#t=e,this[M0]();return}else this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[N0]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[N0];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[M0]().headers}get status(){return this[N0]?.[0]??this[M0]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(F0.prototype,e,{get(){return this[M0]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(F0.prototype,e,{value:function(){return this[M0]()[e]()}})}),Object.defineProperty(F0.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[j0]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(F0,P0),Object.setPrototypeOf(F0.prototype,P0.prototype);async function Rxe(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function I0(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function zxe(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:I0(e.getReader(),t)}var L0=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,i]of e)r===`set-cookie`?n.push(i):t[r]=i;return n.length>0&&(t[`set-cookie`]=n),t[`content-type`]??=`text/plain; charset=UTF-8`,t},Bxe=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=Ete);var R0=Symbol(`outgoingEnded`),z0=Symbol(`incomingDraining`),Vxe=500,Hxe=64*1024*1024,B0=e=>{let t=e;if(e.destroyed||t[z0])return;if(t[z0]=!0,e instanceof yd){try{e.stream?.close?.(zte.NGHTTP2_NO_ERROR)}catch{}return}let n=0,r=()=>{clearTimeout(a),e.off(`data`,o),e.off(`end`,r),e.off(`error`,r)},i=()=>{r();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},a=setTimeout(i,Vxe);a.unref?.();let o=e=>{n+=e.length,n>Hxe&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},Uxe=()=>new Response(null,{status:400}),V0=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),H0=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},U0=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},W0=async(e,t)=>{let[n,r,i]=e[N0],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=L0(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=L0(e)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(U0(t),await zxe(r,t)?.catch(e=>H0(e,t))),t[R0]?.()},Wxe=e=>typeof e.then==`function`,Gxe=async(e,t,n={})=>{if(Wxe(e))if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(V0);if(N0 in e)return W0(e,t);let r=L0(e.headers);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await Rxe(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&U0(t),await I0(n,t,o))}else r[Bxe]||(t.writeHead(e.status,r),t.end());t[R0]?.()},G0=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==C0&&(Object.defineProperty(global,`Request`,{value:C0}),Object.defineProperty(global,`Response`,{value:F0})),async(r,i)=>{let a,o;try{o=Lxe(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[w0]=!0,r.on(`end`,()=>{s=!0}),r instanceof yd&&(i[R0]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{B0(r)})})}),i.on(`finish`,()=>{s||B0(r)})),i.on(`close`,()=>{o[k0]&&(r.errored?o[k0].abort(r.errored.toString()):i.writableFinished||o[k0].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{B0(r)})})}),a=e(o,{incoming:r,outgoing:i}),N0 in a)return W0(a,i)}catch(e){if(a)return H0(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:Mxe(e)),!a)return}else a=o?V0(e):Uxe()}try{return await Gxe(a,i,t)}catch(e){return H0(e,i)}}},Kxe=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:i,id:null}),{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore||r<`2025-11-25`)return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),o={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(o[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),new Response(a,{headers:o})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{}}),o=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(i,r,t,e)){this.onerror?.(Error(`Failed replay events`));try{i.close()}catch{}}}});return this._streamMapping.set(o,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(o);try{i.close()}catch{}}}),new Response(a,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
|
|
1176
1176
|
`;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},a;if(t?.parsedBody!==void 0)a=t.parsedBody;else try{a=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let o;try{o=Array.isArray(a)?a.map(e=>W$.parse(e)):[W$.parse(a)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(Z$);if(s){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(o.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!s){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(!o.some(L$)){for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=o.find(e=>Z$(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of o)L$(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i})});let d=new TextEncoder,f,p=new ReadableStream({start:e=>{f=e},cancel:()=>{this._streamMapping.delete(c)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of o)L$(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of o){let n,r;L$(e)&&this._eventStore&&u>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i,closeSSEStream:n,closeStandaloneSSEStream:r})}return new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!C$.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${C$.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${C$.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((B$(e)||U$(e))&&(n=e.id),n===void 0){if(B$(e)||U$(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(B$(e)||U$(e)){this._requestResponseMap.set(n,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(new Response(JSON.stringify(n[0]),{status:200,headers:e})):i.resolveJson(new Response(JSON.stringify(n),{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},qxe=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Kxe(e),this._requestListener=G0(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,n){let r=e.auth;await G0(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};function K0(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let n=t.validateToolInput;if(typeof n!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,r){if(!e.inputSchema||!Jxe(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=oe(i.error);throw new V1(V$.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function Jxe(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const q0=2e3,J0=2e3,Yxe=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function Y0(e){return Yxe.some(t=>t.test(e))}function Xxe(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return yu(e)?e:null}catch{return null}}function Zxe(e){let t=e.indexOf(`--ok-project-path=`);if(t===-1)return null;let n=t+18,r=e.slice(n),i=r.search(/\s--/),a=(i===-1?r:r.slice(0,i)).trim();return a&&yu(a)?a:null}function Qxe(e){let t=[];for(let n of e.split(`
|
|
@@ -2014,4 +2014,4 @@ native-divergence-injected
|
|
|
2014
2014
|
`))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}ee(!1),await be.flushDeferredStores(`discard-stale`),t=!0,Ae?.emitBranchSwitched(i)}finally{ve.abortBranchSwitch(r),t||(ee(!1),await be.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&j.current&&t>0){let t=p??`.`;try{let n=await kx(j.current,t,e.oldHead,e.newHead,i);qb(),b.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),on.push(`head-watcher`)}function l(e){for(let t of e)try{let e=HM(I(n,F(r,t)));if(e.startsWith(`..`))continue;let i=Vx(e),a=we.documents.get(i);if(!a)continue;let o=Bt(i);o===null?b.warn({docName:i,file:t},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let t of e)try{let e=HM(I(n,F(r,t)));if(e.startsWith(`..`))continue;let i=we.documents.get(Vx(e));i&&Ut(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=ZMe(h),m=ne();m.mode!==`off`&&b.info({mode:m.mode,source:m.source},`[sync] mode active at boot`);try{tn=new KMe({projectDir:r,contentDir:n,contentFilter:_e,contentRoot:p,mode:m.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:f,cc1Broadcaster:Ae,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||be.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=j.current;n&&await jx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=j.current;n&&await jx(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await Ss({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:Te(t.error),configPath:Vs(`project-local`,r)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await tn.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),tn=null}Je(`files`),ve.announceReadyViews();let g=EL();g!==void 0&&DL(`readyMs`,g),oe()}return sn().then(()=>{Qe=!0,He(),ft()},e=>{$e=!0,et.abort(),lt({status:`failed`,indexCount:0}),ve.close(),Ge(),Ue(e)}),{hocuspocus:we,durabilityState:x,sessionManager:Ee,nativeApi:De,localApi:Oe,cc1Broadcaster:Ae,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Ne,maintenanceCoordinator:ye,contentFilter:_e,basenameIndex:pe,serverInstanceId:ue,destroy:an,ready:We,generatedIndexSweepReady:st,degraded:on,lockDir:de,get syncEngine(){return tn},getLinkPreviewsEnabled:k,resolveEmbed:me,acpRegistry:fe,acpPermissions:A}}function f9(e){return e/1048576}function $Me(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:f9(e.rss),heapTotalMb:f9(e.heapTotal),heapUsedMb:f9(e.heapUsed),externalMb:f9(e.external),arrayBuffersMb:f9(e.arrayBuffers)}}}let p9=null,m9=null,h9=null;const g9=1e6;let _9=null,v9=null;ks(()=>{p9=null,m9=null,h9=null,_9?.disable(),_9=null,v9=null});function eNe(){if(p9)return;let e=ec().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=$Me();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),p9=e}function tNe(){if(!m9){let e=ec().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!_9){_9=kte({resolution:20}),_9.enable();return}e.observe(_9.percentile(50)/g9,{stat:`p50`}),e.observe(_9.percentile(99)/g9,{stat:`p99`}),_9.reset()}),m9=e}if(!h9){let e=ec().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=v9;if(v9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),h9=e}}const y9=N(`skill-migrate`);function b9(e){return[{host:`agents`,root:Ao},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=JD.indexOf(e.host),r=JD.indexOf(t.host);return(n===-1?JD.length:n)-(r===-1?JD.length:r)||e.host.localeCompare(t.host)})}const nNe=b9(Zo),rNe=b9(dr);function iNe(e,t){return z(L(e,ha(t)))}function aNe(e,t){Hs(P(t),{recursive:!0});try{Fs(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;Gs(e,t,{recursive:!0}),Ks(e,{recursive:!0,force:!0})}}function oNe(e,t,n){let r=FI(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function x9(e,t){let n;try{n=V(L(e,`.ok`,`skills`))}catch{n=L(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!V(L(e,t.dir)).startsWith(n+R)}catch{return!0}}).map(e=>e.name))}async function S9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??nNe,a={migrated:[],skipped:[]};if(!z(n))return a;let o;try{o=Hu(n)}catch{return a}let s=I(t,n).split(R).join(`/`),c=new Set;for(let[e,n]of Object.entries(pX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Do.test(e)||XF.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=L(n,e);if(!z(F(o,`SKILL.md`)))continue;let s=LD(o)?.contentHash;if(s===void 0)continue;let l=V(o),u=i.map(({host:n,root:r})=>{let i=L(t,r);return{host:n,root:r,path:F(i,e),escapes:UI(t,i),state:oNe(F(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>iNe(t,e.root));if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?Ks(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&Ks(d.path,{recursive:!0,force:!0}),aNe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(Ks(e.path,{recursive:!0,force:!0}),Gs(d.path,e.path,{recursive:!0}));await CN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),y9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),y9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const C9=N(`skill-reconcile`),sNe=XF;function w9(){let e=[];for(let t of wt){let n=Zo[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:Ao,editor:null}),e}function cNe(e,t){let n=I(e,L(t));return yu(n)?L(t):n}function T9(e){let{frontmatter:t,body:n}=Ur(e),r={};if(t!==``)try{let e=(0,sk.parse)(Fr(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function lNe(e,t){let n=T9(e),r=T9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function E9(e,t){let n=D9(e),r=D9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=F(e,o),c=F(t,o);if(i+=qu(s).size+qu(c).size,i>1048576)return!1;let l=B(s),u=B(c);if(!l.equals(u)&&(o!==`SKILL.md`||!lNe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function D9(e,t=``){let n=[];for(let r of Hu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...D9(F(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function O9(e,t,n){Ks(t,{recursive:!0,force:!0}),Hs(e,{recursive:!0}),Rs(cNe(e,n),t,`dir`)}function k9(e,t){try{let n=Uu(e);return L(yu(n)?n:L(P(e),n))===L(t)}catch{return!1}}function uNe(e,t){try{let n=Uu(e),r=yu(n)?L(n):L(P(e),n);if(!z(r))return!1;let i=I(L(t),r);return i!==``&&(i.startsWith(`..`)||yu(i))}catch(t){return C9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const dNe=[...wt,`agents`];function fNe(e){for(let t of dNe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function pNe(e){let{projectDir:t,skillsRoot:n}=e;if(!z(n))return;let r;try{r=Hu(n)}catch{return}let i=w9();for(let e of r){let r=fNe(e);if(r===null)continue;let a=L(n,e),o=L(n,r);if(z(o))try{let n=Fu(a);if(n.isSymbolicLink()||!n.isDirectory()||!z(F(a,`SKILL.md`))||!z(F(o,`SKILL.md`))||!E9(o,a))continue;for(let{rel:n}of i){let r=L(t,n);if(UI(t,r))continue;let i=F(r,e);k9(i,a)&&O9(r,i,o)}Ks(a,{recursive:!0,force:!0}),C9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){C9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function mNe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of w9()){let o=L(t,e);if(!z(o)||UI(t,o))continue;let s;try{s=Hu(o)}catch(e){C9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(sNe.has(e))continue;let t=F(o,e),s=L(n,e),c=z(s);try{let l=Fu(t);if(l.isSymbolicLink()){if(k9(t,s)&&c)continue;if(uNe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(O9(o,t,s),r.healed.push({name:e,editor:i})):(Ks(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Do.test(e)){C9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&E9(t,s)){O9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){C9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=bN(t);for(let[r,a]of i){let i=L(n,r);if(!z(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await SN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??RI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){C9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{pNe({projectDir:t,skillsRoot:n})}catch(e){C9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let A9=null,j9=!1;function M9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function N9(e){if(!M9())return;let t=zk(e);A9=new lc({currentPath:L(t,`tolerance-telemetry.jsonl`),previousPath:L(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),tt(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};A9?.append(`${JSON.stringify(t)}\n`).catch(e=>{j9||(j9=!0,N(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function P9(){tt(null),await A9?.drain(),A9=null,j9=!1}vs();const hNe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],gNe=[`cache`,`tmp`];function _Ne(e){let t=L(e,ge);if(!(()=>{if(!z(t))return!0;try{return Hu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of hNe)z(L(e,t))&&n.push(t);for(let t of gNe){let r=L(e,t);try{z(r)&&qu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function vNe(e){let t=Od(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const F9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function yNe(e){_he();let t=e.projectDir??e.contentDir,n=Ave({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}ac.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}$s({localSink:n?.telemetry}),N9(t),eNe(),tNe();let{kind:r,gitdir:i}=vNe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Ws(i));let o=Ove(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>As(`ok.boot`,{attributes:a},async()=>bNe(e)),l=()=>{if(s)try{let e=gs.extract(ys.active(),{traceparent:s});return ys.with(e,c)}catch(e){N(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function bNe(e){let t=e.skipAutoInit??!1,n=e.log??N(`boot`),r=e.serverRuntime??{...Ua(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((li(r)||!ra(i))&&!r.allowExternal)throw new EB(`refusing to start: the server would bind a non-loopback address (${(ra(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=kB({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrlSource!==`server`&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-Bii6_-R-.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=L(p,`.ok`);if(!z(L(m,`config.yml`)))throw new _8(z(m)?`config`:`okdir`,p);let h=L(m,`.gitignore`);z(h)||N(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let g=e.gitPreflight??nK;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof $G||e instanceof eK){let t=e instanceof eK?e.detected:``,r=e instanceof eK?`too_old`:`not_available`;xK(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await Qs(),await Promise.race([P9(),new Promise(e=>setTimeout(e,F9))]),e}let _=_Ne(m);_.length>0&&N(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ge}/.`);let v=d9({contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te}=v,D=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ne=e.port??0,re=()=>r.externalUrlSource===`server`&&r.externalUrl!==void 0?r.externalUrl.replace(/\/+$/,``):`http://${D}:${ne}`,ie=e.ephemeral?void 0:u8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>re(),localApi:v.localApi,log:n}),O=c();O.headersTimeout=3e4,O.requestTimeout=6e4;let k=e.serveContentAssets===!1?void 0:BZ({contentFilter:v.contentFilter,contentSirv:Lc(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:_e,assetExtensions:w,blocklistExtensions:je,ingressPolicy:a}),ae=!1;if(e.reactShellDistDir)try{UX(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ae=!0}catch(e){if(e instanceof HX)n.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:C},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await b().catch(()=>{}),u(C),e}let oe=e.reactShellDistDir?Lc(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,se=e.ephemeral?null:new FE({contentDir:e.contentDir,localDir:C,globalDir:L(Zu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:T,agentPresenceBroadcaster:ee,resolveEmbed:v.resolveEmbed,isExcludedPath:e=>v.contentFilter.isExcluded(e),isIgnoredPath:e=>v.contentFilter.isPathIgnored(e),getLoadedDocText:e=>y.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>re(),getMcpStdioCommand:()=>PE(e.localOpCliArgs,ne),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:n});se!==null&&await se.init();let ce=`pending`;x.then(()=>{ce=`ready`},()=>{ce=`failed`});let le=h8({httpServer:O,hocuspocus:y,nativeApi:v.nativeApi,mcpHttpHandler:ie,ingressPolicy:a,health:{readiness:()=>ce,degraded:()=>S},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:k,reactShellMiddleware:oe,ephemeral:e.ephemeral,acpThreadManager:se}),ue=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},de=null;e.idleShutdownMs!==null&&(de=eQ({httpServer:O,thresholdMs:e.idleShutdownMs??18e5,log:n,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ue()})})),await I9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:n});let fe=[...new Set(i)],A=fe[0],pe=async()=>{if(ae)try{KX(C)}catch(e){n.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}await b().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(C)},me=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await me(O,e.port??0,A??`127.0.0.1`)}catch(e){throw await pe(),e}let he=O.address(),ve=typeof he==`object`&&he?he.port:e.port??0,j=[];for(let e of fe.slice(1)){let t=c();t.headersTimeout=O.headersTimeout,t.requestTimeout=O.requestTimeout;for(let e of O.listeners(`request`))t.on(`request`,e);for(let e of O.listeners(`upgrade`))t.on(`upgrade`,e);try{await me(t,ve,e)}catch(t){n.error({err:t,failedAddress:e,port:ve,alreadyBound:j.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...j,O])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await pe(),t}j.push(t)}let ye=EL();ye!==void 0&&DL(`httpListenMs`,ye);let be=O.address(),xe=typeof be==`object`&&be?be.port:e.port??0;ne=xe;let Se=`http://${D}:${xe}`;d(C,xe,Se),ae&&WX(C,xe,Se);let Ce=!1,we=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${F9}ms`))},F9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};ue=async()=>{if(Ce)return;Ce=!0,ce=`draining`;let e=[],t=async(t,r)=>{try{await we(t,r)}catch(r){e.push(r),n.warn({err:r,step:t},`bootServer destroy step failed`)}};try{l(C),ae&&Q_e(C)}catch(e){n.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{de?.detach()}catch(t){e.push(t),n.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(se!==null&&await t(`acpThreads.destroy`,()=>se.destroy()),await t(`secondaryListeners.close`,async()=>{for(let e of j)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await t(`mount.shutdown`,()=>le.shutdown()),ie!==void 0&&await t(`mcpHttpHandler.close`,()=>ie.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{le.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{O.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{O.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),ae&&await t(`releaseUiLock`,async()=>KX(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>Qs()),await t(`teardownToleranceTelemetry`,()=>P9()),await t(`flushLogFileSinks`,()=>ac.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await S9({projectDir:p,skillsRoot:L(e.contentDir,`.ok`,`skills`),inPlaceNames:x9(e.contentDir,pL(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=Zu(),t=await S9({projectDir:e,skillsRoot:L(e,`.ok`,`skills`),hostRoots:rNe,inPlaceNames:x9(e,mL(e))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await mNe({projectDir:p,skillsRoot:L(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:O,destroy:ue,lockDir:C,contentDir:e.contentDir,port:xe,ready:x,generatedIndexSweepReady:v.generatedIndexSweepReady,degraded:S,didAutoInit:f,serverInstance:v,runtime:Rke(v,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:se}}async function I9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new ZZ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=kd(n),t=e?F(e,`MERGE_HEAD`):null;if(!t||!z(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=mc({baseDir:n,timeout:{block:5e3}});s=new Set(await Wb(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=Vx(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const xNe=Pe;function SNe(e={}){let t=e.home??Zu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?z(F(t,`Library`,`Application Support`,`Claude`)):n===`win32`?z(F(r.APPDATA??F(t,`AppData`,`Roaming`),`Claude`)):!1}var L9=t(cc(),1);const R9=F(Zu(),`.ok`,`logs`),CNe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function wNe(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],n=e.toLowerCase();if(t.includes(n))return n}return process.env.NODE_ENV===`test`?`silent`:`info`}function TNe(e){Iu(e,{recursive:!0})}function z9(){return new Date().toISOString().slice(0,10)}function ENe(e){try{if(qu(e).size<5242880)return}catch{return}for(let t=2;t>=1;t--){let n=t===1?e:`${e}.${t-1}`,r=`${e}.${t}`;try{Wu(n,r)}catch{}}try{Ju(`${e}.3`)}catch{}}function DNe(e){try{let t=Date.now(),n=10080*60*1e3,r=Hu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=qu(F(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{Ju(F(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{Ju(F(e,t.name)),a-=t.size}catch{}}}catch{}}function ONe(e){TNe(R9);let t=z9(),n=e.filePath??F(R9,`${e.name}.${t}.log`);ENe(n),(e._setTimeout??setTimeout)(()=>DNe(R9),5e3).unref();let r=L9.default.destination({dest:n,append:!0,sync:!0});return(0,L9.default)({level:wNe(),name:e.name,redact:{paths:CNe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:L9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function kNe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[L9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function ANe(e){return F(R9,`${e}.${z9()}.log`)}function jNe(){return R9}function MNe(e){let t=L(e),n=0;for(;n<30;){let e=!1;try{e=z(L(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=P(t);if(r===t)return null;t=r,n+=1}return null}const B9=_d(du),V9=N(`project-git`);var H9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function NNe(e,t){try{return await B9(e,[`var`,`GIT_COMMITTER_IDENT`],JM({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function PNe(e,t){try{let{stdout:n}=await B9(e,[`for-each-ref`,`--count=1`,`refs/`],JM({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return V9.warn({path:t,stderr:U9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function FNe(e){let t=L(e,`packed-refs`);if(z(t))try{if(B(t,`utf-8`).split(`
|
|
2015
2015
|
`).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return Hu(L(e,`refs/heads`)).length>0}catch{return!1}}function U9(e){let t=typeof e==`object`&&e?e:null,n=t?.stderr;return n==null?String(t?.message??e):Buffer.isBuffer(n)?n.toString(`utf-8`):String(n)}async function W9(e,t){if(await PNe(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await NNe(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await B9(e,i,JM({cwd:t,encoding:`utf-8`})),r||V9.info({path:t},`created initial commit with fallback identity (git identity unset)`)}catch(e){V9.warn({path:t,stderr:U9(e)},`could not create initial commit`)}}async function INe(e,t){try{let{stdout:n}=await B9(e,[`rev-parse`,`--is-inside-work-tree`],JM({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function LNe(e){let t=L(e),n=L(t,`.git`),r=L(n,`HEAD`),i=!1,a=!1;if(z(n)){if(!qu(n).isDirectory())return{didInit:!1};if(z(r)){if(FNe(n))return{didInit:!1};a=!0}else V9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=nK()}catch(e){throw e instanceof $G||e instanceof eK?(xK(e),V9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof eK?`too_old`:`not_available`,detectedVersion:e instanceof eK?e.detected:``},e instanceof eK?`git binary too old`:`git binary not found`)):V9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let s=o.resolvedPath;if(a)return await W9(s,t),{didInit:!1};if(!i&&await INe(s,t))return{didInit:!1};let c=``;try{c=(await B9(s,[`init`,`--initial-branch=main`,t],JM({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new H9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!z(r))throw new H9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,c);return await W9(s,t),i?(V9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(V9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=N(`project-skill-git`),K9=/^[0-9a-f]{40}$/,RNe=Vn.map(e=>e.replace(/\/$/,``));async function zNe(e){let t=kd(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(UNe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=hc(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await pc(async()=>{let t=await BNe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await VNe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=hc(e,{gitIndexFile:F(ed(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await HNe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await gB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;_c(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${xa}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!K9.test(f))return G9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return G9.info({branch:t,err:J9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){G9.info({err:J9(e)},`real-index reset after untrack failed (cosmetic)`)}return G9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:J9(e)}}}async function q9(e){let t=[];for(let n of RNe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function BNe(e){try{let t=(await e.git.raw([`rev-parse`,`--abbrev-ref`,`HEAD`])).trim();return t.length===0||t===`HEAD`?null:t}catch{return null}}async function VNe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function HNe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function UNe(e){return z(F(e,`MERGE_HEAD`))||z(F(e,`rebase-merge`))||z(F(e,`rebase-apply`))||z(F(e,`CHERRY_PICK_HEAD`))||z(F(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function WNe(e,t){let n;try{n=uu(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=P(n),r=0;r<32;r+=1){let n=F(t,`package.json`);if(z(n))try{let t=JSON.parse(await id(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=P(t);if(r===t)return;t=r}}const GNe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Y9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of GNe)t=t.replace(e,n);return t}function X9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Y9(e.message)??``,stack:Y9(e.stack),code:e.code,cause:e.cause===void 0?void 0:X9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Y9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Y9(String(r.message??``))??``,stack:Y9(r.stack),code:r.code,cause:r.cause===void 0?void 0:X9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Z9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},Q9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function KNe(e){if(!zx(e))throw new $9(e);let t;try{t=V(L(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!qu(t).isFile())throw new Q9(e);let n=P(t),r=eB(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Vx(I(qNe(e),t).split(R).join(`/`)),canonicalFilePath:t}}let i=gu(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Vx(i)}}function qNe(e){return L(e,Ts({absPath:Vs(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function JNe(e){let t=Lu(L(ed(),`ok-ephemeral-`)),n=L(t,`.ok`);return Iu(n,{recursive:!0}),Yu(L(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Yu(L(n,`.gitignore`),`local/
|
|
2016
2016
|
`,`utf-8`),t}export{_2 as $,Sx as $i,WR as $n,WM as $r,FJ as $t,K7 as A,Tw as Ai,bB as An,LP as Ar,LZ as At,o7 as B,pS as Bi,jz as Bn,EP as Br,zJ as Bt,d9 as C,Nd as Ca,tD as Ci,EB as Cn,$F as Cr,HZ as Ct,q7 as D,Sd as Da,EE as Di,MB as Dn,LF as Dr,cve as Dt,W7 as E,Ad as Ea,FE as Ei,wB as En,bme as Er,aZ as Et,Hje as F,vw as Fi,cz as Fn,jP as Fr,KX as Ft,m8 as G,rS as Gi,Mz as Gn,nN as Gr,WJ as Gt,g8 as H,fS as Hi,pz as Hn,eP as Hr,Nhe as Ht,_7 as I,lw as Ii,Pz as In,AP as Ir,WX as It,s8 as J,Zx as Ji,ez as Jn,aN as Jr,qJ as Jt,f8 as K,$x as Ki,dz as Kn,oN as Kr,Phe as Kt,g7 as L,jC as Li,hz as Ln,OP as Lr,Hhe as Lt,P7 as M,yw as Mi,vB as Mn,FP as Mr,HX as Mt,j7 as N,Sw as Ni,eB as Nn,epe as Nr,UX as Nt,H7 as O,PE as Oi,NB as On,ZP as Or,lve as Ot,h7 as P,_w as Pi,$z as Pn,kP as Pr,GX as Pt,f2 as Q,Dx as Qi,JR as Qn,JM as Qr,PJ as Qt,Aje as R,MC as Ri,mz as Rn,Yfe as Rr,eY as Rt,P9 as S,Yd as Sa,HO as Si,AW as Sn,QF as Sr,JZ as St,V7 as T,qd as Ta,ZE as Ti,LB as Tn,eI as Tr,oZ as Tt,_8 as U,aS as Ui,Nz as Un,Nfe as Ur,YJ as Ut,r7 as V,G as Vi,Ez as Vn,Jfe as Vr,Fhe as Vt,h8 as W,Qx as Wi,Zz as Wn,rN as Wr,UJ as Wt,u2 as X,Tx as Xi,qR as Xn,YM as Xr,JJ as Xt,Z6 as Y,Px as Yi,KR as Yn,eN as Yr,KJ as Yt,d2 as Z,Ex as Zi,YR as Zn,QM as Zr,GJ as Zt,xNe as _,yh as _a,Oj as _i,OW as _n,sI as _r,qZ as _t,KNe as a,Nx as aa,ude as ai,eK as an,Jme as ar,nSe as at,N9 as b,Xd as ba,Rk as bi,kW as bn,rI as br,GZ as bt,zNe as c,Ix as ca,cde as ci,yK as cn,OI as cr,m0 as ct,MNe as d,sx as da,Gj as di,iK as dn,DI as dr,bye as dt,kx as ea,AM as ei,TK as en,FR as er,mSe as et,ONe as f,ax as fa,Nue as fi,JG as fn,CI as fr,L$ as ft,SNe as g,_h as ga,Ej as gi,DW as gn,lI as gr,WZ as gt,jNe as h,Tie as ha,kj as hi,yW as hn,wI as hr,YZ as ht,JNe as i,vx as ia,Yj as ii,$G as in,NI as ir,tSe as it,B7 as j,rw as ji,yB as jn,RP as jr,lZ as jt,G7 as k,Cw as ki,AB as kn,IP as kr,zZ as kt,H9 as l,gx as la,Zue as li,tK as ln,TI as lr,W$ as lt,ANe as m,Ase as ma,jue as mi,WG as mn,Pme as mr,eQ as mt,Z9 as n,wx as na,$j as ni,bK as nn,dR as nr,r2 as nt,X9 as o,jx as oa,sde as oi,ZG as on,Hme as or,rSe as ot,kNe as p,Qb as pa,Aj as pi,qG as pn,SI as pr,B$ as pt,u8 as q,nS as qi,$R as qn,iN as qr,XJ as qt,$9 as r,Fx as ra,Qj as ri,xK as rn,PI as rr,Q0 as rt,WNe as s,Mx as sa,lde as si,nK as sn,AI as sr,K0 as st,Q9 as t,bx as ta,kM as ti,CK as tn,bR as tr,i2 as tt,LNe as u,lx as ua,Rj as ui,cK as un,EI as ur,S$ as ut,yNe as v,vh as va,Dj as vi,CW as vn,cI as vr,UZ as vt,u9 as w,Md as wa,$E as wi,kB as wn,YF as wr,BZ as wt,M9 as x,nf as xa,Bk as xi,xW as xn,aI as xr,wve as xt,I9 as y,tf as ya,zk as yi,MW as yn,oI as yr,KZ as yt,l7 as z,tw as zi,Fz as zn,DP as zr,QJ as zt};
|
|
2017
|
-
//# sourceMappingURL=src-
|
|
2017
|
+
//# sourceMappingURL=src-CyDF8_Em.mjs.map
|