@inkeep/open-knowledge 0.59.0-beta.33 → 0.59.0-beta.35
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-Dsnqy0qw.mjs → acp-harness-probe-vsGUe6qp.mjs} +2 -2
- package/dist/cli.mjs +6 -6
- package/dist/constants-ZaRc-oTU.mjs +2 -0
- package/dist/index.mjs +1 -1
- package/dist/init-IRj6tWLS.mjs +1 -0
- package/dist/{init-DtrBRC9X.mjs → init-r0YtTtfz.mjs} +3 -3
- package/dist/{launch-json-removal-B6wYkgVM.mjs → launch-json-removal-Om4i-L6S.mjs} +2 -2
- package/dist/loader-BUmJVdvY.mjs +1 -0
- package/dist/{loader-gvjGD75Z.mjs → loader-CR3h5Mju.mjs} +2 -2
- package/dist/{open-browser-BoXWzzB3.mjs → open-browser-Buuo3P-E.mjs} +2 -2
- package/dist/preview-9ouAo77k.mjs +1 -0
- package/dist/{preview-BupSAjt8.mjs → preview-BT3Oifm5.mjs} +2 -2
- package/dist/public/assets/{ActivityModeContent-DOpDpkQL.js → ActivityModeContent-ZMkynbjt.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-CzgUZIPo.js → AgentDiffPane-B8nC1KUO.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-CwMSmIBj.js → CodeMirrorPropInput-D7nB1aDJ.js} +1 -1
- package/dist/public/assets/{DocumentContext-mHHM9ElG.js → DocumentContext-DK6WjZtm.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-B9BxwEaC.js → EditorModeToggle-Bw3g_RS7.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-BHCuvd7J.js → EnableSyncConfirmDialog-D6G6yrqT.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-DEHhObiP.js → ExcalidrawDocEditor-BUL0FNWm.js} +1 -1
- package/dist/public/assets/FeedbackForm-DW0x7yxI.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-CjPKDQBK.js → ImportSkillDialog-Eb3L_zjp.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-C_Vfj_OU.js → LintConfigEditor-DfvsohvN.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-jNRmYNzs.js → ManagedArtifactProperties-BmksuBSn.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-lJ8wwEp2.js +1 -0
- package/dist/public/assets/{MermaidDocEditor-Dj2CGDpm.js → MermaidDocEditor-QByjyMzX.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-DpWgpyY9.js → PropertyDisplayRow-CE9D0uq8.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-D2BFbCrq.js → SchemaConfigEditor-vZ4Iznw7.js} +1 -1
- package/dist/public/assets/SessionsHost-p4B3j2uq.js +2 -0
- package/dist/public/assets/SettingsDialogBody-CzOL2SRu.js +13 -0
- package/dist/public/assets/{ShareReceiveMissDialog-BidjxXjR.js → ShareReceiveMissDialog-D4TxU2FH.js} +1 -1
- package/dist/public/assets/{SkillInstallMenu-Cx58499S.js → SkillInstallMenu-Djr9cLyQ.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-BjPK4rLl.js → SkillToolbarControls-NDRzmFvN.js} +1 -1
- package/dist/public/assets/{SourceEditor-CziLRamo.js → SourceEditor-D280BxeC.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-BN42DLuZ.js → TerminalWindowApp-DiFRQ0Wj.js} +1 -1
- package/dist/public/assets/{TextDocEditor-jDn4bHh4.js → TextDocEditor-B19eo9Zu.js} +1 -1
- package/dist/public/assets/{ThreadView-D4orJWbz.js → ThreadView-DuWlmKjj.js} +2 -2
- package/dist/public/assets/{TimelineDiffPane-Bh01rWRX.js → TimelineDiffPane-iZl0xaNU.js} +1 -1
- package/dist/public/assets/{agent-diff-store-CnqY1OQH.js → agent-diff-store-d13OQwxA.js} +1 -1
- package/dist/public/assets/{auth-state-cache-DhmqOBfL.js → auth-state-cache-CE_bMumR.js} +1 -1
- package/dist/public/assets/{comment-chips-DLcjFmVN.js → comment-chips-DxWHm9Cs.js} +1 -1
- package/dist/public/assets/{config-provider-B54GosQj.js → config-provider-KCmXGgSj.js} +3 -3
- package/dist/public/assets/i18n-CxTgngSa.js +1 -0
- package/dist/public/assets/index-BT38n3zl.js +2098 -0
- package/dist/public/assets/{messages-W4EQLozB.js → messages-1FEsSIIj.js} +1 -1
- package/dist/public/assets/{messages-DoKxyRgP.js → messages-41bTs04W.js} +1 -1
- package/dist/public/assets/{messages-D9ldJ6Xm.js → messages-5S8je5LW.js} +1 -1
- package/dist/public/assets/{messages-C8jffdCe.js → messages-BaIuOlWR.js} +1 -1
- package/dist/public/assets/{messages-DdRp2uUH.js → messages-BqArTNvV.js} +1 -1
- package/dist/public/assets/{messages-DN37a6Ol.js → messages-CMcVg4Ix.js} +1 -1
- package/dist/public/assets/{messages-D3MBHECc.js → messages-DFzZnRi7.js} +1 -1
- package/dist/public/assets/{messages-CHwiuY_J.js → messages-DOht_ZsB.js} +1 -1
- package/dist/public/assets/{messages-CiFiW58E.js → messages-DQN4o7er.js} +1 -1
- package/dist/public/assets/{messages-CjKUNgHP.js → messages-Dhio81WF.js} +1 -1
- package/dist/public/assets/{messages-CU7VLvME.js → messages-DyPdsAJb.js} +1 -1
- package/dist/public/assets/{messages-J0QBWpSt.js → messages-Vv0nGwDC.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-BRSGFYxK.js → pending-receive-nav-store-eivLgf-S.js} +1 -1
- package/dist/public/assets/{progress-CBxzVuzZ.js → progress-BzUYuL-V.js} +1 -1
- package/dist/public/assets/{selection-context-C09_QCK1.js → selection-context-gHo_9Fbo.js} +1 -1
- package/dist/public/assets/skill-actions-DtcJ1SJd.js +1 -0
- package/dist/public/assets/{src-B1BHrZl0.js → src-NjVFjnQM.js} +1 -1
- package/dist/public/assets/terminal-cli-display-C2erLHKw.js +1 -0
- package/dist/public/assets/terminal-launch-events-CKR4fyca.js +1 -0
- package/dist/public/assets/{terminal-telemetry-Cm0Met9j.js → terminal-telemetry-DVJphneI.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-KkE8c4Vi.js → typing-burst-detector-CgfR26-J.js} +1 -1
- package/dist/public/assets/{uninstall-CtNQlhEE.js → uninstall-ZTgWvcqD.js} +1 -1
- package/dist/public/assets/{use-activity-panel-9bQHoObM.js → use-activity-panel-D-Xmd1zX.js} +1 -1
- package/dist/public/assets/{use-open-skill-aRFadf4f.js → use-open-skill-Cwhk0mI6.js} +1 -1
- package/dist/public/assets/{use-popular-skills-BxJfjPnS.js → use-popular-skills-C4zNnQqG.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-Q8tbeQdS.js → use-terminal-enabled-QPWQYOg5.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-Cn1xybVO.js → use-timeline-entry-diff-BcxlAt36.js} +1 -1
- package/dist/public/index.html +25 -25
- package/dist/public/uninstall.html +3 -3
- package/dist/{repair-launch-json-03f6Lh0E.mjs → repair-launch-json-DNtAoYuK.mjs} +2 -2
- package/dist/{repair-mcp-configs-CVfBp4g6.mjs → repair-mcp-configs-CE3qqMQw.mjs} +2 -2
- package/dist/{repair-skills-CVBoZIiO.mjs → repair-skills-BsBXroSe.mjs} +2 -2
- package/dist/repair-skills-K7CwEUhi.mjs +1 -0
- package/dist/{resolve-project-root-9pJU-v6u.mjs → resolve-project-root-BCtyt-M3.mjs} +2 -2
- package/dist/{skill-teardown-Bk-FU2uA.mjs → skill-teardown-CEOCC6te.mjs} +2 -2
- package/dist/{src-DglWR2eG.mjs → src-3c-GN0Vv.mjs} +3 -3
- package/dist/src-B-ikueq5.mjs +1 -0
- package/dist/{src-C8WBxBLt.mjs → src-BReyc6U1.mjs} +1 -1
- package/dist/{src-qqsp5LYS.mjs → src-DdFbH19m.mjs} +2 -2
- package/dist/start-BU-5d7w8.mjs +1 -0
- package/dist/{start-Jp250mlL.mjs → start-DJZtRPBb.mjs} +3 -3
- package/package.json +4 -4
- package/dist/constants-CEhsHkzu.mjs +0 -2
- package/dist/init-CTc2FAxI.mjs +0 -1
- package/dist/loader-NNqVeTLU.mjs +0 -1
- package/dist/preview-DISuvmS7.mjs +0 -1
- package/dist/public/assets/FeedbackForm-B5mA-zp3.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-BU8BzGED.js +0 -1
- package/dist/public/assets/SessionsHost-B76Z99qW.js +0 -2
- package/dist/public/assets/SettingsDialogBody-C9rgO08d.js +0 -13
- package/dist/public/assets/i18n-CctDYDxT.js +0 -1
- package/dist/public/assets/index-amQimFo_.js +0 -2098
- package/dist/public/assets/skill-actions-B8BU9tYy.js +0 -1
- package/dist/public/assets/terminal-cli-display-Cx78jPxI.js +0 -1
- package/dist/public/assets/terminal-launch-events-DHOdsro0.js +0 -1
- package/dist/repair-skills-C_-Lco2y.mjs +0 -1
- package/dist/src-D5BLIKTF.mjs +0 -1
- package/dist/start-AsXoIIvq.mjs +0 -1
|
@@ -26,7 +26,7 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,A as i,At
|
|
|
26
26
|
`))n.trim()!==``&&(e.stderrTail.push(n.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift(),e.authStderr!==null&&(e.authStderr.push(n.slice(0,500)),e.authStderr.length>6&&e.authStderr.shift(),e.info.signInOutput=[...e.authStderr],this.broadcastInfo(e)))}),o.on(`error`,t=>{this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),o.on(`exit`,(t,n)=>{if(e.child=null,a.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),e.closed||e.info.archived===!0)return;if(e.info.status===`error`){this.failPendingPermissions(e);return}let r=e.stderrTail.slice(-10).join(`
|
|
27
27
|
`);this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,code:t,signal:n,machineDetail:rE(e)},`[acp-threads] agent exited unexpectedly`),this.emitStatus(e,`exited`,`agent exited (${n??t??`unknown`})${r?`\n${r}`:``}`),this.failPendingPermissions(e)}),o.stdin===null||o.stdout===null)throw new UT(`spawn-failed`,`agent process has no stdio`);let s=Eie(qte.toWeb(o.stdin),Wu.toWeb(o.stdout)),c=Jie({name:`open-knowledge`}).onRequest(Lm.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(Lm.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(Lm.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(Lm.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),a.create(t.params))).onRequest(Lm.client.terminal.output,e=>a.output(e.params.terminalId)).onRequest(Lm.client.terminal.waitForExit,e=>a.waitForExit(e.params.terminalId)).onRequest(Lm.client.terminal.kill,async e=>(await a.kill(e.params.terminalId),{})).onRequest(Lm.client.terminal.release,async e=>(await a.release(e.params.terminalId),{})).onNotification(Lm.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(s);e.conn=c,c.closed.then(()=>{!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`)});let l;try{l=await c.agent.request(Lm.agent.initialize,{protocolVersion:1,clientInfo:{name:`open-knowledge`,title:`Open Knowledge`,version:bc},clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(t){throw this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] initialize failed`),new UT(`spawn-failed`,`initialize failed: ${eE(t)}`)}return e.closed?null:(e.lastInit=l,e.info.promptCapabilities=l.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:c,init:l,launch:n})}async ensureLaunchable(e,t){let n;try{await Gw(t),n=await this.withLoginShellPathIfEligible(t)}catch(r){if(!(r instanceof Iw)||r.code!==`command-not-found`)throw r;let i=await this.retryWithLoginShellPath(t);if(i===null)return this.fallbackToManagedRuntime(e,t,r);n=i}return e.closed?null:this.ensureInterpreterRuns(e,n)}async ensureInterpreterRuns(e,t){if(t.kind!==`npx`&&t.kind!==`uvx`)return t;let n=await this.probeInterpreterOnce(t);if(e.closed)return null;if(n===null)return t;if(n.kind===`incompatible`){let n=await this.withPreferredLoginShellPathIfEligible(t);if(e.closed)return null;if(Jw(n.env)!==Jw(t.env))try{await Gw(n);let t=await this.probeInterpreterOnce(n);if(e.closed)return null;if(t===null)return this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id},`[acp-threads] compatible Node resolved via the preferred login-shell PATH`),n;this.opts.log.debug({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:n.cmd,kind:n.kind,failureKind:t.kind,detail:t.detail},`[acp-threads] preferred login-shell PATH did not provide a compatible Node`)}catch(e){if(!(e instanceof Iw)||e.code!==`command-not-found`)throw e}}this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:t.cmd,kind:t.kind,failureKind:n.kind,detail:n.detail},`[acp-threads] interpreter cannot run this agent — offering the managed runtime`);let r=new Iw(`command-not-found`,n.kind===`incompatible`?aue(t,n.detail):$le(t,n.detail));return this.fallbackToManagedRuntime(e,t,r,r)}async fallbackToManagedRuntime(e,t,n,r){if(t.kind!==`npx`&&t.kind!==`uvx`)throw n;let i=uue(t.kind);if(!hT(i))throw n;let a=await this.provideManagedRuntime(e,i,r===void 0?`missing`:`broken`).catch(e=>{throw r!==void 0&&e instanceof Iw&&e.code===`command-not-found`?r:e});if(a===null)return null;let o=Bw(t,a);await Gw(o);let s=await this.probeInterpreterOnce(o);if(s===null)return o;if(s.kind===`incompatible`)throw new Iw(`install-failed`,Kw(s.detail));return this.repairManagedRuntime(e,t,i,s.detail)}async repairManagedRuntime(e,t,n,r){let i={threadId:e.info.threadId,agentId:e.info.agent.id,runtime:n,detail:r};if(this.opts.log.warn(i,`[acp-threads] OK's own managed runtime failed to run — replacing it`),!await ST(n,this.opts.log,this.opts.runtimeInstall?.root))throw new Iw(`install-failed`,tue(t,r));let a=await this.provideManagedRuntime(e,n,`damaged`).catch(e=>{throw e instanceof Iw&&e.code===`command-not-found`?new Iw(`command-not-found`,nue(t)):e});if(a===null)return null;let o=Bw(t,a);await Gw(o);let s=await this.probeInterpreterOnce(o);if(s===null)return o;throw this.opts.log.error({...i,detail:s.detail},`[acp-threads] a freshly downloaded managed runtime failed to run`),new Iw(`install-failed`,s.kind===`incompatible`?Kw(s.detail):eue(o,s.detail))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,Jw(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await rue(e,void 0,this.opts.log);if(n!==null)return{kind:`unhealthy`,detail:n};if(e.kind===`npx`){let t=await iue(e,void 0,this.opts.log);if(t!==null)return{kind:`incompatible`,detail:t}}return this.healthyInterpreters.add(t),null}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(Jw(t.env)===Jw(e.env))return null;try{await Gw(t)}catch(t){if(!(t instanceof Iw))throw t;return this.opts.log.debug({cmd:e.cmd,kind:e.kind},`[acp] login-shell PATH did not resolve the command either`),null}return this.opts.log.info({cmd:e.cmd,kind:e.kind},`[acp] command resolved via the login-shell PATH; skipping the managed-runtime offer`),t}async withLoginShellPathIfEligible(e){if(e.pathFromOverlay||Yw(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:Vw(e,t)}async withPreferredLoginShellPathIfEligible(e){if(e.pathFromOverlay||Yw(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:Gle(e,t)}async provideManagedRuntime(e,t,n){let r=this.opts.runtimeInstall?.root;await xT(t,this.opts.log,r);let i=await yT(t,r).catch(()=>null);if(i!==null)return i;let a=await this.requestRuntimeConsent(e,t,n);if(a===`closed`||e.closed)return null;if(a!==`granted`)throw new Iw(`command-not-found`,QT(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=cT(t).displayName;throw new Iw(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n){let r=crypto.randomUUID(),i=cT(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:r,runtime:t,displayName:i.displayName,provides:i.provides,version:i.version,approxSizeMB:i.approxSizeMB,sourceHost:i.sourceHost,agentName:e.info.agent.name,reason:n,ts:Date.now()}),new Promise(t=>{let n=setTimeout(()=>{e.pendingRuntimeConsent.delete(r),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:r,decision:`timeout`,ts:Date.now()}),t(`timeout`)},3e5);n.unref?.(),e.pendingRuntimeConsent.set(r,{resolve:t,timer:n})})}respondRuntimeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingRuntimeConsent.get(t);if(i===void 0)return;r.pendingRuntimeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;this.appendEvent(r,{kind:`runtime_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async downloadRuntime(e,t){this.emitStatus(e,`installing`);let n=0;return CT(t,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:r=>{let i=Date.now();i-n<400||(n=i,!e.closed&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:t,phase:`downloading`,receivedBytes:r.receivedBytes,totalBytes:r.totalBytes??void 0,ts:i}))}})}async buildMcpServers(e,t){if(await this.harnessAlreadyHasOkMcp(e)!==null)return[];let n=[],r=this.opts.getServerUrl?.();if(r!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)n.push({type:`http`,name:`open-knowledge`,url:`${r}/mcp`,headers:[{name:aw,value:`1`}]});else{let e=this.opts.getMcpStdioCommand?.();e!=null&&n.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:ar,value:`1`}]})}return n}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=Ane[e.agentRef.id];if(n===void 0)return null;let r;try{r=await t(n,e.cwd)}catch(t){return this.opts.log.warn({err:t,threadId:e.info.threadId,editorId:n},`[acp-threads] harness MCP-config probe failed — injecting OK MCP`),null}return r!==null&&this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,editorId:r.editorId,scope:r.scope,configPath:r.configPath},`[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry`),r}async startThread(e,t,n){let r;try{r=await this.connectAgent(e,n)}catch(t){let n=t instanceof Iw||t instanceof UT?t.message:String(t);this.emitStatus(e,`error`,n,{reason:`connect`,agentMessage:n,machineDetail:rE(e)}),await this.teardownFailedAgent(e);return}if(r===null)return;let{conn:i,init:a,launch:o}=r;await this.openSession(e,i,a,t.settings)===!0&&(this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:o.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`),(t.prompt!==void 0&&t.prompt!==``||t.attachments!==void 0&&t.attachments.length>0)&&this.sendPrompt(e.info.threadId,t.prompt??``,t.attachments))}async openSession(e,t,n,r,i=`park`){e.info.availableCommands=null;let a=await this.buildMcpServers(e,n);try{let n=await t.agent.request(Lm.agent.session.new,{cwd:e.cwd,mcpServers:a});e.sessionId=n.sessionId,e.envNotePending=!0,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),n.modes!==void 0&&n.modes!==null&&(e.info.modes=n.modes,this.emitInfo(e)),n.configOptions!==void 0&&n.configOptions!==null&&(e.info.configOptions=n.configOptions,this.emitInfo(e))}catch(t){if($T(t)){if(i===`report`)return`auth-required`;this.emitStatus(e,`auth_required`,`sign in required: ${eE(t)}`,{reason:`auth-required`,agentMessage:eE(t),machineDetail:aE(t,e),authMethods:oE(n.authMethods)})}else this.emitStatus(e,`error`,`session setup failed: ${eE(t)}`,{reason:`session-setup`,agentMessage:eE(t),machineDetail:iE(tE(t),rE(e))}),await this.teardownFailedAgent(e);return!1}return e.closed||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),e.closed)||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),e.closed)?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new UT(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.info.archived!==!0)throw new UT(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new UT(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new UT(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.resumeInFlight=!0;let i=Date.now();try{await this.ensureLogResolved(r);let a=r.sessionId,{info:o,custom:s}=await this.resolveAgentInfo(r.agentRef);if(this.destroyed)throw new UT(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new UT(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.info.agent=o,r.info.archived=!1,r.info.availableCommands=null,r.stderrTail=[],r.midTurnOnDisk&&(r.midTurnOnDisk=!1,this.appendEvent(r,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}));let c=t!==void 0&&t!==``||n!==void 0&&n.length>0;c&&(this.echoUserMessage(r,t??``,n),this.flushBroadcast(r)),this.emitStatus(r,`installing`);try{if(a===null)throw new UT(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,s);if(o===null)throw new UT(`not-ready`,`thread closed during resume`);let{conn:l,init:u}=o,d=await this.buildMcpServers(r,u),f=u.agentCapabilities,p=f?.sessionCapabilities?.resume!=null,m;if(p)m=await l.agent.request(Lm.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:d});else if(f?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{m=await l.agent.request(Lm.agent.session.load,{sessionId:a,cwd:r.cwd,mcpServers:d}),await this.awaitReplayQuiescence(r)}finally{r.suppressUpdates=!1}}else throw new UT(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);r.sessionId=a;let h=m.modes;h!=null&&(r.info.modes=h);let g=m.configOptions;return g!=null&&(r.info.configOptions=g),this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:p?`session/resume`:`session/load`,msToResumed:Date.now()-i},`[acp-threads] thread resumed`),c&&this.dispatchPrompt(r,t??``,n,{echo:!1}),{...r.info}}catch(t){throw await this.abortResume(r),t instanceof UT?t:t instanceof Iw?new UT(t.code===`install-failed`?`install-failed`:`spawn-failed`,t.message):(this.opts.log.warn({err:t,threadId:e},`[acp-threads] resume rejected by the agent`),new UT(`resume-unsupported`,`couldn't resume the previous session: ${eE(t)}`))}}finally{r.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new UT(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new UT(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new UT(`not-ready`,`this thread did not fail to start`);if(t.sessionId!==null)throw new UT(`not-ready`,`this thread already has an agent session`);if(t.resumeInFlight)throw new UT(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{Rle(),this.healthyInterpreters.clear();let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);await this.teardownFailedAgent(t),t.info.agent=n,t.stderrTail=[],t.cancelRequested=!1,t.turnActive=!1,this.emitStatus(t,`installing`);try{await this.startThread(t,{agent:t.agentRef,settings:t.launchSettings},r)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new UT(`spawn-failed`,n)}if(t.closed)throw new UT(`not-ready`,`thread closed during retry`);let i=this.getInfo(e)?.status;if(i===`ready`||i===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new UT(`spawn-failed`,nE(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new UT(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new UT(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new UT(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit;if(r===null||i===null||n.child===null)throw new UT(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new UT(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new UT(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0,n.authStderr=[],n.info.signInOutput=void 0;try{this.emitStatus(n,`authenticating`);try{await this.requestAuthenticate(r,t)}catch(e){if(n.conn!==r)throw KT();let t=e instanceof WT?`the sign-in didn't complete in time — try again`:eE(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:aE(e,n),authMethods:oE(i.authMethods)}),new UT(`not-ready`,t)}if(n.closed)throw new UT(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw KT();let a=await this.openSession(n,r,i,n.launchSettings,`report`);if(a===`auth-required`){this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] signed in but session still refused — relaunching the agent`),this.closeSignInCapture(n);try{return await this.retryThread(e)}catch(t){throw this.getInfo(e)?.status===`authenticating`&&this.emitStatus(n,`auth_required`,`sign in required: ${eE(t)}`,{reason:`auth-required`,agentMessage:eE(t),machineDetail:aE(t,n),authMethods:oE(i.authMethods)}),t}}if(a!==!0)throw new UT(`not-ready`,nE(n)??`${n.info.agent.name} still couldn't start a conversation`);return this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] thread signed in`),{...n.info}}finally{n.authInFlight=!1,this.closeSignInCapture(n)}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new WT),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(Lm.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e){e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingRuntimeConsent(e);try{e.conn?.close()}catch{}let t=e.child;t!==null&&await nT(t,{graceMs:HT}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(rh(e.agentSessionId)),e.info.archived=!0,this.emitStatus(e,`exited`,`resume failed`),this.flushBroadcast(e),this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),await this.persistence.whenIdle(e.info.threadId),e.baseSeq=e.info.lastSeq+1,e.events=[]}async awaitReplayQuiescence(e){let t=Date.now()+3e3;for(;Date.now()-e.lastSuppressedAt<300&&Date.now()<t;)await new Promise(e=>setTimeout(e,50))}sendPrompt(e,t,n){let r=this.mustGet(e);if(r.info.archived===!0)throw new UT(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new UT(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new UT(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new UT(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new UT(`not-ready`,`20 messages are already waiting — let the agent catch up`);let i={id:crypto.randomUUID(),content:t,ts:Date.now()};n!==void 0&&n.length>0&&(i.attachments=n),r.info.queue=[...e,i],r.info.lastActivityAt=Date.now(),this.emitInfo(r);return}this.dispatchPrompt(r,t,n,{echo:!0})}steerPrompt(e,t,n){let r=this.mustGet(e);if(r.info.archived===!0)throw new UT(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new UT(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new UT(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new UT(`not-ready`,`thread has no live agent session`);if(!r.turnActive){this.dispatchPrompt(r,t,n,{echo:!0});return}this.clearSteer(r);let i={content:t,ts:Date.now()};n!==void 0&&n.length>0&&(i.attachments=n),r.info.steer=i,r.info.lastActivityAt=Date.now(),this.emitInfo(r);let a=setTimeout(()=>this.demoteStalledSteer(r),this.steerStallMs);a.unref?.(),r.steerStallTimer=a,this.cancelTurn(r,{clearQueue:!1})}demoteStalledSteer(e){e.steerStallTimer=null;let t=e.info.steer;if(t===void 0||e.closed||!e.turnActive)return;e.info.steer=void 0;let n={id:crypto.randomUUID(),content:t.content,ts:t.ts};t.attachments!==void 0&&t.attachments.length>0&&(n.attachments=t.attachments),e.info.queue=[n,...e.info.queue??[]],this.emitInfo(e)}clearSteer(e){e.steerStallTimer!==null&&(clearTimeout(e.steerStallTimer),e.steerStallTimer=null),e.info.steer=void 0}takeSteer(e){let t=e.info.steer;return t===void 0?null:(this.clearSteer(e),t)}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,content:n,held:!1}:e),this.emitInfo(r),this.drainIfIdle(r),!0):!1}holdQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,held:n}:e),this.emitInfo(r),n||this.drainIfIdle(r),!0):!1}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);return i.length===r.length?!1:(n.info.queue=i.length>0?i:void 0,this.emitInfo(n),!0)}drainIfIdle(e){if(e.turnActive||e.closed||e.resumeInFlight||e.info.archived===!0||e.sessionId===null||e.conn===null)return;let t=this.takeNextQueued(e);t!==null&&this.dispatchPrompt(e,t.content,t.attachments,{echo:!0})}takeNextQueued(e){let t=e.info.queue;if(t===void 0||t.length===0)return null;let n=t.findIndex(e=>e.held!==!0);if(n===-1)return null;let r=t[n],i=[...t.slice(0,n),...t.slice(n+1)];return e.info.queue=i.length>0?i:void 0,r??null}echoUserMessage(e,t,n){if(e.hadUserMessage=!0,e.info.title===e.info.agent.name&&t.trim()!==``){let n=e.titleHint!==void 0&&e.titleHint.trim()!==``?e.titleHint:t;e.titleHint=void 0,e.info.title=RT(n),this.appendEvent(e,{kind:`title_changed`,title:e.info.title,ts:Date.now()}),this.emitInfo(e)}let r={kind:`user_message`,content:t,ts:Date.now()};n!==void 0&&n.length>0&&(r.attachments=n),this.appendEvent(e,r)}async renameThread(e,t){let n=this.mustGet(e);if(n.closed)throw new UT(`not-ready`,`the thread is closing`);let r=LT(t);r===``||r===n.info.title||(await this.ensureLogResolved(n),n.info.title=r,n.info.lastActivityAt=Date.now(),this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId))}dispatchPrompt(e,t,n,r){if(e.sessionId===null||e.conn===null)throw new UT(`not-ready`,`thread has no live agent session`);r.echo&&this.echoUserMessage(e,t,n);let i=t;e.envNotePending&&!t.startsWith(`/`)&&(e.envNotePending=!1,i=`Note on your environment: you are running inside the OpenKnowledge app, connected over ACP (Agent Client Protocol) — not inside your own terminal app. Your host CLI's terminal UI is not present, so its built-in slash commands (such as /tasks or /bashes) and keyboard shortcuts (such as Ctrl+O) do not exist here; never recommend them. The only slash commands available to the user are the ones you advertise over ACP.\n\n${t}`),e.turnActive=!0,e.cancelRequested=!1,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`);let a=e.sessionId;cw(i,n,e.info.promptCapabilities,e=>this.confinePath(e).then(({abs:e,rel:t})=>({abs:e,rel:t}))).then(t=>{if(t.dropped.length>0){this.opts.log.warn({threadId:e.info.threadId,dropped:t.dropped.map(e=>({kind:e.part.kind,reason:e.reason}))},`[acp-threads] dropped attachment parts before session/prompt`);let n=Date.now();for(let r of t.dropped){let t=r.part.kind===`image`||r.part.kind===`blob`?r.part.name:r.part.name||r.part.path;this.appendEvent(e,{kind:`agent_stderr`,line:`[attachment dropped] ${t}: ${r.reason}`,ts:n})}}if(e.sessionId===null||e.conn===null)throw new UT(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new GT;return e.conn.agent.request(Lm.agent.session.prompt,{sessionId:a,prompt:[...t.blocks]})}).then(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:t.stopReason,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,t.attachments,{echo:!0});return}let n=this.takeNextQueued(e);if(n!==null){this.dispatchPrompt(e,n.content,n.attachments,{echo:!0});return}}this.emitStatus(e,`ready`)}}).catch(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,t.attachments,{echo:!0});return}}if(e.cancelRequested){this.emitStatus(e,`ready`),this.drainIfIdle(e);return}if($T(t)){this.emitStatus(e,`auth_required`,`sign in required: ${eE(t)}`,{reason:`auth-required`,agentMessage:eE(t),machineDetail:aE(t,e),authMethods:oE(e.lastInit?.authMethods)});return}this.emitStatus(e,`error`,`prompt failed: ${eE(t)}`,{reason:`prompt`,agentMessage:eE(t),machineDetail:iE(tE(t),rE(e))})}})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){t.clearQueue&&(e.info.queue!==void 0||e.info.steer!==void 0)&&(e.info.queue=void 0,this.clearSteer(e),this.emitInfo(e)),!(e.conn===null||e.sessionId===null)&&(e.turnActive&&(e.cancelRequested=!0),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(Lm.agent.session.cancel,{sessionId:e.sessionId}).catch(t=>{this.opts.log.debug({err:t,threadId:e.info.threadId},`[acp-threads] cancel notification never reached the agent`)}))}setMode(e,t){let n=this.mustGet(e);if(n.conn===null||n.sessionId===null)throw new UT(`not-ready`,`thread has no live agent session`);n.conn.agent.request(Lm.agent.session.setMode,{sessionId:n.sessionId,modeId:t}).then(()=>{n.info.modes&&(n.info.modes={...n.info.modes,currentModeId:t},this.emitInfo(n))}).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] set_mode failed`)})}setConfigOption(e,t,n){let r=this.mustGet(e);if(r.conn===null||r.sessionId===null)throw new UT(`not-ready`,`thread has no live agent session`);let i=typeof n==`boolean`?{sessionId:r.sessionId,configId:t,type:`boolean`,value:n}:{sessionId:r.sessionId,configId:t,value:n};r.conn.agent.request(Lm.agent.session.setConfigOption,i).then(e=>{r.info.configOptions=e.configOptions,this.emitInfo(r)}).catch(n=>{this.opts.log.warn({err:n,threadId:e,configId:t},`[acp-threads] set_config_option failed`)})}async applyInitialConfig(e,t,n){let r=e.sessionId;if(r===null)return;let i=t=>(e.info.configOptions??[]).find(e=>e.id===t)?.category===`model`,a=Object.keys(n).sort((e,t)=>Number(i(t))-Number(i(e))),o=!1,s=[];for(let i of a){let a=n[i];if(a===void 0)continue;let c=(e.info.configOptions??[]).find(e=>e.id===i);if(c===void 0||c.currentValue===a||!ZT(c,a))continue;let l=typeof a==`boolean`?{sessionId:r,configId:i,type:`boolean`,value:a}:{sessionId:r,configId:i,value:a};try{let n=await t.agent.request(Lm.agent.session.setConfigOption,l);e.info.configOptions=n.configOptions,o=!0}catch(t){s.push(i),this.opts.log.warn({err:t,threadId:e.info.threadId,configId:i},`[acp-threads] initial config apply failed`)}if(e.closed)return}s.length>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:s},`[acp-threads] some remembered config options could not be applied to the new session`),o&&this.emitInfo(e)}async applyInitialMode(e,t,n){let r=e.sessionId;if(r===null)return;let i=e.info.modes;if(i!=null&&i.availableModes.some(e=>e.id===n)){if(i.currentModeId===n)return;try{await t.agent.request(Lm.agent.session.setMode,{sessionId:r,modeId:n}),e.info.modes={...i,currentModeId:n},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let a=(e.info.configOptions??[]).find(e=>e.category===`mode`&&ZT(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(Lm.agent.session.setConfigOption,{sessionId:r,configId:a.id,value:n});e.info.configOptions=i.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_config_option`},`[acp-threads] initial mode apply failed`)}}respondPermission(e,t,n){let r=this.mustGet(e),i=r.pendingPermissions.get(t);i!==void 0&&(r.pendingPermissions.delete(t),clearTimeout(i.timer),n.kind===`selected`?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingRuntimeConsent(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await nT(r,{graceMs:t?.killGraceMs??VT})||this.opts.log.error({threadId:e,pid:r.pid},`[acp-threads] agent process survived SIGKILL escalation`)),n.child=null,n.conn=null,n.lastInit=null,await n.terminals?.disposeAll(),n.terminals=null,this.opts.agentPresenceBroadcaster?.clearPresence(rh(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)});let i=n.info.status===`error`||n.info.status===`auth_required`;if(!n.hadUserMessage&&!i){this.threads.delete(e),n.subscribers.clear(),n.flushTimer!==null&&(clearTimeout(n.flushTimer),n.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] empty thread discarded on close`);return}n.turnActive&&(n.turnActive=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),n.info.archived=!0,this.emitStatus(n,`exited`,`thread closed`),this.flushBroadcast(n),this.persistence.queueMetaWrite(e,this.buildMeta(n)),await this.persistence.whenIdle(e),n.baseSeq=n.info.lastSeq+1,n.events=[],n.pendingBroadcast=[],n.closed=!1,this.opts.log.info({threadId:e},`[acp-threads] thread archived`)}async deleteThread(e){let t=this.mustGet(e);if(t.info.archived!==!0)throw new UT(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new UT(`not-ready`,`a resume is in progress`);this.threads.delete(e),t.subscribers.clear(),t.flushTimer!==null&&(clearTimeout(t.flushTimer),t.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] thread deleted`)}async destroy(){this.destroyed=!0,clearInterval(this.reapTimer),await Promise.allSettled([...this.threads.keys()].map(e=>this.closeThread(e,{killGraceMs:HT})))}async handlePermissionRequest(e,t,n){e.info.lastActivityAt=Date.now();let r=this.opts.permissions.decide(e.info.agent.id,t,n);if(r.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:r.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:r.auto.optionId}}}let i=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_request`,requestId:i,toolCall:t,options:n,ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(r=>{let a=setTimeout(()=>{e.pendingPermissions.delete(i),this.appendEvent(e,{kind:`permission_resolved`,requestId:i,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),r({outcome:{outcome:`cancelled`}})},6e5);a.unref?.(),e.pendingPermissions.set(i,{timer:a,resolve:i=>{if(i.outcome.outcome===`selected`){let r=n.find(e=>i.outcome.outcome===`selected`&&e.optionId===i.outcome.optionId);r!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,r)}r(i)}})})}handleSessionUpdate(e,t){e.info.lastActivityAt=Date.now();let n=t.update;if(n.sessionUpdate===`current_mode_update`&&e.info.modes&&(e.info.modes={...e.info.modes,currentModeId:n.currentModeId},this.emitInfo(e)),n.sessionUpdate===`config_option_update`&&(e.info.configOptions=n.configOptions,this.emitInfo(e)),n.sessionUpdate===`available_commands_update`&&(e.info.availableCommands=n.availableCommands,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:pw(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await Bu(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await Bu(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
|
|
28
28
|
`),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
|
|
29
|
-
`)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel};t.dc.document.transact(()=>{let r=$C(t.dc.document);QC(t.dc.document,n,`replace`,i,void 0,XC(t));let a=Ei(r,$C(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...a===void 0?{}:{changedBlocks:a}})},t.origin),this.setPresence(e,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await import(`./fs-traced-DjggEXdh.mjs`);await e(P(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return YT(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new UT(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&vw(n[n.length-1],t))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>BT){let t=e.events.length-BT;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason,machineDetail:r?.machineDetail},`[acp-threads] thread failure status`),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await nT(t,{graceMs:VT})}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),this.broadcastInfo(e)}broadcastInfo(e){for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}closeSignInCapture(e){e.authStderr=null,e.info.signInOutput!==void 0&&(e.info.signInOutput=void 0,this.broadcastInfo(e))}buildMeta(e){let{queue:t,steer:n,signInOutput:r,...i}=e.info;return{version:1,info:i,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingRuntimeConsent(e){for(let t of e.pendingRuntimeConsent.values())clearTimeout(t.timer),t.resolve(`closed`);e.pendingRuntimeConsent.clear()}setPresence(e,t){let n=this.opts.agentPresenceBroadcaster;if(n!=null)try{let r=Zo(e.info.agent.id),i=Yr[r]??rs(e.agentSessionId);n.setPresence(rh(e.agentSessionId),{displayName:e.info.agent.name,icon:r,color:i,currentDoc:t,mode:`writing`,ts:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function YT(e,t,n){let r=await Hu(e),i=su(ou(t)?t:L(r,t)),a=i,o=``;for(;;)try{let e=await Hu(a),i=o===``?e:F(e,o),s=I(r,i);if(s===``||s.startsWith(`..`)||ou(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(R).join(`/`),t=s.split(R).join(`/`);!Lx(e)&&!Rx(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(R).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=P(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):F(a.slice(t.length+1),o),a=t}}function XT(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0,steer:void 0,signInOutput:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1}}function ZT(e,t){if(typeof t==`boolean`)return e.type===`boolean`;if(e.type!==`select`)return!1;for(let n of e.options)if(`value`in n){if(n.value===t)return!0}else if(n.options.some(e=>e.value===t))return!0;return!1}function QT(e){let t=cT(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. OK can download a private copy of ${t.displayName} for you, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function $T(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.code===-32e3||typeof t.data==`object`&&t.data!==null&&t.data.errorKind===`authentication_failed`}function eE(e){return e instanceof Error?e.message:String(e)}function tE(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return JSON.stringify(t).slice(0,300)}catch{return}}function nE(e){for(let t=e.events.length-1;t>=0;--t){let n=e.events[t];if(!(n===void 0||n.kind!==`status`)&&!(n.status!==`error`&&n.status!==`auth_required`))return n.detail??n.failure?.agentMessage}}function rE(e){let t=e.stderrTail.join(`
|
|
29
|
+
`)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel};t.dc.document.transact(()=>{let r=$C(t.dc.document);QC(t.dc.document,n,`replace`,i,void 0,XC(t));let a=Ei(r,$C(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...a===void 0?{}:{changedBlocks:a}})},t.origin),this.setPresence(e,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await import(`./fs-traced-DjggEXdh.mjs`);await e(P(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return YT(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new UT(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&vw(n[n.length-1],t))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>BT){let t=e.events.length-BT;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason,machineDetail:r?.machineDetail},`[acp-threads] thread failure status`),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await nT(t,{graceMs:VT})}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),this.broadcastInfo(e)}broadcastInfo(e){for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}closeSignInCapture(e){e.authStderr=null,e.info.signInOutput!==void 0&&(e.info.signInOutput=void 0,this.broadcastInfo(e))}buildMeta(e){let{queue:t,steer:n,signInOutput:r,...i}=e.info;return{version:1,info:i,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingRuntimeConsent(e){for(let t of e.pendingRuntimeConsent.values())clearTimeout(t.timer),t.resolve(`closed`);e.pendingRuntimeConsent.clear()}setPresence(e,t){let n=this.opts.agentPresenceBroadcaster;if(n!=null)try{let r=Zo(e.info.agent.id),i=Yr[r]??rs(e.agentSessionId);n.setPresence(rh(e.agentSessionId),{displayName:e.info.agent.name,icon:r,color:i,currentDoc:t,mode:`writing`,ts:Date.now(),docTs:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function YT(e,t,n){let r=await Hu(e),i=su(ou(t)?t:L(r,t)),a=i,o=``;for(;;)try{let e=await Hu(a),i=o===``?e:F(e,o),s=I(r,i);if(s===``||s.startsWith(`..`)||ou(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(R).join(`/`),t=s.split(R).join(`/`);!Lx(e)&&!Rx(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(R).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=P(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):F(a.slice(t.length+1),o),a=t}}function XT(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0,steer:void 0,signInOutput:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1}}function ZT(e,t){if(typeof t==`boolean`)return e.type===`boolean`;if(e.type!==`select`)return!1;for(let n of e.options)if(`value`in n){if(n.value===t)return!0}else if(n.options.some(e=>e.value===t))return!0;return!1}function QT(e){let t=cT(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. OK can download a private copy of ${t.displayName} for you, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function $T(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.code===-32e3||typeof t.data==`object`&&t.data!==null&&t.data.errorKind===`authentication_failed`}function eE(e){return e instanceof Error?e.message:String(e)}function tE(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return JSON.stringify(t).slice(0,300)}catch{return}}function nE(e){for(let t=e.events.length-1;t>=0;--t){let n=e.events[t];if(!(n===void 0||n.kind!==`status`)&&!(n.status!==`error`&&n.status!==`auth_required`))return n.detail??n.failure?.agentMessage}}function rE(e){let t=e.stderrTail.join(`
|
|
30
30
|
`);return t===``?void 0:t}function iE(...e){let t=e.filter(e=>e!==void 0&&e!==``).join(`
|
|
31
31
|
`);return t===``?void 0:t}function aE(e,t){let n=t.authStderr===null?void 0:t.authStderr.join(`
|
|
32
32
|
`);return iE(tE(e),n)}function oE(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 sE=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 cE(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 fue(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`||!sE.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 cE(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`||!cE(n.attachments)?null:n;case`steer`:{if(!r(`threadId`)||!r(`reqId`)||typeof n.content!=`string`||!cE(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`||!cE(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 lE(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(pue(e,t,n));e.on(`message`,e=>{let s=fue(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 UT?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 UT)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 pue(e,t,n){return{op:`error`,code:e,message:t,...n}}var uE=class{hocuspocus;log=N(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){ih(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){ih(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(Ni);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),mue(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function mue(e){return e?.awareness??null}var dE=class{hocuspocus;log=N(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!ih(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(!ih(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(!ih(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(!ih(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 Qse(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(Ni);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),hue(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function hue(e){return e?.awareness??null}var fE=class extends Error{};const gue=[`/.well-known/agent-skills/index.json`,`/.well-known/skills/index.json`],pE=1024*1024;async function mE(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 fE(`Website skill redirect carried no location: ${i}`);let o;try{o=new URL(a,i)}catch{throw new fE(`Website skill redirect target is not a URL: ${a}`)}if(o.protocol!==`https:`||o.origin!==n)throw new fE(`Website skill redirect left the origin (${n}): ${o.href}`);i=o.href}throw new fE(`Website skill fetch exceeded 5 redirects: ${t}`)}function hE(e){let t;try{t=new URL(e)}catch{throw new fE(`Invalid website skill origin: ${e}`)}if(t.protocol!==`https:`||t.username||t.password)throw new fE(`Website skill origins must be credential-free HTTPS URLs: ${e}`);if(t.pathname!==`/`||t.search||t.hash)throw new fE(`Website skill origins cannot include a path, query, or fragment: ${e}`);return t.origin}function gE(e){return!e||e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function _ue(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`||!gE(t)||t.includes(`/`)||r!==void 0&&typeof r!=`string`||!Array.isArray(i)||i.length===0||i.length>513||!i.every(e=>typeof e==`string`&&gE(e))||new Set(i).size!==i.length||!i.includes(`SKILL.md`))return null;n.push({name:t,description:r??``,files:i})}return n}function vue(e,t,n,r){let i=[n,...r.split(`/`)].map(encodeURIComponent).join(`/`);return new URL(`${t}/${i}`,e).href}async function _E(e,t,n){let r=[];for(let i of gue){let a=new URL(i,e).href;try{let o=await mE(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)>pE){r.push(`${i}: index exceeds ${pE} bytes`);continue}let c;try{c=JSON.parse(s)}catch{r.push(`${i}: response is not JSON`);continue}let l=_ue(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 fE(`No usable website skill index at ${e} (${r.join(`; `)})`)}async function yue(e,t={}){let{skills:n}=t.index??await vE(e,t);return n.map(({name:e,description:t})=>({name:e,description:t}))}async function vE(e,t={}){let n=hE(e),r=t.fetchImpl??globalThis.fetch;if(!r)throw new fE(`No fetch implementation available.`);return _E(n,r,t.timeoutMs??15e3)}async function bue(e,t={}){if(!gE(e.skill)||e.skill.includes(`/`))throw new fE(`Invalid website skill name: ${e.skill}`);let n=hE(e.origin),r=t.fetchImpl??globalThis.fetch;if(!r)throw new fE(`No fetch implementation available.`);let i=t.timeoutMs??15e3,{basePath:a,skills:o}=t.index??await _E(n,r,i),s=o.find(t=>t.name===e.skill);if(!s)throw new fE(`Website skill index does not contain ${e.skill}`);let c=bu(F(Iu(),`ok-skill-site-`)),l=F(c,s.name),u=0;try{let e=[...s.files],t=async e=>{let t=await mE(r,vue(n,a,s.name,e),n,{signal:AbortSignal.timeout(i)});if(!t.ok)throw new fE(`Website skill file returned HTTP ${t.status}: ${e}`);let o=Number(t.headers.get(`content-length`));if(Number.isFinite(o)&&o>16777216)throw new fE(`Website skill file exceeds ${tt} bytes: ${e}`);let c=new Uint8Array(await t.arrayBuffer());if(c.byteLength>16777216)throw new fE(`Website skill file exceeds ${tt} bytes: ${e}`);if(u+=c.byteLength,u>67108864)throw new fE(`Website skill bundle exceeds ${Sr} bytes.`);let d=F(l,...e.split(`/`));yu(P(d),{recursive:!0}),ju(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:()=>Du(c,{recursive:!0,force:!0})}}catch(t){throw Du(c,{recursive:!0,force:!0}),t instanceof fE?t:new fE(`Could not fetch website skill ${e.skill}: ${t instanceof Error?t.message:String(t)}`)}}const xue=ed($l),Sue=/^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/,yE=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/];function bE(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 yE.some(e=>e.test(t))?{kind:`git`,url:t}:null;let n=Sue.exec(t);if(n){let[,e,t,r]=n;return{kind:`git`,url:`https://github.com/${e}/${t}.git`,subpath:r}}return null}function xE(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 SE(e,t={}){if(e.kind===`well-known`)return bue(e,t);if(e.kind===`local`){let t=L(e.path.replace(/^~(?=\/|$)/,process.env.HOME??`~`));if(!z(t))throw new fE(`Local path not found: ${t}`);return{dir:t,cleanup:()=>{}}}if(/^[a-z][a-z0-9+.-]+:/i.test(e.url)&&!yE.some(t=>t.test(e.url)))throw new fE(`Unsupported git transport: ${e.url}`);let n=bu(F(Iu(),`ok-skill-import-`));try{await xue(`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){Du(n,{recursive:!0,force:!0});let r=t instanceof Error?t.message:String(t);throw new fE(`git clone failed for ${e.url}: ${r}`)}let r;try{r=Ite(`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(`..`)||ou(a))throw Du(n,{recursive:!0,force:!0}),new fE(`subpath escapes the clone: ${e.subpath}`);if(!z(i))throw Du(n,{recursive:!0,force:!0}),new fE(`subpath not found in repo: ${e.subpath}`);return{dir:i,ref:r,cleanup:()=>Du(n,{recursive:!0,force:!0})}}const CE=[`.ok`,`skills-lock.json`],Cue=a({source:v(),pluginProvider:v().optional(),skill:v().optional(),ref:v().optional(),contentHash:v(),files:k(v()).optional(),localHash:v().optional(),baselineRef:v().optional(),publisher:v().optional(),importedAt:se(),autoUpdate:l().optional()}),wue=a({schema:M(1),skills:p(v(),Cue).default({})});function wE(){return{schema:1,skills:{}}}function TE(e){let t;try{t=JSON.parse(e)}catch{return null}let n=wue.safeParse(t);return n.success?n.data:null}function EE(e,t,n){return{...e,skills:{...e.skills,[t]:n}}}const Tue=new Set(Object.values(Ai));function Eue(e,t,n,r){return e.startsWith(`open-knowledge-pack-`)?DE(e,t,n):!Tue.has(e)||r?.selfIdentifiesAsPack!==!0?null:DE(e,t,n)}function DE(e,t,n){return{source:Ia,skill:e,contentHash:t,importedAt:n}}function Due(e,t){for(let[n,r]of Object.entries(e.skills))if(r.contentHash===t)return n;return null}function OE(e,t){let n=t,r=``,{frontmatter:i}=Za(e);if(i!==``){let{map:e}=Ba(xo(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 kE=new Set([`.git`,`node_modules`]),Oue=new Set([...kE,`scripts`,`references`]);function kue(e){let t=[],n=r=>{for(let i of wu(r,{withFileTypes:!0})){let a=F(r,i.name);if(i.isDirectory()){kE.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 AE(e){let t=F(e,`SKILL.md`);return z(t)?OE(B(t,`utf-8`),ru(e)):null}function jE(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`))?ku(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 ${tt}.`;if(n>67108864)return`Skill exceeds ${Sr} bytes; that is the import bundle cap.`;let a=o=>{if(r!==null)return;let s;try{s=wu(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()){kE.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=ku(s).size}catch(e){i(`stat ${l}`,e);return}if(u>16777216){r=`${l} is ${u} bytes; the import per-file cap is ${tt}.`;return}if(n+=u,n>67108864){r=`Skill exceeds ${Sr} 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 ME(e){let t=F(e,`SKILL.md`);if(!z(t))return null;let n=B(t,`utf-8`),{name:r,description:i}=OE(n,ru(e)),a=kue(e),o=Ku(`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(`
|
|
@@ -1969,7 +1969,7 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
|
|
|
1969
1969
|
`),{asset:{ok:!0,...p?{src:p}:{},...m?{path:m}:{},...h?{deduped:h}:{}}})}async function AAe(e,t,n,r,i){let a=r.identityRef?.current,o=e.description!==void 0,s=e.files??[];if(!o&&s.length===0)return J("Error: provide `description` (to author SKILL.md) and/or `files` (to write references/scripts) — a skill write with neither does nothing.",!0);if(e.body!==void 0&&!o)return J('Error: `body` updates SKILL.md, so it needs a `description` too. To write a reference, use `files: [{ path: "references/...", content }]` instead.',!0);for(let e of s){let t=x2(e.path);if(!t.ok)return J(`Error: ${t.error}`,!0)}let c=[],l=null;if(o&&(l=await w2(n,{name:e.name,scope:e.scope,description:e.description,body:e.body,summary:t,identity:a,lockDir:i}),l.isError))return l;for(let r of s){let i=await E2(n,{name:e.name,scope:e.scope,path:r.path,content:r.content,summary:t,identity:a}),o=i.structuredContent;if(i.isError)c.push({path:r.path,ok:!1,error:i.content[0]?.text??`write failed`});else{let e=o?.skill?.file??{};c.push({path:r.path,ok:!0,...typeof e.kind==`string`?{kind:e.kind}:{},...typeof e.created==`boolean`?{created:e.created}:{}})}}let u=c.filter(e=>e.ok).length,d=c.some(e=>!e.ok),f=l?.structuredContent??{},p=f.skill??{ok:!0},m={...f,skill:{...p,...s.length>0?{files:c}:{}}},h=[];if(o&&l&&h.push(l.content[0]?.text??``),s.length>0){h.push(`${u}/${s.length} bundle file(s) written.`);for(let e of c)h.push(e.ok?` ${e.path} (${e.kind??`file`})`:` Failed ${e.path}: ${e.error}`)}return rO(h.filter(Boolean).join(`
|
|
1970
1970
|
`),m,d)}async function jAe(e,t,n,r,i,a,o){let s=[];for(let a of e)s.push(await X6(a,t,n,r,i));let c=s.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=d2(e.docName,{lockDir:a}),n=A2(e.raw.warnings),r=j2(e.raw.brokenLinks);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...n?{warnings:n}:{},...e.templateHint?{templateHint:e.templateHint}:{},brokenLinks:r}}),l=c.filter(e=>e.ok).length,u=l===c.length,d=e.map((e,t)=>{let n=s[t];if(!n?.ok)return`Failed ${e.path}: ${n?.error??`unknown error`}`;if(Y6(n.position,e.content))return`No change to ${e.path} — empty ${n.position}, document unchanged.`;let r=c[t],i=[`Wrote ${e.path} (${n.position}).`];if(r?.ok&&r.warnings&&i.push(...swe(r.warnings)),r?.ok){let e=ewe(r.brokenLinks);e&&i.push(e)}return n.ok&&n.templateHint&&i.push(`ℹ ${n.templateHint.length} template${n.templateHint.length===1?``:`s`} available here (pass \`template\`).`),i.join(` `)}),f=e.flatMap((e,t)=>{let n=s[t];if(!n?.ok)return[];let r=J6(n.position,e.content);return[...r?[r]:[],...n.extensionNote?[n.extensionNote]:[]].map(t=>`${e.path} — ${t}`)}),p=[`${l}/${c.length} written.`,...d,...f].join(`
|
|
1971
1971
|
`),m={documents:c},h=s.find(e=>e.ok);return h&&h.raw.systemSubscriberCount===0&&(m.warning=a2(d2(h.docName,{lockDir:a}),o)),rO(p,m,!u)}async function MAe(e,t,n,r,i,a,o){let s=await X6(e,t,n,r,i);if(!s.ok)return J(`Error: ${s.error}`,!0);let c=s.raw,l=d2(s.docName,{lockDir:a}),u=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,d=Array.isArray(c.hints)?c.hints:void 0,f=c.summary&&typeof c.summary==`object`?c.summary:void 0,p=typeof f?.hint==`string`?f.hint:void 0,m=A2(c.warnings),h=j2(c.brokenLinks),g=[Y6(s.position,e.content)??(s.fromTemplate===void 0?`Written successfully (${s.position}).`:`Written successfully (instantiated from template "${s.fromTemplate}").`)],_=J6(s.position,e.content);if(_&&g.push(_),s.extensionNote&&g.push(s.extensionNote),u&&!l&&g.push(o2),p&&g.push(p),d)for(let e of d)e.message&&g.push(e.message);m&&g.push(...L2(m)),g.push(...M2(h)),s.templateHint&&g.push(EAe(s.templateHint));let v=g.join(`
|
|
1972
|
-
`),y={brokenLinks:h};return d&&(y.hints=d),f&&(y.summary=f),m&&(y.warnings=m),s.templateHint&&(y.templateHint=s.templateHint),rO(v,eO(l,u?a2(l,o):void 0,y))}function NAe(e,t){let n={path:v().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:v().optional().describe("The full Markdown body. Mutually exclusive with `template`."),extension:qCe.optional(),template:v().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:p2.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:KCe.optional()};e.registerTool(`write`,{description:SAe,inputSchema:{document:w(n).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:w({path:v().describe(`Folder path. Example: "meetings".`),frontmatter:p2.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:w({path:v().describe(h2),content:v().describe("Starter content — the Markdown a new document becomes. A leading `---…---` frontmatter block here sets the STARTING PROPERTIES every doc created from this template gets (e.g. `type`, `status`, `tags`); the markdown below it is the body. The template's own picker identity (title/description) is the separate `frontmatter` field, NOT this block — it is stripped at instantiation and never copied onto created docs. (On disk this composes to one frontmatter block with the identity under a reserved `template:` key; you don't author that — just give the starter content here.) Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time."),frontmatter:w({title:v().min(1).describe(`Required — the label shown when an agent picks this template.`),description:v().optional().describe(`Optional — shown beside the title in the template menu.`),tags:k(v()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:w({name:v().describe(_2),description:v().optional().describe(`${v2} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:v().optional().describe("SKILL.md body (markdown guidance). Authored WITHOUT frontmatter — `name` + `description` are passed separately and composed server-side. Keep under ~500 lines; move depth into one-level-deep `references/`."),files:k(w({path:v().describe(`Skill-relative path, e.g. "references/tiers.md" or "assets/logo.svg". Must stay inside the skill dir.`),content:v().describe(`Full text of the bundle file.`)})).optional().describe('Bundle files to write beside `SKILL.md`, as an ARRAY of `{ path, content }` (consistent with `documents`/`asset`). `path` is SKILL-RELATIVE and must stay inside the skill dir (e.g. "references/tiers.md", "scripts/run.sh", "assets/logo.svg") — no `../`, no absolute paths. `content` is the full text. Text only (no binary). Independent of `body`: write one reference without resending SKILL.md.'),scope:y2.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files via the `files` array — any skill-relative path that stays inside the skill dir (`references/**` and `scripts/**` are the conventional homes; `assets/` and per-harness dirs are accepted because published skills ship them). Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:w({path:v().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:v().optional().describe(`Base64 of the binary. Use for small files.`),source:v().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:k(w({...n,summary:GD})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:GD,cwd:v().optional().describe(WD)},outputSchema:nO({document:w({hints:ZD.optional().describe(`Server-provided write hints, when any.`),...$D}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `summary`/`hints`/`warnings`."),folder:w({ok:l(),path:v(),frontmatterError:v().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:w({ok:l(),path:v(),created:l().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:w({ok:l(),path:v().optional(),created:l().optional().describe(`true if created, false if an existing skill was overwritten.`),files:ZD.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`.")}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:w({ok:l(),src:v().optional().describe(`The reference src to embed in a doc.`),path:v().optional(),deduped:l().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:ZD.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write."),previewUrl:qD.optional(),previewUrlSource:JD,warning:QD})},async e=>{let n=await cO(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return J(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n,o=zD(r),s=LD(i,r),c=i.appearance.preview.autoOpen;if(e.documents!==void 0){let n=S2(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return n?J(`Error: ${n}`,!0):a?jAe(e.documents,r,s,a,t,o,c):J(iO,!0)}let l=S2(e,[`document`,`folder`,`template`,`skill`,`asset`]);return l?J(`Error: ${l}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?kAe(e.asset,r,a,t):AAe(e.skill,e.summary,a,t,o):OAe(e.template,e.summary,a,t):DAe(e.folder,e.summary,a,t):a?MAe({...e.document,summary:e.summary},r,s,a,t,o,c):J(iO,!0)})}function Z6(e,t){let n=t.logger,r=OCe(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(Y0()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(Y0()??n)?.warn(`tool call failed`,{tool:e,err:t,...r?{explicit:r}:{}}),t}};QOe(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),nAe(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl,localApi:t.localApi}),hke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`links`),localApi:t.localApi}),Tke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`lint`),identityRef:t.identityRef}),ACe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`audit`)}),NAe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write`),identityRef:t.identityRef,localApi:t.localApi}),Cwe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit`),identityRef:t.identityRef}),$Ce(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`delete`),identityRef:t.identityRef,localApi:t.localApi}),Pke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`move`),identityRef:t.identityRef}),pke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`install`),identityRef:t.identityRef,localApi:t.localApi}),uke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`import`),identityRef:t.identityRef,localApi:t.localApi}),cke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`history`)}),xAe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`skills`)}),NCe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`checkpoint`),identityRef:t.identityRef,localApi:t.localApi}),Gke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`restore_version`),identityRef:t.identityRef}),Bke(r,{resolveCwd:i(`palette`),config:t.config}),RCe(r,{config:t.config,resolveCwd:i(`config`)}),ake(r,{config:t.config,resolveCwd:i(`preview_url`),serverUrl:t.serverUrl,isHostedAgent:t.isHostedAgent,...t.serverUrl?{ensureSingleFileSession:dCe()}:{}}),BCe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`conflicts`)}),Uke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`resolve_conflict`)}),uAe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`share_link`)})}function Q6(e){return Array.isArray(e)?e[0]:e}function $6(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(n))}function PAe(e,t,n,r){let i=e.config,a=new n0({name:ts,version:bc});L0(a);let o=n??qu(),s={current:{connectionId:o,displayName:o,colorSeed:o}};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=ow(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:ci(t),colorSeed:t}};let c=e.projectDir??e.contentDir;return Z6(a,{serverUrl:async()=>e.getServerUrl(),localApi:e.localApi,resolveCwd:async e=>{if(e===void 0)return c;let t=HD(c,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:i,identityRef:s,isHostedAgent:r}),I0(a),{server:a,transport:t}}function e8(e){let t=new Map,n=e.sessionTtlMs??1800*1e3,r=e.maxSessions??100;async function i(n,r){let i=t.get(n);if(!i)return;t.delete(n),i.ttlTimer!==void 0&&clearTimeout(i.ttlTimer);let a=await Promise.allSettled([i.server.close(),i.transport.close()]);for(let t of a)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:n,reason:r},`MCP HTTP session close failed`);e.log?.info?.({sessionId:n,reason:r},`MCP HTTP session closed`)}function a(t,r){r.ttlTimer!==void 0&&clearTimeout(r.ttlTimer),r.ttlTimer=setTimeout(()=>{i(t,`ttl-expired`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},n),r.ttlTimer.unref?.()}return{async handle(n,o){let s=Q6(n.headers[`mcp-session-id`]);if(s){let e=t.get(s);if(!e){$6(o,404,`MCP session not found`);return}a(s,e),await e.transport.handleRequest(n,o);return}if(n.method!==`POST`){$6(o,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=r){e.log?.warn?.({activeSessions:t.size,maxSessions:r},`MCP HTTP session cap reached`),$6(o,503,`Too many active MCP sessions`);return}let c=Q6(n.headers[iw]),l=nh(c)??void 0;c!==void 0&&l===void 0&&e.log?.warn?.({headerLength:c.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let u=Q6(n.headers[aw])===`1`,d=new KSe({sessionIdGenerator:()=>qu(),enableJsonResponse:!0,onsessioninitialized:async n=>{try{let r=PAe(e,d,l,u);await r.server.connect(d),t.set(n,r),a(n,r),e.log?.info?.({sessionId:n},`MCP HTTP session initialized`)}catch(r){throw t.delete(n),e.log?.error?.({err:r,sessionId:n},`MCP HTTP session initialization failed`),r}}});d.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},d.onclose=()=>{let t=d.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}i(t,`transport-closed`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await d.handleRequest(n,o)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>i(e,`handler-close`)))}}}const t8=1024*1024;function n8(e){if(!e)return null;try{return nh(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}function r8(e){return e===null||e.length===0||e.length>256||/[\u0000-\u001f\u007f]/.test(e)?null:e}function FAe(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),n=r8(t.searchParams.get(`displayName`)),r=r8(t.searchParams.get(`clientName`)),i=r8(t.searchParams.get(`colorSeed`));return n===null||r===null||i===null?null:{displayName:n,clientName:r,colorSeed:i}}catch{return null}}function i8(e){let{hocuspocus:t,log:n,sessionManager:r,agentFocusBroadcaster:i,agentPresenceBroadcaster:a,maintenanceCoordinator:o,acpThreadManager:s}=e,c=e.ingressPolicy??TB({}),l=e.keepaliveGraceMs??1e4,u=new Fte.default({noServer:!0,maxPayload:t8}),d=new Map,f=new Set,p=new Set,m=!1,h;u.on(`error`,e=>n.error({err:e},`WebSocketServer error`));let g=e=>EB(e.socket.remoteAddress,c)&&OB(Array.isArray(e.headers.host)?e.headers.host[0]:e.headers.host,c),_=(e,t)=>{e.on(`error`,e=>{qb(e)||n.error({err:e},`${t} socket error`)}),p.add(e),e.once(`close`,()=>p.delete(e))},v=(e,t,r,i,a)=>{try{u.handleUpgrade(e,t,r,a)}catch(r){n.error({err:r,url:e.url},`[collab] ${i} handleUpgrade threw`);try{t.destroy()}catch{}}},y=(e,t,s)=>{if(!g(e)||e.headers.origin!==void 0&&!kB(e.headers.origin,c)){n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/keepalive upgrade refused`),t.destroy();return}_(t,`MCP keepalive`),v(e,t,s,`keepalive`,t=>{let s=n8(e.url);if(s){let e=d.get(s);e!==void 0&&(clearTimeout(e),d.delete(s),n.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&a){let t=FAe(e.url);if(t)try{let e=Zo(t.clientName);a.setPresence(rh(s),{displayName:t.displayName,icon:e,color:Yr[e]??rs(t.colorSeed),currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){n.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let c=setInterval(()=>{try{t.ping()}catch{}},3e4);c.unref?.();let u=s?setInterval(()=>a?.bumpPresenceTs(rh(s)),3e3):null;u?.unref?.(),t.on(`close`,()=>{if(clearInterval(c),u!==null&&clearInterval(u),!s||m)return;let e=setTimeout(()=>{if(d.delete(s),m)return;let e=(async()=>{n.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await r?.closeAllForAgent(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{i?.clearFocus(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{a?.clearPresence(rh(s))}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await o?.onSessionClose()}catch(e){n.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();f.add(e),e.finally(()=>f.delete(e))},l);e.unref?.(),d.set(s,e),n.info({connectionId:s,graceMs:l},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{qb(e)||n.error({err:e},`MCP keepalive WS error`),t.terminate()})})};return{wss:u,handleUpgrade:(e,r,i)=>{if(!e.url?.startsWith(`/collab`))return!1;if(n.info({url:e.url,protocol:e.headers[`sec-websocket-protocol`]??`none`,host:e.headers.host??`none`,origin:e.headers.origin??`none`},`[collab] upgrade received`),MB(e,{}),AB(e,c))return n.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),r.destroy(),!0;if(e.url.startsWith(`/collab/thread`))return s==null||!g(e)||e.headers.origin!==void 0&&!kB(e.headers.origin,c)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/thread upgrade refused`),r.destroy(),!0):(_(r,`ACP thread`),v(e,r,i,`thread`,e=>lE(e,s,n)),!0);if(e.url.startsWith(`/collab/keepalive`))return y(e,r,i),!0;let a=e.headers.origin!==void 0&&!kB(e.headers.origin,c),o=c.allowExternal;return a||o&&!g(e)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab upgrade refused`),r.destroy(),!0):(_(r,`Upgrade`),n.info({url:e.url},`[collab] handleUpgrade starting`),v(e,r,i,`collaboration`,r=>{let i=t.getConnectionsCount?.()??-1,a=t.handleConnection(r,e);n.info({url:e.url,connectionsBefore:i},`[collab] handshake complete`);let o=!1;r.on(`message`,e=>{if(!o){if(e.byteLength>t8){o=!0,Kb(),n.warn({event:`collab-message-too-large`,bytes:e.byteLength,limit:t8},`Collab WebSocket message rejected before Yjs processing`),r.close(1009,`Message Too Big`);return}a.handleMessage(new Uint8Array(e))}}),r.on(`close`,(e,t)=>a.handleClose({code:e,reason:t.toString()})),r.on(`error`,e=>{e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`?(Kb(),n.warn({event:`collab-message-too-large`,limit:t8},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`)):qb(e)||n.error({err:e},`WebSocket error`),r.terminate()})}),!0)},shutdown:()=>(h??=(async()=>{m=!0;for(let e of p)try{e.destroy()}catch{}p.clear();for(let e of d.values())clearTimeout(e);d.clear(),await Promise.allSettled(f)})(),h)}}const IAe={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function a8(e){let{httpServer:t,hocuspocus:n,mcpHttpHandler:r,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d}=e,f=e.ingressPolicy??TB({}),p=i8({hocuspocus:n,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,keepaliveGraceMs:e.keepaliveGraceMs,acpThreadManager:e.acpThreadManager,ingressPolicy:f}),m=(e,t)=>{let a=e.url?.split(`?`)[0];if(!PU(e,t,f,`mcp-mount`))return;if(r!==void 0&&a===`/mcp`){let n=e.headers.origin,a=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!EB(e.socket.remoteAddress,f)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`mcp`});return}if(!OB(e.headers.host,f)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`,detail:xB});return}if(n!==void 0&&!kB(n,f)){G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`));for(let[e,n]of Object.entries(IAe))t.setHeader(e,n);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}r.handle(e,t).catch(e=>{i.error({err:e,sessionId:a},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(a?.startsWith(`/api/`)){n.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||G(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${a}`})}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let o=(n,r,a)=>{if(n===void 0){a();return}try{n(e,t,()=>{t.writableEnded||t.headersSent||a()})}catch(e){i.error({err:e},`Unhandled ${r} middleware error`),!t.writableEnded&&!t.headersSent?G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},s=n=>{if(d===!0&&l!==void 0){if(!EB(e.socket.remoteAddress,f)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!OB(e.headers.host,f)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:xB});return}}o(l,`content-asset`,n)},c=e=>o(u,`react-shell`,e),p=()=>{t.writableEnded||t.headersSent||G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`${u===void 0?"This server is running without the web UI. Restart it with plain `ok start` to serve the editor. ":``}No handler for ${a??`/`}`})};if(u!==void 0&&(a?.startsWith(`/assets/`)||a?.startsWith(`/excalidraw-assets/`))){c(()=>s(p));return}if(l!==void 0||u!==void 0){s(()=>c(p));return}G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`This server is running without the web UI. Restart it with plain \`ok start\` to serve the editor. No handler for ${a??`/`}`})},h=(e,t,n)=>{p.handleUpgrade(e,t,n)||(AB(e,f)&&i.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),t.destroy())},{requestListener:g}=LU({health:e.health,nativeApi:e.nativeApi,ingressPolicy:f,legacyDispatch:m,log:i});t.on(`request`,g),t.on(`upgrade`,h);let _;return{wss:p.wss,shutdown:()=>(_??=(async()=>{t.off(`upgrade`,h),await p.shutdown()})(),_)}}const o8=`OpenKnowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var s8=class extends Error{kind;projectDir;constructor(e,t,n){super(o8,n),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};function LAe(e,t){return{crdt:{hocuspocus:e.hocuspocus,durabilityState:e.durabilityState,cc1Broadcaster:e.cc1Broadcaster,serverInstanceId:e.serverInstanceId},content:{contentDir:t.contentDir,projectDir:t.projectDir,contentFilter:e.contentFilter},indexes:{basenameIndex:e.basenameIndex,resolveEmbed:e.resolveEmbed},git:{get syncEngine(){return e.syncEngine}},agents:{sessionManager:e.sessionManager,agentFocusBroadcaster:e.agentFocusBroadcaster,agentPresenceBroadcaster:e.agentPresenceBroadcaster,acpRegistry:e.acpRegistry,acpPermissions:e.acpPermissions},background:{maintenanceCoordinator:e.maintenanceCoordinator},config:{getLinkPreviewsEnabled:e.getLinkPreviewsEnabled},ready:e.ready,get degraded(){return e.degraded},destroy:e.destroy}}let c8=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const RAe=(e,t)=>{jh(e,c8.PermissionDenied),Ph(e,t)},zAe=(e,t)=>{jh(e,c8.Authenticated),Ph(e,t)},BAe=e=>{jh(e,c8.Token)},l8={code:4205,reason:`Reset Connection`},u8={code:4401,reason:`Unauthorized`},VAe={code:4403,reason:`Forbidden`},HAe={code:4408,reason:`Connection Timeout`},UAe=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var WAe=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let d8=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const GAe=Error(`request for lock canceled`);var KAe=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},qAe=class{constructor(e,t=GAe){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=f8(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return KAe(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),JAe(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function JAe(e,t){let n=f8(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function f8(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var YAe=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},XAe=class{constructor(e){this._semaphore=new qAe(1,e)}acquire(){return YAe(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let p8,m8,h8,g8,_8=!0;typeof process<`u`&&({FORCE_COLOR:p8,NODE_DISABLE_COLORS:m8,NO_COLOR:h8,TERM:g8}=process.env||{},_8=process.stdout&&process.stdout.isTTY);const v8={enabled:!m8&&h8==null&&g8!==`dumb`&&(p8!=null&&p8!==`0`||_8),reset:b8(0,0),bold:b8(1,22),dim:b8(2,22),italic:b8(3,23),underline:b8(4,24),inverse:b8(7,27),hidden:b8(8,28),strikethrough:b8(9,29),black:b8(30,39),red:b8(31,39),green:b8(32,39),yellow:b8(33,39),blue:b8(34,39),magenta:b8(35,39),cyan:b8(36,39),white:b8(37,39),gray:b8(90,39),grey:b8(90,39),bgBlack:b8(40,49),bgRed:b8(41,49),bgGreen:b8(42,49),bgYellow:b8(43,49),bgBlue:b8(44,49),bgMagenta:b8(45,49),bgCyan:b8(46,49),bgWhite:b8(47,49)};function y8(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function ZAe(e,t){let n={has:e,keys:t};return n.reset=v8.reset.bind(n),n.bold=v8.bold.bind(n),n.dim=v8.dim.bind(n),n.italic=v8.italic.bind(n),n.underline=v8.underline.bind(n),n.inverse=v8.inverse.bind(n),n.hidden=v8.hidden.bind(n),n.strikethrough=v8.strikethrough.bind(n),n.black=v8.black.bind(n),n.red=v8.red.bind(n),n.green=v8.green.bind(n),n.yellow=v8.yellow.bind(n),n.blue=v8.blue.bind(n),n.magenta=v8.magenta.bind(n),n.cyan=v8.cyan.bind(n),n.white=v8.white.bind(n),n.gray=v8.gray.bind(n),n.grey=v8.grey.bind(n),n.bgBlack=v8.bgBlack.bind(n),n.bgRed=v8.bgRed.bind(n),n.bgGreen=v8.bgGreen.bind(n),n.bgYellow=v8.bgYellow.bind(n),n.bgBlue=v8.bgBlue.bind(n),n.bgMagenta=v8.bgMagenta.bind(n),n.bgCyan=v8.bgCyan.bind(n),n.bgWhite=v8.bgWhite.bind(n),n}function b8(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:v8.enabled?y8(this.keys,t+``):t+``):t===void 0?ZAe([e],[n]):v8.enabled?y8([n],t+``):t+``}}const x8=Math.floor,QAe=(e,t)=>e<t?e:t,$Ae=(e,t)=>e>t?e:t;Number.isNaN;const eje=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const tje=()=>new Set,nje=Array.from;Array.isArray;const rje=String.fromCharCode;String.fromCodePoint,rje(65535);const ije=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},S8=typeof TextEncoder<`u`?new TextEncoder:null,aje=S8?e=>S8.encode(e):ije;let C8=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});C8&&C8.decode(new Uint8Array).length===1&&(C8=null);const w8=e=>Error(e);var oje=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const T8=()=>new oje,E8=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},D8=e=>{let t=new Uint8Array(E8(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},O8=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},k8=(e,t)=>{for(;t>127;)O8(e,128|127&t),t=x8(t/128);O8(e,127&t)},A8=new Uint8Array(3e4),sje=A8.length/3,j8=S8&&S8.encodeInto?(e,t)=>{if(t.length<sje){let n=S8.encodeInto(t,A8).written||0;k8(e,n);for(let t=0;t<n;t++)O8(e,A8[t])}else M8(e,aje(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;k8(e,r);for(let t=0;t<r;t++)O8(e,n.codePointAt(t))},cje=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=QAe(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array($Ae(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},M8=(e,t)=>{k8(e,t.byteLength),cje(e,t)},lje=w8(`Unexpected end of array`),uje=w8(`Integer out of Range`);var dje=class{constructor(e){this.arr=e,this.pos=0}};const N8=e=>new dje(e),fje=e=>e.pos!==e.arr.length,pje=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},P8=e=>pje(e,I8(e)),F8=e=>e.arr[e.pos++],I8=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>eje)throw uje}throw lje},L8=C8?e=>C8.decode(P8(e)):e=>{let t=I8(e);if(t===0)return``;{let n=String.fromCodePoint(F8(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(F8(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}};var R8=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=N8(e)}get encoder(){return this.encoderInternal||=T8(),this.encoderInternal}readVarUint8Array(){return P8(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=P8(this.decoder);return this.decoder.pos=e,t}readVarUint(){return I8(this.decoder)}readVarString(){return L8(this.decoder)}toUint8Array(){return D8(this.encoder)}writeVarUint(e){k8(this.encoder,e)}writeVarString(e){j8(this.encoder,e)}get length(){return E8(this.encoder)}};const z8=Date.now,B8=()=>new Map,mje=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var hje=class{constructor(){this._observers=B8()}on(e,t){mje(this._observers,e,tje).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return nje((this._observers.get(e)||B8()).values()).forEach(e=>e(...t))}destroy(){this._observers=B8()}};const V8=Symbol(`Equality`),gje=Object.keys,H8=e=>gje(e).length,_je=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),U8=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[V8]!=null)return e[V8](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!U8(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(H8(e)!==H8(t))return!1;for(let n in e)if(!_je(e,n)||!U8(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!U8(e[n],t[n]))return!1;break;default:return!1}return!0},W8=3e4;var vje=class extends hje{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=z8();this.getLocalState()!==null&&W8/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&W8<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&G8(this,t,`timeout`)},x8(W8/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:z8()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),U8(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}};const G8=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:z8()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},yje=(e,t,n=e.states)=>{let r=t.length,i=T8();k8(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;k8(i,r),k8(i,s),j8(i,JSON.stringify(o))}return D8(i)},K8=(e,t,n)=>{let r=N8(t),i=z8(),a=[],o=[],s=[],c=[],l=I8(r);for(let t=0;t<l;t++){let t=I8(r),n=I8(r),l=JSON.parse(L8(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(U8(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},bje=(e,t)=>{k8(e,0),M8(e,nv(t))},xje=(e,t,n)=>{k8(e,1),M8(e,X_(t,n))},Sje=(e,t,n)=>xje(t,n,P8(e)),q8=(e,t,n,r)=>{try{q_(t,P8(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},Cje=(e,t)=>{k8(e,2),M8(e,t)},wje=q8;function J8(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function Tje(e){if(!J8(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let Y8=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var X8=class{constructor(e){this.encoder=T8(),j8(this.encoder,e)}createSyncMessage(){return this.type=Y8.Sync,k8(this.encoder,Y8.Sync),this}createSyncReplyMessage(){return this.type=Y8.SyncReply,k8(this.encoder,Y8.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=Y8.Awareness,this.category=`Update`;let n=yje(e,t||Array.from(e.getStates().keys()));return k8(this.encoder,Y8.Awareness),M8(this.encoder,n),this}writeQueryAwareness(){return this.type=Y8.QueryAwareness,this.category=`Update`,k8(this.encoder,Y8.QueryAwareness),this}writeTokenSyncRequest(){return this.type=Y8.Auth,this.category=`TokenSync`,k8(this.encoder,Y8.Auth),BAe(this.encoder),this}writeAuthenticated(e){return this.type=Y8.Auth,this.category=`Authenticated`,k8(this.encoder,Y8.Auth),zAe(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=Y8.Auth,this.category=`PermissionDenied`,k8(this.encoder,Y8.Auth),RAe(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,bje(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,Cje(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,k8(this.encoder,Y8.Stateless),j8(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,k8(this.encoder,Y8.BroadcastStateless),j8(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,k8(this.encoder,Y8.SyncStatus),k8(this.encoder,+!!e),this}writeCloseMessage(e){return this.type=Y8.CLOSE,k8(this.encoder,Y8.CLOSE),j8(this.encoder,e),this}toUint8Array(){return D8(this.encoder)}},Eje=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,n){let{message:r}=this,i=r.readVarUint(),a=r.length;switch(i){case Y8.Sync:case Y8.SyncReply:r.writeVarUint(Y8.Sync),await this.readSyncMessage(r,e,t,n,i!==Y8.SyncReply),r.length>a+1&&(n?n(r.toUint8Array()):t&&t.send(r.toUint8Array()));break;case Y8.Awareness:K8(e.awareness,r.readVarUint8Array(),t??null);break;case Y8.QueryAwareness:this.applyQueryAwarenessMessage(e,t,n);break;case Y8.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:L8(r.decoder)});break;case Y8.BroadcastStateless:{let t=r.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case Y8.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case Y8.Auth:if(r.readVarUint()===c8.Token){t?.callbacks.onTokenSyncCallback({token:r.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${i}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,n,r,i=!0){let a=e.readVarUint(),o=n?.messageAddress??t.name;switch(n&&await n.callbacks.beforeSync(n,{type:a,payload:e.peekVarUint8Array()}),a){case 0:if(Sje(e.decoder,e.encoder,t),r&&i)r(new X8(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new X8(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case 1:if(n?.readOnly){if(yv(hv(t),P8(e.decoder))){let e=new X8(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new X8(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}q8(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new X8(o).writeSyncStatus(!0).toUint8Array());break;case 2:if(n?.readOnly){n.send(new X8(o).writeSyncStatus(!1).toUint8Array());break}wje(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new X8(o).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${a}`)}return a}applyQueryAwarenessMessage(e,t,n){let r=new X8(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},Dje=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,n,r,i,a=!1,o,s){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=i,this.document=n,this.request=t,this.socketId=r,this.readOnly=a,this.sessionId=o??null,this.providerVersion=s??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===d8.Closing||this.webSocket.readyState===d8.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new X8(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new X8(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new X8(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new X8(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new R8(e),n=t.readVarString(),r=n.indexOf(`\0`),i=r===-1?n:n.substring(0,r);if(i!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new Eje(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${i}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:l8.code,reason:`reason`in e?e.reason:l8.reason})}this.messageQueue.shift()}}},Oje=class extends j_{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,n)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new XAe,this.lastChangeTime=0,this.name=e,this.awareness=new vje(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{q_(this,X_(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&G8(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return K8(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:n},r){let i=e.concat(t,n);if(r!==null){let t=this.connections.get(r);t&&(e.forEach(e=>t.clients.add(e)),n.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new X8(e.messageAddress).createAwarenessUpdateMessage(this.awareness,i);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let n=new X8(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(n.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},kje=`4.0.0-rc.1`;function Z8(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var Aje=class{constructor(e,t,n,r,i,a={}){this.websocket=e,this.request=t,this.documentProvider=n,this.hooks=r,this.opts=i,this.defaultContext=a,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=Gu.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(HAe)},this.setUpNewConnection=async(e,t,n)=>{let r=this.hookPayloads[e],i=await this.documentProvider.createDocument(t,r.request,r.socketId,r.connectionConfig,r.context),a=this.createConnection(this.websocket,i,r,n,r.providerVersion);if(a.onClose((t,n)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),a.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...r,...e,document:i,connection:a,documentName:t},e=>{r.context={...r.context,...e}})}catch(e){console.error(e);let t={...u8,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===d8.Closing||this.websocket.readyState===d8.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{a.handleMessage(e)}),await this.hooks(`connected`,{...r,documentName:t,context:r.context,connection:a})},this.handleQueueingMessage=async(e,t,n)=>{try{let r=new R8(e);if(L8(r.decoder),!(I8(r.decoder)===Y8.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),I8(r.decoder);let i=L8(r.decoder),a=null;fje(r.decoder)&&(a=L8(r.decoder));let o=t.indexOf(`\0`),s=o===-1?null:t.substring(o+1),c=t;try{let e=this.hookPayloads[t];e.providerVersion=a,await this.hooks(`onConnect`,{...e,documentName:n},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:i,...e,documentName:n},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let r=new X8(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||VAe,r=new X8(c).writePermissionDenied(n.reason??`permission-denied`);this.websocket.send(r.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(l8.code,l8.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=L8(new R8(e).decoder),n=t.indexOf(`\0`),r=n===-1?t:t.substring(0,n),i=this.documentConnections[t]??this.documentConnections[r];if(i){i.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:Z8(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(u8.code,u8.reason)}},this.timeout=i.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,n,r,i){let a=new Dje(e,n.request,t,n.socketId,n.context,n.connectionConfig.readOnly,r,i);return a.onClose(async(e,t)=>{await a.waitForPendingMessages();let r={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:n.context,document:e,socketId:n.socketId,documentName:e.name,requestHeaders:n.request.headers,requestParameters:Z8(n.request)};await this.hooks(`onDisconnect`,r),this.callbacks.onClose.forEach(t=>t(e,r))}),a.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),a.beforeHandleMessage((e,r)=>{let i={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:n.context,document:t,socketId:n.socketId,connection:e,documentName:t.name,requestHeaders:n.request.headers,requestParameters:Z8(n.request),update:r};return this.hooks(`beforeHandleMessage`,i)}),a.beforeSync((e,r)=>{let i={clientsCount:t.getConnectionsCount(),context:n.context,document:t,documentName:t.name,connection:e,type:r.type,payload:r.payload};return this.hooks(`beforeSync`,i)}),a}},jje=class{constructor(e,t,n){this.document=null,this.document=e,this.instance=t,this.context=n??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new Rte}),await this.instance.unloadDocument(this.document)),null)}};const Mje=()=>{let e=new Map,t=new Map;return{debounce:async(n,r,i,a)=>{let o=e.get(n),s=o?.start||Date.now(),c=async()=>{t.has(n)&&await t.get(n),e.delete(n);let i=r();t.set(n,i);let a=await i;return t.delete(n),a};if(o?.timeout&&clearTimeout(o.timeout),i===0||Date.now()-s>=a)return c();e.set(n,{start:s,timeout:setTimeout(c,i),func:c})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let n=e.get(t);if(n)return clearTimeout(n.timeout),n.func()}}},Nje={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var Pje=class{constructor(e){this.configuration={...Nje,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=Mje(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let n=e.priority===void 0?100:e.priority,r=t.priority===void 0?100:t.priority;return n>r?-1:+(n<r)}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version:kje,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,n)=>(n.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+n.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(l8)})})}handleConnection(e,t,n={}){let r=new Aje(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},n);return r.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),r}handleDocumentUpdate(e,t,n){let r=J8(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=J8(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},o={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:i?.headers??new Headers,requestParameters:Z8(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),Tje(t))return;let s={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:a,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,s)}async createDocument(e,t,n,r,i){if(!e.trim())throw Error(`Document name must not be empty`);let a=this.loadingDocuments.get(e);if(a)return a;let o=this.documents.get(e);if(o)return Promise.resolve(o);let s=this.loadDocument(e,t,n,r,i);this.loadingDocuments.set(e,s);try{let t=await s;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,n,r,i){let a=t.headers,o=Z8(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new Oje(e,{...this.configuration.yDocOptions,...c}),u={instance:this,context:s,connectionConfig:r,document:l,documentName:e,socketId:n,requestHeaders:a,requestParameters:o};try{await this.hooks(`onLoadDocument`,u,e=>{e instanceof j_?q_(l,X_(e)):e instanceof Uint8Array&&q_(l,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(l),t}return l.isLoading=!1,l.onUpdate((e,t,n)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,n)}),await this.hooks(`afterLoadDocument`,u),l.beforeBroadcastStateless((e,t)=>{let n={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,n)}),l.awareness.on(`update`,(t,n)=>{this.hooks(`onAwarenessUpdate`,{document:l,documentName:e,instance:this,...t,transactionOrigin:n,connection:J8(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:UAe(l.awareness.getStates())})}),l}storeDocumentHooks(e,t,n){let r=`onStoreDocument-${e.name}`;return this.debouncer.debounce(r,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof WAe){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},n?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,n=null){let{extensions:r}=this.configuration,i=Promise.resolve();return r.filter(t=>typeof t[e]==`function`).forEach(r=>{i=i.then(()=>r[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),n&&(i=i.then((...e)=>n(...e)))}),i}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let n=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(n)),await n,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new jje(await this.createDocument(e,new Request(`http://localhost`),Gu.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},Q8=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$8=Ql(import.meta.url),e5=Q8(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),t5=Q8(((e,t)=>{let{EMPTY_BUFFER:n}=e5(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=$8(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),Fje=Q8(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),n5=Q8(((e,t)=>{let n=$8(`zlib`),r=t5(),i=Fje(),{kStatusCode:a}=e5(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),r5=Q8(((e,t)=>{let{isUtf8:n}=$8(`buffer`),{hasBlob:r}=e5(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=$8(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),i5=Q8(((e,t)=>{let{Writable:n}=$8(`stream`),r=n5(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=e5(),{concat:c,toArrayBuffer:l,unmask:u}=t5(),{isValidStatusCode:d,isValidUTF8:f}=r5(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),a5=Q8(((e,t)=>{let{Duplex:n}=$8(`stream`),{randomFillSync:r}=$8(`crypto`),i=n5(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=e5(),{isBlob:c,isValidStatusCode:l}=r5(),{mask:u,toBuffer:d}=t5(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),Ije=Q8(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=e5(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),o5=Q8(((e,t)=>{let{tokenChars:n}=r5();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),s5=Q8(((e,t)=>{let n=$8(`events`),r=$8(`https`),i=$8(`http`),a=$8(`net`),o=$8(`tls`),{randomBytes:s,createHash:c}=$8(`crypto`),{Duplex:l,Readable:u}=$8(`stream`),{URL:d}=$8(`url`),f=n5(),p=i5(),m=a5(),{isBlob:h}=r5(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=e5(),{EventTarget:{addEventListener:T,removeEventListener:E}}=Ije(),{format:ee,parse:te}=o5(),{toBuffer:ne}=t5(),re=Symbol(`kAborted`),ie=[8,13],D=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],O=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var k=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),ae(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,de),i.on(`drain`,fe),i.on(`error`,A),i.on(`message`,me),i.on(`ping`,he),i.on(`pong`,ge),a.onerror=ve,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,be),t.on(`data`,j),t.on(`end`,M),t.on(`error`,xe),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){le(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ye(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){le(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(k,`CONNECTING`,{enumerable:!0,value:D.indexOf(`CONNECTING`)}),Object.defineProperty(k.prototype,`CONNECTING`,{enumerable:!0,value:D.indexOf(`CONNECTING`)}),Object.defineProperty(k,`OPEN`,{enumerable:!0,value:D.indexOf(`OPEN`)}),Object.defineProperty(k.prototype,`OPEN`,{enumerable:!0,value:D.indexOf(`OPEN`)}),Object.defineProperty(k,`CLOSING`,{enumerable:!0,value:D.indexOf(`CLOSING`)}),Object.defineProperty(k.prototype,`CLOSING`,{enumerable:!0,value:D.indexOf(`CLOSING`)}),Object.defineProperty(k,`CLOSED`,{enumerable:!0,value:D.indexOf(`CLOSED`)}),Object.defineProperty(k.prototype,`CLOSED`,{enumerable:!0,value:D.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(k.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(k.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),k.prototype.addEventListener=T,k.prototype.removeEventListener=E,t.exports=k;function ae(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:ie[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!ie.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${ie.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;oe(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?ce:se),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=ee({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!O.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{le(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[re]||(S=e._req=null,oe(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){le(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{oe(e,SyntaxError(`Invalid URL: ${i}`));return}ae(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||le(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==k.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){le(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){le(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){le(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){le(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=te(u)}catch{le(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){le(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{le(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function oe(e,t){e._readyState=k.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function se(e){return e.path=e.socketPath,a.connect(e)}function ce(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function le(e,t,n){e._readyState=k.CLOSING;let r=Error(n);Error.captureStackTrace(r,le),t.setHeader?(t[re]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(oe,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ue(e,t,n){if(t){let n=h(t)?t.size:ne(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${D[e.readyState]})`);process.nextTick(n,t)}}function de(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,j),process.nextTick(_e,n._socket),e===1005?n.close():n.close(e,t))}function fe(){let e=this[C];e.isPaused||e._socket.resume()}function A(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,j),process.nextTick(_e,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function pe(){this[C].emitClose()}function me(e,t){this[C].emit(`message`,e,t)}function he(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ge(e){this[C].emit(`pong`,e)}function _e(e){e.resume()}function ve(e){let t=this[C];t.readyState!==k.CLOSED&&(t.readyState===k.OPEN&&(t._readyState=k.CLOSING,ye(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ye(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function be(){let e=this[C];if(this.removeListener(`close`,be),this.removeListener(`data`,j),this.removeListener(`end`,M),e._readyState=k.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,pe),e._receiver.on(`finish`,pe))}function j(e){this[C]._receiver.write(e)||this.pause()}function M(){let e=this[C];e._readyState=k.CLOSING,e._receiver.end(),this.end()}function xe(){let e=this[C];this.removeListener(`error`,xe),this.on(`error`,w),e&&(e._readyState=k.CLOSING,this.destroy())}})),Lje=Q8(((e,t)=>{s5();let{Duplex:n}=$8(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),Rje=Q8(((e,t)=>{let{tokenChars:n}=r5();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),zje=Q8(((e,t)=>{let n=$8(`events`),r=$8(`http`),{Duplex:i}=$8(`stream`),{createHash:a}=$8(`crypto`),o=o5(),s=n5(),c=Rje(),l=s5(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=e5(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
1972
|
+
`),y={brokenLinks:h};return d&&(y.hints=d),f&&(y.summary=f),m&&(y.warnings=m),s.templateHint&&(y.templateHint=s.templateHint),rO(v,eO(l,u?a2(l,o):void 0,y))}function NAe(e,t){let n={path:v().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:v().optional().describe("The full Markdown body. Mutually exclusive with `template`."),extension:qCe.optional(),template:v().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:p2.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:KCe.optional()};e.registerTool(`write`,{description:SAe,inputSchema:{document:w(n).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:w({path:v().describe(`Folder path. Example: "meetings".`),frontmatter:p2.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:w({path:v().describe(h2),content:v().describe("Starter content — the Markdown a new document becomes. A leading `---…---` frontmatter block here sets the STARTING PROPERTIES every doc created from this template gets (e.g. `type`, `status`, `tags`); the markdown below it is the body. The template's own picker identity (title/description) is the separate `frontmatter` field, NOT this block — it is stripped at instantiation and never copied onto created docs. (On disk this composes to one frontmatter block with the identity under a reserved `template:` key; you don't author that — just give the starter content here.) Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time."),frontmatter:w({title:v().min(1).describe(`Required — the label shown when an agent picks this template.`),description:v().optional().describe(`Optional — shown beside the title in the template menu.`),tags:k(v()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:w({name:v().describe(_2),description:v().optional().describe(`${v2} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:v().optional().describe("SKILL.md body (markdown guidance). Authored WITHOUT frontmatter — `name` + `description` are passed separately and composed server-side. Keep under ~500 lines; move depth into one-level-deep `references/`."),files:k(w({path:v().describe(`Skill-relative path, e.g. "references/tiers.md" or "assets/logo.svg". Must stay inside the skill dir.`),content:v().describe(`Full text of the bundle file.`)})).optional().describe('Bundle files to write beside `SKILL.md`, as an ARRAY of `{ path, content }` (consistent with `documents`/`asset`). `path` is SKILL-RELATIVE and must stay inside the skill dir (e.g. "references/tiers.md", "scripts/run.sh", "assets/logo.svg") — no `../`, no absolute paths. `content` is the full text. Text only (no binary). Independent of `body`: write one reference without resending SKILL.md.'),scope:y2.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files via the `files` array — any skill-relative path that stays inside the skill dir (`references/**` and `scripts/**` are the conventional homes; `assets/` and per-harness dirs are accepted because published skills ship them). Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:w({path:v().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:v().optional().describe(`Base64 of the binary. Use for small files.`),source:v().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:k(w({...n,summary:GD})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:GD,cwd:v().optional().describe(WD)},outputSchema:nO({document:w({hints:ZD.optional().describe(`Server-provided write hints, when any.`),...$D}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `summary`/`hints`/`warnings`."),folder:w({ok:l(),path:v(),frontmatterError:v().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:w({ok:l(),path:v(),created:l().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:w({ok:l(),path:v().optional(),created:l().optional().describe(`true if created, false if an existing skill was overwritten.`),files:ZD.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`.")}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:w({ok:l(),src:v().optional().describe(`The reference src to embed in a doc.`),path:v().optional(),deduped:l().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:ZD.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write."),previewUrl:qD.optional(),previewUrlSource:JD,warning:QD})},async e=>{let n=await cO(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return J(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n,o=zD(r),s=LD(i,r),c=i.appearance.preview.autoOpen;if(e.documents!==void 0){let n=S2(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return n?J(`Error: ${n}`,!0):a?jAe(e.documents,r,s,a,t,o,c):J(iO,!0)}let l=S2(e,[`document`,`folder`,`template`,`skill`,`asset`]);return l?J(`Error: ${l}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?kAe(e.asset,r,a,t):AAe(e.skill,e.summary,a,t,o):OAe(e.template,e.summary,a,t):DAe(e.folder,e.summary,a,t):a?MAe({...e.document,summary:e.summary},r,s,a,t,o,c):J(iO,!0)})}function Z6(e,t){let n=t.logger,r=OCe(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(Y0()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(Y0()??n)?.warn(`tool call failed`,{tool:e,err:t,...r?{explicit:r}:{}}),t}};QOe(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),nAe(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl,localApi:t.localApi}),hke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`links`),localApi:t.localApi}),Tke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`lint`),identityRef:t.identityRef}),ACe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`audit`)}),NAe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write`),identityRef:t.identityRef,localApi:t.localApi}),Cwe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit`),identityRef:t.identityRef}),$Ce(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`delete`),identityRef:t.identityRef,localApi:t.localApi}),Pke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`move`),identityRef:t.identityRef}),pke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`install`),identityRef:t.identityRef,localApi:t.localApi}),uke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`import`),identityRef:t.identityRef,localApi:t.localApi}),cke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`history`)}),xAe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`skills`)}),NCe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`checkpoint`),identityRef:t.identityRef,localApi:t.localApi}),Gke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`restore_version`),identityRef:t.identityRef}),Bke(r,{resolveCwd:i(`palette`),config:t.config}),RCe(r,{config:t.config,resolveCwd:i(`config`)}),ake(r,{config:t.config,resolveCwd:i(`preview_url`),serverUrl:t.serverUrl,isHostedAgent:t.isHostedAgent,...t.serverUrl?{ensureSingleFileSession:dCe()}:{}}),BCe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`conflicts`)}),Uke(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`resolve_conflict`)}),uAe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`share_link`)})}function Q6(e){return Array.isArray(e)?e[0]:e}function $6(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(n))}function PAe(e,t,n,r){let i=e.config,a=new n0({name:ts,version:bc});L0(a);let o=n??qu(),s={current:{connectionId:o,displayName:o,colorSeed:o}};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=ow(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:ci(t),colorSeed:t}};let c=e.projectDir??e.contentDir;return Z6(a,{serverUrl:async()=>e.getServerUrl(),localApi:e.localApi,resolveCwd:async e=>{if(e===void 0)return c;let t=HD(c,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:i,identityRef:s,isHostedAgent:r}),I0(a),{server:a,transport:t}}function e8(e){let t=new Map,n=e.sessionTtlMs??1800*1e3,r=e.maxSessions??100;async function i(n,r){let i=t.get(n);if(!i)return;t.delete(n),i.ttlTimer!==void 0&&clearTimeout(i.ttlTimer);let a=await Promise.allSettled([i.server.close(),i.transport.close()]);for(let t of a)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:n,reason:r},`MCP HTTP session close failed`);e.log?.info?.({sessionId:n,reason:r},`MCP HTTP session closed`)}function a(t,r){r.ttlTimer!==void 0&&clearTimeout(r.ttlTimer),r.ttlTimer=setTimeout(()=>{i(t,`ttl-expired`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},n),r.ttlTimer.unref?.()}return{async handle(n,o){let s=Q6(n.headers[`mcp-session-id`]);if(s){let e=t.get(s);if(!e){$6(o,404,`MCP session not found`);return}a(s,e),await e.transport.handleRequest(n,o);return}if(n.method!==`POST`){$6(o,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=r){e.log?.warn?.({activeSessions:t.size,maxSessions:r},`MCP HTTP session cap reached`),$6(o,503,`Too many active MCP sessions`);return}let c=Q6(n.headers[iw]),l=nh(c)??void 0;c!==void 0&&l===void 0&&e.log?.warn?.({headerLength:c.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let u=Q6(n.headers[aw])===`1`,d=new KSe({sessionIdGenerator:()=>qu(),enableJsonResponse:!0,onsessioninitialized:async n=>{try{let r=PAe(e,d,l,u);await r.server.connect(d),t.set(n,r),a(n,r),e.log?.info?.({sessionId:n},`MCP HTTP session initialized`)}catch(r){throw t.delete(n),e.log?.error?.({err:r,sessionId:n},`MCP HTTP session initialization failed`),r}}});d.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},d.onclose=()=>{let t=d.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}i(t,`transport-closed`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await d.handleRequest(n,o)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>i(e,`handler-close`)))}}}const t8=1024*1024;function n8(e){if(!e)return null;try{return nh(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}function r8(e){return e===null||e.length===0||e.length>256||/[\u0000-\u001f\u007f]/.test(e)?null:e}function FAe(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),n=r8(t.searchParams.get(`displayName`)),r=r8(t.searchParams.get(`clientName`)),i=r8(t.searchParams.get(`colorSeed`));return n===null||r===null||i===null?null:{displayName:n,clientName:r,colorSeed:i}}catch{return null}}function i8(e){let{hocuspocus:t,log:n,sessionManager:r,agentFocusBroadcaster:i,agentPresenceBroadcaster:a,maintenanceCoordinator:o,acpThreadManager:s}=e,c=e.ingressPolicy??TB({}),l=e.keepaliveGraceMs??1e4,u=new Fte.default({noServer:!0,maxPayload:t8}),d=new Map,f=new Set,p=new Set,m=!1,h;u.on(`error`,e=>n.error({err:e},`WebSocketServer error`));let g=e=>EB(e.socket.remoteAddress,c)&&OB(Array.isArray(e.headers.host)?e.headers.host[0]:e.headers.host,c),_=(e,t)=>{e.on(`error`,e=>{qb(e)||n.error({err:e},`${t} socket error`)}),p.add(e),e.once(`close`,()=>p.delete(e))},v=(e,t,r,i,a)=>{try{u.handleUpgrade(e,t,r,a)}catch(r){n.error({err:r,url:e.url},`[collab] ${i} handleUpgrade threw`);try{t.destroy()}catch{}}},y=(e,t,s)=>{if(!g(e)||e.headers.origin!==void 0&&!kB(e.headers.origin,c)){n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/keepalive upgrade refused`),t.destroy();return}_(t,`MCP keepalive`),v(e,t,s,`keepalive`,t=>{let s=n8(e.url);if(s){let e=d.get(s);e!==void 0&&(clearTimeout(e),d.delete(s),n.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&a){let t=FAe(e.url);if(t)try{let e=Zo(t.clientName);a.setPresence(rh(s),{displayName:t.displayName,icon:e,color:Yr[e]??rs(t.colorSeed),currentDoc:`(connected)`,mode:`idle`,ts:Date.now(),docTs:Date.now()})}catch(e){n.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let c=setInterval(()=>{try{t.ping()}catch{}},3e4);c.unref?.();let u=s?setInterval(()=>a?.bumpPresenceTs(rh(s)),3e3):null;u?.unref?.(),t.on(`close`,()=>{if(clearInterval(c),u!==null&&clearInterval(u),!s||m)return;let e=setTimeout(()=>{if(d.delete(s),m)return;let e=(async()=>{n.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await r?.closeAllForAgent(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{i?.clearFocus(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{a?.clearPresence(rh(s))}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await o?.onSessionClose()}catch(e){n.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();f.add(e),e.finally(()=>f.delete(e))},l);e.unref?.(),d.set(s,e),n.info({connectionId:s,graceMs:l},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{qb(e)||n.error({err:e},`MCP keepalive WS error`),t.terminate()})})};return{wss:u,handleUpgrade:(e,r,i)=>{if(!e.url?.startsWith(`/collab`))return!1;if(n.info({url:e.url,protocol:e.headers[`sec-websocket-protocol`]??`none`,host:e.headers.host??`none`,origin:e.headers.origin??`none`},`[collab] upgrade received`),MB(e,{}),AB(e,c))return n.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),r.destroy(),!0;if(e.url.startsWith(`/collab/thread`))return s==null||!g(e)||e.headers.origin!==void 0&&!kB(e.headers.origin,c)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/thread upgrade refused`),r.destroy(),!0):(_(r,`ACP thread`),v(e,r,i,`thread`,e=>lE(e,s,n)),!0);if(e.url.startsWith(`/collab/keepalive`))return y(e,r,i),!0;let a=e.headers.origin!==void 0&&!kB(e.headers.origin,c),o=c.allowExternal;return a||o&&!g(e)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab upgrade refused`),r.destroy(),!0):(_(r,`Upgrade`),n.info({url:e.url},`[collab] handleUpgrade starting`),v(e,r,i,`collaboration`,r=>{let i=t.getConnectionsCount?.()??-1,a=t.handleConnection(r,e);n.info({url:e.url,connectionsBefore:i},`[collab] handshake complete`);let o=!1;r.on(`message`,e=>{if(!o){if(e.byteLength>t8){o=!0,Kb(),n.warn({event:`collab-message-too-large`,bytes:e.byteLength,limit:t8},`Collab WebSocket message rejected before Yjs processing`),r.close(1009,`Message Too Big`);return}a.handleMessage(new Uint8Array(e))}}),r.on(`close`,(e,t)=>a.handleClose({code:e,reason:t.toString()})),r.on(`error`,e=>{e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`?(Kb(),n.warn({event:`collab-message-too-large`,limit:t8},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`)):qb(e)||n.error({err:e},`WebSocket error`),r.terminate()})}),!0)},shutdown:()=>(h??=(async()=>{m=!0;for(let e of p)try{e.destroy()}catch{}p.clear();for(let e of d.values())clearTimeout(e);d.clear(),await Promise.allSettled(f)})(),h)}}const IAe={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function a8(e){let{httpServer:t,hocuspocus:n,mcpHttpHandler:r,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d}=e,f=e.ingressPolicy??TB({}),p=i8({hocuspocus:n,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,keepaliveGraceMs:e.keepaliveGraceMs,acpThreadManager:e.acpThreadManager,ingressPolicy:f}),m=(e,t)=>{let a=e.url?.split(`?`)[0];if(!PU(e,t,f,`mcp-mount`))return;if(r!==void 0&&a===`/mcp`){let n=e.headers.origin,a=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!EB(e.socket.remoteAddress,f)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`mcp`});return}if(!OB(e.headers.host,f)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`,detail:xB});return}if(n!==void 0&&!kB(n,f)){G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`));for(let[e,n]of Object.entries(IAe))t.setHeader(e,n);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}r.handle(e,t).catch(e=>{i.error({err:e,sessionId:a},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(a?.startsWith(`/api/`)){n.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||G(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${a}`})}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let o=(n,r,a)=>{if(n===void 0){a();return}try{n(e,t,()=>{t.writableEnded||t.headersSent||a()})}catch(e){i.error({err:e},`Unhandled ${r} middleware error`),!t.writableEnded&&!t.headersSent?G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},s=n=>{if(d===!0&&l!==void 0){if(!EB(e.socket.remoteAddress,f)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!OB(e.headers.host,f)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:xB});return}}o(l,`content-asset`,n)},c=e=>o(u,`react-shell`,e),p=()=>{t.writableEnded||t.headersSent||G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`${u===void 0?"This server is running without the web UI. Restart it with plain `ok start` to serve the editor. ":``}No handler for ${a??`/`}`})};if(u!==void 0&&(a?.startsWith(`/assets/`)||a?.startsWith(`/excalidraw-assets/`))){c(()=>s(p));return}if(l!==void 0||u!==void 0){s(()=>c(p));return}G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`This server is running without the web UI. Restart it with plain \`ok start\` to serve the editor. No handler for ${a??`/`}`})},h=(e,t,n)=>{p.handleUpgrade(e,t,n)||(AB(e,f)&&i.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),t.destroy())},{requestListener:g}=LU({health:e.health,nativeApi:e.nativeApi,ingressPolicy:f,legacyDispatch:m,log:i});t.on(`request`,g),t.on(`upgrade`,h);let _;return{wss:p.wss,shutdown:()=>(_??=(async()=>{t.off(`upgrade`,h),await p.shutdown()})(),_)}}const o8=`OpenKnowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var s8=class extends Error{kind;projectDir;constructor(e,t,n){super(o8,n),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};function LAe(e,t){return{crdt:{hocuspocus:e.hocuspocus,durabilityState:e.durabilityState,cc1Broadcaster:e.cc1Broadcaster,serverInstanceId:e.serverInstanceId},content:{contentDir:t.contentDir,projectDir:t.projectDir,contentFilter:e.contentFilter},indexes:{basenameIndex:e.basenameIndex,resolveEmbed:e.resolveEmbed},git:{get syncEngine(){return e.syncEngine}},agents:{sessionManager:e.sessionManager,agentFocusBroadcaster:e.agentFocusBroadcaster,agentPresenceBroadcaster:e.agentPresenceBroadcaster,acpRegistry:e.acpRegistry,acpPermissions:e.acpPermissions},background:{maintenanceCoordinator:e.maintenanceCoordinator},config:{getLinkPreviewsEnabled:e.getLinkPreviewsEnabled},ready:e.ready,get degraded(){return e.degraded},destroy:e.destroy}}let c8=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const RAe=(e,t)=>{jh(e,c8.PermissionDenied),Ph(e,t)},zAe=(e,t)=>{jh(e,c8.Authenticated),Ph(e,t)},BAe=e=>{jh(e,c8.Token)},l8={code:4205,reason:`Reset Connection`},u8={code:4401,reason:`Unauthorized`},VAe={code:4403,reason:`Forbidden`},HAe={code:4408,reason:`Connection Timeout`},UAe=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var WAe=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let d8=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const GAe=Error(`request for lock canceled`);var KAe=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},qAe=class{constructor(e,t=GAe){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=f8(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return KAe(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),JAe(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function JAe(e,t){let n=f8(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function f8(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var YAe=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},XAe=class{constructor(e){this._semaphore=new qAe(1,e)}acquire(){return YAe(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let p8,m8,h8,g8,_8=!0;typeof process<`u`&&({FORCE_COLOR:p8,NODE_DISABLE_COLORS:m8,NO_COLOR:h8,TERM:g8}=process.env||{},_8=process.stdout&&process.stdout.isTTY);const v8={enabled:!m8&&h8==null&&g8!==`dumb`&&(p8!=null&&p8!==`0`||_8),reset:b8(0,0),bold:b8(1,22),dim:b8(2,22),italic:b8(3,23),underline:b8(4,24),inverse:b8(7,27),hidden:b8(8,28),strikethrough:b8(9,29),black:b8(30,39),red:b8(31,39),green:b8(32,39),yellow:b8(33,39),blue:b8(34,39),magenta:b8(35,39),cyan:b8(36,39),white:b8(37,39),gray:b8(90,39),grey:b8(90,39),bgBlack:b8(40,49),bgRed:b8(41,49),bgGreen:b8(42,49),bgYellow:b8(43,49),bgBlue:b8(44,49),bgMagenta:b8(45,49),bgCyan:b8(46,49),bgWhite:b8(47,49)};function y8(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function ZAe(e,t){let n={has:e,keys:t};return n.reset=v8.reset.bind(n),n.bold=v8.bold.bind(n),n.dim=v8.dim.bind(n),n.italic=v8.italic.bind(n),n.underline=v8.underline.bind(n),n.inverse=v8.inverse.bind(n),n.hidden=v8.hidden.bind(n),n.strikethrough=v8.strikethrough.bind(n),n.black=v8.black.bind(n),n.red=v8.red.bind(n),n.green=v8.green.bind(n),n.yellow=v8.yellow.bind(n),n.blue=v8.blue.bind(n),n.magenta=v8.magenta.bind(n),n.cyan=v8.cyan.bind(n),n.white=v8.white.bind(n),n.gray=v8.gray.bind(n),n.grey=v8.grey.bind(n),n.bgBlack=v8.bgBlack.bind(n),n.bgRed=v8.bgRed.bind(n),n.bgGreen=v8.bgGreen.bind(n),n.bgYellow=v8.bgYellow.bind(n),n.bgBlue=v8.bgBlue.bind(n),n.bgMagenta=v8.bgMagenta.bind(n),n.bgCyan=v8.bgCyan.bind(n),n.bgWhite=v8.bgWhite.bind(n),n}function b8(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:v8.enabled?y8(this.keys,t+``):t+``):t===void 0?ZAe([e],[n]):v8.enabled?y8([n],t+``):t+``}}const x8=Math.floor,QAe=(e,t)=>e<t?e:t,$Ae=(e,t)=>e>t?e:t;Number.isNaN;const eje=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const tje=()=>new Set,nje=Array.from;Array.isArray;const rje=String.fromCharCode;String.fromCodePoint,rje(65535);const ije=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},S8=typeof TextEncoder<`u`?new TextEncoder:null,aje=S8?e=>S8.encode(e):ije;let C8=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});C8&&C8.decode(new Uint8Array).length===1&&(C8=null);const w8=e=>Error(e);var oje=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const T8=()=>new oje,E8=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},D8=e=>{let t=new Uint8Array(E8(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},O8=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},k8=(e,t)=>{for(;t>127;)O8(e,128|127&t),t=x8(t/128);O8(e,127&t)},A8=new Uint8Array(3e4),sje=A8.length/3,j8=S8&&S8.encodeInto?(e,t)=>{if(t.length<sje){let n=S8.encodeInto(t,A8).written||0;k8(e,n);for(let t=0;t<n;t++)O8(e,A8[t])}else M8(e,aje(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;k8(e,r);for(let t=0;t<r;t++)O8(e,n.codePointAt(t))},cje=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=QAe(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array($Ae(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},M8=(e,t)=>{k8(e,t.byteLength),cje(e,t)},lje=w8(`Unexpected end of array`),uje=w8(`Integer out of Range`);var dje=class{constructor(e){this.arr=e,this.pos=0}};const N8=e=>new dje(e),fje=e=>e.pos!==e.arr.length,pje=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},P8=e=>pje(e,I8(e)),F8=e=>e.arr[e.pos++],I8=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>eje)throw uje}throw lje},L8=C8?e=>C8.decode(P8(e)):e=>{let t=I8(e);if(t===0)return``;{let n=String.fromCodePoint(F8(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(F8(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}};var R8=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=N8(e)}get encoder(){return this.encoderInternal||=T8(),this.encoderInternal}readVarUint8Array(){return P8(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=P8(this.decoder);return this.decoder.pos=e,t}readVarUint(){return I8(this.decoder)}readVarString(){return L8(this.decoder)}toUint8Array(){return D8(this.encoder)}writeVarUint(e){k8(this.encoder,e)}writeVarString(e){j8(this.encoder,e)}get length(){return E8(this.encoder)}};const z8=Date.now,B8=()=>new Map,mje=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var hje=class{constructor(){this._observers=B8()}on(e,t){mje(this._observers,e,tje).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return nje((this._observers.get(e)||B8()).values()).forEach(e=>e(...t))}destroy(){this._observers=B8()}};const V8=Symbol(`Equality`),gje=Object.keys,H8=e=>gje(e).length,_je=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),U8=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[V8]!=null)return e[V8](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!U8(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(H8(e)!==H8(t))return!1;for(let n in e)if(!_je(e,n)||!U8(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!U8(e[n],t[n]))return!1;break;default:return!1}return!0},W8=3e4;var vje=class extends hje{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=z8();this.getLocalState()!==null&&W8/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&W8<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&G8(this,t,`timeout`)},x8(W8/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:z8()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),U8(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}};const G8=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:z8()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},yje=(e,t,n=e.states)=>{let r=t.length,i=T8();k8(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;k8(i,r),k8(i,s),j8(i,JSON.stringify(o))}return D8(i)},K8=(e,t,n)=>{let r=N8(t),i=z8(),a=[],o=[],s=[],c=[],l=I8(r);for(let t=0;t<l;t++){let t=I8(r),n=I8(r),l=JSON.parse(L8(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(U8(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},bje=(e,t)=>{k8(e,0),M8(e,nv(t))},xje=(e,t,n)=>{k8(e,1),M8(e,X_(t,n))},Sje=(e,t,n)=>xje(t,n,P8(e)),q8=(e,t,n,r)=>{try{q_(t,P8(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},Cje=(e,t)=>{k8(e,2),M8(e,t)},wje=q8;function J8(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function Tje(e){if(!J8(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let Y8=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var X8=class{constructor(e){this.encoder=T8(),j8(this.encoder,e)}createSyncMessage(){return this.type=Y8.Sync,k8(this.encoder,Y8.Sync),this}createSyncReplyMessage(){return this.type=Y8.SyncReply,k8(this.encoder,Y8.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=Y8.Awareness,this.category=`Update`;let n=yje(e,t||Array.from(e.getStates().keys()));return k8(this.encoder,Y8.Awareness),M8(this.encoder,n),this}writeQueryAwareness(){return this.type=Y8.QueryAwareness,this.category=`Update`,k8(this.encoder,Y8.QueryAwareness),this}writeTokenSyncRequest(){return this.type=Y8.Auth,this.category=`TokenSync`,k8(this.encoder,Y8.Auth),BAe(this.encoder),this}writeAuthenticated(e){return this.type=Y8.Auth,this.category=`Authenticated`,k8(this.encoder,Y8.Auth),zAe(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=Y8.Auth,this.category=`PermissionDenied`,k8(this.encoder,Y8.Auth),RAe(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,bje(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,Cje(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,k8(this.encoder,Y8.Stateless),j8(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,k8(this.encoder,Y8.BroadcastStateless),j8(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,k8(this.encoder,Y8.SyncStatus),k8(this.encoder,+!!e),this}writeCloseMessage(e){return this.type=Y8.CLOSE,k8(this.encoder,Y8.CLOSE),j8(this.encoder,e),this}toUint8Array(){return D8(this.encoder)}},Eje=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,n){let{message:r}=this,i=r.readVarUint(),a=r.length;switch(i){case Y8.Sync:case Y8.SyncReply:r.writeVarUint(Y8.Sync),await this.readSyncMessage(r,e,t,n,i!==Y8.SyncReply),r.length>a+1&&(n?n(r.toUint8Array()):t&&t.send(r.toUint8Array()));break;case Y8.Awareness:K8(e.awareness,r.readVarUint8Array(),t??null);break;case Y8.QueryAwareness:this.applyQueryAwarenessMessage(e,t,n);break;case Y8.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:L8(r.decoder)});break;case Y8.BroadcastStateless:{let t=r.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case Y8.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case Y8.Auth:if(r.readVarUint()===c8.Token){t?.callbacks.onTokenSyncCallback({token:r.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${i}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,n,r,i=!0){let a=e.readVarUint(),o=n?.messageAddress??t.name;switch(n&&await n.callbacks.beforeSync(n,{type:a,payload:e.peekVarUint8Array()}),a){case 0:if(Sje(e.decoder,e.encoder,t),r&&i)r(new X8(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new X8(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case 1:if(n?.readOnly){if(yv(hv(t),P8(e.decoder))){let e=new X8(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new X8(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}q8(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new X8(o).writeSyncStatus(!0).toUint8Array());break;case 2:if(n?.readOnly){n.send(new X8(o).writeSyncStatus(!1).toUint8Array());break}wje(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new X8(o).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${a}`)}return a}applyQueryAwarenessMessage(e,t,n){let r=new X8(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},Dje=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,n,r,i,a=!1,o,s){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=i,this.document=n,this.request=t,this.socketId=r,this.readOnly=a,this.sessionId=o??null,this.providerVersion=s??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===d8.Closing||this.webSocket.readyState===d8.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new X8(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new X8(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new X8(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new X8(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new R8(e),n=t.readVarString(),r=n.indexOf(`\0`),i=r===-1?n:n.substring(0,r);if(i!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new Eje(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${i}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:l8.code,reason:`reason`in e?e.reason:l8.reason})}this.messageQueue.shift()}}},Oje=class extends j_{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,n)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new XAe,this.lastChangeTime=0,this.name=e,this.awareness=new vje(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{q_(this,X_(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&G8(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return K8(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:n},r){let i=e.concat(t,n);if(r!==null){let t=this.connections.get(r);t&&(e.forEach(e=>t.clients.add(e)),n.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new X8(e.messageAddress).createAwarenessUpdateMessage(this.awareness,i);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let n=new X8(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(n.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},kje=`4.0.0-rc.1`;function Z8(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var Aje=class{constructor(e,t,n,r,i,a={}){this.websocket=e,this.request=t,this.documentProvider=n,this.hooks=r,this.opts=i,this.defaultContext=a,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=Gu.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(HAe)},this.setUpNewConnection=async(e,t,n)=>{let r=this.hookPayloads[e],i=await this.documentProvider.createDocument(t,r.request,r.socketId,r.connectionConfig,r.context),a=this.createConnection(this.websocket,i,r,n,r.providerVersion);if(a.onClose((t,n)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),a.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...r,...e,document:i,connection:a,documentName:t},e=>{r.context={...r.context,...e}})}catch(e){console.error(e);let t={...u8,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===d8.Closing||this.websocket.readyState===d8.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{a.handleMessage(e)}),await this.hooks(`connected`,{...r,documentName:t,context:r.context,connection:a})},this.handleQueueingMessage=async(e,t,n)=>{try{let r=new R8(e);if(L8(r.decoder),!(I8(r.decoder)===Y8.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),I8(r.decoder);let i=L8(r.decoder),a=null;fje(r.decoder)&&(a=L8(r.decoder));let o=t.indexOf(`\0`),s=o===-1?null:t.substring(o+1),c=t;try{let e=this.hookPayloads[t];e.providerVersion=a,await this.hooks(`onConnect`,{...e,documentName:n},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:i,...e,documentName:n},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let r=new X8(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||VAe,r=new X8(c).writePermissionDenied(n.reason??`permission-denied`);this.websocket.send(r.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(l8.code,l8.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=L8(new R8(e).decoder),n=t.indexOf(`\0`),r=n===-1?t:t.substring(0,n),i=this.documentConnections[t]??this.documentConnections[r];if(i){i.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:Z8(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(u8.code,u8.reason)}},this.timeout=i.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,n,r,i){let a=new Dje(e,n.request,t,n.socketId,n.context,n.connectionConfig.readOnly,r,i);return a.onClose(async(e,t)=>{await a.waitForPendingMessages();let r={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:n.context,document:e,socketId:n.socketId,documentName:e.name,requestHeaders:n.request.headers,requestParameters:Z8(n.request)};await this.hooks(`onDisconnect`,r),this.callbacks.onClose.forEach(t=>t(e,r))}),a.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),a.beforeHandleMessage((e,r)=>{let i={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:n.context,document:t,socketId:n.socketId,connection:e,documentName:t.name,requestHeaders:n.request.headers,requestParameters:Z8(n.request),update:r};return this.hooks(`beforeHandleMessage`,i)}),a.beforeSync((e,r)=>{let i={clientsCount:t.getConnectionsCount(),context:n.context,document:t,documentName:t.name,connection:e,type:r.type,payload:r.payload};return this.hooks(`beforeSync`,i)}),a}},jje=class{constructor(e,t,n){this.document=null,this.document=e,this.instance=t,this.context=n??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new Rte}),await this.instance.unloadDocument(this.document)),null)}};const Mje=()=>{let e=new Map,t=new Map;return{debounce:async(n,r,i,a)=>{let o=e.get(n),s=o?.start||Date.now(),c=async()=>{t.has(n)&&await t.get(n),e.delete(n);let i=r();t.set(n,i);let a=await i;return t.delete(n),a};if(o?.timeout&&clearTimeout(o.timeout),i===0||Date.now()-s>=a)return c();e.set(n,{start:s,timeout:setTimeout(c,i),func:c})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let n=e.get(t);if(n)return clearTimeout(n.timeout),n.func()}}},Nje={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var Pje=class{constructor(e){this.configuration={...Nje,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=Mje(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let n=e.priority===void 0?100:e.priority,r=t.priority===void 0?100:t.priority;return n>r?-1:+(n<r)}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version:kje,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,n)=>(n.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+n.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(l8)})})}handleConnection(e,t,n={}){let r=new Aje(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},n);return r.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),r}handleDocumentUpdate(e,t,n){let r=J8(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=J8(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},o={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:i?.headers??new Headers,requestParameters:Z8(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),Tje(t))return;let s={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:a,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,s)}async createDocument(e,t,n,r,i){if(!e.trim())throw Error(`Document name must not be empty`);let a=this.loadingDocuments.get(e);if(a)return a;let o=this.documents.get(e);if(o)return Promise.resolve(o);let s=this.loadDocument(e,t,n,r,i);this.loadingDocuments.set(e,s);try{let t=await s;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,n,r,i){let a=t.headers,o=Z8(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new Oje(e,{...this.configuration.yDocOptions,...c}),u={instance:this,context:s,connectionConfig:r,document:l,documentName:e,socketId:n,requestHeaders:a,requestParameters:o};try{await this.hooks(`onLoadDocument`,u,e=>{e instanceof j_?q_(l,X_(e)):e instanceof Uint8Array&&q_(l,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(l),t}return l.isLoading=!1,l.onUpdate((e,t,n)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,n)}),await this.hooks(`afterLoadDocument`,u),l.beforeBroadcastStateless((e,t)=>{let n={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,n)}),l.awareness.on(`update`,(t,n)=>{this.hooks(`onAwarenessUpdate`,{document:l,documentName:e,instance:this,...t,transactionOrigin:n,connection:J8(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:UAe(l.awareness.getStates())})}),l}storeDocumentHooks(e,t,n){let r=`onStoreDocument-${e.name}`;return this.debouncer.debounce(r,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof WAe){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},n?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,n=null){let{extensions:r}=this.configuration,i=Promise.resolve();return r.filter(t=>typeof t[e]==`function`).forEach(r=>{i=i.then(()=>r[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),n&&(i=i.then((...e)=>n(...e)))}),i}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let n=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(n)),await n,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new jje(await this.createDocument(e,new Request(`http://localhost`),Gu.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},Q8=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$8=Ql(import.meta.url),e5=Q8(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),t5=Q8(((e,t)=>{let{EMPTY_BUFFER:n}=e5(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=$8(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),Fje=Q8(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),n5=Q8(((e,t)=>{let n=$8(`zlib`),r=t5(),i=Fje(),{kStatusCode:a}=e5(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),r5=Q8(((e,t)=>{let{isUtf8:n}=$8(`buffer`),{hasBlob:r}=e5(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=$8(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),i5=Q8(((e,t)=>{let{Writable:n}=$8(`stream`),r=n5(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=e5(),{concat:c,toArrayBuffer:l,unmask:u}=t5(),{isValidStatusCode:d,isValidUTF8:f}=r5(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),a5=Q8(((e,t)=>{let{Duplex:n}=$8(`stream`),{randomFillSync:r}=$8(`crypto`),i=n5(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=e5(),{isBlob:c,isValidStatusCode:l}=r5(),{mask:u,toBuffer:d}=t5(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),Ije=Q8(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=e5(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),o5=Q8(((e,t)=>{let{tokenChars:n}=r5();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),s5=Q8(((e,t)=>{let n=$8(`events`),r=$8(`https`),i=$8(`http`),a=$8(`net`),o=$8(`tls`),{randomBytes:s,createHash:c}=$8(`crypto`),{Duplex:l,Readable:u}=$8(`stream`),{URL:d}=$8(`url`),f=n5(),p=i5(),m=a5(),{isBlob:h}=r5(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=e5(),{EventTarget:{addEventListener:T,removeEventListener:E}}=Ije(),{format:ee,parse:te}=o5(),{toBuffer:ne}=t5(),re=Symbol(`kAborted`),ie=[8,13],D=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],O=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var k=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),ae(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,de),i.on(`drain`,fe),i.on(`error`,A),i.on(`message`,me),i.on(`ping`,he),i.on(`pong`,ge),a.onerror=ve,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,be),t.on(`data`,j),t.on(`end`,M),t.on(`error`,xe),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){le(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ye(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ue(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){le(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(k,`CONNECTING`,{enumerable:!0,value:D.indexOf(`CONNECTING`)}),Object.defineProperty(k.prototype,`CONNECTING`,{enumerable:!0,value:D.indexOf(`CONNECTING`)}),Object.defineProperty(k,`OPEN`,{enumerable:!0,value:D.indexOf(`OPEN`)}),Object.defineProperty(k.prototype,`OPEN`,{enumerable:!0,value:D.indexOf(`OPEN`)}),Object.defineProperty(k,`CLOSING`,{enumerable:!0,value:D.indexOf(`CLOSING`)}),Object.defineProperty(k.prototype,`CLOSING`,{enumerable:!0,value:D.indexOf(`CLOSING`)}),Object.defineProperty(k,`CLOSED`,{enumerable:!0,value:D.indexOf(`CLOSED`)}),Object.defineProperty(k.prototype,`CLOSED`,{enumerable:!0,value:D.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(k.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(k.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),k.prototype.addEventListener=T,k.prototype.removeEventListener=E,t.exports=k;function ae(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:ie[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!ie.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${ie.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;oe(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?ce:se),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=ee({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!O.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{le(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[re]||(S=e._req=null,oe(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){le(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{oe(e,SyntaxError(`Invalid URL: ${i}`));return}ae(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||le(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==k.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){le(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){le(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){le(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){le(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=te(u)}catch{le(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){le(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{le(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function oe(e,t){e._readyState=k.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function se(e){return e.path=e.socketPath,a.connect(e)}function ce(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function le(e,t,n){e._readyState=k.CLOSING;let r=Error(n);Error.captureStackTrace(r,le),t.setHeader?(t[re]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(oe,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ue(e,t,n){if(t){let n=h(t)?t.size:ne(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${D[e.readyState]})`);process.nextTick(n,t)}}function de(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,j),process.nextTick(_e,n._socket),e===1005?n.close():n.close(e,t))}function fe(){let e=this[C];e.isPaused||e._socket.resume()}function A(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,j),process.nextTick(_e,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function pe(){this[C].emitClose()}function me(e,t){this[C].emit(`message`,e,t)}function he(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ge(e){this[C].emit(`pong`,e)}function _e(e){e.resume()}function ve(e){let t=this[C];t.readyState!==k.CLOSED&&(t.readyState===k.OPEN&&(t._readyState=k.CLOSING,ye(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ye(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function be(){let e=this[C];if(this.removeListener(`close`,be),this.removeListener(`data`,j),this.removeListener(`end`,M),e._readyState=k.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,pe),e._receiver.on(`finish`,pe))}function j(e){this[C]._receiver.write(e)||this.pause()}function M(){let e=this[C];e._readyState=k.CLOSING,e._receiver.end(),this.end()}function xe(){let e=this[C];this.removeListener(`error`,xe),this.on(`error`,w),e&&(e._readyState=k.CLOSING,this.destroy())}})),Lje=Q8(((e,t)=>{s5();let{Duplex:n}=$8(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),Rje=Q8(((e,t)=>{let{tokenChars:n}=r5();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),zje=Q8(((e,t)=>{let n=$8(`events`),r=$8(`http`),{Duplex:i}=$8(`stream`),{createHash:a}=$8(`crypto`),o=o5(),s=n5(),c=Rje(),l=s5(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=e5(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
|
|
1973
1973
|
`).join(`\r
|
|
1974
1974
|
`)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
|
|
1975
1975
|
`)+`\r
|
|
@@ -2026,4 +2026,4 @@ native-divergence-injected
|
|
|
2026
2026
|
`))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 M.flushDeferredStores(`discard-stale`),t=!0,ke?.emitBranchSwitched(i)}finally{ye.abortBranchSwitch(r),t||(ee(!1),await M.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&be.current&&t>0){let t=p??`.`;try{let n=await hx(be.current,t,e.oldHead,e.newHead,i);Nb(),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`),rn.push(`head-watcher`)}function l(e){for(let t of e)try{let e=MM(I(n,F(r,t)));if(e.startsWith(`..`))continue;let i=Dx(e),a=Ce.documents.get(i);if(!a)continue;let o=zt(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=MM(I(n,F(r,t)));if(e.startsWith(`..`))continue;let i=Ce.documents.get(Dx(e));i&&Vt(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=MF(r);b.debug({resetAmbientCredentials:f,originKind:AF(r).kind},`[sync] ambient credential-chain reset decision at boot`);let m=mc(h,{resetAmbient:f}),g=re();g.mode!==`off`&&b.info({mode:g.mode,source:g.source},`[sync] mode active at boot`);try{$t=new $Ne({projectDir:r,contentDir:n,contentFilter:ge,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:g.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialConfig:m,cc1Broadcaster:ke,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||M.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=be.current;n&&await _x(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=be.current;n&&await _x(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 ys({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:Ee(t.error),configPath:Rs(`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 $t.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),$t=null}Je(`files`),ye.announceReadyViews();let _=xL();_!==void 0&&SL(`readyMs`,_),oe()}return an().then(()=>{Qe=!0,He(),dt()},e=>{$e=!0,et.abort(),ct({status:`failed`,indexCount:0}),ye.close(),Ge(),Ue(e)}),{hocuspocus:Ce,durabilityState:x,sessionManager:we,nativeApi:Te,localApi:De,cc1Broadcaster:ke,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:j,contentFilter:ge,basenameIndex:pe,serverInstanceId:ue,destroy:nn,ready:We,generatedIndexSweepReady:st,degraded:rn,lockDir:de,get syncEngine(){return $t},getLinkPreviewsEnabled:k,resolveEmbed:me,acpRegistry:fe,acpPermissions:A}}function f9(e){return e/1048576}function aPe(){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;Es(()=>{p9=null,m9=null,h9=null,_9?.disable(),_9=null,v9=null});function oPe(){if(p9)return;let e=Zs().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}=aPe();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 sPe(){if(!m9){let e=Zs().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=ene({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=Zs().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:Si},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=RE.indexOf(e.host),r=RE.indexOf(t.host);return(n===-1?RE.length:n)-(r===-1?RE.length:r)||e.host.localeCompare(t.host)})}const cPe=b9(kn),lPe=b9(Fn);function uPe(e,t){return z(L(e,st(t)))}function dPe(e,t){zs(P(t),{recursive:!0});try{Ms(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;Hs(e,t,{recursive:!0}),Us(e,{recursive:!0,force:!0})}}function fPe(e,t,n){let r=AI(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??cPe,a={migrated:[],skipped:[]};if(!z(n))return a;let o;try{o=wu(n)}catch{return a}let s=I(t,n).split(R).join(`/`),c=new Set;for(let[e,n]of Object.entries(nX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!no.test(e)||GF.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=ME(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:RI(t,i),state:fPe(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=>uPe(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`?Us(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&Us(d.path,{recursive:!0,force:!0}),dPe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(Us(e.path,{recursive:!0,force:!0}),Hs(d.path,e.path,{recursive:!0}));await pN(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`),pPe=GF;function w9(){let e=[];for(let t of Rt){let n=kn[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:Si,editor:null}),e}function mPe(e,t){let n=I(e,L(t));return ou(n)?L(t):n}function T9(e){let{frontmatter:t,body:n}=Za(e),r={};if(t!==``)try{let e=(0,oD.parse)(xo(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function hPe(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+=ku(s).size+ku(c).size,i>1048576)return!1;let l=B(s),u=B(c);if(!l.equals(u)&&(o!==`SKILL.md`||!hPe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function D9(e,t=``){let n=[];for(let r of wu(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){Us(t,{recursive:!0,force:!0}),zs(e,{recursive:!0}),Fs(mPe(e,n),t,`dir`)}function k9(e,t){try{let n=Tu(e);return L(ou(n)?n:L(P(e),n))===L(t)}catch{return!1}}function gPe(e,t){try{let n=Tu(e),r=ou(n)?L(n):L(P(e),n);if(!z(r))return!1;let i=I(L(t),r);return i!==``&&(i.startsWith(`..`)||ou(i))}catch(t){return C9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const _Pe=[...Rt,`agents`];function vPe(e){for(let t of _Pe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function yPe(e){let{projectDir:t,skillsRoot:n}=e;if(!z(n))return;let r;try{r=wu(n)}catch{return}let i=w9();for(let e of r){let r=vPe(e);if(r===null)continue;let a=L(n,e),o=L(n,r);if(z(o))try{let n=vu(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(RI(t,r))continue;let i=F(r,e);k9(i,a)&&O9(r,i,o)}Us(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 bPe(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)||RI(t,o))continue;let s;try{s=wu(o)}catch(e){C9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(pPe.has(e))continue;let t=F(o,e),s=L(n,e),c=z(s);try{let l=vu(t);if(l.isSymbolicLink()){if(k9(t,s)&&c)continue;if(gPe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(O9(o,t,s),r.healed.push({name:e,editor:i})):(Us(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!no.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=uN(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 fN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??NI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){C9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{yPe({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=RD(e);A9=new ic({currentPath:L(t,`tolerance-telemetry.jsonl`),previousPath:L(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),zt(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(){zt(null),await A9?.drain(),A9=null,j9=!1}hs();const xPe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],SPe=[`cache`,`tmp`];function CPe(e){let t=L(e,ye);if(!(()=>{if(!z(t))return!0;try{return wu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of xPe)z(L(e,t))&&n.push(t);for(let t of SPe){let r=L(e,t);try{z(r)&&ku(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function wPe(e){let t=dd(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 TPe(e){Xhe();let t=e.projectDir??e.contentDir,n=kye({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}`)}ec.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}Xs({localSink:n?.telemetry}),N9(t),oPe(),sPe();let{kind:r,gitdir:i}=wPe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Vs(i));let o=Dye(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ds(`ok.boot`,{attributes:a},async()=>EPe(e)),l=()=>{if(s)try{let e=ps.extract(gs.active(),{traceparent:s});return gs.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 EPe(e){let t=e.skipAutoInit??!1,n=e.log??N(`boot`),r=e.serverRuntime??{...ea(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((za(r)||!co(i))&&!r.allowExternal)throw new SB(`refusing to start: the server would bind a non-loopback address (${(co(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=TB({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrl===void 0&&(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-DEUsqKAE.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 s8(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??tK;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof QG||e instanceof $G){let t=e instanceof $G?e.detected:``,r=e instanceof $G?`too_old`:`not_available`;bK(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 Ys(),await Promise.race([P9(),new Promise(e=>setTimeout(e,F9))]),e}let _=CPe(m);_.length>0&&N(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ye}/.`);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,mcpTomlEditor:e.mcpTomlEditor,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:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee}=v,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),re=e.port??0,ie=()=>`http://${te}:${re}`,D=e.ephemeral?void 0:e8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>ie(),localApi:v.localApi,log:n}),O=c();O.headersTimeout=3e4,O.requestTimeout=6e4;let k=e.serveContentAssets===!1?void 0:wZ({contentFilter:v.contentFilter,contentSirv:LZ(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:be,assetExtensions:ne,blocklistExtensions:Ne,ingressPolicy:a}),ae=e.reactShellDistDir?LZ(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new JT({contentDir:e.contentDir,localDir:C,globalDir:L(Nu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:w,agentPresenceBroadcaster:E,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:()=>ie(),getMcpStdioCommand:()=>qT(e.localOpCliArgs,re),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:n});oe!==null&&await oe.init();let se=`pending`;x.then(()=>{se=`ready`},()=>{se=`failed`});let ce=a8({httpServer:O,hocuspocus:y,nativeApi:v.nativeApi,mcpHttpHandler:D,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>S},log:n,sessionManager:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:k,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;e.idleShutdownMs!==null&&(ue=HZ({httpServer:O,thresholdMs:e.idleShutdownMs??18e5,log:n,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await I9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:n});let de=[...new Set(i)],fe=de[0],A=async()=>{await b().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(C)},pe=(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 pe(O,e.port??0,fe??`127.0.0.1`)}catch(e){throw await A(),e}let me=O.address(),he=typeof me==`object`&&me?me.port:e.port??0,ge=[];for(let e of de.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 pe(t,he,e)}catch(t){n.error({err:t,failedAddress:e,port:he,alreadyBound:ge.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...ge,O])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await A(),t}ge.push(t)}let _e=xL();_e!==void 0&&SL(`httpListenMs`,_e);let ve=O.address(),j=typeof ve==`object`&&ve?ve.port:e.port??0;re=j,d(C,j,ie());let M=!1,xe=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)}};le=async()=>{if(M)return;M=!0,se=`draining`;let e=[],t=async(t,r)=>{try{await xe(t,r)}catch(r){e.push(r),n.warn({err:r,step:t},`bootServer destroy step failed`)}};try{l(C)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),n.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await t(`acpThreads.destroy`,()=>oe.destroy()),await t(`secondaryListeners.close`,async()=>{for(let e of ge)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`,()=>ce.shutdown()),D!==void 0&&await t(`mcpHttpHandler.close`,()=>D.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.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()),await t(`shutdownTelemetry`,()=>Ys()),await t(`teardownToleranceTelemetry`,()=>P9()),await t(`flushLogFileSinks`,()=>ec.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,cL(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=Nu(),t=await S9({projectDir:e,skillsRoot:L(e,`.ok`,`skills`),hostRoots:lPe,inPlaceNames:x9(e,lL(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 bPe({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:le,lockDir:C,contentDir:e.contentDir,port:j,ready:x,generatedIndexSweepReady:v.generatedIndexSweepReady,degraded:S,didAutoInit:f,serverInstance:v,runtime:LAe(v,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:oe}}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=fd(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=uc({baseDir:n,timeout:{block:5e3}});s=new Set(await Ab(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=Dx(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 DPe=Ie;function OPe(e={}){let t=e.home??Nu(),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(rc(),1);const R9=F(Nu(),`.ok`,`logs`),kPe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function APe(){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 jPe(e){yu(e,{recursive:!0})}function z9(){return new Date().toISOString().slice(0,10)}function MPe(e){try{if(ku(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{Eu(n,r)}catch{}}try{Au(`${e}.3`)}catch{}}function NPe(e){try{let t=Date.now(),n=10080*60*1e3,r=wu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ku(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{Au(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{Au(F(e,t.name)),a-=t.size}catch{}}}catch{}}function PPe(e){jPe(R9);let t=z9(),n=e.filePath??F(R9,`${e.name}.${t}.log`);MPe(n),(e._setTimeout??setTimeout)(()=>NPe(R9),5e3).unref();let r=L9.default.destination({dest:n,append:!0,sync:!0});return(0,L9.default)({level:APe(),name:e.name,redact:{paths:kPe,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 FPe(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 IPe(e){return F(R9,`${e}.${z9()}.log`)}function LPe(){return R9}function RPe(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=ed($l),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 zPe(e,t){try{return await B9(e,[`var`,`GIT_COMMITTER_IDENT`],RM({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function BPe(e,t){try{let{stdout:n}=await B9(e,[`for-each-ref`,`--count=1`,`refs/`],RM({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 VPe(e){let t=L(e,`packed-refs`);if(z(t))try{if(B(t,`utf-8`).split(`
|
|
2027
2027
|
`).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return wu(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 BPe(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await zPe(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await B9(e,i,RM({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 HPe(e,t){try{let{stdout:n}=await B9(e,[`rev-parse`,`--is-inside-work-tree`],RM({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function UPe(e){let t=L(e);_W(t);let n=L(t,`.git`),r=L(n,`HEAD`),i=!1,a=!1;if(z(n)){if(!ku(n).isDirectory())return{didInit:!1};if(z(r)){if(VPe(n))return{didInit:!1};a=!0}else V9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=tK()}catch(e){throw e instanceof QG||e instanceof $G?(bK(e),V9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof $G?`too_old`:`not_available`,detectedVersion:e instanceof $G?e.detected:``},e instanceof $G?`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 HPe(s,t))return{didInit:!1};let c=``;try{c=(await B9(s,[`init`,`--initial-branch=main`,t],RM({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}$/,WPe=sn.map(e=>e.replace(/\/$/,``));async function GPe(e){let t=fd(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(YPe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=dc(e,{credentialConfig:[]});if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await lc(async()=>{let t=await KPe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await qPe(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=dc(e,{gitIndexFile:F(Iu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`),credentialConfig:[]});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 JPe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await fB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;gc(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 \`${Tn}\` 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 WPe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function KPe(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 qPe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function JPe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function YPe(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 XPe(e,t){let n;try{n=Ql(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 Bu(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 ZPe=[{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 ZPe)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 QPe(e){if(!Tx(e))throw new $9(e);let t;try{t=V(L(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!ku(t).isFile())throw new Q9(e);let n=P(t),r=Xz(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Dx(I($Pe(e),t).split(R).join(`/`)),canonicalFilePath:t}}let i=ru(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Dx(i)}}function $Pe(e){return L(e,Ss({absPath:Rs(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function eFe(e){let t=bu(L(Iu(),`ok-ephemeral-`)),n=L(t,`.ok`);return yu(n,{recursive:!0}),ju(L(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),ju(L(n,`.gitignore`),`local/
|
|
2028
2028
|
`,`utf-8`),t}export{c2 as $,fx as $i,WR as $n,HM as $r,yK as $t,F7 as A,qT as Ai,EB as An,WP as Ar,eye as At,Y5 as B,CC as Bi,jz as Bn,yP as Br,IJ as Bt,d9 as C,Hd as Ca,zD as Ci,gW as Cn,qF as Cr,hye as Ct,I7 as D,Md as Da,lE as Di,bB as Dn,YF as Dr,WX as Dt,N7 as E,hd as Ea,uE as Ei,NB as En,Qme as Er,wZ as Et,VMe as F,rw as Fi,Yz as Fn,Npe as Fr,VJ as Ft,i8 as G,qx as Gi,qz as Gn,mpe as Gr,PJ as Gt,o8 as H,tS as Hi,Sz as Hn,gP as Hr,jJ as Ht,o7 as I,Ele as Ii,iz as In,SP as Ir,zJ as It,Z6 as J,zx as Ji,YR as Jn,XM as Jr,MJ as Jt,n8 as K,Rx as Ki,Oz as Kn,qM as Kr,NJ as Kt,a7 as L,Dle as Li,Az as Ln,wP as Lr,EJ as Lt,C7 as M,ow as Mi,hB as Mn,AP as Mr,xZ as Mt,b7 as N,KC as Ni,mB as Nn,jP as Nr,qX as Nt,j7 as O,pd as Oa,JT as Oi,OB as On,$me as Or,UX as Ot,i7 as P,tw as Pi,Xz as Pn,OP as Pr,Nge as Pt,r2 as Q,dx as Qi,GR as Qn,zM as Qr,SK as Qt,kMe as R,QC as Ri,dz as Rn,CP as Rr,Ege as Rt,P9 as S,Id as Sa,LD as Si,hW as Sn,eI as Sr,kZ as St,A7 as T,gd as Ta,dE as Ti,TB as Tn,WF as Tr,EZ as Tt,s8 as U,G as Ui,lz as Un,_P as Ur,Tge as Ut,K5 as V,WC as Vi,Dz as Vn,bP as Vr,AJ as Vt,a8 as W,eS as Wi,kz as Wn,WN as Wr,LJ as Wt,t2 as X,Lx as Xi,HR as Xn,YM as Xr,SJ as Xt,V6 as Y,Ux as Yi,XR as Yn,JM as Yr,xJ as Yt,n2 as Z,bx as Zi,UR as Zn,WM as Zr,wK as Zt,DPe as _,Xie as _a,AA as _i,OW as _n,iI as _r,NZ as _t,QPe as a,xx as aa,kj as ai,vK as an,OI as ar,tCe as at,N9 as b,nh as ba,OA as bi,mW as bn,tI as br,DZ as bt,GPe as c,_x as ca,Aj as ci,rK as cn,TI as cr,P0 as ct,RPe as d,nx as da,aj as di,UG as dn,xI as dr,M$ as dt,px as ea,RM as ei,bK as en,BR as er,pCe as et,PPe as f,Yb as fa,oj as fi,vW as fn,SI as fr,u$ as ft,OPe as g,$se as ga,jA as gi,jW as gn,yI as gr,HZ as gt,LPe as h,Rb as ha,PA as hi,SW as hn,phe as hr,O$ as ht,eFe as i,ux as ia,Pj as ii,tK as in,kI as ir,eCe as it,k7 as j,iw as ji,gB as jn,kP as jr,CZ as jt,P7 as k,ad as ka,zT as ki,kB as kn,jF as kr,$ve as kt,H9 as l,vx as la,Mj as li,qG as ln,CI as lr,I0 as lt,IPe as m,Gb as ma,NA as mi,DW as mn,_I as mr,T$ as mt,Z9 as n,hx as na,bM as ni,$G as nn,gR as nr,J0 as nt,X9 as o,ix as oa,Tj as oi,eK as on,Dhe as or,nCe as ot,FPe as p,qb as pa,vj as pi,EW as pn,vI as pr,ybe as pt,e8 as q,Wx as qi,sz as qn,KM as qr,FJ as qt,$9 as r,ox as ra,yM as ri,XG as rn,sR as rr,U0 as rt,XPe as s,yx as sa,Nj as si,sK as sn,xhe as sr,L0 as st,Q9 as t,cx as ta,PM as ti,QG as tn,jR as tr,Y0 as tt,UPe as u,Sx as ua,jj as ui,KG as un,bI as ur,n0 as ut,TPe as v,th as va,EA as vi,bW as vn,nI as vr,OZ as vt,u9 as w,Fd as wa,rD as wi,SB as wn,JF as wr,MZ as wt,M9 as x,Vd as xa,RD as xi,_W as xn,QF as xr,AZ as xt,I9 as y,rh as ya,kA as yi,kW as yn,rI as yr,jZ as yt,Q5 as z,SC as zi,uz as zn,xP as zr,wge as zt};
|
|
2029
|
-
//# sourceMappingURL=src-
|
|
2029
|
+
//# sourceMappingURL=src-3c-GN0Vv.mjs.map
|