@inkeep/open-knowledge 0.86.23-beta.3 → 0.87.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +75 -75
- package/dist/constants-CLt-YYUO.mjs +1 -0
- package/dist/{dist-Ds1SZERP.mjs → dist-0gI1oLbO.mjs} +493 -493
- package/dist/dist-_mI3Jjf-.mjs +1 -0
- package/dist/index.d.mts +80 -6
- package/dist/index.mjs +247 -247
- package/dist/{init-BVMADGS2.mjs → init-CFHi1Fcj.mjs} +15 -15
- package/dist/init-rHEB41mj.mjs +1 -0
- package/dist/{launch-json-removal-BRySMyPV.mjs → launch-json-removal-NqBZ7pN8.mjs} +1 -1
- package/dist/{loader-BMNiWrib.mjs → loader-DQFZDbSn.mjs} +1 -1
- package/dist/loader-DcZUqBSG.mjs +1 -0
- package/dist/{open-browser-BGyDP4ZD.mjs → open-browser-3bURxjbo.mjs} +1 -1
- package/dist/{preview-DXhCGcEu.mjs → preview-B_25nN_N.mjs} +1 -1
- package/dist/preview-PCp5ecCo.mjs +1 -0
- package/dist/public/assets/{AccountSection-CMmMULN1.js → AccountSection-BFqWrFlT.js} +1 -1
- package/dist/public/assets/{ActivityModeContent-DCUclZ6p.js → ActivityModeContent-yhgI8oFG.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-Bt_VrQUZ.js → AddPropertiesButton-MLzWjidH.js} +1 -1
- package/dist/public/assets/{AgentConnectionsSection-B9_oKPEW.js → AgentConnectionsSection-BBrTu_Hd.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-DitXoPUm.js → AgentDiffPane-odHOX5ou.js} +1 -1
- package/dist/public/assets/{AgentThreadClientBinder-C_cPFOsE.js → AgentThreadClientBinder-BKZL1FEK.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-gNKc_SeK.js → AttachmentsSection-CtybpzGF.js} +1 -1
- package/dist/public/assets/{BugReportHistory-CHujhV74.js → BugReportHistory-DCPpzbO5.js} +1 -1
- package/dist/public/assets/{BugReportHistoryDialog-CaE3cXFx.js → BugReportHistoryDialog-D-QZYqdF.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-C-LA9RZj.js → CodeMirrorPropInput--W4wCHlF.js} +1 -1
- package/dist/public/assets/{ContentRulesSection-DRI8_9cr.js → ContentRulesSection-CykOS7NO.js} +1 -1
- package/dist/public/assets/{DeleteConfirmationDialog-CUUTX6Ez.js → DeleteConfirmationDialog-B0lltyMh.js} +1 -1
- package/dist/public/assets/{DocumentContext-skdHXmIx.js → DocumentContext-DuzPYn-L.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-D09LAycY.js → EditorModeToggle-D1bGTuIo.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-DXpYBsW3.js → ExcalidrawDocEditor-DCGw91_j.js} +1 -1
- package/dist/public/assets/FeedbackForm-LftMOkox.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-B5H51ry5.js → ImportSkillDialog-BOo8ydBK.js} +1 -1
- package/dist/public/assets/{LinkPreviewsSection-CQP_Vwon.js → LinkPreviewsSection-rkuua-2U.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-CY9ean4q.js → LintConfigEditor-CRNSneRW.js} +1 -1
- package/dist/public/assets/{LintingSection-Y1p4tPbo.js → LintingSection-DFFZeQ-E.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-BR717PH9.js → ManagedArtifactProperties-B-_jchqJ.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-DphHurUG.js +1 -0
- package/dist/public/assets/{McpConsentDialogBody-CVZcuVhW.js → McpConsentDialogBody-9u-ImAfw.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-Ck2Pm93Y.js → MermaidDocEditor-DTu-dvsD.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-Z0cogGml.js → NetworkAccessSection-CuhVVg7m.js} +1 -1
- package/dist/public/assets/{ProjectTemplatesSection-BEchYRnN.js → ProjectTemplatesSection-DYj1MFJG.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-DdG1TJQ6.js → PropertyDisplayRow-DvxuFae6.js} +1 -1
- package/dist/public/assets/{PublishToGitHubDialog-u-Kf-7fz.js → PublishToGitHubDialog-BT4fGIzU.js} +1 -1
- package/dist/public/assets/{ReportBugDialogBody-jHepd9au.js → ReportBugDialogBody-Bbd3DGIB.js} +1 -1
- package/dist/public/assets/{ReportBugMenuTrigger-KsljCE5p.js → ReportBugMenuTrigger-DFg5tOG8.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-BWxTLiHi.js → SchemaConfigEditor-D9mAflq9.js} +1 -1
- package/dist/public/assets/{SearchSection-CrbsRy_b.js → SearchSection-DNy_Kbe5.js} +1 -1
- package/dist/public/assets/{SessionsHost-CSF36yQa.js → SessionsHost-CO8vZSW-.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-C3aJD4t2.js → SettingsDialogBody-CPTiFO3W.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-CRo5ZsQS.js → ShareReceiveMissDialog-1Fih4rJ_.js} +1 -1
- package/dist/public/assets/SkillInstallMenu-DtXyIqB8.js +1 -0
- package/dist/public/assets/{SkillPluginBundleDialog-BnQu_DSM.js → SkillPluginBundleDialog-XB1fO90e.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-Brxdm5zY.js → SkillToolbarControls-C-hNz5u-.js} +1 -1
- package/dist/public/assets/{SkillsManagerSection-D4YW1uOY.js → SkillsManagerSection-DCJlhnvy.js} +1 -1
- package/dist/public/assets/{SourceEditor-YuX3qk7k.js → SourceEditor-Wc_sKhIh.js} +1 -1
- package/dist/public/assets/{SpellingSettings-C72xD-Zu.js → SpellingSettings-DhyHqpT4.js} +1 -1
- package/dist/public/assets/{SyncSection-B-Z2q0Zq.js → SyncSection-DtwPj2AH.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-Bh6uqVnr.js → SyncStatusBadge-CgInLUSB.js} +1 -1
- package/dist/public/assets/{TemplateRow-4LHta_yW.js → TemplateRow-B04s7sdl.js} +1 -1
- package/dist/public/assets/{TerminalLaunchContext-DprnLNoQ.js → TerminalLaunchContext-VC_1IQ2O.js} +1 -1
- package/dist/public/assets/{TerminalPanel-D93jMQs_.js → TerminalPanel-Bj0ZrCsM.js} +2 -2
- package/dist/public/assets/{TerminalSection-B9LK0nnU.js → TerminalSection-BwGCsSyU.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-BEVlr5GI.js → TerminalWindowApp-8ziyU5HN.js} +1 -1
- package/dist/public/assets/{TextDocEditor-mKIqhYBd.js → TextDocEditor-_z2CYvAE.js} +1 -1
- package/dist/public/assets/{ThemePluginSection-BHfep7sw.js → ThemePluginSection-DvtPYcRy.js} +1 -1
- package/dist/public/assets/ThreadView-dlfnVx0Q.js +28 -0
- package/dist/public/assets/{TimelineDiffPane-BE3b_fjl.js → TimelineDiffPane-Cgyz-JUw.js} +1 -1
- package/dist/public/assets/{agent-connections-D6YhmKlS.js → agent-connections-BdU_6bUV.js} +1 -1
- package/dist/public/assets/alert-dialog-Mwvu63aS.js +7 -0
- package/dist/public/assets/{client-version-BHMlOjvp.js → client-version-DQp_Y_G_.js} +1 -1
- package/dist/public/assets/{comment-chips-C7bM644Z.js → comment-chips-CpTTTT-b.js} +1 -1
- package/dist/public/assets/{config-provider-BdwMWK6h.js → config-provider-CW6aAAL3.js} +1 -1
- package/dist/public/assets/config-schema-gPKGwQR7.js +1 -0
- package/dist/public/assets/{doc-undo-manager-BSoaU6SU.js → doc-undo-manager-B5X19Hs2.js} +1 -1
- package/dist/public/assets/field-controls-DShsojhy.js +1 -0
- package/dist/public/assets/{field-controls-DBnF9Har.js → field-controls-DtQ6Aw_j.js} +1 -1
- package/dist/public/assets/{index-CGt5tH6Q.js → index-CZNo33D6.js} +113 -113
- package/dist/public/assets/{lint-config-client-B249C1D2.js → lint-config-client-DZxh6x0d.js} +1 -1
- package/dist/public/assets/{lint-plugins-B4zyv7AM.js → lint-plugins-wol9ZIt4.js} +1 -1
- package/dist/public/assets/{markdown-lint-BMeMGAz_.js → markdown-lint-CYB8LZHY.js} +1 -1
- package/dist/public/assets/{markdownlint-rule-browser-Bt2f856y.js → markdownlint-rule-browser-BHLBJ88w.js} +1 -1
- package/dist/public/assets/messages-BDCxJPx2.js +1 -0
- package/dist/public/assets/messages-BEW0uPVX.js +1 -0
- package/dist/public/assets/messages-BO-eBk9m.js +1 -0
- package/dist/public/assets/messages-BaDp2_Fp.js +1 -0
- package/dist/public/assets/messages-CDO-xexo.js +1 -0
- package/dist/public/assets/messages-CRHWN_nJ.js +1 -0
- package/dist/public/assets/messages-CVuWmrbN.js +1 -0
- package/dist/public/assets/messages-C_w7Btlk.js +1 -0
- package/dist/public/assets/messages-CtVlTdzP.js +1 -0
- package/dist/public/assets/messages-Cz11LTJA.js +1 -0
- package/dist/public/assets/messages-D3qz2TwL.js +1 -0
- package/dist/public/assets/messages-DHXe_6Gj.js +1 -0
- package/dist/public/assets/messages-DKWtuhsU.js +1 -0
- package/dist/public/assets/{pending-receive-nav-store-Bd4RfWjz.js → pending-receive-nav-store-BvFp7bbT.js} +1 -1
- package/dist/public/assets/{preferred-session-events-gE5MTWn9.js → preferred-session-events-BW2NoJIm.js} +1 -1
- package/dist/public/assets/{progress-D3LBnbHU.js → progress-DhQ_OqoO.js} +1 -1
- package/dist/public/assets/restart-collab-server-D_8KLQoA.js +1 -0
- package/dist/public/assets/{saved-themes-client-DFijgxrT.js → saved-themes-client-BPWMEtsb.js} +1 -1
- package/dist/public/assets/{schema-section-BHt16UFk.js → schema-section-DUv4SBzP.js} +1 -1
- package/dist/public/assets/{selection-context-gfpT4D2n.js → selection-context-C92qzena.js} +1 -1
- package/dist/public/assets/{sign-in-terminal-events-DFnpq2Xu.js → sign-in-terminal-events-BjvOWBuh.js} +1 -1
- package/dist/public/assets/{src-gMHqNkrm.js → src-C_IMHIyQ.js} +1 -1
- package/dist/public/assets/{telemetry-impl-eEV_kZ4U.js → telemetry-impl-CeFc7iRI.js} +1 -1
- package/dist/public/assets/{telemetry-startup-DuqQdLdC.js → telemetry-startup-tcbRnMqw.js} +1 -1
- package/dist/public/assets/thread-client-CySNJ-9g.js +3 -0
- package/dist/public/assets/{typing-burst-detector-B9DZ8zkq.js → typing-burst-detector-BruIt80B.js} +1 -1
- package/dist/public/assets/{uninstall-Is26Mh1k.js → uninstall-DnITG12q.js} +1 -1
- package/dist/public/assets/{use-activity-panel-Cj33FV4Y.js → use-activity-panel-BK8FZj48.js} +1 -1
- package/dist/public/assets/{use-apply-config-language-DhdpbJI9.js → use-apply-config-language-DlSviEmN.js} +2 -2
- package/dist/public/assets/{use-installed-clis-BTrIR9--.js → use-installed-clis-IB8iDaEn.js} +2 -2
- package/dist/public/assets/{use-open-skill-B_KFVcJQ.js → use-open-skill-Dy5-n3wk.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-C0wjnLPA.js → use-terminal-enabled-DnZSDoBa.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-CwuaVyAR.js → use-timeline-entry-diff-Ds9D7JhW.js} +1 -1
- package/dist/public/index.html +34 -34
- package/dist/public/uninstall.html +3 -3
- package/dist/{registry-probes-Bx4JMRjq.mjs → registry-probes-DoaNqJKv.mjs} +9 -9
- package/dist/{removal-file-path-CPyBvxpx.mjs → removal-file-path-bmO442-0.mjs} +1 -1
- package/dist/{repair-launch-json-lpbMaBB8.mjs → repair-launch-json-DLoUITs6.mjs} +1 -1
- package/dist/{repair-mcp-configs-BBLWRdKU.mjs → repair-mcp-configs-Dj0hD_J2.mjs} +1 -1
- package/dist/src-CAHywvX5.mjs +1 -0
- package/dist/src-arh6MdSM.mjs +16 -0
- package/dist/start-19QN2tiz.mjs +5 -0
- package/dist/start-DsdR2ocV.mjs +1 -0
- package/package.json +4 -4
- package/dist/constants-Byeyagc8.mjs +0 -1
- package/dist/dist-nfglEvqM.mjs +0 -1
- package/dist/init-C_DfEWMe.mjs +0 -1
- package/dist/loader-CGCqxeRw.mjs +0 -1
- package/dist/preview-BolYsbgi.mjs +0 -1
- package/dist/public/assets/FeedbackForm-4RZxei-E.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-DBLg8cix.js +0 -1
- package/dist/public/assets/SkillInstallMenu-29VzNm-A.js +0 -2
- package/dist/public/assets/ThreadView-y6JNzcp7.js +0 -28
- package/dist/public/assets/alert-dialog-BA3e7-10.js +0 -7
- package/dist/public/assets/config-schema-zP71feeS.js +0 -1
- package/dist/public/assets/field-controls-B49FSs4r.js +0 -1
- package/dist/public/assets/messages-B3hGIlOW.js +0 -1
- package/dist/public/assets/messages-B8VdcD3O.js +0 -1
- package/dist/public/assets/messages-BFNQsHgi.js +0 -1
- package/dist/public/assets/messages-BGmL7MgU.js +0 -1
- package/dist/public/assets/messages-C6AMkVgN.js +0 -1
- package/dist/public/assets/messages-CW0D4yWD.js +0 -1
- package/dist/public/assets/messages-Czw7FUyE.js +0 -1
- package/dist/public/assets/messages-D0VKiuAT.js +0 -1
- package/dist/public/assets/messages-DA0gX6QO.js +0 -1
- package/dist/public/assets/messages-DMOSEYr-.js +0 -1
- package/dist/public/assets/messages-DSIrnwaj.js +0 -1
- package/dist/public/assets/messages-DWWaq0e2.js +0 -1
- package/dist/public/assets/messages-DrETOalU.js +0 -1
- package/dist/public/assets/restart-collab-server-DKIjp3iW.js +0 -1
- package/dist/public/assets/thread-client-B5QuHu0p.js +0 -3
- package/dist/src-C97lXQfs.mjs +0 -16
- package/dist/src-CZz3OQDf.mjs +0 -1
- package/dist/start-CMvTynJ0.mjs +0 -1
- package/dist/start-CrB3JLFw.mjs +0 -5
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./dist-C_FzPxEX2.js";import{i as t}from"./constants-product-BVSOzxVs.js";import{t as n}from"./channel-cli-copy-DOAEiMde.js";function r(t){switch(t.reason){case`other-channel`:return i(t.holderChannel);case`eperm`:return e._({id:`XuQzrk`});case`other`:{let t=n();return e._({id:`cD5D4S`,values:{cliCommand:t}})}}}function i(n){let r=t(n);return e._({id:`CacpkO`,values:{holder:r}})}async function a(e){let t=await e.restartServer(e.config.projectPath);return t.ok?{ok:!0}:{ok:!1,message:r(t)}}export{a as n,i as t};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./chunk-CYidjpOJ.js";import{t}from"./react-f2sANaYj.js";import{t as n}from"./compiler-runtime-BfE3aGVn.js";import{n as r}from"./dist-BGzUo_18.js";import{t as i}from"./dist-C_FzPxEX2.js";import{t as a}from"./acp-thread-protocol-DEJR583g.js";import{i as o}from"./acp-tool-call-input-BvswXDFl.js";var s=e(t(),1),c=n(),l=`ok-acp-agent-settings-v1`;function u(e){return`${e.source}:${e.id}`}function d(){try{let e=localStorage.getItem(l);if(e===null)return{};let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch(e){console.warn(`[acp-settings] could not persist agent settings`,e)}}function p(e,t,n){let r=d(),i=r[e]??{};r[e]={...i,config:{...i.config,[t]:n}},f(r)}function m(e){let t=d()[e]?.config;if(typeof t!=`object`||!t)return;let n={};for(let[e,r]of Object.entries(t))(typeof r==`string`||typeof r==`boolean`)&&(n[e]=r);return Object.keys(n).length>0?n:void 0}function h(e,t){if(t===``)return;let n=d();n[e]={...n[e]??{},modeId:t},f(n)}function g(e){let t=d()[e]?.modeId;return typeof t==`string`&&t!==``?t:void 0}function _(e,t){let n=d(),r=n[e]??{};if(t===null||!Number.isFinite(t)||t<=0){let{contextWindow:t,...i}=r;n[e]=i}else n[e]={...r,contextWindow:Math.floor(t)};f(n)}function ee(e){let t=d()[e]?.contextWindow;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:void 0}var v=`codex-acp`,y=[`Warning: `,`Config warning: `],b=`
|
|
2
|
-
|
|
3
|
-
`;function x(e,t){if(t==null||t.source!==`registry`||t.id!==v||typeof e!=`object`||!e)return!1;let n=e;if(n.sessionUpdate!==`agent_message_chunk`||n.messageId!==void 0)return!1;let r=n.content;if(typeof r!=`object`||!r)return!1;let i=r;if(i.type!==`text`||typeof i.text!=`string`)return!1;let a=i.text;return a.endsWith(b)?y.some(e=>a.startsWith(e)):!1}var S=64e3;function C(e){if(typeof e!=`object`||!e)return null;let t=e;return t.type===`text`&&typeof t.text==`string`?t.text:null}function w(e,t){return e===`execute`?o(t):null}function T(e){return e!==null&&(e.reason===`connect`||e.reason===`session-setup`||e.reason===`auth-required`||e.reason===`exited`)}var E=class{agent;constructor(e){this.agent=e}items=[];plan=[];turnActive=!1;tokenUsage=null;terminals={};toolCallIndex=new Map;permissionIndex=new Map;permissionByToolCall=new Map;permissionsByToolCall={};messageIndex=new Map;runtimeConsentIndex=new Map;piBridgeIndex=new Map;lastConsentIndex=null;appliedCount=0;dirty=!1;snapshot={items:[],plan:[],turnActive:!1,tokenUsage:null,terminals:{},permissionsByToolCall:{}};sync(e){e.length<this.appliedCount&&this.reset();for(let t=this.appliedCount;t<e.length;t++)this.applyEvent(e[t],t);return this.appliedCount=e.length,this.dirty&&=(this.snapshot={items:[...this.items],plan:this.plan,turnActive:this.turnActive,tokenUsage:this.tokenUsage,terminals:{...this.terminals},permissionsByToolCall:{...this.permissionsByToolCall}},!1),this.snapshot}reset(){this.items=[],this.plan=[],this.turnActive=!1,this.tokenUsage=null,this.terminals={},this.toolCallIndex=new Map,this.permissionIndex=new Map,this.permissionByToolCall=new Map,this.permissionsByToolCall={},this.messageIndex=new Map,this.runtimeConsentIndex=new Map,this.piBridgeIndex=new Map,this.lastConsentIndex=null,this.appliedCount=0,this.dirty=!0}applyEvent(e,t){switch(this.dirty=!0,e.kind){case`user_message`:{let t={kind:`message`,role:`user`,text:e.content,messageId:`user-${this.items.length}`,sentAt:e.ts};e.attachments!==void 0&&e.attachments.length>0&&(t.attachments=e.attachments),this.items.push(t),this.messageIndex.clear();break}case`turn_started`:this.turnActive=!0;break;case`browser_unavailable`:this.items.push({kind:`browser_unavailable`,reason:e.reason,seq:t});break;case`turn_ended`:this.turnActive=!1,this.messageIndex.clear();break;case`status`:if(e.status===`exited`&&(this.turnActive=!1),this.lastConsentIndex!==null){let t=this.items[this.lastConsentIndex];t?.kind===`runtime_consent`&&t.install===`running`&&(e.status===`spawning`||e.status===`ready`||e.status===`running`?this.items[this.lastConsentIndex]={...t,install:`done`}:(e.status===`error`||e.status===`exited`)&&(this.items[this.lastConsentIndex]={...t,install:`failed`}))}if(e.status===`ready`)for(let e=0;e<this.items.length;e+=1){let t=this.items[e];t?.kind===`notice`&&t.superseded!==!0&&T(t.failure)&&(this.items[e]={...t,superseded:!0})}if((e.status===`error`||e.status===`auth_required`||e.status===`exited`&&e.failure?.reason===`exited`)&&(e.failure!==void 0||(e.detail??``)!==``)){let t={kind:`notice`,text:e.detail??``,tone:e.status===`auth_required`?`info`:`error`,failure:e.failure??null,attempts:1},n=this.items[this.items.length-1];n?.kind===`notice`&&n.superseded!==!0&&A(n,t)?this.items[this.items.length-1]={...n,attempts:n.attempts+1}:this.items.push(t)}break;case`permission_request`:{let t=e.toolCall.toolCallId??null,n=t===null?void 0:this.toolCallIndex.get(t),r=n===void 0?void 0:this.items[n],a=r?.kind===`tool_call`?r.toolKind:void 0,o=e.toolCall.kind??a??`other`,s={kind:`permission`,requestId:e.requestId,title:e.toolCall.title??i._({id:`Ya3PlJ`}),toolKind:o,command:w(o,e.toolCall.rawInput)??w(o,r?.kind===`tool_call`?r.rawInput:void 0),options:e.options,readOnlyShell:e.readOnlyShell===!0,resolved:null,toolCallId:t,mergedIntoToolCall:n!==void 0};this.permissionIndex.set(e.requestId,this.items.length),t!==null&&(this.permissionByToolCall.set(t,this.items.length),this.permissionsByToolCall[t]=s),this.items.push(s);break}case`permission_resolved`:{let t=this.permissionIndex.get(e.requestId);if(t===void 0)break;let n=this.items[t];if(n.kind!==`permission`)break;let r={...n,resolved:{optionId:e.optionId,auto:e.auto}};this.items[t]=r,r.toolCallId!==null&&(this.permissionsByToolCall[r.toolCallId]=r);break}case`runtime_consent_request`:this.runtimeConsentIndex.set(e.requestId,this.items.length),this.lastConsentIndex=this.items.length,this.items.push({kind:`runtime_consent`,requestId:e.requestId,runtime:e.runtime,displayName:e.displayName,provides:e.provides,version:e.version,approxSizeMB:e.approxSizeMB,sourceHost:e.sourceHost,agentName:e.agentName,reason:e.reason??`missing`,resolved:null,install:null,progress:null});break;case`runtime_consent_resolved`:{let t=this.runtimeConsentIndex.get(e.requestId);if(t===void 0)break;let n=this.items[t];if(n.kind!==`runtime_consent`)break;this.items[t]={...n,resolved:e.decision,install:e.decision===`granted`?`running`:null};break}case`pi_bridge_consent_request`:this.piBridgeIndex.set(e.requestId,this.items.length),this.items.push({kind:`pi_bridge`,row:`prompted`,prompt:{requestId:e.requestId,agentName:e.agentName,cwd:e.cwd,otherExtensions:e.otherExtensions??[]},bridgePath:e.bridgePath,decision:null,outcome:null});break;case`pi_bridge_consent_resolved`:{let t=this.piBridgeIndex.get(e.requestId);if(t===void 0)break;let n=this.items[t];if(n.kind!==`pi_bridge`)break;this.items[t]={...n,decision:e.decision};break}case`pi_bridge_status`:{let t={state:e.state,detail:e.detail??null},n=e.requestId===void 0?void 0:this.piBridgeIndex.get(e.requestId),r=n===void 0?void 0:this.items[n];if(n!==void 0&&r?.kind===`pi_bridge`){this.items[n]={...r,outcome:t};break}this.items.push({kind:`pi_bridge`,row:`notice`,prompt:null,bridgePath:e.bridgePath,decision:null,outcome:t});break}case`runtime_install_progress`:{if(this.lastConsentIndex===null)break;let t=this.items[this.lastConsentIndex];if(t===void 0||t.kind!==`runtime_consent`)break;this.items[this.lastConsentIndex]={...t,progress:{receivedBytes:e.receivedBytes??0,totalBytes:e.totalBytes??null}};break}case`terminal_created`:this.terminals[e.terminalId]={terminalId:e.terminalId,command:e.command,args:e.args,output:``,truncated:!1,exit:null};break;case`terminal_output`:{let t=this.terminals[e.terminalId];if(t===void 0)break;let n=t.output+e.chunk,r=t.truncated;n.length>S&&(n=n.slice(-S),r=!0),this.terminals[e.terminalId]={...t,output:n,truncated:r};break}case`terminal_exit`:{let t=this.terminals[e.terminalId];if(t===void 0)break;this.terminals[e.terminalId]={...t,exit:{exitCode:e.exitCode,signal:e.signal}};break}case`session_update`:this.applyUpdate(e.update,t);break;default:break}}mergePermissionInto(e){let t=this.permissionByToolCall.get(e);if(t===void 0)return;let n=this.items[t];if(n===void 0||n.kind!==`permission`||n.mergedIntoToolCall)return;let r={...n,mergedIntoToolCall:!0};this.items[t]=r,this.permissionsByToolCall[e]=r}fillPermissionCommand(e,t,n){let r=this.permissionByToolCall.get(e);if(r===void 0)return;let i=this.items[r];if(i?.kind!==`permission`||i.command!==null)return;let a=w(i.toolKind===`other`?t:i.toolKind,n);if(a===null)return;let o={...i,command:a};this.items[r]=o,this.permissionsByToolCall[e]=o}pushMessageChunk(e,t,n){let r=`${e}:${t}`,i=this.messageIndex.get(r);if(i!==void 0&&i===this.items.length-1){let e=this.items[i];this.items[i]={...e,text:e.text+n};return}this.messageIndex.set(r,this.items.length),this.items.push({kind:`message`,role:e,text:n,messageId:t})}applyUpdate(e,t){switch(e.sessionUpdate){case`agent_message_chunk`:{let n=C(e.content);if(n===null)break;if(x(e,this.agent)){this.items.push({kind:`agent_notice`,source:`codex_legacy`,severity:`warning`,text:n,seq:t});break}this.pushMessageChunk(`agent`,O(e),n);break}case`agent_thought_chunk`:{let t=C(e.content);t!==null&&this.pushMessageChunk(`thought`,O(e),t);break}case`user_message_chunk`:{let t=C(e.content);t!==null&&this.pushMessageChunk(`user`,O(e),t);break}case`tool_call`:{let t={kind:`tool_call`,toolCallId:e.toolCallId,title:e.title??i._({id:`EvIJVD`}),toolKind:e.kind??`other`,status:e.status??`pending`,diffs:[],terminalIds:[],content:[],locations:k(e.locations),rawInput:e.rawInput};M(t,e.content),this.toolCallIndex.set(e.toolCallId,this.items.length),this.items.push(t),this.mergePermissionInto(e.toolCallId),this.fillPermissionCommand(e.toolCallId,t.toolKind,t.rawInput);break}case`tool_call_update`:{let t=this.toolCallIndex.get(e.toolCallId);if(t===void 0)break;let n=this.items[t];if(n.kind!==`tool_call`)break;let r={...n,diffs:[...n.diffs],terminalIds:[...n.terminalIds],content:[...n.content]};e.status&&(r.status=e.status),e.title&&(r.title=e.title),e.locations&&(r.locations=k(e.locations));let i=e.rawInput;i!==void 0&&(r.rawInput=i,this.fillPermissionCommand(e.toolCallId,r.toolKind,i)),M(r,e.content),this.items[t]=r;break}case`plan`:{let t=e.entries;Array.isArray(t)&&(this.plan=t.map(e=>e).filter(e=>typeof e.content==`string`).map(e=>({content:e.content,priority:typeof e.priority==`string`?e.priority:void 0,status:typeof e.status==`string`?e.status:void 0})));break}case`usage_update`:{let t=e;this.tokenUsage={used:typeof t.used==`number`?t.used:void 0,size:typeof t.size==`number`?t.size:void 0};break}default:{let t=e.usage;t!==void 0&&(this.tokenUsage={used:t.used,size:t.size});break}}}};function te(e){return e.items.some(e=>e.kind===`message`&&e.role===`user`)}function D(e){let t=e.resolved;if(t===null)return null;if(t.optionId===null)return t.auto?{kind:`dismissed`}:{kind:`denied`,auto:!1,optionName:null};let n=e.options.find(e=>e.optionId===t.optionId);if(n===void 0)return{kind:`dismissed`};let r=n.kind.startsWith(`reject`),i=n.kind.startsWith(`allow`);return!r&&!i?{kind:`dismissed`}:{kind:r?`denied`:`approved`,auto:t.auto,optionName:n.name}}function O(e){let t=e.messageId;return typeof t==`string`?t:`default`}function k(e){return Array.isArray(e)?e.map(e=>e).filter(e=>typeof e.path==`string`).map(e=>({path:e.path,line:typeof e.line==`number`?e.line:void 0})):[]}function A(e,t){return!(e.tone!==t.tone||e.text!==t.text||e.failure===null!=(t.failure===null)||e.failure!==null&&t.failure!==null&&(e.failure.reason!==t.failure.reason||(e.failure.agentMessage??``)!==(t.failure.agentMessage??``)||(e.failure.machineDetail??``)!==(t.failure.machineDetail??``)||!j(e.failure.exit,t.failure.exit)))}function j(e,t){return e===void 0||t===void 0?e===t:e.cause===t.cause&&e.exitCode===t.exitCode&&e.signal===t.signal}function M(e,t){if(Array.isArray(t))for(let n of t){let t=n;if(t.type===`diff`&&typeof t.path==`string`&&typeof t.newText==`string`)e.diffs.push({path:t.path,oldText:typeof t.oldText==`string`?t.oldText:null,newText:t.newText});else if(t.type===`terminal`&&typeof t.terminalId==`string`)e.terminalIds.includes(t.terminalId)||e.terminalIds.push(t.terminalId);else if(t.type===`content`){let n=C(t.content);n!==null&&e.content.push(n)}else{let n=C(t);n!==null&&e.content.push(n)}}}function N(e){if(typeof e!=`object`||!e)return`info`;let t=e;if(typeof t.threadId!=`string`||t.threadId.length===0)return`threadId`;let n=t.agent;return typeof n!=`object`||!n?`agent`:typeof n.id==`string`?typeof n.name==`string`?n.source!==`custom`&&n.source!==`registry`?`agent.source`:typeof t.title==`string`?typeof t.status==`string`?typeof t.createdAt==`number`?typeof t.lastActivityAt==`number`?typeof t.lastSeq==`number`?null:`lastSeq`:`lastActivityAt`:`createdAt`:`status`:`title`:`agent.name`:`agent.id`}function P(e){return typeof e!=`object`||!e||!(`threadId`in e)?null:typeof e.threadId==`string`?e.threadId:null}var F=Object.freeze({kind:`agent_stderr`,line:`[missing log entry]`,ts:0}),I=500,L=15e3,R=3e4,z=a,B=a,V=33e4,H=8e3,U=1e4,W=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadContextWindowError`,this.code=e}},G=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadResumeError`,this.code=e}},K=class extends Error{code;constructor(e,t){super(t),this.name=`ThreadAuthenticateError`,this.code=e}},q=class extends Error{constructor(){super(`agent-thread channel is not connected`),this.name=`ThreadChannelUnavailableError`}},J=class{url=null;ws=null;reconnectDelay=I;reconnectTimer=null;threads=new Map;listeners=new Set;pendingCreates=new Map;pendingResumes=new Map;pendingRetries=new Map;pendingTerminalAuthLaunches=new Map;pendingContextWindows=new Map;pendingAuths=new Map;pendingQueueEdits=new Map;openedArchived=new Set;lastViewedByThread=new Map;resumingThreads=new Set;reqCounter=0;connectionGeneration=0;status=`idle`;version=0;initialRosterIds=null;markThreadViewed=e=>{let t=this.threads.get(e);if(t===void 0||t.info.status!==`ready`)return;let n=t.info.lastActivityAt;this.lastViewedByThread.get(e)!==n&&(this.lastViewedByThread.set(e,n),this.bump())};getThreadUnread=e=>{let t=this.threads.get(e);if(t===void 0||t.info.status!==`ready`)return!1;let n=this.lastViewedByThread.get(e);return n===void 0?!1:t.info.lastActivityAt>n};setUrl(e){e!==this.url&&(this.teardownSocket(),this.url=e,this.initialRosterIds=null,this.threads.clear(),this.modelBuilders.clear(),this.openedArchived.clear(),this.bump(),e===null?this.setStatus(`idle`):this.connect())}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));threadsSnapshot=[];threadsSnapshotVersion=-1;getThreads=()=>(this.threadsSnapshotVersion!==this.version&&(this.threadsSnapshot=[...this.threads.values()].map(e=>e.info).sort((e,t)=>e.createdAt-t.createdAt),this.threadsSnapshotVersion=this.version),this.threadsSnapshot);openTabsSnapshot=[];openTabsSnapshotVersion=-1;getOpenTabs=()=>(this.openTabsSnapshotVersion!==this.version&&(this.openTabsSnapshot=[...this.threads.values()].map(e=>e.info).filter(e=>e.archived!==!0||this.openedArchived.has(e.threadId)).sort((e,t)=>e.createdAt-t.createdAt),this.openTabsSnapshotVersion=this.version),this.openTabsSnapshot);getThread=e=>this.threads.get(e)??null;getInitialRosterThreadIds=()=>this.initialRosterIds;modelBuilders=new Map;getThreadModel=e=>{let t=this.threads.get(e);if(t===void 0)return null;let n=this.modelBuilders.get(e);return n===void 0&&(n=new E(t.info.agent),this.modelBuilders.set(e,n)),n.sync(t.events)};getConnectionStatus=()=>this.status;getConnectionGeneration=()=>this.connectionGeneration;getThreadScope=()=>this.url;async createThread(e,t){this.connectNow(),await this.waitForOpen(H),this.reqCounter+=1;let n=`create-${this.reqCounter}`,r=new Promise((e,r)=>{let i=setTimeout(()=>{this.pendingCreates.delete(n),r(Error(`thread creation timed out`))},R);this.pendingCreates.set(n,{resolve:e,reject:r,timer:i,onCreated:t})}),i=u(e.agent),a=m(i),o=g(i),s=ee(i),c=a!==void 0||o!==void 0||s!==void 0?{...a===void 0?{}:{config:a},...o===void 0?{}:{modeId:o},...s===void 0?{}:{contextWindow:s}}:void 0;return this.send({op:`create`,reqId:n,...e,...c===void 0?{}:{settings:c}}),r}prompt(e,t,n){let r=t.trim(),i=n!==void 0&&n.length>0;r===``&&!i||(this.reqCounter+=1,this.send({op:`prompt`,threadId:e,reqId:`prompt-${this.reqCounter}`,content:r,...i?{attachments:n}:{}}))}steer(e,t,n){let r=t.trim(),i=n!==void 0&&n.length>0;r===``&&!i||(this.reqCounter+=1,this.send({op:`steer`,threadId:e,reqId:`steer-${this.reqCounter}`,content:r,...i?{attachments:n}:{}}))}editQueued(e,t,n){let r=n.trim();if(r===``)return Promise.resolve();this.reqCounter+=1;let i=`queue-edit-${this.reqCounter}`,a=new Promise((e,t)=>{let n=setTimeout(()=>{this.pendingQueueEdits.delete(i),e()},U);this.pendingQueueEdits.set(i,{resolve:e,reject:t,timer:n})});return this.send({op:`queue_edit`,threadId:e,id:t,content:r,reqId:i}),a}holdQueued(e,t,n){this.send({op:`queue_hold`,threadId:e,id:t,held:n})}removeQueued(e,t){this.send({op:`queue_remove`,threadId:e,id:t})}sendQueuedNow(e,t){this.send({op:`queue_send_now`,threadId:e,id:t})}setChatGrant(e,t,n){this.send({op:`set_chat_grant`,threadId:e,grant:t,enabled:n})}respondPermission(e,t,n){this.send({op:`permission_response`,threadId:e,requestId:t,outcome:n})}respondRuntimeConsent(e,t,n){this.send({op:`runtime_consent_response`,threadId:e,requestId:t,outcome:n})}respondPiBridgeConsent(e,t,n){this.send({op:`pi_bridge_consent_response`,threadId:e,requestId:t,outcome:n})}cancel(e){this.send({op:`cancel`,threadId:e})}setMode(e,t){this.send({op:`set_mode`,threadId:e,modeId:t})}renameThread(e,t){let n=t.trim();n!==``&&this.send({op:`rename`,threadId:e,title:n})}setConfigOption(e,t,n){this.send({op:`set_config_option`,threadId:e,configId:t,value:n})}async setContextWindow(e,t){this.connectNow(),await this.waitForOpen(H),this.reqCounter+=1;let n=`context-window-${this.reqCounter}`,r=new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingContextWindows.delete(n),t(new W(`timeout`,`the context window change timed out`))},B);this.pendingContextWindows.set(n,{resolve:e,reject:t,timer:r})});return this.send({op:`set_context_window`,threadId:e,reqId:n,tokens:t}),r}closeThread(e){let t=this.threads.get(e);if(t?.info.archived===!0){this.send({op:`unsubscribe`,threadId:e}),this.openedArchived.delete(e),this.modelBuilders.delete(e),this.threads.set(e,{info:t.info,events:[],lastSeq:-1,replayThroughSeq:1/0}),this.bump();return}this.send({op:`close`,threadId:e}),this.openedArchived.delete(e),this.modelBuilders.delete(e),this.threads.delete(e)&&this.bump()}openArchivedThread(e){let t=this.threads.get(e);t===void 0||t.info.archived!==!0||this.openedArchived.has(e)||(this.openedArchived.add(e),this.send({op:`subscribe`,threadId:e,sinceSeq:t.lastSeq+1}),this.bump())}deleteThread(e){this.send({op:`delete`,threadId:e}),this.openedArchived.delete(e),this.resumingThreads.delete(e),this.modelBuilders.delete(e),this.lastViewedByThread.delete(e),this.threads.delete(e)&&this.bump()}async resumeThread(e,t,n){this.connectNow(),await this.waitForOpen(H),this.reqCounter+=1;let r=`resume-${this.reqCounter}`,i=new Promise((e,t)=>{let n=setTimeout(()=>{this.pendingResumes.delete(r),t(new G(`timeout`,`resume timed out`))},z);this.pendingResumes.set(r,{resolve:e,reject:t,timer:n})});return this.resumingThreads.add(e),this.send({op:`resume`,threadId:e,reqId:r,prompt:t,...n!==void 0&&n.length>0?{attachments:n}:{}}),i}async retryThread(e){this.connectNow(),await this.waitForOpen(H),this.reqCounter+=1;let t=`retry-${this.reqCounter}`,n=new Promise((e,n)=>{let r=setTimeout(()=>{this.pendingRetries.delete(t),n(Error(`retry timed out`))},B);this.pendingRetries.set(t,{resolve:e,reject:n,timer:r})});return this.send({op:`retry`,threadId:e,reqId:t}),n}async terminalAuthLaunch(e,t){this.connectNow(),await this.waitForOpen(H),this.reqCounter+=1;let n=`terminal-auth-${this.reqCounter}`,r=new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingTerminalAuthLaunches.delete(n),t(Error(`the sign-in terminal request timed out`))},B);this.pendingTerminalAuthLaunches.set(n,{resolve:e,reject:t,timer:r})});return this.send({op:`terminal_auth_launch`,threadId:e,reqId:n,methodId:t}),r}async authenticateThread(e,t){this.connectNow(),await this.waitForOpen(H),this.reqCounter+=1;let n=`authenticate-${this.reqCounter}`,r=new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingAuths.delete(n),t(new K(`timeout`,`sign-in timed out`))},V);this.pendingAuths.set(n,{resolve:e,reject:t,timer:r})});return this.send({op:`authenticate`,threadId:e,reqId:n,methodId:t}),r}connectNow(){this.url===null||this.ws!==null||(this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectDelay=I,this.connect())}waitForOpen(e){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN?Promise.resolve():new Promise((t,n)=>{let r=e=>{clearTimeout(a),i(),e?t():n(new q)},i=this.subscribe(()=>{this.ws!==null&&this.ws.readyState===WebSocket.OPEN&&r(!0)}),a=setTimeout(()=>r(!1),e)})}connect(){if(this.url===null)return;this.setStatus(`connecting`);let e;try{e=new WebSocket(this.url)}catch{this.scheduleReconnect();return}this.connectionGeneration+=1,this.ws=e,e.onopen=()=>{if(this.ws===e){this.reconnectDelay=I,this.setStatus(`open`),this.send({op:`list`});for(let[e,t]of this.threads)t.info.archived===!0&&!this.openedArchived.has(e)||this.send({op:`subscribe`,threadId:e,sinceSeq:t.lastSeq+1})}},e.onmessage=t=>{this.ws===e&&typeof t.data==`string`&&this.receiveServerFrame(t.data)},e.onclose=()=>{this.ws===e&&(this.ws=null,this.setStatus(`closed`),this.scheduleReconnect())},e.onerror=()=>{}}teardownSocket(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);for(let e of this.pendingCreates.values())clearTimeout(e.timer),e.reject(new q);this.pendingCreates.clear();for(let e of this.pendingResumes.values())clearTimeout(e.timer),e.reject(new q);this.pendingResumes.clear(),this.resumingThreads.clear();for(let e of this.pendingRetries.values())clearTimeout(e.timer),e.reject(new q);this.pendingRetries.clear();for(let e of this.pendingTerminalAuthLaunches.values())clearTimeout(e.timer),e.reject(new q);this.pendingTerminalAuthLaunches.clear();for(let e of this.pendingContextWindows.values())clearTimeout(e.timer),e.reject(new q);this.pendingContextWindows.clear();for(let e of this.pendingAuths.values())clearTimeout(e.timer),e.reject(new q);this.pendingAuths.clear();for(let e of this.pendingQueueEdits.values())clearTimeout(e.timer),e.resolve();this.pendingQueueEdits.clear();let e=this.ws;if(this.ws=null,e!==null)try{e.close()}catch{}}scheduleReconnect(){if(this.url===null||this.reconnectTimer!==null)return;let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*2,L),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}send(e){let t=this.ws;if(!(t===null||t.readyState!==WebSocket.OPEN))try{t.send(JSON.stringify(e))}catch{}}receiveServerFrame(e){let t;try{t=JSON.parse(e)}catch{return}this.handleFrame(t)}handleFrame(e){switch(e.op){case`created`:{let t=this.pendingCreates.get(e.reqId),n=N(e.info);if(n!==null){console.warn(`[agent-threads] invalid created thread info`,{field:n,threadId:P(e.info),reqId:e.reqId}),t!==void 0&&(this.pendingCreates.delete(e.reqId),clearTimeout(t.timer),t.reject(Error(`invalid created thread info: ${n}`)));return}if(t!==void 0){this.pendingCreates.delete(e.reqId),clearTimeout(t.timer);try{t.onCreated?.(e.info)}catch(t){console.error(`[agent-threads] created-thread callback failed for`,e.info.threadId,t)}t.resolve(e.info)}this.upsertInfo(e.info);return}case`threads`:{this.initialRosterIds===null&&(this.initialRosterIds=new Set(e.threads.filter(e=>e.archived!==!0).map(e=>e.threadId)),this.bump());let t=new Set;for(let n of e.threads){t.add(n.threadId);let e=this.threads.has(n.threadId);this.upsertInfo(n),!e&&n.archived!==!0&&this.send({op:`subscribe`,threadId:n.threadId,sinceSeq:0})}let n=!1;for(let e of Array.from(this.threads.keys()))t.has(e)||(this.threads.delete(e),this.modelBuilders.delete(e),this.openedArchived.delete(e),this.resumingThreads.delete(e),this.lastViewedByThread.delete(e),n=!0);n&&this.bump();return}case`resumed`:{this.resumingThreads.delete(e.info.threadId);let t=this.pendingResumes.get(e.reqId);t!==void 0&&(this.pendingResumes.delete(e.reqId),clearTimeout(t.timer),t.resolve(e.info)),this.upsertInfo(e.info);return}case`retried`:{let t=this.pendingRetries.get(e.reqId);t!==void 0&&(this.pendingRetries.delete(e.reqId),clearTimeout(t.timer),t.resolve(e.info)),this.upsertInfo(e.info);return}case`terminal_auth_launch_ready`:{let t=this.pendingTerminalAuthLaunches.get(e.reqId);t!==void 0&&(this.pendingTerminalAuthLaunches.delete(e.reqId),clearTimeout(t.timer),t.resolve(e.launch));return}case`context_window_set`:{let t=this.pendingContextWindows.get(e.reqId);t!==void 0&&(this.pendingContextWindows.delete(e.reqId),clearTimeout(t.timer),t.resolve(e.info)),this.upsertInfo(e.info);return}case`authenticated`:{let t=this.pendingAuths.get(e.reqId);t!==void 0&&(this.pendingAuths.delete(e.reqId),clearTimeout(t.timer),t.resolve(e.info)),this.upsertInfo(e.info);return}case`subscribed`:{this.upsertInfo(e.info);let t=this.threads.get(e.threadId);t!==void 0&&(this.threads.set(e.threadId,{...t,replayThroughSeq:e.info.lastSeq}),this.bump());return}case`queue_edited`:{let t=this.pendingQueueEdits.get(e.reqId);t!==void 0&&(this.pendingQueueEdits.delete(e.reqId),clearTimeout(t.timer),t.resolve());return}case`info`:this.upsertInfo(e.info);return;case`event`:this.appendEvents(e.threadId,e.seq,[e.event]);return;case`events`:this.appendEvents(e.threadId,e.fromSeq,e.events);return;case`error`:if(e.reqId!==void 0){e.reqId.startsWith(`resume-`)&&e.threadId!==void 0&&this.resumingThreads.delete(e.threadId);let t=this.pendingCreates.get(e.reqId);if(t!==void 0){this.pendingCreates.delete(e.reqId),clearTimeout(t.timer),t.reject(Error(e.message));return}let n=this.pendingResumes.get(e.reqId);if(n!==void 0){this.pendingResumes.delete(e.reqId),clearTimeout(n.timer),n.reject(new G(e.code,e.message));return}let a=this.pendingRetries.get(e.reqId);if(a!==void 0){this.pendingRetries.delete(e.reqId),clearTimeout(a.timer),a.reject(Error(e.message));return}let o=this.pendingTerminalAuthLaunches.get(e.reqId);if(o!==void 0){this.pendingTerminalAuthLaunches.delete(e.reqId),clearTimeout(o.timer),o.reject(Error(e.message));return}let s=this.pendingContextWindows.get(e.reqId);if(s!==void 0){this.pendingContextWindows.delete(e.reqId),clearTimeout(s.timer),s.reject(new W(e.code,e.message));return}let c=this.pendingAuths.get(e.reqId);if(c!==void 0){this.pendingAuths.delete(e.reqId),clearTimeout(c.timer),c.reject(new K(e.code,e.message));return}let l=this.pendingQueueEdits.get(e.reqId);if(l!==void 0){this.pendingQueueEdits.delete(e.reqId),clearTimeout(l.timer),l.reject(Error(e.message));return}if(e.reqId.startsWith(`prompt-`)||e.reqId.startsWith(`steer-`)){r.error(i._({id:`XNBGZw`,values:{0:e.message}}));return}}console.warn(`[agent-threads] server error frame:`,e.code,e.message);return;default:return}}appendEvents(e,t,n){let r=this.threads.get(e);if(r===void 0||n.length===0)return;let i=Math.max(r.lastSeq+1-t,0);if(i>=n.length)return;let a=i===0?n:n.slice(i),o=Math.max(t-(r.lastSeq+1),0);o>0&&console.warn(`[agent-threads] replay opened above the transcript tail`,{threadId:e,fromSeq:t,have:r.lastSeq});let s=r.info;for(let e of a)s=Y(s,e);this.threads.set(e,{info:s,events:[...r.events,...o>0?Array(o).fill(F):[],...a],lastSeq:t+n.length-1,replayThroughSeq:r.replayThroughSeq}),this.bump()}upsertInfo(e){let t=this.threads.get(e.threadId);t===void 0?(this.threads.set(e.threadId,{info:e,events:[],lastSeq:-1,replayThroughSeq:1/0}),this.lastViewedByThread.has(e.threadId)||this.lastViewedByThread.set(e.threadId,e.lastActivityAt)):e.archived===!0&&t.info.archived!==!0&&!this.resumingThreads.has(e.threadId)?(this.openedArchived.delete(e.threadId),this.modelBuilders.delete(e.threadId),this.threads.set(e.threadId,{info:e,events:[],lastSeq:-1,replayThroughSeq:1/0})):this.threads.set(e.threadId,{...t,info:e}),this.bump()}setStatus(e){this.status!==e&&(this.status=e,this.bump())}bump(){this.version+=1;for(let e of this.listeners)e()}};function Y(e,t){switch(t.kind){case`status`:return{...e,status:t.status,lastActivityAt:t.ts};case`title_changed`:return{...e,title:t.title};default:return{...e,lastActivityAt:t.ts}}}var X=new J;function Z(){return X}function Q(){return(0,s.useSyncExternalStore)(X.subscribe,X.getThreads,X.getThreads)}function ne(){return(0,s.useSyncExternalStore)(X.subscribe,X.getOpenTabs,X.getOpenTabs)}function re(){return(0,s.useSyncExternalStore)(X.subscribe,X.getInitialRosterThreadIds,X.getInitialRosterThreadIds)}function ie(e){let t=(0,c.c)(2),n;t[0]===e?n=t[1]:(n=()=>X.getThread(e),t[0]=e,t[1]=n);let r=n;return(0,s.useSyncExternalStore)(X.subscribe,r,r)}function $(e){let t=(0,c.c)(2),n;t[0]===e?n=t[1]:(n=()=>X.getThreadModel(e),t[0]=e,t[1]=n);let r=n;return(0,s.useSyncExternalStore)(X.subscribe,r,r)}function ae(e){let t=(0,c.c)(2),n;t[0]===e?n=t[1]:(n=()=>X.getThreadUnread(e),t[0]=e,t[1]=n);let r=n;return(0,s.useSyncExternalStore)(X.subscribe,r,r)}function oe(){return(0,s.useSyncExternalStore)(X.subscribe,X.getConnectionStatus,X.getConnectionStatus)}function se(){return(0,s.useSyncExternalStore)(X.subscribe,X.getThreadScope,X.getThreadScope)}function ce(e){if(e===null)return null;try{let t=new URL(e);return t.pathname=`/collab/thread`,t.search=``,t.toString()}catch{return null}}export{p as _,ce as a,$ as c,Q as d,re as f,u as g,te as h,Z as i,se as l,D as m,W as n,ie as o,ne as p,G as r,oe as s,q as t,ae as u,_ as v,h as y};
|
package/dist/src-C97lXQfs.mjs
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-tZXQYakl.mjs";import{$c as t,$u as n,Bf as r,Bl as i,Ca as a,Ef as o,Ff as s,G as c,If as l,Mf as u,Sa as d,Tf as ee,U as f,Vl as p,W as m,Yc as h,bf as g,el as te,jf as _,kf as v,l as y,u as ne}from"./md-manager-BGnqyqi1-I7NmBKjQ.mjs";import{Ao as b,At as x,Ea as S,Qn as C,Ri as w,Si as T,Tr as E,Ts as D,as as O,bi as k,cr as re,fr as A,is as j,m as ie,mi as ae,ns as M,os as N,si as P,xi as oe,zi as se}from"./dist-Ds1SZERP.mjs";import{t as ce}from"./yazl-BBz29IQN.mjs";import{ct as le,st as ue,wt as F}from"./init-BVMADGS2.mjs";import{l as de,w as fe}from"./registry-probes-Bx4JMRjq.mjs";import{c as pe}from"./colors-r_owlCuY.mjs";import{t as me}from"./is-object-BGze3w87.mjs";import{n as he}from"./constants-Byeyagc8.mjs";import"./loader-BMNiWrib.mjs";import"./preview-DXhCGcEu.mjs";import{execFile as ge,execSync as _e,spawnSync as ve}from"node:child_process";import{basename as I,dirname as L,isAbsolute as ye,join as R,relative as be,resolve as z,sep as B,win32 as xe}from"node:path";import{closeSync as Se,cpSync as Ce,createWriteStream as we,existsSync as V,lstatSync as Te,mkdirSync as H,mkdtempSync as Ee,openSync as De,readFileSync as U,readSync as Oe,readdirSync as W,readlinkSync as ke,realpathSync as Ae,rmSync as G,rmdirSync as je,statSync as Me,writeFileSync as K}from"node:fs";import{arch as Ne,freemem as Pe,homedir as q,hostname as Fe,platform as Ie,release as Le,tmpdir as Re,totalmem as ze,type as Be,uptime as Ve}from"node:os";import{readFile as He,readdir as Ue,stat as We}from"node:fs/promises";import{createHash as Ge}from"node:crypto";function Ke(e,t){let n=t.map(e=>[D(e),e]);for(let t of e){let e=D(t);if(e===null)continue;let r=n.find(([t])=>t===e);if(r!==void 0)return r[1]}}function qe(e){let{override:t,storedPreference:n,preferenceList:r,supportedLocales:i}=e,a=e.autoDetectableLocales??i;if(t!==void 0){let e=Ke([t],i);if(e!==void 0)return{locale:e,source:`override`}}if(n!==void 0&&n!==`system`&&i.includes(n))return{locale:n,source:`explicit`};let o=Ke(r,a);return o===void 0?{locale:`en`,source:`fallback`}:{locale:o,source:`system`}}function Je(e,t=Date.now()){let n=Date.parse(e);if(!Number.isFinite(n))return`unknown`;let r=Math.floor(Math.max(0,t-n)/1e3);if(r<60)return`${r}s ago`;let i=Math.floor(r/60);if(i<60)return`${i}m ago`;let a=Math.floor(i/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}const Ye=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`lint`,`audit`,`deinit`,`auth`]);function Xe(e,t,n=A){if(e!==void 0&&!Ye.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let Ze=null;function Qe(e){Ze=e}function $e(){return Ze??process.cwd()}const et=`Open Knowledge`;function tt(e={}){let t=e.platformName??process.platform,n=e.productName??u().productName;return ue(t).join(le({...e,platformName:t}),n)}function nt(e={}){let t=e.platformName??process.platform,n=e.home??q(),r=e.env??process.env,i=ue(t),a;return a=t===`win32`?r.LOCALAPPDATA||i.join(n,`AppData`,`Local`):t===`darwin`?i.join(n,`Library`,`Caches`):r.XDG_CACHE_HOME||i.join(n,`.cache`),i.join(a,`${u().packageName.replaceAll(`/`,``)}-updater`)}function rt(e){if(typeof e!=`object`||!e)return null;let t=e.recentProjects;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;typeof t.path==`string`&&typeof t.name==`string`&&n.push({path:t.path,name:t.name})}return n}function it(e){let t=R(e,`state.json`);if(!V(t))return[];let n;try{n=JSON.parse(U(t,`utf-8`))}catch{return[]}return rt(n)??[]}function at(e){let t=R(e,`state.json`);if(!V(t))return!1;try{return rt(JSON.parse(U(t,`utf-8`)))!==null}catch{return!1}}const ot=8192;function st(e,t){if(e.outcome===`not-present`)return`not-present (no DiagnosticReports directory)`;if(e.outcome===`unreadable-directory`)return`unreadable (${e.directoryErrorCode??`unknown`} reading DiagnosticReports)`;let n=[`${e.windowDays}d`,`${e.foreignIgnored} other-process report(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&n.push(`${e.droppedOverCap} older dropped over cap`);let r=e.files.length-t;return r>0&&n.push(`${r} vanished before staging`),e.outcome===`none-in-window`?`none found in window (${n.join(`; `)})`:`${t} collected (${n.join(`; `)})`}function ct(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const lt=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function ut(e){return e.replace(lt,`$1"[REDACTED-DEVICE-ID]"`)}function dt(e){return ut(ct(e))}const ft=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function pt(e){if(typeof e!=`string`)return null;let t=ft.exec(e.trim());if(t===null)return null;let[,n,r,i=``,a,o]=t,s=Date.parse(`${n}T${r}${i}${a}:${o}`);return Number.isNaN(s)?null:s}function mt(e){let t=De(e,`r`);try{let e=Buffer.alloc(ot),n=0,r=!1;for(;n<ot;){let i=Oe(t,e,n,ot-n,n);if(i===0){r=!0;break}let a=n;n+=i;let o=e.subarray(0,n).indexOf(10,a);if(o!==-1)return e.subarray(0,o).toString(`utf-8`)}return r?e.subarray(0,n).toString(`utf-8`):null}finally{Se(t)}}function ht(e){try{let t=mt(e);if(t===null)return{kind:`unreadable`};let n=JSON.parse(t);if(typeof n!=`object`||!n)return{kind:`unreadable`};let{name:r,app_name:i,timestamp:a}=n,o=typeof r==`string`?r:typeof i==`string`?i:null;return o===null?{kind:`unreadable`}:{kind:`named`,name:o,timestampMs:pt(a)}}catch{return{kind:`unreadable`}}}function gt(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function _t(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=W(e,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`?{...n,outcome:`not-present`}:{...n,outcome:`unreadable-directory`,directoryErrorCode:t??`unknown`}}let i=t.getTime()-6048e5,a=[],o=0,s=0;for(let t of r){if(!t.isFile()||!t.name.endsWith(`.ips`))continue;let n=R(e,t.name),r;try{r=Me(n).mtimeMs}catch{continue}if(r<i)continue;let c=ht(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!gt(c.name)){o+=1;continue}a.push({path:n,atMs:l})}a.sort((e,t)=>t.atMs-e.atMs);let c=a.slice(0,25),l={foreignIgnored:o,unparseable:s,droppedOverCap:a.length-c.length,windowDays:7};return c.length===0?{...l,files:[],outcome:`none-in-window`}:{...l,files:c.map(e=>e.path),outcome:`collected`}}const vt=`state/os-termination-evidence.json`,yt=6048e5,bt=/openknowledge/i,xt=v.map(e=>l(o[e]));function St(e={}){return(t,n)=>new Promise(r=>{try{ge(t,n,{encoding:`utf8`,timeout:e.timeoutMs??15e3,maxBuffer:e.maxBuffer??16777216,windowsHide:!0},(e,t,n)=>{r({...Ct(e),stdout:t,stderr:n})})}catch(e){let t=e.code;r({status:null,stdout:``,stderr:``,errorCode:typeof t==`string`?t:`spawn-failed`})}})}function Ct(e){return e===null?{status:0}:typeof e.code==`string`?{status:null,errorCode:e.code}:typeof e.code==`number`?{status:e.code}:e.killed===!0?{status:null,errorCode:`ETIMEDOUT`}:e.signal?{status:null,signal:e.signal}:{status:null}}function wt(e){if(e.errorCode!==void 0)return e.errorCode;if(e.signal!==void 0)return`signal ${e.signal}`;let t=(e.stderr.trim().split(`
|
|
2
|
-
`)[0]??``).replace(/\S*\/journal\/\S*/g,`<journal path>`).replace(/\b[0-9a-f]{32}\b/gi,`<id>`);return`exit ${e.status}${t===``?``:`: ${t}`}`}function J(e,t,n){return{schemaVersion:1,platform:e,source:t,outcome:`none-in-window`,readFrom:n,windowDays:7,foreignIgnored:0,unparseable:0,droppedOverCap:0,events:[]}}function Tt(e,t){return{...e,outcome:`unavailable`,unavailableReason:t}}function Et(e){return{...e,outcome:e.events.length>0?`collected`:`none-in-window`}}function Y(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Dt(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Ot(e,t){let n=t.indexOf(`
|
|
3
|
-
`);if(n===-1)return null;let r,i;try{r=Dt(JSON.parse(t.slice(0,n))),i=Dt(JSON.parse(t.slice(n+1)))}catch{return null}if(r===null||i===null||!Array.isArray(i.processes))return null;let a=[];for(let e of i.processes){let t=Dt(e);t===null||typeof t.name!=`string`||!gt(t.name)||a.push({name:t.name,pid:Y(t.pid),killReason:typeof t.reason==`string`?t.reason:null,residentPages:Y(t.rpages),lifetimeMaxPages:Y(t.lifetimeMax)})}let o=pt(r.timestamp);return{kind:`jetsam`,at:o===null?null:new Date(o).toISOString(),file:e,pageSize:Y(Dt(i.memoryStatus)?.pageSize),largestProcessOwned:typeof i.largestProcess==`string`?gt(i.largestProcess):null,ownedProcesses:a}}const kt=/^JetsamEvent-.*\.ips$/;function At(e,t,n,r){let i=e.flatMap(({file:e,mtimeMs:n})=>n!==null&&n>=t?[{file:e,mtimeMs:n}]:[]);return i.sort((e,t)=>r===`newest-first`?t.mtimeMs-e.mtimeMs:e.mtimeMs-t.mtimeMs),{files:i.slice(0,n).map(({file:e})=>e),statFailed:e.filter(({mtimeMs:e})=>e===null).length,droppedOverCap:Math.max(0,i.length-n)}}async function jt(e,t){let n=J(`darwin`,`macos-jetsam`,[R(e,`JetsamEvent-*.ips`)]),r;try{r=await Ue(e)}catch(e){return Tt(n,e.code??`unknown`)}let i=At(await Promise.all(r.filter(e=>kt.test(e)).map(async t=>{try{return{file:t,mtimeMs:(await We(R(e,t))).mtimeMs}}catch{return{file:t,mtimeMs:null}}})),t.getTime()-yt,50,`newest-first`);n.unparseable+=i.statFailed,n.droppedOverCap=i.droppedOverCap;for(let t of i.files){let r=null;try{r=Ot(t,await He(R(e,t),`utf8`))}catch{}r===null?n.unparseable+=1:r.ownedProcesses.length===0?n.foreignIgnored+=1:n.events.push(r)}return Et(n)}const Mt=[`--no-pager`,`--output=short-iso-precise`,`--since=-7d`,`--grep=Out of memory|oom-kill|Killed process|Killed /|memory pressure`,`_TRANSPORT=kernel`,`+`,`_SYSTEMD_UNIT=systemd-oomd.service`],Nt=[`--user`,`--no-pager`,`--output=short-iso-precise`,`--since=-7d`,`--grep=Fatal Wayland communication error|Wayland protocol error|X IO error|Missing X server`],Pt=/^(\S+) \S+ ([^:\s[]+)(?:\[\d+\])?: (.*)$/,Ft=/\[(\d+)(?::\d+)?:\d{4}\/\d{6}\.\d+:[A-Z0-9]+:[^\]]*\]\s*(.*)$/,It=/^desktop\.\d{4}-\d{2}-\d{2}\.log$/;async function Lt(e,t){let n=new Set,r;try{r=await Ue(e)}catch{return{pids:n,unreadable:!0}}let i=!1;for(let a of r){if(!It.test(a))continue;let r=R(e,a);try{if(t.getTime()-(await We(r)).mtimeMs>yt)continue;for(let e of(await He(r,`utf8`)).split(`
|
|
4
|
-
`)){if(!e.includes(`"event":"desktop.boot"`))continue;let t=/"pid":(\d+)/.exec(e)?.[1];t!==void 0&&n.add(Number(t))}}catch{i=!0}}return{pids:n,unreadable:i}}function Rt(e,t){if(e===`systemd-oomd`){let e=/^Killed (\S+)/.exec(t);if(e===null)return null;let n=e[1]?.split(`/`).pop()??``;return{origin:`systemd-oomd`,action:`oomd-kill`,pid:null,processName:null,unit:bt.test(n)?n:null,trigger:/swap used/.test(t)?`swap`:/memory pressure/.test(t)?`memory-pressure`:null}}if(e!==`kernel`)return null;let n=/Killed process (\d+) \(([^)]+)\)/.exec(t);if(n!==null)return{origin:`kernel`,action:`oom-kill`,pid:Number(n[1]),processName:n[2]??null,unit:null,trigger:null};let r=/task=([^,]+),pid=(\d+)/.exec(t);if(r!==null)return{origin:`kernel`,action:`oom-kill`,pid:Number(r[2]),processName:r[1]??null,unit:null,trigger:null};let i=/^(\S+) invoked oom-killer/.exec(t);return i===null?null:{origin:`kernel`,action:`oom-invoked`,pid:null,processName:i[1]??null,unit:null,trigger:null}}function zt(e){let t=[],n=0,r=0;for(let i of e.split(`
|
|
5
|
-
`)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=Pt.exec(i);if(e===null){r+=1;continue}let[,a=``,o=``,s=``]=e;if(!bt.test(s)){n+=1;continue}let c=Rt(o,s);if(c===null){r+=1;continue}t.push({kind:`journal`,at:a,...c})}return{events:t,foreignIgnored:n,unparseable:r}}function Bt(e){let t=[],n=0,r=0;for(let i of e.split(`
|
|
6
|
-
`)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=Pt.exec(i);if(e===null){r+=1;continue}let[,a=``,,o=``]=e,s=Ft.exec(o);if(s===null){n+=1;continue}t.push({at:a,pid:Number(s[1]),detail:(s[2]??``).slice(0,200)})}return{lines:t,foreignIgnored:n,unparseable:r}}async function Vt(e,t,n){let r=Bt(e);if(r.lines.length===0)return{...r,events:[],unattributed:null};let i=await Lt(t,n),a=[],o=0;for(let e of r.lines){if(!i.pids.has(e.pid)){o+=1;continue}a.push({kind:`journal`,at:e.at,origin:`chromium`,action:`display-connection-lost`,pid:e.pid,processName:null,unit:null,trigger:/Wayland/.test(e.detail)?`wayland`:`x11`,detail:e.detail})}let s=i.pids.size>0&&!i.unreadable;if(o>0&&!s){let e=i.unreadable?`desktop logs unreadable`:`no desktop.boot pid in desktop logs`;return{events:a,foreignIgnored:r.foreignIgnored,unparseable:r.unparseable,unattributed:`${o} Chromium display line(s) not attributed, ${e}`}}return{events:a,foreignIgnored:r.foreignIgnored+o,unparseable:r.unparseable,unattributed:null}}function Ht(e){return e.status===0||e.status===1&&/^-- No entries --$/m.test(e.stdout)}async function Ut(e,t,n){let r=J(`linux`,`linux-journal`,[`journalctl ${Mt.join(` `)}`,`journalctl ${Nt.join(` `)}`]),[i,a]=await Promise.all([e(`journalctl`,[...Mt]),e(`journalctl`,[...Nt])]),o=[];if(Ht(i)){let e=zt(i.stdout);r.droppedOverCap+=Math.max(0,e.events.length-50),r.events.push(...e.events.slice(-50)),r.foreignIgnored+=e.foreignIgnored,r.unparseable+=e.unparseable,/not seeing messages from other users/i.test(`${i.stdout}\n${i.stderr}`)&&(r.restrictedToCurrentUser=!0)}else o.push(`system journal: ${wt(i)}`);if(Ht(a)){let e=await Vt(a.stdout,n,t);r.droppedOverCap+=Math.max(0,e.events.length-50),r.events.push(...e.events.slice(-50)),r.foreignIgnored+=e.foreignIgnored,r.unparseable+=e.unparseable,e.unattributed!==null&&o.push(`user journal: ${e.unattributed}`)}else o.push(`user journal: ${wt(a)}`);return o.length===2?Tt(r,o.join(`; `)):o.length===1?{...r,outcome:`partial`,unavailableReason:o.join(`; `)}:Et(r)}const Wt={41:`Microsoft-Windows-Kernel-Power`,1074:`User32`,2004:`Microsoft-Windows-Resource-Exhaustion-Detector`,6008:`EventLog`},Gt={1e3:`Application Error`,1001:`Windows Error Reporting`,1002:`Application Hang`};function Kt(e){return e===`System`?Wt:Gt}function qt(e){let t=`System[(${Object.keys(Kt(e)).map(e=>`EventID=${e}`).join(` or `)}) and TimeCreated[timediff(@SystemTime) <= ${yt}]]`;return e===`System`?`*[${t}]`:`*[${t} and EventData[${xt.map(e=>`Data='${e}'`).join(` or `)}]]`}function Jt(e){return[`qe`,e,`/q:${qt(e)}`,`/f:xml`,`/rd:true`,`/c:200`]}function Yt(e){return xe.join(e??`C:\\Windows`,`System32`,`wevtutil.exe`)}function Xt(e){return e.replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/&/g,`&`)}function Zt(e){return/[\\/]/.test(e)||/^[a-z]:/i.test(e)}function Qt(e,t){let n=RegExp(`<${t}(?:\\s[^>]*)?>([\\s\\S]*?)</${t}>`,`g`);return[...e.matchAll(n)].map(e=>Xt(e[1]??``).trim())}function $t(e,t){let n=Kt(e),r=[],i=0,a=0;for(let o of t.match(/<Event[\s>][\s\S]*?<\/Event>/g)??[]){let t=/<Provider\s+Name=['"]([^'"]+)['"]/.exec(o)?.[1],s=Number(/<EventID[^>]*>(\d+)<\/EventID>/.exec(o)?.[1]),c=/<TimeCreated\s+SystemTime=['"]([^'"]+)['"]/.exec(o)?.[1];if(t===void 0||!Number.isInteger(s)||c===void 0){a+=1;continue}if(n[s]!==t){i+=1;continue}let l=Qt(o,`Data`),u=Qt(o,`Name`),d=[...l,...u].some(e=>bt.test(e));if(e===`Application`&&!d){i+=1;continue}r.push({kind:`windows-event`,at:c,log:e,provider:t,eventId:s,mentionsOpenKnowledge:d,data:e===`Application`?l.filter(e=>e!==``&&!Zt(e)):[]})}return{events:r,foreignIgnored:i,unparseable:a}}async function en(e,t){let n=Yt(t),r=[`System`,`Application`],i=J(`win32`,`windows-event-log`,r.map(e=>`${n} ${Jt(e).join(` `)}`)),a=await Promise.all(r.map(async t=>({log:t,result:await e(n,Jt(t))}))),o=[];for(let{log:e,result:t}of a){if(t.status!==0){o.push(`${e}: ${wt(t)}`);continue}let n=$t(e,t.stdout);i.droppedOverCap+=Math.max(0,n.events.length-50),i.events.push(...n.events.slice(0,50)),i.foreignIgnored+=n.foreignIgnored,i.unparseable+=n.unparseable}return o.length===r.length?Tt(i,o.join(`; `)):o.length>0?{...i,outcome:`partial`,unavailableReason:o.join(`; `)}:Et(i)}async function tn(e={}){let t=e.platform??process.platform,n=e.runCommand??St(),r=(e.now??(()=>new Date))();switch(t){case`darwin`:return jt(e.macosReportsDir??`/Library/Logs/DiagnosticReports`,r);case`linux`:return Ut(n,r,e.desktopLogsDir??R(M(),`logs`));case`win32`:return en(n,e.systemRoot??process.env.SystemRoot);default:return{...J(t,null,[]),outcome:`unsupported`}}}const nn={schemaVersion:1,outcome:`not-collected`};function rn(e){return`${JSON.stringify(e??nn,null,2)}\n`}const an={"macos-jetsam":`macOS low-memory reports`,"linux-journal":`system and user journals`,"windows-event-log":`Windows event logs`};function on(e){let t=[`${e.windowDays}d`,`${e.events.length} kept`,`${e.foreignIgnored} other-process record(s) ignored`,`${e.unparseable} unparseable`];e.droppedOverCap>0&&t.push(`${e.droppedOverCap} older dropped over cap`);let n=e.source?` from ${an[e.source]}`:``,r=e.unavailableReason?`, ${e.unavailableReason}`:``;return`${e.outcome}${n}${r} (${t.join(`; `)})`}function sn(){return R(M(),`bug-reports`)}function cn(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=sn(),r=`${t}-bugreport`,i=R(n,`${r}.zip`);for(let e=2;V(i);e+=1)i=R(n,`${r}-${e}.zip`);return i}function ln(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function un(e,t){let n=R(e,`.ok`,`config.yml`);if(V(n))try{let e=U(n,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml for project slug; using path-hash fallback`)}return V(R(e,`.ok`))?Ge(`sha256`).update(z(e)).digest(`hex`).slice(0,12):null}function dn(){let e={timestamp:new Date().toISOString(),platform:Ie(),osType:Be(),osRelease:Le(),hostname:`[redacted]`,uptime:Ve(),freeMem:Pe(),totalMem:ze(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=_e(`sw_vers -productVersion 2>/dev/null`,b({encoding:`utf8`})).trim()}catch{}try{let t=R(__dirname,`..`,`..`,`package.json`);V(t)&&(e.okVersion=JSON.parse(U(t,`utf8`)).version)}catch{}return e}const fn=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function pn(e){let t=I(e);return fn.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function mn(e,t){return vn(e,t).files}const hn=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function gn(e,t=de){let n=R(e,`${t}.ShipIt`);if(!V(n))return[];let r;try{r=W(n)}catch{return[]}return hn.flatMap(e=>r.map(t=>{if(t===e)return{entry:t,suffix:-1};if(!t.startsWith(`${e}.`))return null;let n=t.slice(e.length+1);return/^\d+$/.test(n)?{entry:t,suffix:Number(n)}:null}).filter(e=>e!==null).sort((e,t)=>e.suffix-t.suffix).slice(0,4).map(e=>R(n,e.entry)))}function _n(e){if(!V(e))return[];try{let t=new Map;for(let n of W(e).filter(e=>e.endsWith(`.yaml`)).sort()){let e=n.endsWith(`.sent.yaml`)?n.slice(0,-y.length):n.slice(0,-5),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return[...t.values()].slice(-25).flat().map(t=>R(e,t))}catch{return[]}}function vn(e,t){if(!V(t))return{files:[],excludedByProjectSlug:0};let n=W(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>R(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(pn),i=[],a=r.filter(t=>{try{return U(t,`utf8`).includes(`"project":"${e}"`)}catch{return i.push(t),!1}});if(a.length===0)return{files:n,excludedByProjectSlug:0};let o=new Set([...a,...i]);return{files:n.filter(e=>!pn(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function yn(e){let n=R(e,`.ok`,`local`);return V(n)?{files:[`server.lock`,`last-spawn-error.log`,t,h].map(e=>R(n,e)).filter(e=>V(e))}:{files:[]}}function bn(e){let t=R(e,`.ok`,`local`,`logs`);return V(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>R(t,e)).filter(e=>V(e))}:{files:[]}}function xn(e){let t=0,n=new Map,r=e.replace(/("(?:docName|doc\.name|documentName)"\s*:\s*")((?:[^"\\]|\\.)*)"/g,(e,r,i)=>{t+=1;let a=n.get(i);return a===void 0&&(a=`doc#${Ge(`sha256`).update(i).digest(`hex`).slice(0,12)}`,n.set(i,a)),`${r}${a}"`});for(let[e,i]of[...n].sort(([e],[t])=>t.length-e.length)){if(e.length===0||!r.includes(e))continue;let n=r.split(e);t+=n.length-1,r=n.join(i)}return{text:r,count:t}}function Sn(e){let t=e.revealDocNames?e.content:xn(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=a(t);e.zipfile.addBuffer(Buffer.from(n,`utf8`),e.name),e.bundleFiles.push(e.name),r.length>0&&e.redactions.push({file:e.name,lineCount:i,patterns:r})}else e.zipfile.addBuffer(Buffer.from(t,`utf8`),e.name),e.bundleFiles.push(e.name)}function X(e){for(let t of e.files)try{let n=U(t,`utf8`);Sn({zipfile:e.zipfile,name:`${e.prefix}/${I(t)}`,content:t.endsWith(`.ips`)?dt(n):n,redact:e.redact,revealDocNames:e.revealDocNames,bundleFiles:e.bundleFiles,redactions:e.redactions})}catch(n){e.logger?.warn({file:t,prefix:e.prefix,err:n},`bug-report: skipped unreadable file`)}}async function Cn(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??R(M(),`logs`),s=t.projectDir?un(t.projectDir,i):null;H(L(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=dn();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=vn(s,o),{files:ee}=t.projectDir?yn(t.projectDir):{files:[]},{files:f}=t.projectDir?bn(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:ee.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let h=[],g=[],{ZipFile:te}=await import(`./yazl-BsCX6KWo.mjs`).then(t=>e(t.default,1)),_=new te;X({zipfile:_,files:[...l,...p],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:_,files:ee,prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:_,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:_,files:t.bugReportLedgerFiles??[],prefix:ne,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i}),X({zipfile:_,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:g,redactions:h,logger:i});for(let e of t.extraFiles??[])try{let t=U(e.sourcePath),n=`extra/${e.zipName??I(e.sourcePath)}`;_.addBuffer(t,n),g.push(n);let r=ln(e,n);r!==null&&h.push(r)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&Sn({zipfile:_,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:g,redactions:h});let v=new Set(m.map(e=>`diagnostic-reports/${I(e)}`)),y=g.filter(e=>v.has(e)),b=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:st(t.diagnosticReports,y.length);_.addBuffer(Buffer.from(`${b}\n`,`utf8`),`state/diagnostic-reports-status.txt`),g.push(`state/diagnostic-reports-status.txt`),Sn({zipfile:_,name:vt,content:rn(t.osTerminationEvidence),redact:n,revealDocNames:!0,bundleFiles:g,redactions:h});let x=JSON.stringify(c,null,2);_.addBuffer(Buffer.from(x,`utf8`),`sysinfo.json`),g.push(`sysinfo.json`);let S={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:g,redactions:h,sysinfo:c};_.addBuffer(Buffer.from(JSON.stringify(S,null,2),`utf8`),`MANIFEST.json`);let C=h.reduce((e,t)=>e+t.lineCount,0),w=new Set(p.map(e=>`logs/${I(e)}`)),T=g.filter(e=>w.has(e)),E=new Set((t.bugReportLedgerFiles??[]).map(e=>`${ne}/${I(e)}`)),D=g.filter(e=>E.has(e)),O=s?g.filter(e=>e.startsWith(`logs/`)&&!pn(e)&&!w.has(e)):[],k=y.length>0?[`Crash reports under diagnostic-reports/ are rewritten on the way in,`,`independently of this setting: escaped path separators are normalised`,`so the scrub above can read them, and the identifiers that link this`,`machine's bundles to each other are replaced. Nothing else is changed;`,`they are not byte-identical to the files macOS wrote.`]:[],re=k.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...k]:[`Redaction was disabled for this bundle; file contents are unmodified.`],A=[`# Bug Report Bundle`,``,`Generated: ${S.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${S.disciplineVersion}`,``,`## Contents`,``,...g.map(e=>`- ${e}`),``,`## Privacy`,``,...O.length>0?[`Scope: some collected logs are user-wide rather than project-scoped.`,`These are written once per machine per day and can contain activity`,`from other projects open on this machine, including captured console`,`output:`,...O.map(e=>`- ${e}`),``]:[],...T.length>0?[`Installer logs: written by the macOS update helper rather than by`,`OpenKnowledge itself, and machine-wide rather than scoped to any one`,`project. They record the install and update history of this app on`,`this machine. Only this app is collected, never other applications`,`that use the same update mechanism:`,...T.map(e=>`- ${e}`),``]:[],...y.length>0?[`Crash reports: written by macOS itself rather than by OpenKnowledge,`,`and machine-wide rather than scoped to any one project. They record`,`why the operating system ended a process of this app — the signal or`,`exception, the code-signing verdict, and whatever text the process`,`left behind as it died. They also carry machine details the OS puts`,`in every report: the account uid, the Mac model, and the name of the`,`process that launched this app, which on a managed machine can be`,`internal tooling. The identifiers that would link this machine's`,`bundles to each other are replaced before bundling. Only this`,`app's own reports are collected, never another application's, though`,`a report of ours still names the processes it ran alongside:`,...y.map(e=>`- ${e}`),``]:[],...(t.osTerminationEvidence?.events.length??0)>0?[`Termination records: read from the operating system's own logs, covering`,`the last 7 days, to explain an exit the app could not record itself. On`,`macOS: the memory-pressure (jetsam) reports`,`that list processes of this app, with each one's memory use and whether`,`it was killed. On Linux: kernel and systemd-oomd out-of-memory kills of`,`this app, as structured fields with the machine name, cgroup paths and`,`user id left out, plus display-connection errors this app's desktop`,`process wrote to the user's own journal, with Chromium's message cut to`,`200 characters. On Windows: crash and hang records for this app with`,`file paths left out, plus the time of every shutdown, restart, power`,`loss and low-memory warning on the machine, whatever caused it:`,`- ${vt}`,``]:[],...D.length>0?[`Send history: a small record for each bug report previously generated`,`on this machine — when it was generated, whether sending it`,`succeeded, and why it failed if it did. This is what makes a failed`,`send diagnosable at all. It is machine-wide rather than scoped to`,`this project, so it names the other projects reports were filed`,`from. It carries no document content:`,...D.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${d.join(`, `)}`,C>0?`${C} line(s) were scrubbed across ${h.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...k,``,`This bundle is safe to attach to a GitHub issue.`]:re].join(`
|
|
7
|
-
`);_.addBuffer(Buffer.from(A,`utf8`),`README.md`),_.end();let j=we(r);return _.outputStream.pipe(j),await new Promise((e,t)=>{j.on(`close`,e),j.on(`error`,t)}),i?.info({bundlePath:r,fileCount:g.length,redactionCount:C},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:g,redactions:h,redactedLineCount:C,generatedAt:S.generatedAt}}}var wn=n(),Tn=e(ce(),1),Z=e(pe(),1);function En(e){let t=N(`user`,e,e);return j({absPath:t,sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function Dn({home:e=q(),env:t=process.env}={}){let n=En(e),{override:r,preferenceList:a}=O(t),{locale:o,source:s}=qe({override:r,storedPreference:n,supportedLocales:p,preferenceList:a,autoDetectableLocales:i});return{preference:n,locale:o,source:s,systemLanguages:a}}function On(e){let t=new Set([e]);try{t.add(Ae.native(e))}catch{return[e].filter(e=>e.length>0)}return[...t].filter(e=>e.length>0).sort((e,t)=>t.length-e.length)}function kn(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function An(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jn(e,t){if(typeof e==`string`)return kn(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>jn(e,t));if(!An(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=jn(i,t);return n}function Mn(e,t){let n=U(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
|
|
8
|
-
`),i=n.split(`
|
|
9
|
-
`),a=[];for(let e=0;e<i.length;e++){let n=i[e]??``;if(e!==i.length-1||n!==``){if(n.length===0){a.push(``);continue}try{let e=jn(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
|
|
10
|
-
`)}\n`:a.join(`
|
|
11
|
-
`);K(e,o)}function Nn(e,t){let n=U(e,`utf-8`);if(n.trim().length!==0)try{let r=jn(JSON.parse(n),t),i=n.endsWith(`
|
|
12
|
-
`)?`
|
|
13
|
-
`:``;K(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=kn(n,t.contentDirSpellings);r!==n&&K(e,r)}}function Pn(e,t){let n=U(e,`utf-8`),r=kn(n,t.contentDirSpellings);r!==n&&K(e,r)}function Fn(e){try{return W(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>R(e,t.name))}catch{return[]}}const In=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function Ln(e){return/\.log\.\d+$/.test(e)}function Rn(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||Ln(e)}const zn=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function Bn(e){let t={contentDirSpellings:On(e.contentDir)};for(let n of zn)for(let r of Fn(R(e.stagingDir,n)))Rn(r)?Mn(r,t):r.endsWith(`.json`)?Nn(r,t):Pn(r,t);for(let n of Fn(R(e.stagingDir,`state`))){let e=I(n);n.endsWith(`.jsonl`)?Mn(n,t):In.has(e)?Nn(n,t):Pn(n,t)}}const Vn=[`.ok`,`local`,`telemetry`],Hn=[`.ok`,`local`,`logs`],Un=[`.ok`,`local`,`loss-capture`],Wn=`spans-current.jsonl`,Gn=`spans-prev.jsonl`,Kn=`server-current.jsonl`,qn=`server-prev.jsonl`,Jn=`loss-current.jsonl`,Yn=`loss-prev.jsonl`;function Xn(e){return R(e,...Vn,Wn)}function Zn(e){return R(e,...Vn,Gn)}function Qn(e){return R(e,...Hn,Kn)}function $n(e){return R(e,...Hn,qn)}function er(e){return R(e,...Un,Jn)}function tr(e){return R(e,...Un,Yn)}const nr=1e3;async function rr(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(nr)});return t.ok?await t.text():null}catch{return null}}async function ir(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(nr)});return t.ok?await t.text():null}catch{return null}}async function ar(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(nr)});return t.ok?await t.text():null}catch{return null}}function or(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
|
|
14
|
-
`)}\n`:null}catch{return null}}function sr(e){let t=R(e,`.git`,`ok`);if(!V(t))return null;let n=ve(`git`,[`-C`,t,`log`,`--oneline`,`-50`],b({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function cr(e){let t=R(e,`.git`,`ok`);if(!V(t))return null;let n=ve(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],b({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function lr(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function ur(){return{nodeVersion:process.version,platform:Ie(),arch:Ne()}}function dr(){return process.env.OTEL_SDK_DISABLED===`false`}function fr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pr(e){if(!V(e))return{};let t;try{t=(0,wn.parse)(U(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!fr(t))return{};let n=t.telemetry;if(!fr(n))return{};let r=n.localSink;return fr(r)?r:{}}function mr(e){return typeof e==`boolean`?e:void 0}function hr(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function gr(e){if(fr(e))return hr(e.maxBytes)}function _r(e){let t=pr(N(`project`,e)),n=pr(N(`project-local`,e));return{enabled:mr(n.enabled)??mr(t.enabled)??!0,spansMaxBytes:gr(n.spans)??gr(t.spans)??52428800,logsMaxBytes:gr(n.logs)??gr(t.logs)??26214400}}function vr(e){return Ge(`sha256`).update(e).digest(`hex`)}function yr(e){let t=U(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const br=[`"doc.name"`,`"docName"`];function xr(e){let t=U(e,`utf-8`),n=0;for(let e of br){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Q(e,t){if(!V(e))return!1;try{return H(L(t),{recursive:!0}),e.endsWith(`.ips`)?K(t,dt(U(e,`utf-8`))):Ce(e,t),!0}catch{return!1}}function Sr(e){let t=[],n=e=>{let r=W(e,{withFileTypes:!0});for(let i of r){let r=R(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const Cr=new Set([`.jsonl`]);function wr(e){let t=e.lastIndexOf(`.`);return t!==-1&&Cr.has(e.slice(t))}const Tr=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function Er(e){if(Ln(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&Tr.has(e.slice(t))}function Dr(e){let t=[];for(let n of Sr(e)){let r=Or(e,n);if(!Er(r))continue;let{redacted:i,patterns:o,lineCount:s}=a(U(n,`utf-8`));o.length!==0&&(K(n,i),t.push({file:r,lineCount:s,patterns:o}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function Or(e,t){return be(e,t).split(B).join(`/`)}async function kr(e){let n=z(e.contentDir),r=z(e.projectDir??e.contentDir),i=e.deps??{},a=i.fetchAgentPresence??rr,o=i.fetchAgentEffects??ir,s=i.fetchWatcherRecent??ar,c=i.readShadowHead??sr,l=i.readCheckpointRefs??cr,u=i.now??(()=>new Date),d=i.okVersion??(()=>he),ee=i.readDesktopEnv??lr,f=i.readLanguage??Dn,p=i.readRuntime??ur,m=i.isOtlpPushEnabled??dr,g=Ee(R(Re(),`ok-bundle-`));try{H(R(g,`telemetry`),{recursive:!0}),H(R(g,`logs`),{recursive:!0}),H(R(g,`state`),{recursive:!0}),Q(Xn(r),R(g,`telemetry`,Wn)),Q(Zn(r),R(g,`telemetry`,Gn)),Q(Qn(r),R(g,`logs`,Kn)),Q($n(r),R(g,`logs`,qn));for(let t of e.userLogFiles??[])Q(t,R(g,`logs`,I(t)));for(let t of e.userStateFiles??[])Q(t,R(g,ne,I(t)));let _=0;for(let t of e.diagnosticReports?.files??[])Q(t,R(g,`diagnostic-reports`,I(t)))&&(_+=1);let v=R(r,`.ok`,`local`),y=R(v,`server.lock`),b=`not-running`,x=`no server.lock`,S=null;if(V(y)){Q(y,R(g,`state`,`server.lock`));try{let e=U(y,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?S=t.port:x=`lock present but no port`}catch{x=`lock present but unparseable`}}if(S!==null){let e=await a(S);e===null?x=`agent-presence endpoint at :${S} unreachable`:(K(R(g,`state`,`agent-presence.json`),e),b=`running`,x=``);let t=await o(S);t!==null&&K(R(g,`state`,`agent-effects.json`),t);let n=await s(S);if(n!==null){let e=or(n);e!==null&&K(R(g,`state`,`watcher-recent.jsonl`),e)}}let C=c(n);C!==null&&K(R(g,`state`,`shadow-head.txt`),C);let w=l(n);w!==null&&K(R(g,`state`,`checkpoint-refs.txt`),w),Q(er(r),R(g,`state`,Jn)),Q(tr(r),R(g,`state`,Yn)),Q(R(v,`last-spawn-error.log`),R(g,`state`,`last-spawn-error.log`)),Q(R(v,te),R(g,`state`,te)),Q(R(v,t),R(g,`state`,t)),Q(R(v,h),R(g,`state`,h));let T=p(),E=ee(),D=f(),O={ok:{version:d(),nodeVersion:T.nodeVersion,platform:T.platform,arch:T.arch},host:{desktop:E,language:D}};K(R(g,`state`,`runtime.json`),`${JSON.stringify(O,null,2)}\n`);let k=b===`running`?`running
|
|
15
|
-
`:`not-running (${x})\n`;K(R(g,`state`,`server-status.txt`),k);let re=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:st(e.diagnosticReports,_);if(K(R(g,`state`,`diagnostic-reports-status.txt`),`${re}\n`),K(R(g,vt),rn(e.osTerminationEvidence)),e.processDir&&V(e.processDir)){let t=R(g,`process`);H(t,{recursive:!0}),Ce(e.processDir,t,{recursive:!0})}let A=e.redact===!0;A&&Bn({stagingDir:g,contentDir:n}),e.note&&K(R(g,`note.txt`),e.note);let j=null;e.scrubSecrets===!0&&(j=Dr(g));for(let t of e.extraFiles??[]){let e=t.zipName??I(t.sourcePath);if(!Q(t.sourcePath,R(g,`extra`,e))){i.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=ln(t,`extra/${e}`);n!==null&&(j??={redactions:[],redactedLineCount:0},j.redactions.push(n),j.redactedLineCount+=n.lineCount)}let ie=_r(r),ae=Sr(g),M=[],N=0,P=0;for(let e of ae){let t=Or(g,e),n=Me(e).size,r=wr(t)?yr(e):0;M.push({path:t,bytes:n,lines:r}),N+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(P+=xr(e))}let oe={applied:A};j!==null&&(oe.secretScrub=j);let se={schemaVersion:2,createdAt:u().toISOString(),ok:{version:d(),nodeVersion:T.nodeVersion,platform:T.platform,arch:T.arch},host:{desktop:E,language:D},contentDir:{pathSha256:vr(n),absolutePath:A?`<CONTENT_DIR>`:n},telemetry:{localSink:ie,otlpPushEnabled:m()},redaction:oe,serverStatus:b,files:M};K(R(g,`manifest.json`),`${JSON.stringify(se,null,2)}\n`);let ce=On(n),le=ae.some(e=>{try{let t=U(e,`utf-8`);return ce.some(e=>t.includes(e))}catch{return!1}}),ue={stagedDiagnosticReports:_,totalBytes:N,fileCount:M.length,docNameCount:P,contentDirVisible:le,redacted:A},F=!1;return{stagingDir:g,manifest:se,summary:ue,cleanup:()=>{F||(F=!0,G(g,{recursive:!0,force:!0}))}}}catch(e){throw G(g,{recursive:!0,force:!0}),e}}async function Ar(e){let{collected:t,outputPath:n}=e,r=L(n);if(!V(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new Tn.ZipFile,a=Sr(t.stagingDir);for(let e of a){let n=Or(t.stagingDir,e);i.addFile(e,n)}i.end();let o=we(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function jr(e,t){let n=R(e,`.ok`,`config.yml`);if(V(n))try{let t=(0,wn.parse)(U(n,`utf-8`)),r=me(t)?t.content:void 0,i=me(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return z(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return z(e)}async function Mr(e,t,n,r,i,a){let o=un(t,e.logger),s=await kr({contentDir:jr(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...mn(o,e.userLogsDir??R(M(),`logs`)),...gn(e.cachesDir??R(q(),`Library`,`Caches`))],userStateFiles:_n(e.bugReportsDir??sn()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{H(L(e.outputPath),{recursive:!0}),await Ar({collected:s,outputPath:e.outputPath});let t=s.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:o,files:s.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:s.manifest.createdAt}}}finally{s.cleanup()}}async function Nr(e){let{projectDir:t}=e,n=e.readDesktopEnv??lr,r=e.readLanguage??Dn,i=()=>_t(e.diagnosticReportsDir??R(q(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return Mr(e,t,n,r,i(),await tn(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await Cn({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:gn(e.cachesDir??R(q(),`Library`,`Caches`)),bugReportLedgerFiles:_n(e.bugReportsDir??sn()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await tn(e.osTerminationEvidenceDeps):void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}function $(e,t,n={}){let r=T(e,t),i;try{i=U(r,`utf-8`)}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`ENOENT`?{status:`missing`,lockPath:r}:{status:`read-error`,lockPath:r,error:e instanceof Error?e.message:String(e)}}let a;try{a=JSON.parse(i)}catch{return{status:`corrupt`,lockPath:r}}let o=a&&typeof a==`object`?a:{},s=`machineId`in o&&typeof o.machineId==`string`?o.machineId!==(n.machineId??E()):`hostname`in o&&typeof o.hostname==`string`&&o.hostname!==(n.host??Fe());if(!a||typeof a!=`object`||!ae(a.pid))return{status:`corrupt`,lockPath:r,...s?{foreignHost:!0}:{}};let c=a.pid,l=`machineId`in o&&typeof o.machineId==`string`||`hostname`in o&&typeof o.hostname==`string`;return s?{status:`foreign-host`,lockPath:r,lock:a}:(n.isAlive??P)(c)?l?{status:`alive`,lockPath:r,lock:a}:{status:`unverified-owner`,lockPath:r,pid:c}:{status:`dead-pid`,lockPath:r,lock:a}}function Pr(e){return e.status===`unverified-owner`?`Cannot verify shutdown: the server lock at ${e.lockPath} does not record its owning machine, and its recorded process ${e.pid} is still running on this machine. Check whether process ${e.pid} is an OpenKnowledge server. If it is, stop it and retry. Do not remove the lock file while that process is running.`:`Cannot verify shutdown: the server lock at ${e.lockPath} belongs to another machine. Stop OpenKnowledge on the owning machine. Confirm that no OpenKnowledge server is using this directory on the owning machine or any other machine sharing it. Only then remove the stale lock file at ${e.lockPath} and retry cleanup.`}function Fr(e){return e.replace(/:\d+$/,``)}function Ir(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Fr(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Fr(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Fr(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.\-~%]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}const Lr=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function Rr(e){return c(r(),e)}function zr(){return m(r())}function Br(){let e=r();if(e===`stable`)return Lr;let t=f(e);return RegExp(`^# >>> ${t} >>>\\n[\\s\\S]*?^# <<< ${t} <<<\\n?`,`m`)}const Vr={existsSync:e=>V(e),readFileSync:(e,t)=>U(e,t),lstatSync:e=>Te(e),readlinkSync:e=>ke(e)};function Hr(e,t=Vr){let n=Rr(e);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e?.version===1?e:null}catch{return null}}function Ur(e){let t=e.replace(Br(),``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function Wr(e,t,n=Vr){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}const Gr=[{hostDir:`.adal`,pruneRoot:`.adal`},{hostDir:`.aider-desk`,pruneRoot:`.aider-desk`},{hostDir:`.astrbot/data`,pruneRoot:`.astrbot`},{hostDir:`.augment`,pruneRoot:`.augment`},{hostDir:`.autohand`,pruneRoot:`.autohand`},{hostDir:`.bob`,pruneRoot:`.bob`},{hostDir:`.codeartsdoer`,pruneRoot:`.codeartsdoer`},{hostDir:`.codebuddy`,pruneRoot:`.codebuddy`},{hostDir:`.codeium/windsurf`,pruneRoot:`.codeium`},{hostDir:`.codemaker`,pruneRoot:`.codemaker`},{hostDir:`.codestudio`,pruneRoot:`.codestudio`},{hostDir:`.commandcode`,pruneRoot:`.commandcode`},{hostDir:`.config/crush`,pruneRoot:`.config/crush`},{hostDir:`.config/devin`,pruneRoot:`.config/devin`},{hostDir:`.config/goose`,pruneRoot:`.config/goose`},{hostDir:`.config/kimchi/harness`,pruneRoot:`.config/kimchi`},{hostDir:`.continue`,pruneRoot:`.continue`},{hostDir:`.factory`,pruneRoot:`.factory`},{hostDir:`.forge`,pruneRoot:`.forge`},{hostDir:`.grok`,pruneRoot:`.grok`},{hostDir:`.iflow`,pruneRoot:`.iflow`},{hostDir:`.inferencesh`,pruneRoot:`.inferencesh`},{hostDir:`.jazz`,pruneRoot:`.jazz`},{hostDir:`.junie`,pruneRoot:`.junie`},{hostDir:`.kilocode`,pruneRoot:`.kilocode`},{hostDir:`.kiro`,pruneRoot:`.kiro`},{hostDir:`.kode`,pruneRoot:`.kode`},{hostDir:`.lingma`,pruneRoot:`.lingma`},{hostDir:`.mcpjam`,pruneRoot:`.mcpjam`},{hostDir:`.moxby`,pruneRoot:`.moxby`},{hostDir:`.mux`,pruneRoot:`.mux`},{hostDir:`.neovate`,pruneRoot:`.neovate`},{hostDir:`.ona`,pruneRoot:`.ona`},{hostDir:`.openhands`,pruneRoot:`.openhands`},{hostDir:`.pochi`,pruneRoot:`.pochi`},{hostDir:`.qoder`,pruneRoot:`.qoder`},{hostDir:`.qoder-cn`,pruneRoot:`.qoder-cn`},{hostDir:`.qwen`,pruneRoot:`.qwen`},{hostDir:`.reasonix`,pruneRoot:`.reasonix`},{hostDir:`.roo`,pruneRoot:`.roo`},{hostDir:`.rovodev`,pruneRoot:`.rovodev`},{hostDir:`.snowflake/cortex`,pruneRoot:`.snowflake`},{hostDir:`.tabnine/agent`,pruneRoot:`.tabnine`},{hostDir:`.terramind`,pruneRoot:`.terramind`},{hostDir:`.tinycloud`,pruneRoot:`.tinycloud`},{hostDir:`.trae`,pruneRoot:`.trae`},{hostDir:`.trae-cn`,pruneRoot:`.trae-cn`},{hostDir:`.vibe`,pruneRoot:`.vibe`},{hostDir:`.zcode`,pruneRoot:`.zcode`},{hostDir:`.zencoder`,pruneRoot:`.zencoder`}],Kr=[...x.map(e=>ie[e]),`open-knowledge`];function qr(e){if(!ye(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=z(e);if(t===B||L(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function Jr(e,t){let n=be(e,t);if(n.startsWith(`..`)||ye(n))return!1;let r=e;for(let e of n.split(B)){r=R(r,e);try{if(!Te(r).isDirectory())return!1}catch{return!1}}return!0}function Yr(e,t){try{return W(e).every(n=>t.has(R(e,n)))}catch{return!1}}function Xr(e){let t=qr(e),n=[],r=[],i=new Set;for(let e of Gr){let a=R(t,e.hostDir,`skills`);if(!Jr(t,a))continue;let o=Kr.map(e=>R(a,e)).filter(e=>V(e));n.push(...o);for(let e of o)i.add(e);let s=R(t,e.pruneRoot),c=a;for(;Yr(c,i)&&(r.push(c),i.add(c),c!==s);){let e=L(c);if(e===c||e===t||!e.startsWith(t+B))break;c=e}}return{skillDirs:n,emptyDirs:r}}function Zr(e){try{if(!Te(e).isDirectory())return!1;let t=W(e);return t.length===0||t.includes(`SKILL.md`)}catch{return!1}}function Qr(e){let t=new Set,n=new Set;for(let r of Gr){let i=R(e,r.hostDir,`skills`);for(let e of Kr)t.add(R(i,e));let a=R(e,r.pruneRoot),o=i;for(;n.add(o),o!==a;){let t=L(o);if(t===o||t===e||!t.startsWith(e+B))break;o=t}}return{skillDirs:t,emptyDirs:n}}function $r(e,t){let n=qr(e),r=Qr(n),i=[...t.skillDirs.filter(e=>!r.skillDirs.has(e)),...t.emptyDirs.filter(e=>!r.emptyDirs.has(e))];if(i.length>0)throw Error(`refusing skill cleanup — ${i.length} path(s) outside the known legacy set: ${i.join(`, `)}`);let a=[];for(let e of t.skillDirs)if(Jr(n,e)&&Zr(e))try{G(e,{recursive:!0,force:!0}),a.push(e)}catch{}for(let e of t.emptyDirs)if(Jr(n,e))try{je(e),a.push(e)}catch{}return a}function ei(e){let t=qr(e),n=[];for(let e of x){let r=ie[e];n.push({path:R(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of g)n.push({path:R(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function ti(e,t){let n=[];for(let r of ei(e))if(r.bundleId===t)try{G(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}function ni(e){return e!=null&&e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function ri(e,t=Date.now()){if(e===null)return`—`;let n=Je(e,t);return n===`unknown`?`—`:n}function ii(e){let t=L(e);return I(e)===`local`&&I(t)===`.ok`?L(t):I(e)===`.ok`?t:null}function ai(e,t,n,r){if(t.status===`missing`||t.status===`corrupt`||t.status===`read-error`)return null;if(t.status===`unverified-owner`)return{directory:ii(e),server:{port:null,status:t.status,pid:t.pid,startedAt:null,usage:null},ui:null,hostname:null,lockPath:t.lockPath,binary:null,command:null,isDesktop:!1};let i=t.lock,a=t.status===`alive`&&k(i)?{port:i.port,status:t.status,pid:i.pid,startedAt:i.startedAt,usage:r}:null;return{directory:i.worktreeRoot,server:{port:i.port,status:t.status,pid:i.pid,startedAt:i.startedAt,usage:r},ui:a,hostname:i.hostname,lockPath:t.lockPath,binary:n==null?null:re(n),command:n,isDesktop:ni(n)}}function oi(e){let t=e.server.status;switch(t){case`unverified-owner`:return`unverified`;case`alive`:return e.isDesktop?`desktop`:`running`;case`foreign-host`:return e.isDesktop?`desktop`:`foreign`;case`dead-pid`:return`stale`;default:return t}}const si=new Set([`running`,`desktop`,`foreign`,`unverified`]);function ci(e){switch(e){case`running`:return Z.default.green(e);case`desktop`:return Z.default.blue(e);case`foreign`:return Z.default.cyan(e);case`unverified`:case`stale`:return Z.default.yellow(e)}}function li(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function ui(e){return`${li(e.server.usage)} | ${li(e.ui?.usage??null)}`}function di(e){return`${e.server.port===null?`—`:e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null?`—`:String(e.ui.port)}`}function fi(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>[e.directory??`—`,di(e),ui(e),oi(e),String(e.server.pid),ri(e.server.startedAt),e.binary??`—`]),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=ci(oi(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=Z.default.dim(`To stop a server: ${_()} stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
|
|
16
|
-
`)}async function pi(e={}){let t=e.discover??C,n=e.inspect??(e=>$(e,`server`)),r=e.log??(e=>console.log(e)),i=e.resolveCommand??w,a=e.resolveUsage??se,o=await t(),s=[];for(let e of o){let t=n(e),r=ai(e,t,t.status===`missing`||t.status===`corrupt`||t.status===`read-error`||t.status===`unverified-owner`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`||t.status===`read-error`||t.status===`unverified-owner`?null:a(t.lock.pid));r!=null&&s.push(r)}if(e.json){let e=s.map(e=>({...e,displayStatus:oi(e)}));r(JSON.stringify(e,null,2));return}r(fi(e.all?s:s.filter(e=>si.has(oi(e)))))}function mi(){return new F(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale entries (foreign and unverified entries already show)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await pi({all:t.all===!0||e===`all`,json:t.json===!0})})}async function hi(e,t=fe()){let n=$(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=oe(n.lock);if(r===null)return null;try{let n=await fetch(`${r}/api/server-info`,{signal:AbortSignal.timeout(1500),redirect:`manual`});if(!n.ok)return t?.warn({lockDir:e,baseUrl:r,outcome:`http-error`,status:n.status},`stop client-probe failed`),null;let i=(await n.json())?.collabClients;return typeof i==`number`&&Number.isFinite(i)?i:(t?.warn({lockDir:e,baseUrl:r,outcome:`no-client-count`,received:typeof i},`stop client-probe failed`),null)}catch(n){return t?.warn({lockDir:e,baseUrl:r,outcome:`unreachable`,err:n},`stop client-probe failed`),null}}function gi(e,t={}){return{targets:yi(e,t.isAlive??P)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}function _i(e){try{return r()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function vi(e){let t=e.inspect??(()=>$(e.lockDir,`server`)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=e.probeClients??hi,o=e.logger??fe(),c=t(),l=gi(c,{isAlive:e.isAlive});if(l.targets.length===0)return r(`No running open-knowledge processes.`),o?.info({lockDir:e.lockDir,targets:0},`stop found nothing to signal`),{stopped:[],failed:[],hadTargets:!1};let u=c.status===`alive`||c.status===`foreign-host`?c.lock.channel:void 0;if(e.force!==!0&&typeof u==`string`&&u.length>0){let t=e.selfChannel??_i(o);if(t!==void 0&&u!==t)return i(`Not stopping: the server at ${e.lockDir} belongs to ${s(u)}. `+(u===`dev`?`Stop it from that dev build, or run \`${ee} stop\` with OK_CHANNEL=dev set, or re-run with --force to terminate anyway.`:`Stop it from that app or its CLI, or re-run with --force to terminate anyway.`)),o?.warn({lockDir:e.lockDir,holderChannel:u,selfChannel:t,pids:l.targets.map(e=>e.pid)},`stop declined: server belongs to another channel`),{stopped:[],failed:[],hadTargets:!0,declined:{otherChannel:u}}}if(e.force!==!0){let t=await a(e.lockDir,o);if(t!==null&&t>0)return i(`Not stopping: ${t} collaboration client${t===1?``:`s`} (editor window${t===1?``:`s`} or agents) still connected to the server at ${e.lockDir}. Close them, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,clients:t,pids:l.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}let d=[],f=[];for(let e of l.targets)try{n(e.pid,`SIGTERM`),d.push(e)}catch(t){f.push({target:e,error:t instanceof Error?t.message:String(t)})}return d.length>0&&r(`Stopped: ${d.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),o?.info({lockDir:e.lockDir,signalled:d.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:f.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),f.length>0&&i(`Failed to stop: ${f.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:d,failed:f,hadTargets:!0}}function yi(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}async function bi(e,t=P){let n=await C(),r=null;for(let i of n){let n=$(i,`server`);if(yi(n,t)){if(n.lock.port===e)return i;r===null&&n.lock.pid===e&&(r=i)}}return r}async function xi(e,t){let n=await vi({lockDir:e,force:t});return(n.failed.length>0||n.declined!==void 0)&&(process.exitCode=1),n}function Si(e,t,n={}){return t===0?`Nothing was running for ${e}, and no other open-knowledge servers are running.`:`Nothing was running for ${e}. ${t} other open-knowledge server${t===1?` is`:`s are`} running${n.listingFollows===!0?``:` — run \`${_()} ps\` to list them`}.`}async function Ci(e){let t=await C(),n=0;for(let r of t)r!==e&&yi($(r,`server`),P)&&n++;return n}function wi(e){return new F(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the enclosing project — run it from anywhere inside the project. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).option(`--force`,`Stop even when the server belongs to another OpenKnowledge app (Stable, Beta or a dev build run from source) or editor windows or agents are still connected to it`).action(async(t,n)=>{let r=n.force===!0,i=t.length===0?void 0:t.join(` `);if(i===void 0){e();let t=S(process.cwd()),n=await vi({lockDir:t,force:r,log:()=>{}});if(n.hadTargets){if(n.stopped.length>0){let e=n.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}(n.failed.length>0||n.declined!==void 0)&&(process.exitCode=1)}else{let e=await Ci(t);console.log(Si(process.cwd(),e,{listingFollows:e>0})),e>0&&await pi({})}return}if(i===`all`){let e=await C();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let t=0;for(let n of e)yi($(n,`server`),P)&&(await xi(n,r),t++);t===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(i)){let e=Number.parseInt(i,10),t=await bi(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}await xi(t,r);return}let a=z($e(),i),o=S(a),s=[],c=await vi({lockDir:o,force:r,log:e=>s.push(e)});if((c.failed.length>0||c.declined!==void 0)&&(process.exitCode=1),c.hadTargets)for(let e of s)console.log(e);else console.log(Si(a,await Ci(o)))})}export{it as A,tn as C,et as D,st as E,$e as M,Qe as N,nt as O,Xe as P,sn as S,_t as T,$ as _,$r as a,Ar as b,ei as c,Rr as d,zr as f,Pr as g,Ir as h,mi as i,at as j,tt as k,Lr as l,Ur as m,vi as n,Xr as o,Hr as p,wi as r,ti as s,hi as t,Wr as u,Nr as v,on as w,cn as x,kr as y};
|
package/dist/src-CZz3OQDf.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./md-manager-BGnqyqi1-I7NmBKjQ.mjs";import"./src-C97lXQfs.mjs";import"./init-BVMADGS2.mjs";import"./registry-probes-Bx4JMRjq.mjs";import"./start-CrB3JLFw.mjs";import{n as e}from"./loader-BMNiWrib.mjs";import"./preview-DXhCGcEu.mjs";import"./repair-mcp-configs-BBLWRdKU.mjs";export{e as loadConfig};
|
package/dist/start-CMvTynJ0.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{S as e,m as t,p as n,r}from"./start-CrB3JLFw.mjs";export{r as bootStartServer,n as resolveBundledReactShellDir,t as resolveHost,e as startCommand};
|
package/dist/start-CrB3JLFw.mjs
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{C as e,Cl as t,I as n,Q as r,Z as i,i as a,jf as o,yd as s}from"./md-manager-BGnqyqi1-I7NmBKjQ.mjs";import{Li as c,_s as l,bi as u,ci as d,is as f,k as p,os as m,wi as h}from"./dist-Ds1SZERP.mjs";import{B as g,Et as _,R as v,Tt as y,Z as b,b as x,dt as S,wt as C,x as w}from"./init-BVMADGS2.mjs";import{S as T,a as E,c as ee,h as D,i as te,m as O,n as k,o as A,p as j,r as M,s as N,t as ne,u as P}from"./registry-probes-Bx4JMRjq.mjs";import{n as re}from"./constants-Byeyagc8.mjs";import{execFileSync as F,spawn as I}from"node:child_process";import{basename as L,dirname as R,resolve as z}from"node:path";import{existsSync as B,realpathSync as ie}from"node:fs";import{homedir as ae,tmpdir as oe}from"node:os";import{rm as se}from"node:fs/promises";import{setTimeout as ce}from"node:timers/promises";const le=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`],ue={encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,windowsHide:!0};function V(e,t={}){let{login:n}=t,r=t._exec??F,i=H(t._fileExists??B),a=e?[`--hostname`,e]:[];if(n){let e=U(r,i,[`auth`,`token`,...a,`--user`,n]);if(e)return{available:!0,token:e,resolvedLogin:n,fallback:!1}}let o=U(r,i,[`auth`,`token`,...a]);return o?n?{available:!0,token:o,fallback:!0}:{available:!0,token:o}:{available:!1}}function H(e){return[`gh`,...le.filter(e)]}function U(e,t,n){for(let r of t)try{let t=e(r,n,ue).toString().trim();if(t.length>0)return t}catch{}}function de(e,t={}){let n=t._exec??F,r=H(t._fileExists??B),i=[`auth`,`status`,...e?[`--hostname`,e]:[]],a=U(n,r,[...i,`--json`,`hosts`]);if(a!==void 0){let t=fe(a,e);if(t)return t}let o=U(n,r,i);if(o!==void 0){let e=_e(o);if(e.length>0)return e}}function W(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function fe(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=W(W(n)?.hosts);if(!r||t!==void 0&&r[t]===void 0)return;let i=t===void 0?Object.values(r):[r[t]],a=[];for(let e of i){if(!Array.isArray(e))return;for(let t of e){let e=W(t);if(!e)continue;let n=e.login;typeof n==`string`&&n.length!==0&&a.push({login:n,active:e.active===!0})}}return a}const pe=/Logged in to \S+ account (\S+) \(/,me=/(?:Failed to log in to|Timeout trying to log in to) \S+/,he=/^\s*-\s*Active account:\s*true\s*$/,ge=/\u001b\[[0-9;]*m/g;function _e(e){let t=[],n;for(let r of e.split(`
|
|
2
|
-
`)){let e=r.replace(ge,``),i=pe.exec(e)?.[1];if(i){n={login:i,active:!1},t.push(n);continue}if(me.test(e)){n=void 0;continue}n&&he.test(e)&&(n.active=!0)}return t}const ve={mode:`published`,skipAvailabilityCheck:!0,replaceEntry:!0};function G(){return{action:`failed`,errorId:`write-failed`}}function K(){return{action:`skipped-missing`,errorId:`surface-missing`}}function q(e,t,n){l(`agent-integrations-apply`).warn({editor:e,path:t,reason:n},`skill write failed`)}function J(){return{action:`skipped-unsupported`,errorId:`no-writer`}}function ye(e){switch(e){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`left-foreign`:return{action:`skipped-foreign`,errorId:`foreign-artifact`};case`declined`:return{action:`declined`,errorId:`write-declined`}}}function be(e,t,n,r,i){let a=b[e];try{let o=A(a,t,n,r,i);return o.kind===`removed`&&o.trustDetail&&l(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),trust:o.trust,trustDetail:o.trustDetail},`MCP config removal retained Pi folder trust`),ye(o.kind)}catch(i){return l(`agent-integrations-apply`).warn({editor:e,path:r??a.configPath(t,n),reason:i instanceof Error?i.message:String(i)},`MCP config removal failed`),G()}}async function xe(e,t,n){if(b[e].scope!==`global`)return K();if(n===`absent`)return be(e,``,t.home,void 0,t.env);let r=(await w({editors:[e],home:t.home,replaceEntry:!0})).find(t=>t.editorId===e);if(r===void 0)return G();switch(r.action){case`written`:case`overwritten`:return{action:r.action};case`declined`:return{action:`declined`,errorId:`write-declined`};case`skipped-missing`:return K();case`skipped-flag`:return J();default:return G()}}function Se(e,t,n){let r=b[e].projectConfigPath?.(t.cwd);if(r===void 0)return K();if(n===`absent`)return be(e,t.cwd,t.home,r,t.env);let i=x(b[e],t.cwd,ve,void 0,r);switch(i.action){case`written`:case`overwritten`:return{action:i.action};case`declined`:return{action:`declined`,errorId:`write-declined`};default:return G()}}function Ce(e,t,n){let r=t.home??ae();if(n===`absent`){let t=M(e,r);switch(t.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return K();case`failed`:return q(e,t.path,t.error),G()}}let i=E(e,r);switch(i.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return K();case`failed`:return q(e,i.path,i.error),G()}}function we(e,t,n){if(n===`absent`){let n=v(b[e],t.cwd);switch(n.action){case`removed`:return{action:`removed`};case`not-present`:return{action:`no-op`};case`skipped-unsupported`:return K();case`failed`:return q(e,n.path,n.error),G()}}let r=g(b[e],t.cwd);switch(r.action){case`written`:return{action:`written`};case`overwritten`:return{action:`overwritten`};case`skipped-unsupported`:return K();case`skipped-prerequisite`:return{action:`skipped-prerequisite`,errorId:`dependency-failed`};case`failed`:return q(e,r.path,r.error),G()}}function Te(e){return t=>{if(t.pathId===void 0)return J();let n=s(t.pathId);if(n===null||n.kind===`central-skill-store`)return J();switch(n.kind){case`editor-user-config`:return xe(n.editor,e,t.desired);case`editor-project-config`:return Se(n.editor,e,t.desired);case`editor-project-skill-root`:return we(n.editor,e,t.desired);case`editor-user-skill-root`:return Ce(n.editor,e,t.desired)}}}function Ee(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function De(e){if(e===`server`)return e;throw new y(`--only must be 'server'`)}function Oe(e=B,t=import.meta.dirname??new URL(`.`,import.meta.url).pathname){let n=[z(t,`public`),z(t,`../../app/dist`),z(t,`../../../app/dist`)];return e(z(t,`../../app.asar`))&&n.push(z(t,`../../app`)),n.find(t=>e(t))}function ke(e){if(e.explicitDir!==void 0)return{dir:e.explicitDir,missingBundle:!1};if(e.only===`server`)return{dir:void 0,missingBundle:!1};let t=e.findBundledDir();return{dir:t,missingBundle:t===void 0}}function Ae(e){if(e===`off`)return`off`;if(!t.test(e))throw new y(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return e}function je(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function Me(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function Ne(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||je(e.host))&&e.isTTY}function Pe(e,t){let n;try{n=new URL(t)}catch{throw new y(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new y(`${e} must be an http(s) origin (got: ${t})`);return t}function Fe(e){return Pe(`--external-url`,e)}function Ie(e){let t=L(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var Y=class extends Error{cwd;constructor(e){super(`This directory isn't set up yet. Run \`${o()} init\` first, then \`${o()} start\` again.`),this.name=`OkDirMissingError`,this.cwd=e}},X=class extends Error{projectDir;constructor(e){super(`--project-dir must be a throwaway ${p}* directory under the OS temp dir. Refusing to write ephemeral session state into ${e}. Omit --project-dir to let ${o()} start create (and clean up) its own.`),this.name=`EphemeralProjectDirNotThrowawayError`,this.projectDir=e}};function Z(e,t={}){let n=t.tmpdirFn??oe,r=t.realpathFn??ie,i=e=>{try{return r(e)}catch(t){return t.code===`ENOENT`?z(e):null}},a=z(e),o;try{o=r(a)}catch(e){if(e.code===`ENOENT`){let e=i(R(a));o=e===null?null:z(e,L(a))}else o=null}if(o===null)return!1;let s=i(n());return s!==null&&R(o)===s&&L(o).startsWith(`ok-ephemeral-`)}function Le(e,t,n=e=>se(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{if(Z(t))try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}else process.stderr.write(`[start] leaving ${t} in place: only ${p}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function Re(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:+!!i,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(+!!i)}}}async function Q(e){let{config:t,cwd:n,host:r}=e,i=e.skipAutoInit??!1,a=e.idleThresholdMs===void 0?18e5:e.idleThresholdMs,{existsSync:o,mkdirSync:s}=await import(`node:fs`),{basename:l,dirname:u,resolve:f}=await import(`node:path`),{bootServer:p,createEphemeralProjectDir:m,getLogger:g,resolveContentDir:_,resolveLockDir:v,seedEphemeralProjectDir:y,waitForServerLockDrain:b}=await import(`./dist-nfglEvqM.mjs`),x=e.log??g(`start`),C=e.singleFile!==void 0,w=C?c(e.singleFile).canonicalFilePath:void 0,E=w?u(w):void 0,D=w?l(w):void 0,O,A=!1;if(E!==void 0){if(e.projectDir!==void 0){if(O=e.projectDir,!Z(O))throw new X(O);o(f(O,`.ok`,`config.yml`))||y(O,E)}else O=m(E),A=!0}let j=async()=>{if(!(!A||O===void 0)){if(!Z(O)){x.warn({ephemeralProjectDir:O},`[start] refusing to reap self-provisioned ephemeral dir: no longer resolves to an ok-ephemeral-* temp dir`);return}try{await se(O,{recursive:!0,force:!0})}catch(e){x.warn({err:e,ephemeralProjectDir:O},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},M=O;if(!C){if(!i&&!d(n))throw new Y(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{e.severity===`info`?x.debug({event:e},`[start] reclaim sweep event`):x.warn({event:e},`[start] reclaim sweep reported a problem`)};try{let i=(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-BBLWRdKU.mjs`)).repairMcpConfigs)({projectDir:n,reclaimDisableEnv:t,logger:r}).outcomes.filter(e=>e.outcome!==`no-entry`&&e.outcome!==`canonical`&&e.outcome!==`repaired`&&e.outcome!==`foreign`);i.length>0&&x.warn({unhealed:i},`[start] reclaim sweep left entries it could not heal`)}catch(e){x.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-lpbMaBB8.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){x.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}}let P=E??_(t,n);!C&&!o(P)&&(s(P,{recursive:!0}),x.info({contentDir:P},`Created content directory`));let re=T(),F=h(),I;try{{let e=v(O??n),t=Date.now(),r=await b(e);r!==`no-drain`&&x.info({event:`start-waited-for-draining-predecessor`,outcome:r,waitedMs:Date.now()-t,drainLockDir:e},r===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}I=await p({config:t,contentDir:P,projectDir:O??n,contentRoot:C?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:V,detectGhAccounts:de,tokenStore:re,embeddingsKeyStore:F,mcpTomlEditor:S(),...C?{ephemeral:!0,singleDocRelPath:D,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>k(e,t),probePiAcpBridge:e=>ee(e),ensurePiAcpBridge:(e,t)=>N(e,void 0,void 0,void 0,t),agentIntegrations:(()=>{let e={cwd:O??n,home:ae(),env:process.env};return{probe:ne(e),execute:Te(e),userSkillPresentAnywhere:te}})(),idleShutdownMs:a,...e.serverRuntime===void 0?{}:{serverRuntime:e.serverRuntime},...e.bind===void 0?{}:{bind:e.bind},skipAutoInit:!0,idleShutdownHandler:t=>{let n=t;return Re(M===void 0?n:Le(n,M),{log:x,exit:e.idleExit})},log:x,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{},...e.terminalAuthAvailable===!0?{terminalAuthAvailable:!0}:{}})}catch(e){throw await j(),e}let L=I.destroy,R=A?async()=>{try{await L()}finally{await j()}}:L;return{httpServer:I.httpServer,destroy:R,lockDir:I.lockDir,contentDir:P,port:I.port,ready:I.ready,degraded:I.degraded}}function ze(e,t,n=()=>f({absPath:m(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function Be(e){if(e===`browser`||e===`app`)return e;throw new y(`--mode must be 'browser' or 'app'`)}function Ve(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function He(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Ue(t,o){let s=ze(t,o.singleFile),c=Ve(process.env);c!==null&&(process.env.OK_CONSOLE_LEVEL=c);let{renderBanner:l}=await import(`./banner-kywHhVaC.mjs`),{accent:u,dim:d,error:f,warning:p}=await import(`./colors-SgU3JHQu.mjs`),m=process.cwd();process.title=Ie(m);let h;try{h=i(process.env)}catch(e){throw e instanceof a&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=e(s,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=o.bind!==void 0&&o.bind.length>0?o.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=r(g),S=v??(_||b===void 0?[...x.bind]:[b]);Me({flagBindSet:v!==void 0,okBindSet:_,hostEnvSet:b!==void 0,fileBindCount:x.bind.length})&&console.warn(p(`[config] HOST=${b} overrides server.bind — dropping the file-configured addresses (${x.bind.join(`, `)}). Use OK_BIND with a space-separated list to keep multiple binds.`));let C=S[0]??`127.0.0.1`,w=S,T=o.externalUrl,E=r(e(g,{server:{bind:w,...T===void 0?{}:{externalUrl:T}}}));if(E.allowExternal&&(!E.loopbackOnly||E.externalUrl)){let e=E.externalUrl??E.bind.join(`, `);console.warn(p([``,`⚠ EXTERNAL ACCESS ENABLED (server.allowExternal) — no server-side authentication.`,` This server is reachable beyond this machine (${e}). Anyone who can`,` reach it has FULL control of this knowledge base — sync, publishing, GitHub`,` credentials, and local operations (clone, sign-in, repo spawn).`,` Restrict who can reach it at the edge: a Tailscale ACL, a reverse proxy with`,` auth (Cloudflare Access, oauth2-proxy), or a firewall.`,``].join(`
|
|
3
|
-
`)))}let ee=o.port===void 0?void 0:Number(o.port),D=h.overrides.find(e=>e.envVar===`PORT`)?.value,te=ee??D??s.server?.port,O=ke({explicitDir:o.reactShellDistDir,only:o.only,findBundledDir:Oe}),k=O.dir;O.missingBundle&&console.warn(`bundled web UI not found — serving /api and /mcp only. Reinstall @inkeep/open-knowledge, or build packages/app in a source checkout.`);let A;try{A=await Q({config:s,cwd:m,host:C,port:te,bind:w,...o.serveContentAssets===void 0?{}:{serveContentAssets:o.serveContentAssets},...k?{reactShellDistDir:k}:{},idleThresholdMs:n(o.idleShutdown??E.idleShutdown),serverRuntime:E,...o.singleFile?{singleFile:o.singleFile}:{},...o.projectDir?{projectDir:o.projectDir}:{},...o.terminalAuth===!0?{terminalAuthAvailable:!0}:{}})}catch(e){e instanceof Y&&(console.error(f(e.message)),process.exit(1)),e instanceof X&&(console.error(f(e.message)),process.exit(1));let t=await import(`./dist-nfglEvqM.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),e instanceof t.ExposureConsentError&&(console.error(f(e.message)),process.exit(78)),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(f(e.message)),process.exit(1)),(e instanceof t.MissingOkConfigError||e instanceof t.DocumentDurabilityStateError)&&(console.error(f(e.message)),process.exit(1)),Ke(e,t,m)){let e=t.resolveLockDir(m),n=null;try{n=await We({readServerLock:()=>t.readServerLock(e),now:Date.now,sleep:e=>ce(e),timeoutMs:3e3,pollIntervalMs:50})}catch(e){process.stderr.write(`[start] spawn-or-reuse: lock poll failed (${e instanceof Error?e.message:String(e)}) — falling back to the collision message\n`)}if(n!==null){let[e,...t]=Ge(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=$(e,m,t);n!==null&&(console.error(f(n)),process.exit(1)),console.error(`${f(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let j=!1,M=async e=>{if(j)return;j=!0;let[t,...n]=He(e);console.log(u(`\n${t}`));for(let e of n)console.log(d(` ${e}`));try{await A.destroy(`external-signal`)}catch(e){console.error(`${f(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{M(`SIGINT`)}),process.once(`SIGTERM`,()=>{M(`SIGTERM`)});let N=`http://${C.includes(`:`)&&!C.startsWith(`[`)?`[${C}]`:C}:${A.port}`,ne=C===`0.0.0.0`||C===`::`?`http://0.0.0.0:${A.port}`:void 0,P=N;console.log(l({name:`open-knowledge`,version:re,localUrl:P,networkUrl:ne,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let F={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};A.ready.then(async()=>{if(A.degraded.length>0){console.log();for(let e of A.degraded){let t=F[e]??`${e} (check server logs for details)`;console.warn(` ${p(`⚠`)} ${p(e)}: ${d(t)}`)}console.log()}if(Ne({openBrowser:o.openBrowser!==!1&&E.openBrowser,explicitOn:o.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:o.singleFile!==void 0,only:o.only,servesUi:k!==void 0})){let{openBrowser:e}=await import(`./open-browser-BGyDP4ZD.mjs`);e(P)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function We(e){let t=e.now()+e.timeoutMs,n=e.readServerLock();for(;n!==null&&n.draining!==!0&&n.port<=0&&e.now()<t;)await e.sleep(e.pollIntervalMs),n=e.readServerLock();return n===null||n.draining===!0||n.port<=0?null:u(n)&&n.url!==void 0?{url:n.url,kind:n.kind,pid:n.pid,servesUi:!0}:{url:n.url??`http://127.0.0.1:${n.port}`,kind:n.kind,pid:n.pid,servesUi:!1}}function Ge(e){return[`${e.kind===`mcp-spawned`?`An MCP-spawned OpenKnowledge server is already running on this project`:`OpenKnowledge is already running on this project`} (pid ${e.pid}).`,` ${e.url}`,`Leaving it running — run \`${o()} stop\` first if you want a fresh server.`]}function Ke(e,t,n){let r=t.ServerLockCollisionError;if(r!==void 0&&e instanceof r)return!0;let i=t.ServerAuthorityCollisionError;if(i===void 0||!(e instanceof i))return!1;try{return e.existing.scope.kind===`tree`&&ie.native(n)===e.existing.projectDir}catch{return!1}}function $(e,t,n){let r=n.ServerAuthorityCollisionError;if(r!==void 0&&e instanceof r)return e.message;let i=n.ServerAuthorityRegistryError;if(i!==void 0&&e instanceof i)return e.message;let a=n.ServerLockCollisionError;if(a===void 0||!(e instanceof a))return null;try{let e=n.readServerLock(n.resolveLockDir(t)),r=o();return e?.kind===`mcp-spawned`?`An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run \`${r} stop\`.`:`OpenKnowledge server is already running on this project — check \`${r} status\` or \`${r} stop\`.`}catch{return null}}function qe(e){return new C(`start`).description(`Start the OpenKnowledge server (UI + API + MCP + collab on one port)`).option(`-p, --port <port>`,`Server port`,void 0).option(`--bind <address>`,`Bind address (repeatable; default 127.0.0.1 — loopback only)`,(e,t)=>[...t??[],e]).option(`--no-open-browser`,`Do not open the browser after start (interactive loopback starts open it by default)`).option(`--only <module>`,`Serve one module: 'server' (API + MCP only, no shell or browser)`,De).option(`--idle-shutdown <duration>`,`Shut the server down after this long with no connected clients ('off', or a duration like 90s, 30m, 2h; default 30m)`,Ae).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,Be).option(`--serve-content-assets`,`Serve content assets from this server (now the default; kept for compatibility)`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path>`).addOption(new _(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new _(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).addOption(new _(`--terminal-auth`,`Tell in-app agents that this server's client can run terminal sign-ins (the desktop app passes it when it has a terminal)`).hideHelp()).option(`--external-url <url>`,`Canonical external origin clients dial (sets server.externalUrl for this run) — its host joins the Host/Origin allowlists (CORS + external-Host admission). External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).`,Fe).action(async t=>{let n=e();if(t.only===`server`&&t.reactShellDistDir!==void 0&&(process.stderr.write(`error: option '--only server' cannot be combined with '--react-shell-dist-dir'
|
|
4
|
-
`),process.exit(2)),t.projectDir!==void 0&&t.singleFile===void 0&&(process.stderr.write(`error: option '--project-dir' requires '--single-file'
|
|
5
|
-
`),process.exit(2)),t.mode===`app`){let e=[];if(t.port!==void 0&&e.push(`--port`),t.bind!==void 0&&e.push(`--bind`),t.only!==void 0&&e.push(`--only`),t.idleShutdown!==void 0&&e.push(`--idle-shutdown`),t.openBrowser===!1&&e.push(`--no-open-browser`),t.externalUrl!==void 0&&e.push(`--external-url`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=j(P());if(n.available){O({spawn:I},n);return}console.error(D(n.reason)),process.exit(1)}await Ue(n,t)})}export{$ as C,de as D,V as E,qe as S,Re as T,Ve as _,Ge as a,Ne as b,Z as c,Ae as d,De as f,ze as g,We as h,Ie as i,Ke as l,Ee as m,Y as n,He as o,Oe as p,Q as r,je as s,X as t,Fe as u,ke as v,Le as w,Me as x,Ue as y};
|