@inkeep/open-knowledge 0.86.13-beta.10 → 0.86.13-beta.12
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 +60 -60
- package/dist/constants-lgAziYdA.mjs +1 -0
- package/dist/{dist-BtFk8Dn5.mjs → dist-DDooM-sn.mjs} +1 -1
- package/dist/{dist-zDNN5V7x.mjs → dist-DMsiT-GE.mjs} +504 -504
- package/dist/index.mjs +39 -39
- package/dist/init-BkJRnB38.mjs +1 -0
- package/dist/{init-Bo66a3_W.mjs → init-cLsVOMGp.mjs} +27 -27
- package/dist/{launch-json-removal-D2m8-6U5.mjs → launch-json-removal-CN1CHgue.mjs} +1 -1
- package/dist/loader-CPOmChym.mjs +1 -0
- package/dist/{loader-y-TrZa6Y.mjs → loader-Du9EUjvS.mjs} +1 -1
- package/dist/{md-manager-BGnqyqi1-C2aCFGjW.mjs → md-manager-BGnqyqi1-BzZ_8EQ9.mjs} +145 -145
- package/dist/{open-browser-DsUxGgtf.mjs → open-browser-DHuw6ESt.mjs} +1 -1
- package/dist/parse-worker.mjs +1 -1
- package/dist/preview-Bx9qkaKf.mjs +1 -0
- package/dist/{preview-CbBEJMmR.mjs → preview-TPjat07q.mjs} +1 -1
- package/dist/public/assets/{AccountSection-Bs5nCrXk.js → AccountSection-DkNM-aaM.js} +1 -1
- package/dist/public/assets/{ActivityModeContent-QZ6d-7a4.js → ActivityModeContent-Cz9Cmowv.js} +1 -1
- package/dist/public/assets/AddPropertiesButton-D6KoQYQE.js +2 -0
- package/dist/public/assets/{AgentConnectionsSection-BCB6XaTz.js → AgentConnectionsSection-BHPetKxr.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-BIGQK6zr.js → AgentDiffPane-BTmo_vE5.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-GZU1laTi.js → AttachmentsSection-BIAEmImw.js} +1 -1
- package/dist/public/assets/{AuthModal-BbqjE98j.js → AuthModal-X5G4DTEx.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-CYcNRDd1.js → CodeMirrorPropInput-Cb0qKX2H.js} +2 -2
- package/dist/public/assets/{ContentRulesSection-B6dL8ZBP.js → ContentRulesSection-BHp_wZCB.js} +1 -1
- package/dist/public/assets/{DiffViewBoundary-BSQYq_58.js → DiffViewBoundary-oJWWxAbN.js} +1 -1
- package/dist/public/assets/DocumentContext-quy6vWUt.js +108 -0
- package/dist/public/assets/{EditorModeToggle-CGKBO5_T.js → EditorModeToggle-DdtUpmIe.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-DyADjHP1.js → ExcalidrawDocEditor-CtYrgqrg.js} +1 -1
- package/dist/public/assets/FeedbackForm-DLLqiHqI.js +1 -0
- package/dist/public/assets/{GraphPanel-Bq6fUIBW.js → GraphPanel-CGNdettK.js} +1 -1
- package/dist/public/assets/ImportSkillDialog-kYtjXTYj.js +1 -0
- package/dist/public/assets/{LinkPreviewsSection-BJQr4hsZ.js → LinkPreviewsSection-BB1bjNg_.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-DQ5irABI.js → LintConfigEditor-B0L5rUzm.js} +1 -1
- package/dist/public/assets/{LintingSection-TzAf7Zhn.js → LintingSection-Cp1X5inf.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-BJZH6nDl.js +1 -0
- package/dist/public/assets/ManagedArtifactProperties-FyrkWzBk.js +1 -0
- package/dist/public/assets/{MermaidDocEditor-MalnE6MS.js → MermaidDocEditor-YIXLKQfo.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-B6Mxh9fH.js → NetworkAccessSection-Da92wrve.js} +1 -1
- package/dist/public/assets/{ProjectTemplatesSection-BJbZ6ugB.js → ProjectTemplatesSection-D0Bkx3KQ.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-Bhq5IJJj.js → PropertyDisplayRow-ClnrK420.js} +1 -1
- package/dist/public/assets/PublishToGitHubDialog-D4r8iRIM.js +1 -0
- package/dist/public/assets/{RegisteredAgentIcon-BTIzsPkU.js → RegisteredAgentIcon-BBb2bLOu.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-1sW0c_7W.js → SchemaConfigEditor-asdMFShP.js} +1 -1
- package/dist/public/assets/{SearchSection-DEgJ0y5m.js → SearchSection-tlJeLCrv.js} +1 -1
- package/dist/public/assets/{SessionsHost-BPWZxT3I.js → SessionsHost-CgCN1gRH.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-B2BSEdIW.js → SettingsDialogBody-BHz_4a8o.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-DhU5uYRo.js → ShareReceiveMissDialog-klxlJzHP.js} +1 -1
- package/dist/public/assets/SkillCostValue-D5Fs2LwC.js +1 -0
- package/dist/public/assets/{SkillForkDialog-T24C2iFH.js → SkillForkDialog-D2Yx1mWH.js} +1 -1
- package/dist/public/assets/{SkillInstallMenu-CVZobEsw.js → SkillInstallMenu-CKLbtuQf.js} +1 -1
- package/dist/public/assets/{SkillOriginInline-Cs841f5S.js → SkillOriginInline-wxzjBFG4.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-CqAyp6Az.js → SkillToolbarControls-B_2irbtq.js} +1 -1
- package/dist/public/assets/{SkillsManagerSection-zB4Uxwuv.js → SkillsManagerSection-mwDQPVoO.js} +1 -1
- package/dist/public/assets/{SlidesToolbarControls-DONal-Wm.js → SlidesToolbarControls-CTikn8Fl.js} +1 -1
- package/dist/public/assets/{SourceEditor-BqQ3Y-LD.js → SourceEditor-B9jPdpu5.js} +1 -1
- package/dist/public/assets/{SpellingSettings-DYJq-G4I.js → SpellingSettings-Dg988vdp.js} +1 -1
- package/dist/public/assets/{SyncSection-BfQaTVj6.js → SyncSection-DydtYVIG.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-CcOAba6C.js → SyncStatusBadge-CNGrCDAE.js} +1 -1
- package/dist/public/assets/TemplateRow-DaShyoRV.js +7 -0
- package/dist/public/assets/{TerminalLaunchContext-CI-TpGRC.js → TerminalLaunchContext-CjAWwlH6.js} +1 -1
- package/dist/public/assets/{TerminalPanel-C-9jJEyf.js → TerminalPanel-BkBzM1qp.js} +1 -1
- package/dist/public/assets/{TerminalSection-D_zPc-5s.js → TerminalSection-C1eHc1i7.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-CjxHa1xm.js → TerminalWindowApp-CiDlz-Ud.js} +1 -1
- package/dist/public/assets/{TextDocEditor-Wae2EW6d.js → TextDocEditor-C4fsSdta.js} +1 -1
- package/dist/public/assets/{ThemePluginSection-B4bn24Mz.js → ThemePluginSection-BxYvt_G_.js} +1 -1
- package/dist/public/assets/ThreadView-NsjJBfHS.js +28 -0
- package/dist/public/assets/{TimelineDiffPane-L_lcOo0j.js → TimelineDiffPane-csNGBZSW.js} +1 -1
- package/dist/public/assets/{agent-connections-D0ME1tAk.js → agent-connections-GLwwfeSQ.js} +1 -1
- package/dist/public/assets/{agent-registry-ozT_yaRC.js → agent-registry-DoeDgmSS.js} +1 -1
- package/dist/public/assets/{bridge-2KtDdwjE.js → bridge-BeevbgaB.js} +3 -3
- package/dist/public/assets/{card--B2B-S7V.js → card-CnyJ4_sf.js} +1 -1
- package/dist/public/assets/{catalog-nLe25VOf.js → catalog-BCZP9v1Y.js} +1 -1
- package/dist/public/assets/{client-version-DRmVURs6.js → client-version-COAujf9p.js} +1 -1
- package/dist/public/assets/comment-chips-Dpwh4USo.js +8 -0
- package/dist/public/assets/{config-provider-CMGxknTv.js → config-provider-CogbMSvj.js} +2 -2
- package/dist/public/assets/config-schema-DKntRUA6.js +1 -0
- package/dist/public/assets/{css-color-to-hex-DQ05tiK8.js → css-color-to-hex-4NoG2bwl.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-DM1dhLyU.js → doc-undo-manager-Bqo4zf83.js} +1 -1
- package/dist/public/assets/{field-controls-oxASn1fW.js → field-controls-BTAnIIPw.js} +1 -1
- package/dist/public/assets/field-controls-Vvo0Lkt_.js +1 -0
- package/dist/public/assets/globals-CoB8ny3x.css +1 -0
- package/dist/public/assets/{ime-composition-CVvlqJvS.js → ime-composition-CyG03EgC.js} +1 -1
- package/dist/public/assets/index-B2jMcsUA.js +2205 -0
- package/dist/public/assets/{lint-config-client-BuUP6NLf.js → lint-config-client-VoxUDald.js} +1 -1
- package/dist/public/assets/{lint-plugins-D3pWsdpr.js → lint-plugins-21YnDuGP.js} +1 -1
- package/dist/public/assets/{markdown-lint-CBp7xF-c.js → markdown-lint-3sYz4zE8.js} +3 -3
- package/dist/public/assets/{markdownlint-rule-browser-as77OQBK.js → markdownlint-rule-browser-BljyAq4y.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-BLM2BXeS.js → pending-receive-nav-store-CpSN4HBn.js} +1 -1
- package/dist/public/assets/{preferred-session-events-CnOkpJRh.js → preferred-session-events-DLC-rarq.js} +1 -1
- package/dist/public/assets/progress-Bt7UMtSN.js +10 -0
- package/dist/public/assets/saved-themes-client-oll3c0ta.js +1 -0
- package/dist/public/assets/{schema-section-BCpxeE0s.js → schema-section-DJ6iEynt.js} +1 -1
- package/dist/public/assets/{schemas-api-CzJwuc5a.js → schemas-api-CD98jV86.js} +1 -1
- package/dist/public/assets/{selection-context-DtCqhwLp.js → selection-context-D7XIW34q.js} +1 -1
- package/dist/public/assets/{skills-api-DvWR87JW.js → skills-api-Brm92vtB.js} +1 -1
- package/dist/public/assets/{src-0Fjiu8Ee.js → src-D-d779sD.js} +1 -1
- package/dist/public/assets/storage-scope-ldi41iCU.js +1 -0
- package/dist/public/assets/{tag-pill-input-pJw3xLYa.js → tag-pill-input-B9jOgw8L.js} +1 -1
- package/dist/public/assets/{telemetry-impl-CiBHq5jX.js → telemetry-impl-D2OTUygc.js} +1 -1
- package/dist/public/assets/{telemetry-startup-Bx1Ou5CS.js → telemetry-startup-DeW1YLJb.js} +1 -1
- package/dist/public/assets/{terminal-launch-events-NfdixyJK.js → terminal-launch-events-DZK4WV54.js} +1 -1
- package/dist/public/assets/typing-burst-detector-CyrCfMRK.js +8 -0
- package/dist/public/assets/{uninstall-BNoyrj3Z.js → uninstall-B2fm_4nD.js} +1 -1
- package/dist/public/assets/{use-activity-panel-rBSeNU8G.js → use-activity-panel-DPGRlmhU.js} +1 -1
- package/dist/public/assets/{use-apply-config-color-theme-CCEfjhx6.js → use-apply-config-color-theme-DM_OGSn8.js} +2 -2
- package/dist/public/assets/{use-conflicts-CbOb-v8_.js → use-conflicts-Dp9K6H4i.js} +1 -1
- package/dist/public/assets/{use-live-xterm-theme-B01fmTZm.js → use-live-xterm-theme-hdzVNKye.js} +1 -1
- package/dist/public/assets/{use-open-skill-BTJs0gX2.js → use-open-skill-CE_m88gf.js} +1 -1
- package/dist/public/assets/{use-semantic-search-status-BDGrlrdq.js → use-semantic-search-status-8EpcV5XC.js} +1 -1
- package/dist/public/assets/{use-skill-origin-DaM89Ogz.js → use-skill-origin-Bepbv7aT.js} +1 -1
- package/dist/public/assets/{use-skill-targets-DM75u-dx.js → use-skill-targets-ClLUioyZ.js} +1 -1
- package/dist/public/assets/{use-skills-C2Qanq6V.js → use-skills-DLU1dAsd.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-Dji-voVH.js → use-terminal-enabled-OJQP8BOu.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-CayouyDf.js → use-timeline-entry-diff-DLGmI-9t.js} +2 -2
- package/dist/public/assets/{use-workspace-D0A0ZmBO.js → use-workspace-Bgh-YT5K.js} +1 -1
- package/dist/public/index.html +48 -48
- package/dist/public/uninstall.html +3 -3
- package/dist/{registry-probes-BJWtQrWp.mjs → registry-probes-C6-7mNBK.mjs} +3 -3
- package/dist/{removal-file-path-BR4RNXcl.mjs → removal-file-path-DGHqE3V9.mjs} +1 -1
- package/dist/{repair-launch-json-DmpNX9VR.mjs → repair-launch-json-Df4heHjd.mjs} +1 -1
- package/dist/{repair-mcp-configs-CZLPtP2X.mjs → repair-mcp-configs-BxNlmyXQ.mjs} +1 -1
- package/dist/src-CB2AxHE5.mjs +16 -0
- package/dist/src-D6R5qRPv.mjs +1 -0
- package/dist/start-BpsPEUY2.mjs +1 -0
- package/dist/{start-DHtveWWg.mjs → start-DP79VDPx.mjs} +3 -3
- package/package.json +4 -4
- package/dist/constants-3stEn79A.mjs +0 -1
- package/dist/init-DF6ACYPR.mjs +0 -1
- package/dist/loader-x88zzCxw.mjs +0 -1
- package/dist/preview-DbfOwJ87.mjs +0 -1
- package/dist/public/assets/AddPropertiesButton-BGwemosV.js +0 -2
- package/dist/public/assets/DocumentContext-N1JDW9op.js +0 -108
- package/dist/public/assets/FeedbackForm-vdwPygKT.js +0 -1
- package/dist/public/assets/ImportSkillDialog-D5fwO9J1.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-CAT-uTtW.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-CTpxKtXr.js +0 -1
- package/dist/public/assets/PublishToGitHubDialog-DX9ygaL5.js +0 -1
- package/dist/public/assets/SkillCostValue-B-ShSIvZ.js +0 -1
- package/dist/public/assets/TemplateRow-FUuKGsGA.js +0 -7
- package/dist/public/assets/ThreadView-BTyF_a0t.js +0 -28
- package/dist/public/assets/comment-chips-BWPMH63j.js +0 -8
- package/dist/public/assets/config-schema-C37da9RL.js +0 -1
- package/dist/public/assets/field-controls-fZhMOzql.js +0 -1
- package/dist/public/assets/globals-G6Xf2xYI.css +0 -1
- package/dist/public/assets/index-CGrF4mlZ.js +0 -2205
- package/dist/public/assets/progress-DgonS0yg.js +0 -10
- package/dist/public/assets/saved-themes-client-CnQnBq4q.js +0 -1
- package/dist/public/assets/storage-scope-DIpOO45g.js +0 -1
- package/dist/public/assets/typing-burst-detector-D3vEJrYF.js +0 -8
- package/dist/src-Ba8v6dFj.mjs +0 -16
- package/dist/src-vTgTOkUj.mjs +0 -1
- package/dist/start-D6MYrFRx.mjs +0 -1
- /package/dist/public/assets/{globals-aghZx9Sb.js → globals-DOAk0eiA.js} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -426,7 +426,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
|
|
|
426
426
|
`)},mdxJsxFlowElement(e,t,n,r){let i=e,a=i.data?.sourceRaw;if(typeof a==`string`)return a;let o=i.data?.htmlBoundary;if(o&&typeof o.opener==`string`&&typeof o.closer==`string`){let e=n.containerFlow({type:`root`,children:i.children??[]},r);return`${o.opener}\n\n${e}\n\n${o.closer}`}let s=i.name??``,c=bq(i.attributes??[]);if(!i.children||i.children.length===0)return s?c?`<${s} ${c} />`:`<${s} />`:``;let l={...i,attributes:(i.attributes??[]).map(v_e),children:(i.children??[]).map(g_e)};return m_e(l,t,n,r)},mark(e,t,n,r){let i=n.createTracker(r),a=n.enter(`mark`),o=i.move(`==`);return o+=Dq(n.containerPhrasing(e,{before:o,after:`==`,...i.current()}),r,`==`),o+=i.move(`==`),a(),o},underline(e,t,n,r){let i=e.data?.sourceForm===`ins`?`<ins>`:`<u>`,a=e.data?.sourceForm===`ins`?`</ins>`:`</u>`,o=n.createTracker(r),s=n.enter(`underline`),c=o.move(i);return c+=n.containerPhrasing(e,{before:c,after:a,...o.current()}),c+=o.move(a),s(),c},comment(e,t,n,r){let i=e.data?.sourceForm,a=i===`html`?`<!-- `:`%%`,o=i===`html`?` -->`:`%%`,s=n.createTracker(r),c=n.enter(`comment`),l=s.move(a);return l+=n.containerPhrasing(e,{before:l,after:o,...s.current()}),l+=s.move(o),c(),l},commentBlock(e,t,n,r){let i=n.createTracker(r),a=n.enter(`commentBlock`),o=e.children??[],s=e.data?.sourceForm,c=e.data?.sourceLayout,l=o.length===1&&o[0]?.type===`paragraph`;if(s===`html`&&l){let e=o[0],t=n.containerPhrasing(e,{before:`<!-- `,after:` -->`,...i.current()});return a(),`<!-- ${t} -->`}if(c===`inline`&&l){let e=o[0],t=n.containerPhrasing(e,{before:`%% `,after:` %%`,...i.current()});return a(),`%% ${t} %%`}let u=n.containerFlow(e,i.current());return a(),`%%\n\n${u}\n\n%%`},mdxJsxTextElement(e){let t=e.data?.sourceRaw;if(typeof t==`string`)return t;let n=e.name??``,r=bq(e.attributes??[]),i=(e.children??[]).map(e=>e&&typeof e==`object`&&`value`in e?String(e.value??``):``).join(``);return i?r?`<${n} ${r}>${i}</${n}>`:`<${n}>${i}</${n}>`:r?`<${n} ${r} />`:`<${n}/>`},rawMdxFallback(e){return e.value??``},blockquote(e,t,n,r){let i=n.enter(`blockquote`),a=n.createTracker(r);a.move(`> `),a.shift(2);let o=n.containerFlow(e,a.current());i();let s=e.data?.sourceMarkerSpacings,c=0;return n.indentLines(o,(e,t,n)=>{if(n)return`>`;let r=c++,i=s?.[r];return i===`lazy`&&r>0&&!h_e.test(e)?e:i===`none`||i===0?`>${e}`:typeof i==`number`&&i>=2&&!e.startsWith(` `)?`>${` `.repeat(i)}${e}`:`> ${e}`})}};function bq(e){let t=[];for(let n of e){if(n.type===`mdxJsxExpressionAttribute`){t.push(`{${n.value}}`);continue}let e=n.name;if(n.value===null||n.value===void 0){t.push(e);continue}if(typeof n.value==`string`){n.value.includes(`"`)?t.push(`${e}={${xq(n.value)}}`):t.push(`${e}="${n.value}"`);continue}t.push(`${e}={${n.value.value}}`)}return t.join(` `)}function xq(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function v_e(e){return e.type===`mdxJsxAttribute`&&typeof e.value==`string`&&e.value.includes(`"`)?{type:`mdxJsxAttribute`,name:e.name,value:{type:`mdxJsxAttributeValueExpression`,value:xq(e.value)}}:e}function Sq(e,t,n=` `){return t===`single`?`${n}'${e.replace(/'/g,`\\'`)}'`:t===`paren`?`${n}(${e.replace(/[()]/g,`\\$&`)})`:`${n}"${e.replace(/"/g,`\\"`)}"`}function Cq(e,t,n,r=!1){let i=String(n.url??``),a=i.startsWith(`<`)&&i.endsWith(`>`);if(n.data?.sourceUrlForm===`angle-bracketed`&&!a||r){let n=e.enter(`destinationLiteral`),r=t.move(y_e(i,e.stack.includes(`tableCell`)));return n(),r}let o=e.enter(`destinationRaw`),s=t.move(b_e(i));return o(),s}function y_e(e,t=!1){let n=`<`;for(let r=0;r<e.length;r++){let i=e[r];wH(i)||t&&i===`|`?n+=`\\${i}`:n+=i===`
|
|
427
427
|
`?`
`:i===`\r`?`
`:i===`\\`?TH(e[r+1])?`\\\\`:`\\`:i}return`${n}>`}function b_e(e){if(!e)return``;let t=0,n=!0;for(let r of e)r===`(`?t++:r===`)`&&(t--,t<0&&(n=!1));return t!==0&&(n=!1),n?e:e.replace(/[\\()]/g,`\\$&`)}function x_e(e){return e.replace(/(?<!\\)&(?=(#[0-9]+|#[xX][0-9A-Fa-f]+|[A-Za-z][A-Za-z0-9]*);)/g,(e,t)=>S_e(t)?e:`\\${e}`)}function S_e(e){if(e.charCodeAt(0)!==35)return!1;let t=e[1]===`x`||e[1]===`X`?Number.parseInt(e.slice(2),16):Number.parseInt(e.slice(1),10);return t===9||t===10||t===11||t===12||t===13||t===32||t===160}const C_e=/&#(?:x[0-9A-Fa-f]+|X[0-9A-Fa-f]+|[0-9]+);/g;function w_e(e){return e.replace(C_e,e=>rc(e)?``+e.slice(1):e)}function T_e(e){return/[\r\n][\t ]*$/.test(e)}function wq(e,t,n,r=!1){let{matched:i}=MU(t,{escapeAware:!1});if(i.length===0)return Tq(e,t,n,r);let a=``,o=0,s=i=>{i>o&&(a+=Tq(e,t.slice(o,i),{...n,before:n.before+a,after:t.slice(i,i+1)||n.after},r)),o=i};for(let e of i)s(e.start),!T_e(n.before+a)&&(a+=t.slice(e.start,e.end),o=e.end);return s(t.length),a}function Tq(e,t,n,r=!1){let i=e.unsafe;e.unsafe=i.filter(e=>!(e.character===`&`&&e.after===`[#A-Za-z]`||e.character===`<`||e.character===`[`||e.character===`(`||e.character===`!`&&e.after===`\\[`&&e.inConstruct===`phrasing`||e.character===`@`&&e.before===`[+\\-.\\w]`||r&&e.character===`:`&&e.before===`[ps]`&&e.after===`\\/`||e.character===`{`&&Array.isArray(e.inConstruct)&&e.inConstruct.includes(`phrasing`)||e.character==="`"||(e.character===`*`||e.character===`_`||e.character===`~`)&&e.inConstruct===`phrasing`||e.character===`=`&&e.atBreak===!0||e.character===` `&&e.inConstruct===`phrasing`&&e.after===`[\\r\\n]`||e.character===` `&&e.inConstruct===`phrasing`&&e.after===`[\\r\\n]`)),e.unsafe=e.unsafe.map(e=>{if(e.character!==`)`||e.atBreak!==!0||e.before!==`\\d+`||e.after!==void 0)return e;let t={...e,after:`(?:[ \r
|
|
428
428
|
]|$)`};return delete t._compiled,t});let a;try{a=e.safe(w_e(t),n)}finally{e.unsafe=i}return a=a.replaceAll(``,`\\&`),x_e(O_e(a,n))}function Eq(e){if(Number.isNaN(e))return`ws`;let t=Vf(e);return t===1?`ws`:t===2?`punct`:`other`}function E_e(e,t,n){let r=Eq(t),i=Eq(n),a=i!==`ws`&&(i===`other`||r!==`other`),o=r!==`ws`&&(r===`other`||i!==`other`);return e===`_`?a&&(!o||r===`punct`)||o&&(!a||i===`punct`):a||o}function D_e(e,t,n){let r=t;for(;r<e.length&&(e[r]===` `||e[r]===` `);)r++;if(r<e.length)return e[r]===`
|
|
429
|
-
`||e[r]===`\r`;let i=n.after.charCodeAt(0);return Number.isNaN(i)||i===10||i===13}function O_e(e,t){let n=``,r=0;for(;r<e.length;){let i=e.charAt(r);if(i===`\\`){n+=e.slice(r,r+2),r+=2;continue}if(i===`*`||i===`_`||i===`~`||i===`=`){let a=r+1;for(;a<e.length&&e.charAt(a)===i;)a++;let o=r===0?t.before.charCodeAt(t.before.length-1):e.charCodeAt(r-1);if(i===`=`)n+=(Number.isNaN(o)||o===10||o===13)&&D_e(e,a,t)?`\\${e.slice(r,a)}`:e.slice(r,a);else{let s=a<e.length?e.charCodeAt(a):t.after.charCodeAt(0);n+=E_e(i,o,s)?`\\${i}`.repeat(a-r):e.slice(r,a)}r=a;continue}n+=i,r+=1}return n}function Dq(e,t,n){let r=n.startsWith(`_`)?`_`:`*`,i=t.before??``,a=t.after??``,o=e,s=o.charCodeAt(0);Oq(i.charCodeAt(i.length-1),s,r)&&(o=kq(s)+o.slice(1));let c=o.charCodeAt(o.length-1);return Oq(a.charCodeAt(0),c,r)&&(o=o.slice(0,-1)+kq(c)),o}function Oq(e,t,n){return!(Vf(t)!==1||n===`_`&&Vf(e)===void 0)}function kq(e){return`&#x${e.toString(16).toUpperCase()};`}function k_e(e,t,n,r){let i=e.value??``,a=e.data?.sourceDelimiter,o=typeof a==`string`&&/^\$+$/.test(a)?a.length:2;for(o===1&&!j_e(i,r)&&(o=2);RegExp(`(^|[^$])${`\\$`.repeat(o)}([^$]|$)`).test(i);)o++;let s=`$`.repeat(o);/[^ \r\n]/.test(i)&&(/^[ \r\n]/.test(i)&&/[ \r\n]$/.test(i)||/^\$|\$$/.test(i))&&(i=` ${i} `);let c=-1;for(;++c<n.unsafe.length;){let e=n.unsafe[c];if(!e.atBreak)continue;let t=n.compilePattern(e),r;for(;(r=t.exec(i))!==null;){let e=r.index;i.codePointAt(e)===10&&i.codePointAt(e-1)===13&&e--,i=`${i.slice(0,e)} ${i.slice(r.index+1)}`}}return s+i+s}function A_e(e,t,n,r){let i=e.data?.sourceDelimiter===`~`?`~`:`~~`,a=n.createTracker(r),o=n.enter(`strikethrough`),s=a.move(i);return s+=Dq(n.containerPhrasing(e,{...a.current(),before:s,after:`~`}),r,i),s+=a.move(i),o(),s}function j_e(e,t){return!(e.length===0||!/^\S/.test(e)||!/\S$/.test(e)||/[$\r\n]/.test(e)||e.endsWith(`\\`)||/\\[!-/:-@[-`{-~]/.test(e)||/^\d/.test(t.after)||t.before.endsWith(`\\`))}const Aq=[{mode:`protecting`,protect:LH,reservations:FH},{mode:`protecting`,protect:FU,reservations:HH},{mode:`protecting`,protect:jH,reservations:DH},{mode:`serializer-only`,reservations:[{to:``}]}];new Set(Aq.flatMap(({reservations:e})=>e.map(({to:e})=>e)));function M_e(e,t){switch(t.mode){case`protecting`:return t.protect(e);case`serializer-only`:return e}}function jq(e){return Aq.reduce(M_e,e)}function Mq(e){return e.data?.sourceRaw}function N_e(e){return e.type===`text`?e.value===``:e.type===`mdxJsxTextElement`&&Mq(e)===``}function Nq(e){return e.type===`paragraph`&&(e.children??[]).every(N_e)}function Pq(e){let t=e.children??[],n=t[0]?.children?.length??0,r=0;for(let e=1;e<t.length;e++)r=Math.max(r,t[e]?.children?.length??0);let i=e.align??[];return Math.max(n,r,i.length)}function P_e(e){switch(e.type){case`table`:return Pq(e)===0;case`code`:return e.data?.sourceStyle===`indented`&&/^\n*$/.test(e.value??``);case`thematicBreak`:return Mq(e)===``;case`html`:return(e.value??``)===``;case`mdxJsxFlowElement`:return Mq(e)===void 0&&e.data?.htmlBoundary===void 0&&(e.children??[]).length===0&&!e.name;case`list`:return(e.children??[]).length===0;default:return!1}}function F_e(e){let t=[];for(let n of e.children){if(n.type===`table`&&Pq(n)===0){console.warn(JSON.stringify({event:`table-serialize-dropped-empty`,rows:(n.children??[]).length}));continue}P_e(n)||(n.type===`paragraph`&&n.children.length>0&&Nq(n)&&(n.children=[]),t.push(n))}e.children=t}function I_e(e,t){let n=e,r=t;return n.type===`heading`&&n.data?.sourceContiguousNext===!0&&r.type===`paragraph`}const L_e=(e,t)=>{if(Nq(e)||I_e(e,t))return 0;let n=e.position,r=t.position;if(!n||!r)return;let i=r.start.line-n.end.line-1;return i>=1?i:void 0},Fq=/(?<!\\)\$(?=\S)([^$\n]*?[^\s$])\$(?!\d)/g;function R_e(){return(e,t)=>{let n=typeof t.value==`string`?t.value:``;Wf(e,`text`,(e,t,r)=>{if(r===void 0||t==null)return;let i=e.value;if(i.indexOf(`$`)===-1)return;let a=mP(e);Fq.lastIndex=0;let o=[],s;for(;(s=Fq.exec(i))!==null;){let e=s.index,t=e+s[0].length;if(vP(a,e,1)||vP(a,t-1,1)){Fq.lastIndex=e+1;continue}o.push(s)}if(o.length===0)return;let c=[],l=0;for(let t of o){let r=t.index,i=r+t[0].length;r>l&&c.push(_P(n,e,l,r));let a={type:`inlineMath`,value:t[1]},o=xP(n,e,r,i);o&&(a.position=o),c.push(a),l=i}return l<i.length&&c.push(_P(n,e,l,i.length)),r.children.splice(t,1,...c),[yf,t+c.length]})}}const z_e=new Set([`strong`,`emphasis`,`delete`,`link`,`mark`,`comment`]);function B_e(e){if(e?.type!==`break`)return!1;let t=e.data?.sourceRaw;return typeof t!=`string`||t.length===0}function V_e(e){e.data??={},e.data.sourceRaw=`<br />`,e.data.sourceStyle=`html`}function Iq(e){if(e?.type!==`text`)return!1;let t=e.data?.sourceRaw;return typeof t!=`string`||t.length===0}const Lq=/[ \t]+$/,Rq=/^[ \t]*$/;function H_e(e){return e.some(e=>!(Iq(e)&&Rq.test(e.value)))}function zq(e,t=!1){for(;e.length>0;){let n=e[e.length-1];if(B_e(n)){V_e(n);break}if(n&&z_e.has(n.type)&&`children`in n){let t=n.children;if(zq(t,!0),t.length===0){e.pop();continue}}if(!t&&Iq(n)&&Lq.test(n.value)){let t=n.value.replace(Lq,``);if(t.length>0){n.value=t;continue}if(H_e(e.slice(0,-1))){e.pop();continue}if(e.every(e=>Iq(e)&&Rq.test(e.value))){let t=e[0];t.value=t.value.charAt(0),e.splice(1)}}break}}const U_e=new Set([`paragraph`,`heading`,`tableCell`]);function W_e(e){let t=e=>{if(U_e.has(e.type)&&`children`in e&&zq(e.children),`children`in e)for(let n of e.children)t(n)};t(e)}const Bq={handlers:{tag:e=>`#${e.value}`},unsafe:[{character:`#`,inConstruct:[`phrasing`],before:`\\s`,after:`[A-Za-z]|[^\\x00-\\x7F]`}]};function G_e(){let e=this.data();e.toMarkdownExtensions||=[],e.toMarkdownExtensions.some(e=>e===Bq)||e.toMarkdownExtensions.push(Bq)}const K_e=new Set([`u`,`ins`]);function q_e(){return e=>{Wf(e,`mdxJsxTextElement`,(e,t,n)=>{if(n===void 0||t==null||e.name===null||!K_e.has(e.name)||(e.attributes??[]).length>0)return;let r={type:`underline`,children:e.children??[],data:{sourceForm:e.name===`ins`?`ins`:`u`}};return e.position&&(r.position=e.position),n.children.splice(t,1,r),t+1})}}function J_e(e){return e.children.some(e=>{let t=e.type;return t!==`yaml`&&t!==`toml`})?e:{...e,children:[...e.children,{type:`paragraph`,children:[]}]}}const Y_e=[{name:`remark-parse`,plugin:w_},{name:`escape-provenance`,plugin:AK},{name:`remark-mdx-agnostic`,plugin:UU},{name:`remark-gfm`,plugin:Uh},{name:`remark-math`,plugin:qW,options:{singleDollarTextMath:!1}},{name:`remark-wiki-link`,plugin:fW},{name:`remark-github-alerts`,plugin:UW,options:xG},{name:`callout-transformer`,plugin:bG},{name:`restore-from-mdx`,plugin:LU},{name:`void-br-promoter`,plugin:qU},{name:`restore-entity-refs`,plugin:PH},{name:`restore-backslash-escapes`,plugin:RH},{name:`details-accordion-promoter`,plugin:aK},{name:`div-align-promoter`,plugin:mK},{name:`image-promoter`,plugin:RK},{name:`indented-code-promoter`,plugin:WK},{name:`math-promoter`,plugin:eq},{name:`single-dollar-math-promoter`,plugin:R_e},{name:`highlight-promoter`,plugin:LK},{name:`underline-promoter`,plugin:q_e},{name:`mermaid-promoter`,plugin:n_e},{name:`comment-promoter`,plugin:wG},{name:`merged-post-parse-walker`,plugin:e_e},{name:`empty-task-item-unmint`,plugin:xK},{name:`link-reference-destination`,plugin:QK},{name:`non-rendering-context-demote`,plugin:d_e},{name:`ensure-non-empty-doc`,plugin:()=>J_e}];function X_e(e){let t=ug();for(let e of Y_e)t=`options`in e&&e.options!==void 0?t.use(e.plugin,e.options):t.use(e.plugin);return t=t.use(FW,{schema:e.schema,handlers:e.handlers}),t.freeze(),t}function Z_e(e){let t=ug().use(zg,[`yaml`]).use(Uh,{tablePipeAlign:!1}).use(qW,{singleDollarTextMath:!1}).use(UU).use(fW).use(G_e).use(aB,{bullet:`-`,fences:!0,rule:`-`,join:[L_e],...e.toMarkdownHandlers?{handlers:e.toMarkdownHandlers}:{}});return t.freeze(),t}function Vq(e){return e.charCodeAt(0)===65279?{source:e.slice(1),hadBom:!0}:{source:e,hadBom:!1}}const Hq=/^\n+$/,Uq=/^\n{2,}$/;function Wq(e,t,n){let r,i,a=e.children;if(a.length>0){let e=a[0]?.position?.start?.offset;if(typeof e==`number`&&e>0){let n=t.slice(0,e);Hq.test(n)&&(r=n)}let n=a[a.length-1]?.position?.end?.offset;if(typeof n==`number`&&n<=t.length){let e=t.slice(n);Uq.test(e)&&(i=e)}}if(!n&&r===void 0&&i===void 0)return;let o={...n?{bom:!0}:{},...r===void 0?{}:{leading:r},...i===void 0?{}:{trailing:i}};return e.data??={},e.data.sourceDocBoundary=o,o}function Q_e(e){if(typeof e!=`object`||!e)return;let t=e,n={};return t.bom===!0&&(n.bom=!0),typeof t.leading==`string`&&Hq.test(t.leading)&&(n.leading=t.leading),typeof t.trailing==`string`&&Uq.test(t.trailing)&&(n.trailing=t.trailing),n.bom||n.leading||n.trailing?n:void 0}function $_e(e,t){let{source:n,hadBom:r}=Vq(e),i=JG(n),a=new ng(jq(i)),o=t.parse(a);a.value=i;let s=t.runSync(o,a);JK(s,i);let c=Wq(s,i,r),l=c?ws(s,c):void 0,u=t.stringify(s);return l?u.type.create({...u.attrs,sourceDocBoundary:l},u.content,u.marks):u}function eve(e,t){return Gq(e,t,!1)}function tve(e,t){return Gq(e,t,!0)}function Gq(e,t,n){let{source:r,hadBom:i}=Vq(e),a=JG(r),o=new ng(jq(a)),s=t.parse(o);o.value=a;let c=t.runSync(s,o);n&&JK(c,a);let l=Wq(c,a,i);return n&&l&&ws(c,l),c}function nve(e,t,n){let r=LW(e,{schema:n.schema,nodeHandlers:n.pmNodeHandlers,markHandlers:n.pmMarkHandlers});Kq(r),yK(r),W_e(r),F_e(r);let i=Q_e(e.attrs?.sourceDocBoundary),a=String(t.stringify(r));return i?.leading&&(a=i.leading+a),i?.trailing&&(a=a.replace(/\n+$/,``)+i.trailing),i?.bom&&(a=`\uFEFF${a}`),a}function Kq(e){if(!(!(`children`in e)||!Array.isArray(e.children))){for(let t of e.children)Kq(t);for(let t=0;t+1<e.children.length;){let n=e.children[t],r=e.children[t+1],i=n?.data,a=r?.data,o=lP(i)?i.escapedChars:null,s=lP(a)?a.escapedChars:null;if(n?.type!==`text`||r?.type!==`text`||typeof n.data?.sourceRaw==`string`||typeof r.data?.sourceRaw==`string`||o===null&&s===null){t+=1;continue}let c=n.value.length;n.value+=r.value,n.data??={},n.data.escapedChars=[...o??[],...(s??[]).map(e=>({...e,offset:e.offset+c}))],r.data?.entityRefSpans?.length&&(n.data.entityRefSpans=[...n.data.entityRefSpans??[],...r.data.entityRefSpans.map(e=>({...e,offset:e.offset+c}))]),e.children.splice(t+1,1)}}}var rve=class{schema;handlers;pmNodeHandlers;pmMarkHandlers;parseProcessor;serializeProcessor;parseCtx={current:{}};freshnessHolder={checker:void 0};constructor(e){this.schema=yO(e.extensions),this.handlers=cve(this.schema,this.parseCtx),this.freshnessHolder.checker=e.deriveStructuralFreshness?Qs({parse:e=>this.parseWithFallback(e)}):void 0;let{nodeHandlers:t,markHandlers:n}=lve(this.schema,this.freshnessHolder);this.pmNodeHandlers=t,this.pmMarkHandlers=n,this.parseProcessor=X_e({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers}),this.serializeProcessor=Z_e({toMarkdownHandlers:__e})}parse(e,t){if(!e.trim())return{type:`doc`,content:[{type:`paragraph`,content:[]}]};this.parseCtx.current=t??{};try{return $_e(e,this.parseProcessor).toJSON()}finally{this.parseCtx.current={}}}parseToMdast(e){return e.trim()?eve(e,this.parseProcessor):{type:`root`,children:[]}}parseToEditorMdast(e){return e.trim()?tve(e,this.parseProcessor):{type:`root`,children:[]}}parseWithFallback(e,t){return e.trim()?XW(e,{parse:e=>this.parse(e,t)}):{type:`doc`,content:[{type:`paragraph`,content:[]}]}}serialize(e,t){let n;try{n=this.schema.nodeFromJSON(e)}catch(t){let n=`MarkdownManager.serialize() failed: schema rejected JSONContent (type=${e.type}, childCount=${e.content?.length??0})`;throw Error(n,{cause:t})}let r=this.freshnessHolder.checker;t?.skipFreshnessDerive&&(this.freshnessHolder.checker=void 0);try{return nve(n,this.serializeProcessor,{schema:this.schema,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers})}finally{this.freshnessHolder.checker=r}}};const qq=eV();function Jq(e,t){let n=new Map;for(let e of t)n.set(e.name,e);let r={};for(let t of e){if(t.type===`mdxJsxExpressionAttribute`)continue;let e=t.name,i=n.get(e);if(t.value===null||t.value===void 0){r[e]=!0;continue}if(typeof t.value==`string`){if(i?.type===`number`){let n=Number(t.value);r[e]=Number.isNaN(n)?t.value:n}else r[e]=i?.type===`boolean`?t.value===`true`:t.value;continue}let a=t.value.value;try{r[e]=JSON.parse(a)}catch{r[e]=a}}return r}function ive(e){let t=!1;return e.descendants(e=>t?!1:e.type.name===`jsxInline`?(e.attrs.sourceDirty&&(t=!0),!1):e.type.name===`jsxComponent`&&e.attrs.sourceDirty?(t=!0,!1):!0),t}function ave(e,t){return e.attrs.sourceDirty||ive(e)?!0:t?t.isDiverged(e.toJSON()):!1}function ove(e){if(e.type!==`paragraph`)return!1;let t=e.children??[];return t.length===0||t.every(e=>e.type===`text`&&e.value===``)}function Yq(e,t){if(!t)return e;let n={};return t.sourceFenceChar&&(n.sourceFenceChar=t.sourceFenceChar),typeof t.sourceFenceLength==`number`&&(n.sourceFenceLength=t.sourceFenceLength),t.sourcePadded===!0&&(n.sourcePadded=!0),Object.keys(n).length===0?e:{...e,data:n}}function Xq(e,t){if(e.length===0)return Yq({type:`inlineCode`,value:``},t);if(e.every(e=>e.type===`text`))return Yq({type:`inlineCode`,value:e.map(e=>e.value).join(``)},t);if(e.length===1&&`children`in e[0]){let n=e[0];return{...n,children:[Xq(n.children,t)]}}return Yq({type:`inlineCode`,value:Zq(e)},t)}function Zq(e){let t=``;for(let n of e)n.type===`text`?t+=n.value:`children`in n&&Array.isArray(n.children)?t+=Zq(n.children):`value`in n&&typeof n.value==`string`&&(t+=n.value);return t}const sve=Oc;function cve(e,t){let n=e.nodes,r=e.marks,i={};n.paragraph&&(i.paragraph=(e,t,r)=>{let i=r.all(e).flat(),a=i.some(e=>e?.isBlock&&!e?.isInline),o=i.some(e=>e?.isInline||e?.isText||e?.isTextblock);if(a&&!o)return i.length===1?i[0]:i;if(a&&o){let e=i.filter(e=>!e?.isBlock||e?.isInline),t=i.filter(e=>e?.isBlock&&!e?.isInline),r=[],a=n.paragraph.createAndFill(null,e.length>0?e:null);return a&&r.push(a),r.push(...t),r.length===1?r[0]:r}return n.paragraph.createAndFill(null,i.length>0?i:null)}),n.blockquote&&(i.blockquote=MW(n.blockquote,e=>({sourceMarkerSpacings:e.data?.sourceMarkerSpacings??null}))),n.tableCell&&(i.tableCell=(e=>(t,r,i)=>{let a=i.all(t).flat();if(a.length>0&&n.paragraph){let t=n.paragraph.create(null,a);return e.createAndFill(null,[t])}return e.createAndFill(null,null)})(n.tableCell)),n.tableRow&&(i.tableRow=MW(n.tableRow)),n.table&&n.tableRow&&n.tableCell&&(i.table=(e,t,r)=>{let i=e.align??[],a=e.children??[],o=[];for(let e=0;e<a.length;e++){let t=a[e];if(t.type!==`tableRow`)continue;let s=t.children??[],c=[];for(let t=0;t<s.length;t++){let a=s[t];if(a.type!==`tableCell`)continue;let o=r.all(a).flat(),l=o.length>0&&n.paragraph?[n.paragraph.create(null,o)]:null,u=i[t]??null,d=e===0&&n.tableHeader?n.tableHeader:n.tableCell,f=a.data?.sourcePadding??null,p=d.createAndFill({align:u,sourcePadding:f},l);p&&c.push(p)}let l=n.tableRow.createAndFill(null,c.length>0?c:null);l&&o.push(l)}let s=e.data?.sourceDashCounts??null,c=e.data?.sourceOuterPipes??null,l=e.data?.sourceAlignmentPadding??null;return n.table.createAndFill({sourceDashCounts:s,sourceOuterPipes:c,sourceAlignmentPadding:l},o.length>0?o:null)}),n.image&&(i.image=e=>{let r=e.url??``,i=yW(r,t.current.sourcePath);return n.image.createAndFill({src:i,alt:e.alt??null,title:e.title??null,sourceUrl:i===r?null:r,sourceUrlForm:e.data?.sourceUrlForm??null})},i.imageReference=n.imageReference?e=>n.imageReference.createAndFill({alt:e.alt??``,label:e.label??e.identifier??``,identifier:e.identifier??``,referenceType:e.referenceType??`shortcut`}):e=>n.image.createAndFill({src:``,alt:e.alt??null,title:null})),r.escapeMark&&(i.text=t=>{let n=t.value??``,i=typeof t.data?.sourceRaw==`string`?t.data.sourceRaw:null;if(!n&&!i)return null;if(i)return r.sourceLiteral?e.text(n,[r.sourceLiteral.create({sourceRaw:i})]):e.text(n);let a=t.data?.escapedChars,o=t.data?.entityRefSpans;if(!a?.length&&!o?.length)return e.text(n);let s=[...(a??[]).map(e=>({kind:`escape`,offset:e.offset,length:1})),...(o??[]).map(e=>({kind:`entity`,offset:e.offset,length:e.length,raw:e.raw}))];s.sort((e,t)=>e.offset-t.offset);let c=[];for(let e of s){let t=c[c.length-1];e.kind===`entity`&&t?.kind===`entity`&&t.offset+t.length===e.offset&&oc(t.raw)!==null&&rc(e.raw)?c[c.length-1]={kind:`entity`,offset:t.offset,length:t.length+e.length,raw:t.raw+e.raw}:c.push(e)}let l=[],u=0;for(let t of c){if(t.offset>u){let r=n.slice(u,t.offset);r&&l.push(e.text(r))}if(t.offset<n.length){let i=n.slice(t.offset,t.offset+t.length);if(i){if(t.kind===`escape`)l.push(e.text(i,[r.escapeMark.create()]));else if(r.sourceLiteral){let n=oc(t.raw);l.push(e.text(n??i,[r.sourceLiteral.create({sourceRaw:t.raw})]))}else l.push(e.text(i))}u=t.offset+t.length}}if(u<n.length){let t=n.slice(u);t&&l.push(e.text(t))}return l.length===1?l[0]:l}),r.code&&(i.inlineCode=t=>e.text(t.value,[r.code.create({sourceFenceChar:t.data?.sourceFenceChar??"`",sourceFenceLength:typeof t.data?.sourceFenceLength==`number`?t.data.sourceFenceLength:1,sourcePadded:t.data?.sourcePadded===!0})]));let a=r.strike??r.delete;if(a&&(i.delete=NW(a,e=>({sourceDelimiter:e.data?.sourceDelimiter===`~`?`~`:`~~`}))),r.highlight&&(i.mark=NW(r.highlight)),r.underline&&(i.underline=NW(r.underline,e=>({sourceForm:e.data?.sourceForm===`ins`?`ins`:`u`}))),r.comment&&(i.comment=NW(r.comment,e=>({sourceForm:e.data?.sourceForm??`percent`}))),n.commentBlock&&(i.commentBlock=MW(n.commentBlock,e=>({sourceForm:e.data?.sourceForm??`percent`,sourceLayout:e.data?.sourceLayout??`block`}))),r.emphasis&&(i.emphasis=NW(r.emphasis,e=>({sourceDelimiter:e.data?.sourceDelimiter??`*`}))),r.strong&&(i.strong=NW(r.strong,e=>({sourceDelimiter:e.data?.sourceDelimiter??`**`}))),n.heading&&(i.heading=MW(n.heading,e=>({level:e.depth,headingStyle:e.data?.sourceStyle??`atx`,sourceTrailingHashes:e.data?.sourceTrailingHashes??null,sourceUnderlineLength:e.data?.sourceUnderlineLength??null,sourceContiguousNext:e.data?.sourceContiguousNext??!1,sourceLeadingIndent:e.data?.sourceLeadingIndent??null,sourceInteriorSpacing:e.data?.sourceInteriorSpacing??null}))),n.codeBlock&&(i.code=t=>{let r=t.value?[e.text(t.value)]:[];return n.codeBlock.createAndFill({language:t.lang??null,meta:t.meta??null,fenceDelimiter:t.data?.sourceFenceChar??"`",fenceLength:t.data?.sourceFenceLength??3,sourceStyle:t.data?.sourceStyle??`fenced`,sourceClosingFenceLength:t.data?.sourceClosingFenceLength??null,sourceUnclosedFence:t.data?.sourceUnclosedFence??!1,sourceFenceIndent:t.data?.sourceFenceIndent??null,sourceInfoPadding:t.data?.sourceInfoPadding??null,sourceIndents:t.data?.sourceIndents??null},r)}),n.thematicBreak&&(i.thematicBreak=e=>n.thematicBreak.createAndFill({sourceRaw:e.data?.sourceRaw??`---`})),n.hardBreak&&(i.break=e=>n.hardBreak.createAndFill({hardBreakStyle:e.data?.sourceStyle??`spaces`,sourceRaw:e.data?.sourceRaw??null})),n.list&&(i.list=MW(n.list,e=>({ordered:!!e.ordered,start:e.start??1,spread:!!e.spread,bulletMarker:e.data?.bulletMarker??null,listMarkerDelimiter:e.data?.listMarkerDelimiter??null}))),n.listItem&&(i.listItem=MW(n.listItem,e=>({checked:e.checked??null,spread:!!e.spread,sourceMarkerSpacing:e.data?.sourceMarkerSpacing??null,sourceOrdinal:e.data?.sourceOrdinal??null,sourceCheckboxChar:e.data?.sourceCheckboxChar??null,sourceContinuationIndent:e.data?.sourceContinuationIndent??null}))),r.link){let t=r.sourceLiteral;i.link=(n,i,a)=>{if((n.children??[]).length===0){let r=typeof n.data?.sourceRaw==`string`?n.data.sourceRaw:`[](${n.url??``})`;return r?t?e.text(r,[t.create({sourceRaw:r})]):e.text(r):null}let o=a.all(n).flat(),s=r.link.create({href:n.url??``,title:n.title??null,linkStyle:n.data?.sourceStyle??`inline`,refLabel:null,sourceUrlForm:n.data?.sourceUrlForm??null,sourceTitleMarker:n.data?.sourceTitleMarker??null});return o.map(e=>e.mark(s.addToSet(e.marks)))},i.linkReference=(n,i,a)=>{if((n.children??[]).length===0){let r=typeof n.data?.sourceRaw==`string`?n.data.sourceRaw:`[${n.label??``}][${n.identifier??``}]`;return r?t?e.text(r,[t.create({sourceRaw:r})]):e.text(r):null}let o=a.all(n).flat(),s=r.link.create({href:n.data?.resolvedUrl??``,title:n.data?.resolvedTitle??null,linkStyle:n.referenceType??`shortcut`,refLabel:n.label??n.identifier??null});return o.map(e=>e.mark(s.addToSet(e.marks)))}}n.htmlBlock&&(i.html=e=>n.htmlBlock.createAndFill({content:e.value??``}));let o=n.linkDefinition??n.linkRefDef;if(o){let e=!!o.spec.attrs?.url,t=!!o.spec.attrs?.href,n=!!o.spec.attrs?.identifier,r=!!o.spec.attrs?.sourceLayout,a=!!o.spec.attrs?.sourceTitleMarker,s=!!o.spec.attrs?.sourceUrlForm;i.definition=i=>{let c={title:i.title??null};return n&&(c.identifier=i.identifier??``),c.label=i.label??i.identifier??``,e?c.url=i.url??``:t&&(c.href=i.url??``),r&&(c.sourceLayout=i.data?.sourceLayout??null),a&&(c.sourceTitleMarker=i.data?.sourceTitleMarker??null),s&&(c.sourceUrlForm=i.data?.sourceUrlForm??null),o.createAndFill(c)}}if(n.jsxComponent){let r=e=>{if(e&&typeof e==`object`&&`sourceRaw`in e){let t=e.sourceRaw;if(typeof t==`string`)return t}};i.mdxJsxFlowElement=(e,i,a)=>{let o=e.name??``,s=qq.getOrWildcard(o),c=Jq(e.attributes,s.props);if(o===`CommonMarkImage`&&typeof c.src==`string`){let e=c.src,n=yW(e,t.current.sourcePath);n!==e&&(c.src=n,c.sourceUrl=e)}let l=a.all(e).flat();return n.jsxComponent.createAndFill({componentName:o,kind:`element`,attributes:e.attributes,sourceRaw:r(e.data)??``,sourceDirty:!1,props:c},l.length?l:void 0)};let a=(e,t)=>{let n=e.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===t);return n&&typeof n.value==`string`?n.value:null};i.mdxJsxTextElement=t=>{if(t.name===`InlineMath`&&n.mathInline){let e=a(t,`formula`)??``,r=a(t,`id`);return n.mathInline.create({formula:e,id:r??null})}if(t.name===`Tag`&&n.tag){let e=a(t,`value`)??``;return n.tag.create({value:e})}let i=t.name??``,o=i?qq.get(i):void 0;if(o&&n.jsxInline){let e=Jq(t.attributes,o.props),a=r(t.data)??``,s=(t.children??[]).map(e=>e&&typeof e==`object`&&`value`in e?String(e.value??``):``).join(``);return s&&(e.children=s),n.jsxInline.createAndFill({componentName:i,attributes:t.attributes,sourceRaw:a,sourceDirty:!1,props:e})}if(n.jsxInline){let i=r(t.data)??``;return n.jsxInline.createAndFill({},i?[e.text(i)]:null)}return n.jsxComponent.createAndFill({sourceRaw:r(t.data)??``})},i.mdxFlowExpression=e=>{let t=r(e.data)??`{${e.value??``}}`;return n.jsxComponent.createAndFill({kind:`expression`,sourceRaw:t,sourceDirty:!1})},i.mdxTextExpression=t=>{let n=r(t.data)??`{${t.value??``}}`;return e.text(n)}}return n.wikiLink&&(i.wikiLink=e=>n.wikiLink.createAndFill({target:e.data?.target??``,alias:e.data?.alias??null,anchor:e.data?.anchor??null,sourceTarget:e.data?.sourceTarget??null,sourceAnchor:e.data?.sourceAnchor??null,sourceAlias:e.data?.sourceAlias??null})),n.tag&&(i.tag=e=>n.tag.createAndFill({value:e.value})),n.wikiLinkEmbed&&(i.wikiLinkEmbed=(i,a)=>{let o=i.data?.target??``,s=i.data?.alias??null,c=i.data?.anchor??null,l=i.data?.sourceTarget??null,u=i.data?.sourceAnchor??null,d=i.data?.sourceAlias??null,f=sk(o),{resolveEmbed:p,sourcePath:m}=t.current,h=p&&m?p(o,m)??null:null,g=h?`/${h}`:o,_=a?.type===`paragraph`&&Array.isArray(a.children)&&a.children.length===1;if(_&&sve.has(f)&&n.jsxComponent&&qq.has(`WikiEmbedImage`))return n.jsxComponent.createAndFill({componentName:`WikiEmbedImage`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:g,alt:s??o,target:o,anchor:c,alias:s,sourceTarget:l,sourceAnchor:u,sourceAlias:d}});if(_&&kc.has(f)&&n.jsxComponent&&qq.has(`WikiEmbedVideo`))return n.jsxComponent.createAndFill({componentName:`WikiEmbedVideo`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:g,title:s??o,target:o,anchor:c,alias:s,sourceTarget:l,sourceAnchor:u,sourceAlias:d}});if(_&&jc.has(f)&&n.jsxComponent&&qq.has(`WikiEmbedAudio`))return n.jsxComponent.createAndFill({componentName:`WikiEmbedAudio`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:g,title:s??o,target:o,anchor:c,alias:s,sourceTarget:l,sourceAnchor:u,sourceAlias:d}});if(_&&Mc.has(f)&&n.jsxComponent&&qq.has(`WikiEmbedFile`)){let{resolveSize:e}=t.current,r=e&&m?e(o,m)??null:null,i=r===null?null:bW(r);return n.jsxComponent.createAndFill({componentName:`WikiEmbedFile`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:g,target:o,anchor:c,alias:s,size:i,sourceTarget:l,sourceAnchor:u,sourceAlias:d}})}let v=s||(c?`${o}#${c}`:o);if(r.link){let t=r.link.create({href:g,title:null,linkStyle:`inline`,refLabel:null,sourceForm:`wikiembed`,target:o,anchor:c,alias:s,sourceTarget:l,sourceAnchor:u,sourceAlias:d});return e.text(v,[t])}throw Error("[wikiLinkEmbed handler] schema lacks `link` mark — cannot dispatch without violating the STOP rule against emitting PM wikiLinkEmbed server-side")}),n.mathInline&&(i.inlineMath=e=>n.mathInline.create({formula:e.value??``,sourceDelimiter:e.data?.sourceDelimiter??null})),i.math||=t=>{let r=t.value==null?`«unknown:${t.type}»`:t.value;return n.rawMdxFallback?(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled block mdast: ${t.type}`})),n.rawMdxFallback.createAndFill({reason:`Unhandled block mdast: ${t.type}`},r?[e.text(r)]:null)):null},i.inlineMath||=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled inline mdast: ${t.type}`})),t.value==null?e.text(`«unknown:${t.type}»`):e.text(t.value)),n.footnoteReference?i.footnoteReference=e=>n.footnoteReference.create({identifier:e.identifier,label:e.label??e.identifier}):i.footnoteReference||=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:`footnoteReference`,reason:`FootnoteReference extension missing — recovering [^id] source`})),e.text(`[^${t.label??t.identifier}]`)),n.footnoteDefinition?i.footnoteDefinition=MW(n.footnoteDefinition,e=>{let t=e;return{identifier:t.identifier,label:t.label??t.identifier}}):i.footnoteDefinition||=t=>{console.warn(JSON.stringify({event:`unknown-mdast-type`,type:`footnoteDefinition`,reason:`FootnoteDefinition extension missing — recovering [^id]: marker`}));let r=`[^${t.label??t.identifier}]: `;return n.paragraph?n.paragraph.create(null,e.text(r)):null},i.rawMdxFallbackMdast=t=>{if(!n.rawMdxFallback)return null;let r=t.position?{start:t.position.start?.offset??0,end:t.position.end?.offset??0}:{start:0,end:0};return console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.originalType,reason:`Unhandled mdast: ${t.originalType}`,unresolvedPosition:t.unresolvedPosition??!1})),n.rawMdxFallback.createAndFill({reason:`Unhandled mdast: ${t.originalType}`,originalSpan:r},t.value?[e.text(t.value)]:null)},i}function lve(e,t){let n={},r={},i=e.nodes,a=e.marks;i.paragraph&&(n.paragraph=RW(`paragraph`)),i.blockquote&&(n.blockquote=RW(`blockquote`,e=>{let t=e.attrs.sourceMarkerSpacings,n={};return Array.isArray(t)&&t.length>0&&(n.sourceMarkerSpacings=t),Object.keys(n).length>0?{data:n}:{}})),i.heading&&(n.heading=RW(`heading`,e=>({depth:e.attrs.level,data:{sourceStyle:e.attrs.headingStyle,sourceTrailingHashes:e.attrs.sourceTrailingHashes??void 0,sourceUnderlineLength:e.attrs.sourceUnderlineLength??void 0,sourceContiguousNext:e.attrs.sourceContiguousNext===!0||void 0,sourceLeadingIndent:e.attrs.sourceLeadingIndent??void 0,sourceInteriorSpacing:e.attrs.sourceInteriorSpacing??void 0}}))),i.codeBlock&&(n.codeBlock=e=>{let t=e.attrs.sourceStyle===`indented`?`indented`:`fenced`;return{type:`code`,lang:t===`indented`?null:e.attrs.language??null,meta:t===`indented`?null:e.attrs.meta??null,value:e.textContent??``,data:{sourceFenceChar:e.attrs.fenceDelimiter,sourceFenceLength:e.attrs.fenceLength,sourceStyle:t,sourceClosingFenceLength:e.attrs.sourceClosingFenceLength??void 0,sourceUnclosedFence:e.attrs.sourceUnclosedFence===!0||void 0,sourceFenceIndent:e.attrs.sourceFenceIndent??void 0,sourceInfoPadding:e.attrs.sourceInfoPadding??void 0,sourceIndents:e.attrs.sourceIndents??void 0}}}),i.thematicBreak&&(n.thematicBreak=e=>({type:`thematicBreak`,data:{sourceRaw:e.attrs.sourceRaw}})),i.hardBreak&&(n.hardBreak=e=>({type:`break`,data:{sourceStyle:e.attrs.hardBreakStyle,...typeof e.attrs.sourceRaw==`string`&&e.attrs.sourceRaw.length>0?{sourceRaw:e.attrs.sourceRaw}:{}}})),i.list&&(n.list=RW(`list`,e=>({ordered:e.attrs.ordered??!1,start:e.attrs.ordered?e.attrs.start??1:null,spread:e.attrs.spread??!1,data:{bulletMarker:e.attrs.bulletMarker,listMarkerDelimiter:e.attrs.listMarkerDelimiter}}))),i.listItem&&(n.listItem=(e,t,n)=>{let r=n.all(e),i=r.length>1&&ove(r[0])?r.slice(1):r,a={};return typeof e.attrs.sourceMarkerSpacing==`number`&&(a.sourceMarkerSpacing=e.attrs.sourceMarkerSpacing),typeof e.attrs.sourceOrdinal==`number`&&(a.sourceOrdinal=e.attrs.sourceOrdinal),e.attrs.sourceCheckboxChar===`X`&&(a.sourceCheckboxChar=`X`),typeof e.attrs.sourceContinuationIndent==`number`&&(a.sourceContinuationIndent=e.attrs.sourceContinuationIndent),{type:`listItem`,checked:e.attrs.checked??null,spread:e.attrs.spread??!1,...Object.keys(a).length>0?{data:a}:{},children:i}}),i.table&&(n.table=(e,t,n)=>{let r=n.all(e),i=[],a=e.firstChild;a&&a.forEach(e=>{let t=e.attrs.align;i.push(t===`left`||t===`right`||t===`center`?t:null)});let o=r.filter(e=>e.type===`tableRow`),s=e.attrs.sourceDashCounts,c={};Array.isArray(s)&&s.length>0&&(c.sourceDashCounts=s);let l=e.attrs.sourceOuterPipes;typeof l==`object`&&l&&typeof l.leading==`boolean`&&typeof l.trailing==`boolean`&&(c.sourceOuterPipes=l);let u=e.attrs.sourceAlignmentPadding;Array.isArray(u)&&u.length>0&&(c.sourceAlignmentPadding=u);let d=Object.keys(c).length>0?c:void 0,f={type:`table`,align:i,children:o};return d&&(f.data=d),f}),i.tableRow&&(n.tableRow=RW(`tableRow`));let o=(e,t)=>{let n={type:`tableCell`,children:HP(t)},r=e.attrs.sourcePadding;return typeof r==`object`&&r&&typeof r.left==`number`&&typeof r.right==`number`&&(n.data={sourcePadding:r}),n};if(i.tableCell&&(n.tableCell=(e,t,n)=>o(e,n.all(e))),i.tableHeader&&(n.tableHeader=(e,t,n)=>o(e,n.all(e))),i.image&&(n.image=e=>{let t={type:`image`,url:e.attrs.sourceUrl??e.attrs.src,alt:e.attrs.alt,title:e.attrs.title};return e.attrs.sourceUrlForm===`angle-bracketed`&&(t.data={sourceUrlForm:`angle-bracketed`}),t}),i.imageReference&&(n.imageReference=e=>{let t=e.attrs.label??``,n=e.attrs.identifier??t;return{type:`imageReference`,alt:e.attrs.alt??``,identifier:n,label:t||n,referenceType:e.attrs.referenceType??`shortcut`}}),i.htmlBlock&&(n.htmlBlock=e=>({type:`html`,value:e.attrs.content})),i.linkDefinition??i.linkRefDef){let e=i.linkDefinition?`linkDefinition`:`linkRefDef`;n[e]=e=>{let t={},n=e.attrs.sourceLayout;(n===`multiline`||n===`inline`)&&(t.sourceLayout=n);let r=e.attrs.sourceTitleMarker;(r===`single`||r===`double`||r===`paren`)&&(t.sourceTitleMarker=r),e.attrs.sourceUrlForm===`angle-bracketed`&&(t.sourceUrlForm=`angle-bracketed`);let i={type:`definition`,identifier:e.attrs.identifier??e.attrs.label??``,label:e.attrs.label??e.attrs.identifier??``,url:e.attrs.url??e.attrs.href??``,title:e.attrs.title};return Object.keys(t).length>0&&(i.data=t),i}}if(i.jsxComponent&&(n.jsxComponent=(e,n,r)=>{if(e.attrs.kind===`expression`)return{type:`html`,value:e.attrs.sourceRaw??``};let i=e.attrs.componentName||null,a=Array.isArray(e.attrs.attributes)?e.attrs.attributes:[];return!ave(e,t.checker)&&e.attrs.sourceRaw?{type:`mdxJsxFlowElement`,name:i,attributes:a,children:[],data:{sourceRaw:String(e.attrs.sourceRaw)}}:qq.getOrWildcard(i??`*`).serialize(e,{all:e=>r.all(e),registry:qq,serializeChildren:()=>{throw Error(`SerializeContext.serializeChildren is not available in the PM→mdast handler. Compat descriptors that need markdown-byte body rendering must emit a marker mdast node and let the to-markdown handler render the body via state.containerFlow.`)}})}),i.rawMdxFallback&&(n.rawMdxFallback=e=>{let t=e.textContent??``,n=typeof e.attrs.reason==`string`?e.attrs.reason:``,r=e.attrs.originalSpan;return{type:`rawMdxFallback`,value:t,data:{reason:n,originalSpan:r&&typeof r==`object`&&`start`in r&&`end`in r?{start:Number(r.start)||0,end:Number(r.end)||0}:{start:0,end:0}}}}),i.jsxInline&&(n.jsxInline=e=>{let t=e.attrs.componentName||``;if(t&&e.attrs.sourceDirty)return CB(t,e,qq.get(t)?.props);let n=e.attrs.attributes,r=e.attrs.sourceRaw||e.textContent||``;return{type:`mdxJsxTextElement`,name:t||null,attributes:Array.isArray(n)?n:[],children:[],data:{sourceRaw:String(r)}}}),i.mathInline&&(n.mathInline=e=>{let t=e.attrs.formula??``,n=e.attrs.id;if(typeof n==`string`&&n.length>0)return{type:`mdxJsxTextElement`,name:`InlineMath`,attributes:[{type:`mdxJsxAttribute`,name:`formula`,value:t},{type:`mdxJsxAttribute`,name:`id`,value:n}],children:[]};let r=e.attrs.sourceDelimiter;return{type:`inlineMath`,value:t,...typeof r==`string`&&r.length>0?{data:{sourceDelimiter:r}}:{}}}),i.wikiLink&&(n.wikiLink=e=>{let t=e.attrs.target??``,n=e.attrs.anchor??null,r=e.attrs.alias??null,i=r||(n?`${t}#${n}`:t);return{type:`wikiLink`,value:i,data:{target:t,anchor:n,alias:r,sourceTarget:typeof e.attrs.sourceTarget==`string`?e.attrs.sourceTarget:null,sourceAnchor:typeof e.attrs.sourceAnchor==`string`?e.attrs.sourceAnchor:null,sourceAlias:typeof e.attrs.sourceAlias==`string`?e.attrs.sourceAlias:null},children:[{type:`text`,value:i}]}}),i.tag&&(n.tag=e=>({type:`tag`,value:String(e.attrs.value??``)})),i.wikiLinkEmbed&&(n.wikiLinkEmbed=e=>{let t=e.attrs.target??``,n=e.attrs.anchor??null,r=e.attrs.alias??null,i=r||(n?`${t}#${n}`:t);return{type:`wikiLinkEmbed`,value:i,data:{target:t,anchor:n,alias:r},children:[{type:`text`,value:i}]}}),a.emphasis&&(r.emphasis=zW(`emphasis`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),a.strong&&(r.strong=zW(`strong`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),a.code&&(r.code=(e,t,n)=>{let r=e.attrs.sourceFenceChar,i=e.attrs.sourceFenceLength;return Xq(n,{sourceFenceChar:r,sourceFenceLength:i,sourcePadded:e.attrs.sourcePadded===!0||void 0})}),a.strike??a.delete){let e=a.strike?`strike`:`delete`;r[e]=zW(`delete`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter===`~`?`~`:`~~`}}))}return a.highlight&&(r.highlight=zW(`mark`)),a.underline&&(r.underline=zW(`underline`,e=>({data:{sourceForm:e.attrs.sourceForm===`ins`?`ins`:`u`}}))),a.comment&&(r.comment=zW(`comment`,e=>({data:{sourceForm:e.attrs.sourceForm===`html`?`html`:`percent`}}))),i.commentBlock&&(n.commentBlock=RW(`commentBlock`,e=>({data:{sourceForm:e.attrs.sourceForm===`html`?`html`:`percent`,sourceLayout:e.attrs.sourceLayout===`inline`?`inline`:`block`}}))),i.footnoteReference&&(n.footnoteReference=e=>{let t=String(e.attrs.identifier??``);return{type:`footnoteReference`,identifier:t,label:e.attrs.label?String(e.attrs.label):t}}),i.footnoteDefinition&&(n.footnoteDefinition=RW(`footnoteDefinition`,e=>({identifier:String(e.attrs.identifier??``),label:e.attrs.label?String(e.attrs.label):String(e.attrs.identifier??``)}))),a.link&&(r.link=(e,t,n)=>{if(e.attrs.sourceForm===`wikiembed`){let t=typeof e.attrs.target==`string`&&e.attrs.target.length>0?e.attrs.target:e.attrs.href??``,r=typeof e.attrs.anchor==`string`&&e.attrs.anchor.length>0?e.attrs.anchor:null,i=typeof e.attrs.alias==`string`&&e.attrs.alias.length>0?e.attrs.alias:null,a=typeof e.attrs.sourceTarget==`string`?e.attrs.sourceTarget:null,o=typeof e.attrs.sourceAnchor==`string`?e.attrs.sourceAnchor:null,s=typeof e.attrs.sourceAlias==`string`?e.attrs.sourceAlias:null,c=i||(r?`${t}#${r}`:t),l=n.map(e=>`value`in e&&typeof e.value==`string`?e.value:``).join(``);return l!==c&&l.trim().length>0&&!l.includes(`]]`)&&(i=l,c=l),{type:`wikiLinkEmbed`,value:c,data:{target:t,anchor:r,alias:i,sourceTarget:a,sourceAnchor:o,sourceAlias:s},children:[{type:`text`,value:c}]}}let r=e.attrs.linkStyle;if(r===`autolink`)return{type:`link`,url:e.attrs.href??``,title:null,children:n,data:{sourceStyle:`autolink`}};if(r===`gfm-autolink`)return{type:`link`,url:e.attrs.href??``,title:null,children:n,data:{sourceStyle:`gfm-autolink`}};if(r===`inline`||!r){let t={};e.attrs.sourceUrlForm===`angle-bracketed`&&(t.sourceUrlForm=`angle-bracketed`);let r=e.attrs.sourceTitleMarker;return(r===`single`||r===`double`||r===`paren`)&&(t.sourceTitleMarker=r),{type:`link`,url:e.attrs.href??``,title:e.attrs.title??null,children:n,...Object.keys(t).length>0?{data:t}:{}}}return{type:`linkReference`,identifier:(e.attrs.refLabel??``).toLowerCase(),label:e.attrs.refLabel,referenceType:r,children:n}}),a.escapeMark&&(r.escapeMark=(e,t,n)=>{for(let e of n)if(e.type===`text`&&e.value){let t=e;t.data??={},t.data.escapedChars??=[];for(let e=0;e<t.value.length;e++)t.data.escapedChars.push({offset:e,char:t.value[e]})}return n.length===1?n[0]:n}),a.sourceLiteral&&(r.sourceLiteral=(e,t,n)=>{let r=typeof e.attrs.sourceRaw==`string`?e.attrs.sourceRaw:``;if(n.length===1&&n[0]?.type===`text`){let e=n[0],t=r||e.value;return tk(t,e.value)&&(e.data??={},e.data.sourceRaw=t),e}return{type:`text`,value:n.filter(e=>e.type===`text`).map(e=>e.value??``).join(``)||r}}),{nodeHandlers:n,markHandlers:r}}const uve=new Set([`img`,`video`,`audio`,`mark`,`u`,`ins`]);new Map(QB.flatMap(e=>e.surface===`compat`&&uve.has(e.rendersAs)?[[e.name,e]]:[])),Np(`<>`);var Qq={SINGLE_TILDE:0,COMPARISON_OPERATORS:5,HTML_TAGS:10,SETEXT_HEADINGS:15,LINKS:20,BOLD_ITALIC:30,BOLD:35,ITALIC_DOUBLE_UNDERSCORE:40,ITALIC_SINGLE_ASTERISK:41,ITALIC_SINGLE_UNDERSCORE:42,INLINE_CODE:50,STRIKETHROUGH:60,KATEX:70,INLINE_KATEX:75,DEFAULT:100};Qq.SINGLE_TILDE,Qq.COMPARISON_OPERATORS,Qq.HTML_TAGS,Qq.SETEXT_HEADINGS,Qq.LINKS,Qq.BOLD_ITALIC,Qq.BOLD,Qq.ITALIC_DOUBLE_UNDERSCORE,Qq.ITALIC_SINGLE_ASTERISK,Qq.ITALIC_SINGLE_UNDERSCORE,Qq.INLINE_CODE,Qq.STRIKETHROUGH,Qq.KATEX,Qq.INLINE_KATEX,ug().use(w_).use(Uh);const $q=U(bt),dve=U(iee),fve=V({alwaysOn:L().int().nonnegative(),onTrigger:L().int().nonnegative(),onDemand:L().int().nonnegative()}).strict();V({intents:B(V({satisfierId:I().min(1),desired:U([`present`,`absent`])}).loose()),...Ud,summary:Wd}).loose();const pve=V({satisfierId:I(),agentId:I(),piece:I(),scope:I(),kind:I(),pathId:I().optional(),desired:U([`present`,`absent`]),action:U(va),errorId:I().optional()}).loose(),mve=V({kind:I(),satisfierIds:B(I()),agentIds:B(I()),pathId:I().optional(),blockedReason:I().optional()}).loose(),hve=V({state:I(),strictness:B(U(ga)).optional()}).loose(),gve=V({probes:V({env:U([`desktop`,`local-web`,`remote-web`]),satisfiers:H(I(),hve)}).loose(),detection:V({detected:B(I()),probed:R()}).loose()}).loose();V({actions:B(pve),conflicts:B(mve),withheld:B(I()),snapshot:gve}).loose(),V({entries:B(V({level:U([`info`,`warn`,`error`]),message:I().max(8192),event:I().optional(),fields:H(I(),z()).optional(),ts:L().optional(),sourceId:I().optional(),lineNumber:L().optional()}).loose()).max(100),droppedSinceLastFlush:L().int().min(0).optional()}).loose(),V({accepted:L().int().min(0)}).loose();const _ve=V({exact:I().min(1),prefix:I(),suffix:I(),start:L().int().nonnegative(),end:L().int().nonnegative()}),vve=B($i([I(),L().int().nonnegative()])),yve=ea(`kind`,[V({kind:W(`body`)}),V({kind:W(`property`),key:I().min(1),path:vve.default([])})]).default({kind:`body`}),bve=U([`anchored`,`orphaned`,`resolved`]),eJ=V({threadId:I().min(1),docName:I().min(1),target:yve,anchor:_ve.nullable(),state:bve,queued:R(),latestComment:I(),createdBy:I().min(1),createdAt:L(),updatedAt:L().optional()}),tJ=V({docName:I(),instruction:I(),property:I().nullable(),passage:V({exact:I(),prefix:I(),suffix:I()}).nullable(),anchorLost:R(),passageRepeats:R()}).loose(),nJ=V({threadId:I(),ok:W(!0)}),rJ=V({threadId:I(),ok:W(!1),error:W(`not-found`)});V({threads:B(eJ)}).loose(),V({meta:eJ,orphaned:R()}).loose(),V({threadId:I()}).loose(),V({meta:eJ,payload:tJ}).loose(),V({results:B($i([nJ.extend({meta:eJ,payload:tJ}),rJ]))}).loose(),V({results:B($i([nJ.extend({meta:eJ}),rJ]))}).loose();const xve=V({status:I().min(1),reason:I()}).loose();V({docName:I().min(1),content:I(),lifecycle:xve.nullable()}).loose(),V({documents:B(V({kind:U([`document`,`asset`,`folder`,`file`]).default(`document`),docName:I().min(1).optional(),docExt:I().min(1).default(`.md`),size:L().int().nonnegative(),modified:I().min(1),isSymlink:R().default(!1),canonicalDocName:I().nullable().default(null),targetPath:I().nullable().default(null),path:I().min(1).optional(),assetExt:I().min(1).optional(),mediaKind:U([`image`,`video`,`audio`,`pdf`,`text`,`mermaid`,`excalidraw`]).nullable().optional(),referencedBy:B(I().min(1)).optional(),hasChildren:R().optional()}).loose().refine(e=>e.kind===`document`?e.docName!==void 0&&e.path===void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0&&e.hasChildren===void 0:e.kind===`folder`?e.docName===void 0&&e.path!==void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.kind===`file`?e.path!==void 0&&e.mediaKind===void 0&&e.referencedBy===void 0&&e.hasChildren===void 0:e.path!==void 0&&e.assetExt!==void 0&&e.referencedBy!==void 0&&e.hasChildren===void 0,{message:`document/asset/folder/file kind must match its required fields (document → docName; asset → path+assetExt+referencedBy; folder → path only, no docName; file → path, no mediaKind/referencedBy/hasChildren)`})),truncated:R().optional()}).loose();const Sve=V({source:I().min(1),anchor:I().nullable(),title:I(),snippet:I().nullable()}).loose();V({docName:I().min(1),backlinks:B(Sve)}).loose(),V({counts:H(I().min(1),L().int().nonnegative())}).loose(),V({counts:H(I().min(1),L().int().nonnegative())}).loose();const Cve=ea(`kind`,[V({kind:W(`doc`),docName:I().min(1),anchor:I().nullable(),title:I(),snippet:I().nullable()}).loose(),V({kind:W(`external`),url:I().min(1),title:I(),snippet:I().nullable()}).loose()]),wve=V({role:I().min(1),sourceForm:I().min(1),targetKind:I().min(1),href:I(),resolvedTarget:I().nullable(),status:I().min(1),reason:I().nullable(),resolutionMethod:I().min(1),fallbackTarget:I().nullable().default(null),range:V({start:L().int().nonnegative(),end:L().int().nonnegative()}),line:L().int().nonnegative(),column:L().int().nonnegative(),definition:V({label:I(),line:L().int().nonnegative()}).nullable().default(null)}).loose();V({docName:I().min(1),forwardLinks:B(Cve),localTargets:B(wve).optional()}).loose();const Tve=ea(`kind`,[V({id:I().min(1),kind:W(`doc`),docName:I().min(1),anchor:I().nullable(),label:I(),cluster:I().nullable(),category:I().nullable(),tags:B(I()).nullable(),managed:R().optional()}).loose(),V({id:I().min(1),kind:W(`external`),url:I().min(1),label:I()}).loose()]),Eve=V({source:I().min(1),target:I().min(1)}).loose();V({nodes:B(Tve),links:B(Eve)}).loose();const Dve=V({ts:L().int().min(0),url:I(),method:I(),ua:I().optional(),origin:I().optional(),referer:I().optional(),host:I().optional(),remote:I().optional(),secChUa:I().optional(),secChUaMobile:I().optional(),secChUaPlatform:I().optional(),secFetchSite:I().optional(),secFetchDest:I().optional(),secFetchMode:I().optional(),secFetchUser:I().optional()}).loose(),Ove=V({app:$i([W(`cursor`),W(`codex`),W(`claude`),qi()]),signals_fired:B(I())}).loose();V({entries:B(Dve),count:L().int().min(0),detection:Ove}).loose();const iJ=V({path:I().min(1),code:U([`M`,`A`,`D`,`R`,`C`,`U`,`T`,`?`,`!`,` `]),origPath:I().min(1).optional(),syncScoped:R(),open:ea(`kind`,[V({kind:W(`doc`),docName:I().min(1)}),V({kind:W(`asset`),path:I().min(1)})]).optional()}).loose();V({branch:I().nullable(),detached:R(),upstream:I().nullable(),staged:B(iJ),notStaged:B(iJ),untracked:B(iJ),incoming:B(iJ),truncated:R(),readable:R().default(!0)}).loose();const kve=U([`AWAITING_CHECKS`,`LOCKED`,`MERGEABLE`,`QUEUED`,`UNMERGEABLE`]),Ave=U([`BEHIND`,`BLOCKED`,`CLEAN`,`DIRTY`,`DRAFT`,`HAS_HOOKS`,`UNKNOWN`,`UNSTABLE`]),jve=U([`APPROVED`,`CHANGES_REQUESTED`,`REVIEW_REQUIRED`]),Mve=U([`ERROR`,`EXPECTED`,`FAILURE`,`PENDING`,`SUCCESS`]),Nve=V({mergeQueue:V({position:L().int().nonnegative(),state:kve.nullable().catch(null)}).nullable().catch(null),autoMerge:R(),mergeState:Ave.nullable().catch(null),reviewDecision:jve.nullable().catch(null),checks:Mve.nullable().catch(null)}).loose(),Pve=V({kind:U([`pull`,`issue`]),repo:I().min(1),number:L().int().positive(),title:I(),author:I().nullable(),createdAt:I(),lifecycle:U([`open`,`draft`,`merged`,`closed`,`completed`,`not-planned`]),additions:L().int().nonnegative().optional(),deletions:L().int().nonnegative().optional(),status:Nve.optional()}).loose();V({url:I()}).loose(),ea(`ok`,[V({ok:W(!0),preview:Pve}).loose(),V({ok:W(!1),reason:I()}).loose()]),V({writers:B(V({id:I().min(1),name:I().optional(),email:I().optional()}).loose()).optional(),summary:Wd,...Ud}).loose(),V({checkpointRef:I().min(1)}).loose();const Fve=V({v:L().int().optional(),id:I().min(1),name:I().min(1),colorSeed:I().optional(),docs:B(I()),summaries:B(I()).optional()}).loose();V({entries:B(V({sha:I().min(1),timestamp:I().min(1),author:I(),authorEmail:I(),type:U([`checkpoint`,`wip`,`upstream`,`park`]),message:I(),contributors:B(Fve),checkpoint:z().nullable(),parentSha:I().nullable().optional()}).loose()),total:L().int().nonnegative().optional(),truncated:R().optional(),hasMore:R().optional()}).loose(),V({sha:I().regex(/^[0-9a-f]{40}$/i),content:I(),timestamp:I(),author:I()}).loose(),V({contentDir:I().min(1),pathSeparator:U([`/`,`\\`]),symlinkResolved:R()}).loose(),B(ea(`source`,[V({docName:I().min(1),timestamp:I().min(1),size:L().int().nonnegative(),source:W(`flat`)}).loose(),V({docName:I().min(1),timestamp:I().min(1),source:W(`timeline`),sha:I().min(1)}).loose()])).meta({description:"Flat array of rescue buffer entries; discriminated via `source`."});const Ive=V({domain:I().min(1),title:I().optional(),description:I().optional(),siteName:I().optional(),faviconDataUri:I().optional()}).loose();V({url:I()}).loose(),ea(`ok`,[V({ok:W(!0),metadata:Ive}).loose(),V({ok:W(!1),reason:I()}).loose()]),V({orphans:B(V({docName:I().min(1),title:I()}).loose())}).loose(),V({hubs:B(V({docName:I().min(1),title:I(),count:L().int().nonnegative()}).loose())}).loose();const Lve=V({source:I().min(1),title:I(),snippet:I().nullable()}).loose();V({deadLinks:B(V({target:I().min(1),sources:B(Lve)}).loose())}).loose(),V({target:V({docName:I().min(1),title:I(),aliases:B(I())}).loose(),mentions:B(V({source:I().min(1),excerpt:I(),offset:L().int().nonnegative()}).loose()),truncated:R()}).loose(),V({projectPath:I().min(1)}).loose();const Rve=U([`not-a-git-worktree`,`init-failed`]);ea(`ok`,[V({ok:W(!0),projectPath:I().min(1)}).loose(),V({ok:W(!1),reason:Rve,message:I().min(1)}).loose()]),V({host:I().min(1).optional()}).loose(),V({host:I().min(1).optional(),token:I().min(1)}).loose(),V({host:I(),login:I()}).loose(),V({host:I().refine(hc,{message:`Host must be a hostname with an optional :port, with no scheme or path`}),username:I().min(1),token:I().min(1)}).loose(),V({host:I(),login:I()}).loose(),V({key:I().min(1)}).loose(),V({keyPresent:R()}).loose();const zve=U([`no_key`,`invalid_endpoint`,`rate_limit`,`timeout`,`http_error`,`network`,`dims_mismatch`,`malformed_response`]);ea(`ok`,[V({ok:W(!0),endpoint:I().min(1),model:I().min(1),dimensions:L().int().positive()}).loose(),V({ok:W(!1),endpoint:I().min(1),model:I().min(1),reason:zve,status:L().int().optional()}).loose()]),V({name:I().refine(e=>e.trim().length>0,{message:`name must be non-empty`}),email:I().refine(e=>e.trim().length>0,{message:`email must be non-empty`})}).loose(),V({authenticated:R()}).loose(),V({channel:U([`login`,`gh-login`]).default(`login`)}).loose(),V({}).loose();const Bve=V({stackIndex:L().int().min(0),ts:L().int().min(0),additions:L().int().min(0),deletions:L().int().min(0)}).loose(),Vve=V({docName:I().min(1),additionsTotal:L().int().min(0),deletionsTotal:L().int().min(0),lastTs:L().int().min(0),bursts:B(Bve)}).loose(),Hve=V({displayName:I().min(1),color:I().min(1),icon:I().optional(),connectionId:I().min(1)}).loose();V({sessionAlive:R(),agent:Hve.nullable(),files:B(Vve)}).loose(),V({diff:I(),before:I(),after:I(),properties:kP,generatedAt:L().int().min(0)}).loose(),V({}).loose(),V({}).loose(),V({}).loose(),V({}).loose(),V({}).loose(),V({}).loose();const Uve=V({displayName:I().min(1),icon:I(),color:I().min(1),currentDoc:I().nullable(),mode:U([`idle`,`writing`]),ts:L().int().min(0)}).loose();V({presence:H(I().min(1),Uve)}).loose();const Wve=V({sessionId:I().min(1),agentType:I().min(1),ts:L().int().min(0),insertedChars:L().int().min(0),deletedChars:L().int().min(0)}).loose();V({effects:B(V({"doc.name":I().min(1),entries:B(Wve)}).loose())}).loose(),V({decisions:B(V({ts:L().int().min(0),decision:I().min(1),kind:I().min(1),"doc.name":I().min(1),pathRole:I().min(1)}).loose())}).loose(),H(I().min(1),R()).meta({description:`Flat boolean record keyed by agent-scheme name (claude / codex / cursor). True = installed.`}),V({path:I().min(1,`path must be non-empty`)}).loose(),V({}).loose();const Gve=V({fromDocName:I().min(1),toDocName:I().min(1)}).loose(),Kve=V({fromPath:I().min(1),toPath:I().min(1)}).loose();V({}).loose(),V({path:I().min(1),...Ud,summary:Wd}).loose(),V({docName:I().min(1)}).loose(),V({path:I().min(1),...Ud,summary:Wd}).loose(),V({path:I().min(1)}).loose(),V({kind:U([`file`,`folder`]),path:I().min(1),...Ud,summary:Wd}).loose(),V({kind:U([`file`,`folder`]),path:I().min(1),duplicatedDocNames:B(I().min(1))}).loose(),V({pages:B(V({docName:I().min(1),title:I(),docExt:I().min(1),size:L().int().nonnegative(),modified:I().min(1),icon:I().min(1).max(2048).optional()}).loose())}).loose();const qve=V({level:L().int().min(1).max(6),text:I(),slug:I()}).loose();V({docName:I().min(1),headings:B(qve)}).loose();const Jve=V({docName:I().min(1),rewrites:L().int().nonnegative()}).loose();V({kind:U([`file`,`folder`,`asset`]),fromPath:I().min(1),toPath:I().min(1),...Ud,summary:Wd}).loose(),V({renamed:B(Gve),renamedAssets:B(Kve),rewrittenDocs:B(Jve).optional(),summary:Kd.optional()}).loose(),V({kind:U([`file`,`folder`,`asset`]),path:I().min(1),...Ud}).loose(),V({deletedDocNames:B(I().min(1))}).loose(),V({kind:U([`file`,`folder`,`asset`]),path:I().min(1),...Ud,summary:Wd}).loose(),V({deletedDocNames:B(I().min(1))}).loose(),V({docName:I().min(1),commitSha:I().regex(/^[0-9a-f]{40}$/i,{message:`commitSha must be a 40-char git SHA`}),summary:Wd,...Ud}).loose(),V({restoredFrom:I().min(1),timestamp:I().min(1),summary:Kd.optional(),warnings:Zd.optional()}).loose();const Yve=/^#[0-9a-fA-F]{6}$/,Xve=V(Object.fromEntries(el.map(e=>[e,I().regex(Yve,`must be a #rrggbb hex color`)]))),aJ=I().min(1).refine(al,{message:`must contain a non-whitespace character`}),oJ=V({name:aJ,author:aJ.optional(),variant:U([`dark`,`light`]),palette:Xve}).loose();V({name:I().min(1),scheme:oJ,stem:I().min(1).optional(),extension:U([`.yaml`,`.yml`]).optional()}).loose(),V({id:I().min(1),filename:I().min(1)}).loose(),V({id:I().min(1),scheme:oJ}).loose(),V({id:I().min(1),filename:I().min(1)}).loose(),ea(`existed`,[V({existed:W(!1)}).loose(),V({existed:W(!0),filename:I().min(1),scheme:oJ}).loose()]),V({themes:B(ea(`ok`,[V({ok:W(!0),id:I().min(1),filename:I().min(1),scheme:oJ}),V({ok:W(!1),filename:I().min(1),id:I().min(1).optional(),code:I().min(1),conflictingFilenames:B(I().min(1)).min(2).optional()})])),truncated:R()}).loose();function Zve(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function Qve(e){let t=Zve(e).at(-1);return t!==void 0&&Dd.some(e=>t.toLowerCase().endsWith(e))}V({tags:B(V({name:I().min(1),count:L().int().nonnegative(),isLeaf:R()}).loose())}).loose();const $ve=V({docName:I().min(1),title:I(),matchingTags:B(I().min(1)),snippet:I().nullable()}).loose();V({name:I().min(1),docs:B($ve)}).loose(),V({folder:z(),frontmatter_local:H(I(),z()).nullable(),warnings:B(I()).optional().meta({description:"Non-fatal degradations of this response, one per entry; the field each affects is absent, null, or incomplete — the aligned `warningCodes` entry names which field and how."}),warningCodes:B(U([`symlink-refused`,`malformed-yaml`,`unverifiable`,`templates-symlink-refused`,`templates-unverifiable`])).optional().meta({description:"Machine-readable codes aligned 1:1 with `warnings`; switch on these, never on the English. `symlink-refused` / `malformed-yaml` / `unverifiable`: this folder's own `.ok/frontmatter.yml` (a symlink, malformed YAML, or an lstat failure) — `frontmatter_local` is null. `templates-symlink-refused` / `templates-unverifiable`: the `.ok/templates` directory on this folder, or a `.ok` or `.ok/templates` directory on an ancestor it inherits from — a symlink (wherever it points, dangling included), or a non-ENOTDIR `lstat` failure — `folder.templates_available` omits that directory's templates and may still list others. A non-directory `.ok` / `.ok/templates` (ENOTDIR) is treated as empty and yields no `templates-*` code. This folder's own symlinked `.ok` is a 400, never a warning."})}).loose(),V({path:I(),frontmatter:H(I(),z()).optional()}).loose(),V({applied:z()}).loose();const sJ=H(I(),z()).meta({description:`Free-form frontmatter map embedded in template payloads.`});V({template:V({name:I().min(1),folder:I(),scope:U([`local`,`inherited`]),path:I().min(1),frontmatter:sJ,body:I()}).strict()}).strict(),V({templates:B(V({name:I().min(1),title:I().optional(),description:I().optional(),path:I().min(1),source_folder:I()}).strict()),truncated:R()}).strict(),V({folder:I(),name:I(),body:Bd.optional(),frontmatter:sJ.optional(),...Ud,summary:Wd}).strict(),V({path:I().min(1),created:R(),warnings:B(I())}).strict(),V({sourcePath:I().min(1),targetFolder:I(),name:I().optional(),title:I().optional(),deleteSource:R().optional(),...Ud,summary:Wd}).strict(),V({path:I().min(1),created:R(),warnings:B(I())}).strict(),V({existed:R(),path:I().min(1)}).strict(),V({fromFolder:I(),fromName:I(),toFolder:I(),toName:I(),body:Bd.optional(),frontmatter:sJ.optional(),...Ud,summary:Wd}).strict(),V({from:I().min(1),to:I().min(1),committed:R()}).strict();const cJ=U(Ed),eye=/^[a-z0-9-]+$/,lJ=V({name:I(),description:I(),metadata:V({pack:I()}).strict().optional()}).strict();V({skill:V({name:I().min(1),scope:cJ,path:I().min(1),frontmatter:lJ,body:I(),files:B(V({path:I().min(1),text:I().nullable()})).optional(),managed:R().optional()}).strict()}).strict();const tye=V({source:I().min(1),publisher:I().optional(),skill:I().optional(),marketplaceUrl:I().optional(),importedAt:I().min(1),autoUpdate:R().optional()}).strict(),nye=V({name:I().min(1),description:I().optional(),scope:cJ,path:I().min(1),canonicalPath:I().min(1).optional(),filePaths:B(I()).optional(),absolutePath:I().min(1).optional(),installed:R(),hosts:B(I()),hostQualifier:I().optional().meta({description:"Set on a GLOBAL entry that shares its name with a distinct-content bundle in another host dir AND is not the by-name default: the host id whose root holds THIS bundle. Doc-name builders append it (`__skill__/global/<name>@<host>`) so each same-named bundle keeps its own tab and its own write-back path; the default bundle keeps the stable unqualified name."}),driftPaths:B(I()).optional().meta({description:`Recorded locations whose on-disk form (copy vs symlink) no longer matches what OK last wrote there — evidence another tool rewrote the path.`}),hostAliases:H(I(),I()).optional().meta({description:`Host skills roots that are symlink ALIASES of another location (host id → base-relative target root). An aliased folder is a derived view — no menu row, never a write target; the host's icon rides the target root's row.`}),conflictHosts:B(I()).optional().meta({description:`Hosts whose dir holds a DIFFERENT same-name skill (fork/conflict) — occupied, not this skill.`}),symlinkedHosts:B(I()).optional(),installableEditors:B(I()).optional(),hubOffered:R().optional().meta({description:"Whether the vendor-neutral `.agents/skills` hub is a live destination at this scope on THIS machine — server-computed via the same predicate that filters the Folders surface, so the install menu and Settings cannot disagree. True when the project already uses the hub OR a host that reads it is installed (`HUB_READER_EDITORS`)."}),linkMode:R().optional(),customPlacements:B(V({path:I(),mode:U([`copy`,`link`])}).strict()).optional(),plugin:V({name:I().min(1),marketplace:I().min(1),provider:I().min(1),url:I().optional()}).strict().optional(),managed:R().optional(),origin:tye.optional(),pack:I().optional(),modified:R().optional(),revertable:R().optional(),ignored:R().optional(),size:fve.optional()}).strict();V({name:I().min(1),scope:cJ,apply:R().optional()}).strict(),V({line:I().min(1),gitignorePath:I().min(1),applied:R(),alreadyTracked:R().optional()}).strict(),V({skills:B(nye),truncated:R()}).strict(),V({scope:cJ.default(`project`),name:I().meta({description:`Managed skill name to create or update.`}),body:Bd.optional(),frontmatter:lJ,...Ud,summary:Wd}).strict();const uJ=[`skill-name-vendor-word`,`skill-body-too-long`],dJ=B(U(uJ)).meta({description:"Machine-readable codes aligned 1:1 with `warnings` (`warnings[i]` is the display text for `warningCodes[i]`)."});V({path:I().min(1),created:R(),warnings:B(I()),warningCodes:dJ}).strict(),V({scope:cJ.default(`project`),name:I(),dryRun:R().optional(),setAutoUpdate:R().optional(),...Ud,summary:Wd}).strict(),V({name:I().min(1),updated:R(),source:I().min(1),localBody:I().optional(),upstreamBody:I().optional(),gitTracked:R().optional(),warnings:B(I()),warningCodes:dJ}).strict(),V({scope:cJ.default(`project`),name:I(),...Ud,summary:Wd}).strict(),V({name:I().min(1),baselineRef:I().min(1),restoredFiles:B(I()),warnings:B(I())}).strict();const fJ=`This member also carries the one bookkeeping failure that does not undo the operation: the content change landed, but a state file this server keeps beside it refused to be rewritten because it could not be read, so the install or import records still describe the old state until an operator repairs that file. Absent when there is nothing to report; a server that predates this member omits it, so treat its absence as no warning rather than as an error.`;V({existed:R(),path:I().min(1),warnings:B(I()).optional().meta({description:`Present when this delete removed a directory a retention record ties to a recovery copy an earlier failed move kept, whose source was never verified unchanged — either because this server verified the deleted directory against the copy that record describes, or because it could not read the directory and so could not confirm either way. Each entry says which of the two it is; neither claims more than the check established. ${fJ}`})}).strict(),V({scope:cJ.default(`project`),fromName:I(),toName:I(),body:Bd.optional(),frontmatter:lJ.optional(),...Ud,summary:Wd}).strict(),V({from:I().min(1),to:I().min(1),committed:R(),warnings:B(I()).optional().meta({description:`Present when the rename itself completed but something beside it did not. ${fJ}`})}).strict(),V({name:I(),toName:I().optional().meta({description:"Name for the skill at the destination scope; defaults to `name`. The SKILL.md `name` frontmatter is rewritten to match."}),fromScope:cJ,toScope:cJ,...Ud,summary:Wd}).strict(),V({scope:cJ,path:I().optional(),droppedLocations:B(I()).default([]).meta({description:"Locations the skill occupied at the source that were removed and not re-created at the destination: the `agents` hub and custom roots, which projection does not cover. Entries are install location ids, so they can be passed straight back as an install `add` list with `scope` set to the destination scope; custom roots resolve against that scope's base."}),warnings:B(I()).optional().meta({description:`Present when the move itself completed but something beside it did not. ${fJ}`})}).strict().meta({description:"Scope-move result. Rename paths deliberately do not emit authoring warnings, consistent with same-scope rename and duplicate. Content-authoring and import responses carry those warnings and their codes. The Skills Studio client parses `droppedLocations` off the wire but deliberately does not render it yet; how a human is told what was removed is an open product decision."}),V({scope:cJ,name:I(),toName:I(),...Ud,summary:Wd}).strict(),V({name:I().min(1)}).strict(),V({name:I(),home:I().min(1)}).strict(),V({docName:I().min(1)}).strict();const pJ=U([`reference`,`script`,`file`]);V({scope:cJ.default(`project`),name:I(),path:I().min(1),content:I(),...Ud,summary:Wd}).strict().superRefine((e,t)=>{Qve(e.path)&&zd(e.content,t,[`content`])}),V({path:I().min(1),created:R(),kind:pJ,content:R()}).strict(),V({scope:cJ.default(`project`),name:I(),from:I().min(1),to:I().min(1),...Ud,summary:Wd}).strict(),V({from:I().min(1),to:I().min(1),fromDocName:I().optional(),toDocName:I().optional()}).strict(),V({path:I().min(1),kind:pJ,text:I()}).strict(),V({path:I().min(1),existed:R(),kind:pJ}).strict();const mJ=$i([dve,W(`agents`)]),hJ=I().min(1).refine(e=>!e.startsWith(`/`)&&!e.startsWith(`~`)&&!/^[A-Za-z]:/.test(e),{error:`a custom root is base-relative (e.g. ".tim/skills"), not absolute or ~-prefixed`}).refine(e=>e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{error:`a custom root may not contain "..", "." or empty path segments`}).refine(e=>e.includes(`/`),{error:`a custom root is a path (e.g. ".tim/skills") — bare editor names are host ids`}),gJ=$i([mJ,hJ]);V({scope:cJ.default(`project`),name:I(),targets:B(mJ).optional().meta({description:'SET-EXACT install targets (editor ids, plus "agents" for the .agents hub — in-place skills only): the COMPLETE resulting host set. Omit to use project-configured editors; pass [] to uninstall everywhere. Stateless callers should prefer `add`/`remove`.'}),add:B(gJ).optional().meta({description:`Locations to ADD the skill to (everything else untouched). Editor ids fan out a managed copy/symlink; a custom root path (".tim/skills") places the bundle there.`}),remove:B(gJ).optional().meta({description:"Locations to REMOVE the skill from (lossless only — a hand-edited fork is refused, never deleted). The source cannot be removed; move it first with `source`."}),mode:U([`copy`,`link`]).optional().meta({description:`"link": one real folder (the source); every other location becomes a symlink to it. "copy": independent real folders, refreshed from the source until hand-edited (a hand-edit forks that copy). Converts existing locations losslessly. Omit to follow the form the skill already uses.`}),source:gJ.optional().meta({description:`Move the skill's REAL folder to this location (the old source becomes a symlink to it — never a removal). Sticky across rescans.`}),linkMode:R().optional(),setSource:I().min(1).optional(),place:V({dir:I().min(1).meta({description:`Project-relative directory the bundle dir is created under (e.g. ".windsurf/skills").`}),mode:U([`copy`,`link`])}).strict().optional(),convert:V({target:gJ.meta({description:`The installed location to convert — an editor id, "agents", or a recorded custom placement path.`}),mode:U([`copy`,`link`]).meta({description:`"link": replace this location with a symlink to the source. "copy": replace it with an independent real folder.`})}).strict().optional(),unplace:V({path:I().min(1).meta({description:`The recorded placement bundle path (e.g. ".windsurf/skills/my-skill").`})}).strict().optional(),...Ud,summary:Wd,fork:V({editor:I().min(1),action:U([`align`,`make-source`,`rename`]),toName:I().optional()}).strict().optional()}).strict().refine(e=>e.targets===void 0||e.add===void 0&&e.remove===void 0,{error:"`targets` is set-exact; `add`/`remove` are additive — use one style per call"}).refine(e=>e.fork===void 0||e.targets===void 0&&e.add===void 0&&e.remove===void 0&&e.source===void 0&&e.setSource===void 0,{error:"`fork` is its own operation — run it in a separate call"}).refine(e=>e.fork?.action!==`rename`||e.fork.toName!==void 0,{error:"`fork.rename` requires `toName`"}).refine(e=>e.source===void 0||e.add===void 0&&e.remove===void 0,{error:"a `source` move is its own operation — run it in a separate call from `add`/`remove`"}).refine(e=>[e.targets!==void 0||e.add!==void 0||e.remove!==void 0,e.place!==void 0,e.unplace!==void 0,e.convert!==void 0,e.source!==void 0||e.setSource!==void 0,e.fork!==void 0].filter(Boolean).length<=1,{error:"one operation per call — membership (`targets`/`add`/`remove`), `place`, `unplace`, `convert`, `source`, and `fork` are mutually exclusive"});const _J=[`no-targets`,`scripts-present`,`name-conflict`,`no-description`,`skill-fork-name-unpatched`,`place-path-invalid`,`place-fork-refused`,`links-not-permitted`];V({name:I().min(1).meta({description:`Managed skill name installed or uninstalled.`}),hosts:B(I()).meta({description:`Editor ids the skill is projected into after the operation; [] is expected after uninstall.`}),scripts:R().meta({description:`True when the skill ships executable scripts, projected but never run.`}),warnings:B(I()).meta({description:`Non-fatal install/uninstall warnings from target projection.`}),warningCodes:B(U(_J)).meta({description:"Machine-readable warning codes aligned with `warnings`."}),placedAt:I().optional(),sourceMovedTo:I().optional()}).strict(),V({scope:cJ.default(`project`),name:I().meta({description:`Managed skill name to uninstall without deleting source.`})}).strict(),V({name:I().min(1).meta({description:`Managed skill name requested for uninstall.`}),uninstalled:R().meta({description:`True when an install marker existed and was removed; false for an idempotent no-op.`})}).strict(),V({targets:B($q),configured:R(),folders:B(V({scope:cJ,host:I(),root:I(),state:U([`own`,`linked`,`linked-parent`,`absent`]),target:I().optional(),drift:W(!0).optional(),expected:I().optional()}).strict()).optional()}).strict();const vJ=V({action:W(`link`),scope:cJ,root:I().min(1).meta({description:`The folder to link (e.g. ".codex/skills").`}),target:I().min(1).meta({description:`The root it merges into (e.g. ".agents/skills"). Required.`})}),yJ=V({action:W(`unlink`),scope:cJ,root:I().min(1).meta({description:`The linked folder to materialize back.`}),exclude:B(I().min(1)).optional().meta({description:`Skill names to LEAVE OUT when materializing — the folder keeps every other skill it currently sees (as per-skill links) and stops auto-following the target root.`})}).strict(),bJ=V({action:W(`add-root`),scope:cJ,root:hJ.meta({description:`New custom skills root to declare (base-relative, e.g. ".team/skills").`})}).strict(),rye=ea(`action`,[vJ.extend({preview:R().optional().meta({description:`Return the merge plan only (moves, drops, removes, conflicts, strays) — nothing is written.`})}).strict(),yJ,bJ]);ea(`action`,[vJ.strict(),yJ,bJ]),V({folderAction:rye}).strict();const iye=V({moves:B(I()),drops:B(I()),removes:B(I()),replaces:B(I()),conflicts:B(I()),strays:B(I())}).strict();V({targets:B($q),reprojected:B(V({name:I(),hosts:B(I())}).strict()),bundleHosts:B(I()),removedFrom:B(I()),folder:V({moved:B(I()),dropped:B(I()),linked:B(I())}).strict().optional(),preview:iye.optional()}).strict(),V({scope:cJ.default(`project`),name:I(),version:I().regex(/^[0-9a-f]{40}$/i),...Ud,summary:Wd}).strict(),V({name:I().min(1),version:I(),restoredFiles:B(I()),warnings:B(I())}).strict(),V({query:I().optional(),intent:U([`autocomplete`,`full_text`,`omnibar`]).optional(),ranking:U([`navigation`,`relevance`]).optional(),scopes:B(U([`page`,`folder`,`content`,`file`])).optional(),scope:I().optional(),limit:L().int().nonnegative().optional(),semantic:R().optional(),source:U([`omnibar`,`mcp`,`http`]).optional()}).loose();const aye=V({kind:U([`page`,`folder`,`content`,`file`]),path:I().min(1),title:I(),score:L(),signals:H(I(),z()),snippet:I().optional()}).loose(),oye=U([`applied`,`no_match`,`warming`,`incapable`,`provider_error`,`restart_required`,`query_too_short`]),xJ=U([`warm`,`corpus`,`query`,`dimensions`,`configured_dimensions`]),SJ=V({capable:R(),applied:R(),outcome:oye,providerErrorReason:xJ.nullable().optional().catch(null),coverage:V({embedded:L().int().nonnegative(),total:L().int().nonnegative()})}).loose();V({enabled:R(),keyPresent:R(),keyNotRequired:R(),keySource:U([`project`,`file`,`env`]).nullable(),keyHint:I().nullable(),ready:R(),capable:R(),providerError:R().optional(),providerErrorReason:xJ.nullable().optional().catch(null),embedded:L().int().nonnegative(),total:L().int().nonnegative()}).loose(),V({query:I(),intent:U([`autocomplete`,`full_text`,`omnibar`]),results:B(aye),elapsedMs:L().nonnegative(),semantic:SJ.optional(),truncated:R().optional(),ready:R().optional()}).loose();const sye=V({version:I().min(1),recordedAt:I().min(1)}).loose();V({currentVersion:I().min(1),targets:H(I(),sye.nullable())}).loose(),V({scope:cJ.default(`project`),source:I().min(1).meta({description:`External skill source: full skills.sh skill-page URL (https://www.skills.sh/<owner>/<repo>/<skill>, or https://www.skills.sh/site/<hostname>/<skill> for a website catalog), GitHub owner/repo[/subpath], git URL, or local/file path.`}),skill:I().min(1).optional().meta({description:`Specific skill name to import from a multi-skill source.`}),install:R().optional().meta({description:`Pass false to import WITHOUT the default-editor auto-projection (the caller installs explicitly afterwards). Default true.`}),marketplace:R().optional().meta({description:"The source came from a skills.sh listing the user chose (the Explore tab), so the install is reported to skills.sh and counts toward that listing. Off by default: a hand-typed repo must not be announced to skills.sh. Honors the `telemetry.skillInstallReports.enabled` setting and DO_NOT_TRACK."}),...Ud,summary:Wd}).strict(),V({scope:cJ.default(`project`),source:I().min(1).meta({description:`External skill source: full skills.sh skill-page URL, GitHub owner/repo[/subpath], git URL, or local/file path.`}),skills:B(I().min(1)).min(1).max(100).meta({description:`Skill names to import from the source.`}),install:R().optional().meta({description:`Pass false to import WITHOUT the default-editor auto-projection. Default true.`}),marketplace:R().optional().meta({description:"The source came from a skills.sh listing the user chose (a marketplace plugin bundle), so the import is reported to skills.sh as one batched install event and counts toward that listing. Off by default: a hand-typed repo must not be announced to skills.sh. Honors the `telemetry.skillInstallReports.enabled` setting and DO_NOT_TRACK."}),...Ud,summary:Wd}).strict(),V({results:B(V({requested:I(),status:U([`imported`,`already-imported`,`not-found`,`failed`]),name:I().optional(),collisionRenamedFrom:I().optional(),warnings:B(I()),warningCodes:dJ,error:I().optional()}).loose()),imported:L(),alreadyImported:L(),failed:L()}).loose(),V({scope:cJ.default(`project`),names:B(I().min(1)).min(1).max(100).meta({description:`Managed skill names to refresh from their recorded upstreams.`}),...Ud,summary:Wd}).strict(),V({results:B(V({requested:I(),status:U([`updated`,`up-to-date`,`not-found`,`failed`]),source:I().optional(),warnings:B(I()),warningCodes:dJ,error:I().optional()}).loose()),updated:L(),upToDate:L(),failed:L()}).loose();const cye=V({source:I(),ref:I().optional(),contentHash:I(),publisher:I().optional()}).loose();V({name:I().min(1).meta({description:`Managed skill name created or matched.`}),path:I().min(1).meta({description:`Store-relative path to the imported skill source.`}),created:R().meta({description:`True when this request created new source files.`}),alreadyImported:R().meta({description:`True when identical content was already present and no files changed.`}),collisionRenamedFrom:I().optional().meta({description:`Original source name when collision handling renamed the import.`}),provenance:cye,warnings:B(I()).meta({description:`Non-fatal import warnings, such as skipped unsupported files.`}),warningCodes:dJ}).loose();const lye=U([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`,`tags`,`comments`,`lint-config`,`local-targets`]);V({v:W(1),ch:W(`server-info`),seq:L(),serverInstanceId:I().min(1),currentBranch:I().min(1).optional()}).loose(),V({v:W(1),ch:W(`branch-switched`),seq:L(),branch:I().min(1)}).loose(),V({v:W(1),ch:lye,seq:L()}).loose(),V({v:W(1),ch:W(`disk-ack`),seq:L(),docName:I().min(1),sv:I().min(1)}).loose(),V({v:W(1),ch:W(`config-validation-rejected`),seq:L(),docName:I().min(1),error:Qie}).loose(),V({v:W(1),ch:W(`config-ignore-nested-error`),seq:L(),path:I().min(1),error:I().min(1)}).loose(),(()=>{let e=globalThis.Intl.Segmenter;return e?new e(`en`,{granularity:`word`}):null})();const uye=Zi({name:I(),description:I(),files:Zi({skillMd:I(),scripts:B(I()),references:B(I())})}),dye=Zi({pluginProvider:I().optional(),plugin:I().optional(),marketplace:I().optional(),repositoryUrl:I().optional(),version:I().optional(),gitCommitSha:I().optional(),scope:I().optional(),projectPath:I().optional()}),fye=Zi({commands:R(),hooks:R(),mcp:R()}),pye=Zi({...uye.shape,sourceHarness:I(),sourceHarnesses:B(I()),home:I(),provenance:dye,inert:fye,outsideProject:R().optional()}),mye=Zi({schema:W(1),name:I(),version:I(),description:I().optional(),author:Zi({name:I()}).optional(),skills:B(I()),hostCompatibility:B(I()).optional(),capabilities:Zi({scripts:I(),network:I(),inert:B(I())}).optional(),provenance:Zi({source:I(),ref:I(),contentHash:I()}).optional()});V({skills:B(pye),packs:B(mye)}).loose(),V({results:B(V({id:I().min(1),name:I().min(1),source:I().min(1),description:I(),installs:L().int().nonnegative().nullable(),publisher:I().nullable()}).loose()),backend:U([`skills.sh`,`github-fallback`]),degraded:R()}).loose(),V({title:I(),description:I(),image:I().nullable(),skillsUrl:I().nullable(),sourceKind:U([`github`,`site`]),sourceUrl:I()}).loose(),V({skills:B(V({name:I(),description:I().nullable()}).loose())}).loose(),V({kind:U([`local`,`import`,`none`]),scope:U(Ed).optional(),name:I().optional(),dir:I().optional(),source:I().optional(),ref:I().optional(),via:U([`source`,`publisher`]).optional()}).loose();const hye=V({relPath:I(),content:I().nullable()}).loose(),gye=V({provider:I(),plugin:I(),version:I().optional(),marketplace:I().optional(),repositoryUrl:I().optional()}).loose(),_ye=V({provider:I(),plugin:I(),version:I().optional(),description:I().optional(),repositoryUrl:I().optional(),bundledSkills:B(I()),capabilities:V({commands:R(),hooks:R(),mcp:R(),agents:R()}),setupSupported:R()}).loose();V({name:I(),description:I().nullable(),skillMd:I(),files:B(hye),plugin:gye.optional(),pluginBundle:_ye.optional()}).loose();const vye=[`auth-error`,`detached-head`,`dirty-tree`,`diverged-local-commits`,`external-changes-pending`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`no-push-permission`,`non-content-merge-failure`,`protected-branch`,`unsafe-incoming-symlinks`],CJ=e=>e*8+4;CJ(92),CJ(40),Array.from({length:256},(e,t)=>(t+256).toString(16).slice(1));const wJ={fileSystem:`File System`,gitUpstream:`Git (upstream)`,service:`OpenKnowledge (service)`,generator:`OpenKnowledge (generated)`},TJ=`state/bug-reports`,yye=Zi({at:I(),transport:I(),outcome:I(),reference:I().optional(),error:I().optional(),errorCode:I().optional()}),bye=Zi({reason:I(),at:I(),errorCode:I().optional()});Zi({version:L().int().catch(1),id:I(),createdAt:I(),bundleLevel:I(),zipBytes:L().int().nonnegative().catch(0),zipDeleted:R().optional(),state:I(),systemWide:R().optional(),projectSlug:I().nullable().optional(),reference:I().optional(),lastError:bye.optional(),attempts:B(yye).optional(),note:I().optional()}),Zi({version:L().int().catch(1),id:I().optional(),sentAt:I().optional(),reference:I().optional()});const xye=new Map([[`PORT`,[`server`,`port`]],[`OK_BIND`,[`server`,`bind`]],[`OK_EXTERNAL_URL`,[`server`,`externalUrl`]],[`OK_ALLOW_EXTERNAL`,[`server`,`allowExternal`]],[`OK_OPEN_BROWSER`,[`server`,`openBrowser`]],[`OK_IDLE_SHUTDOWN`,[`server`,`idleShutdown`]]]);function Sye(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toUpperCase()}function Cye(e){return`OK_${(e[0]===`server`?e.slice(1):e).map(Sye).join(`_`)}`}function wye(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Tye(e){let{value:t,file:n,source:r,doc:i}=e,a=[],o=(e,t)=>{if(t.length>0){let e=Wl(Ul,t);if(e!==void 0){if(e.scope===`project-local`){let e=Cye(t),o;i!=null&&r!=null&&n!=null&&(o=Zu({file:n,source:r,doc:i,path:t})),a.push({path:[...t],...xye.has(e)?{envVar:e}:{},...o===void 0?{}:{source:o}})}return}}if(wye(e))for(let[n,r]of Object.entries(e))o(r,[...t,n])};return o(t,[]),a}const EJ=`(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)`;RegExp(`^127\\.${EJ}\\.${EJ}\\.${EJ}$`);function DJ(e,t){return e===`unix-chain`?`# ok-mcp${t}-v`:`# ok-mcp${t}-win-v`}function OJ(e){return e.replace(/\/+/g,`/`).replace(/\/+$/,``)}function Eye(e){return rt[e].userHomeDirName}function Dye(e,t){return e===`stable`?`${OJ(t)}/Library/Application Support/OpenKnowledge/path-install.json`:`${OJ(t)}/${Eye(e)}/path-install.json`}const Oye=[`.ok`,cd,`installed-skills.json`],kye=U(Ed),Aye=Zi({hosts:B(I()),scope:kye,scripts:R(),installedAt:ki(),projection:U([`symlink`,`copy`]).optional(),contentHash:I().optional()}),jye=Zi({schema:W(1),skills:H(I(),Aye).default({})});function Mye(e){let t;try{t=JSON.parse(e)}catch{return null}let n=jye.safeParse(t);return n.success?n.data:null}function kJ(e){if(e===``)throw Error(`toPathspec: empty path. ":(literal)" is an empty pattern that matches every tracked path; pass "." if you meant the repo root.`);return`:(literal)${e}`}function Nye(e){if(e.length===0)throw Error(`pathspecArgs: empty path list. A bare "--" removes the pathspec restriction rather than selecting nothing.`);return[`--`,...e.map(e=>kJ(e))]}const AJ=[{tagName:`Mirror`,attrName:`src`,resolution:`bare-doc-name`},{tagName:`Excalidraw`,attrName:`src`,resolution:`doc-relative`}];for(let e of AJ){let t=QB.find(t=>t.name===e.tagName);if(!t)throw Error(`JSX_SRC_REF_TAGS: no built-in component descriptor named '${e.tagName}' — the rename-rewrite and backlink passes for this entry would silently never match. Fix the tagName to match a descriptor in builtInComponents.`);if(!t.props.some(t=>t.name===e.attrName))throw Error(`JSX_SRC_REF_TAGS: component '${e.tagName}' declares no prop named '${e.attrName}' — the rename-rewrite and backlink passes for this entry would silently never match. Fix the attrName to match one of the descriptor's props.`)}gH(),PV(),FV();function Pye(){return QB.filter(e=>e.surface===`canonical`&&e.name!==`*`)}function Fye(){return Pye().filter(e=>{let t=Iye(e);return t!==`fence`&&t!==`html`})}function Iye(e){return e.name===`MermaidFence`?`fence`:e.name===`HtmlAlignBlock`?`html`:e.hasChildren?`jsx-block`:`jsx-void`}const jJ=Symbol.for(`@inkeep/open-knowledge/skill-state-field-registry`),MJ=globalThis;MJ[jJ]===void 0&&(MJ[jJ]=sr());const NJ=MJ[jJ],PJ=Zi({version:I().regex(/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/,`version must match /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/`).register(NJ,{description:`Recorded skill version for this target.`}),recordedAt:ki().register(NJ,{description:`ISO 8601 timestamp of the most recent successful write. Updated on every write, including reinstalls of the same version.`}),surface:U([`server-build-and-open`,`electron-build-and-open`,`cli-npx-skills-add`,`desktop-direct`,`cli-start`]).register(NJ,{description:`Install-source surface that recorded this entry.`}).optional()}),Lye=Zi({enabled:R().register(NJ,{description:`Whether this user-global skill bundle is opted in.`}),decidedAt:ki().register(NJ,{description:`ISO 8601 timestamp of the opt-in / opt-out decision.`})});Zi({schema:W(1).register(NJ,{description:`Schema major version. Bumped only on breaking shape changes.`}),targets:Zi({"claude-cowork":PJ.optional(),"cli-hosts":PJ.optional()}).register(NJ,{description:`Per-target install-state entries. Absent target = no recorded install.`}).default({}),bundles:H(I(),Lye).register(NJ,{description:`Per-bundle opt-in decisions keyed by install name. Absent key = no recorded decision.`}).optional(),installsReported:B(I()).register(NJ,{description:"Skill installs already reported to skills.sh from this machine, as `<owner/repo>#<skill>`. Append-only; presence suppresses a re-report."}).optional()});function Rye(e,t,n,r){return e.success?{code:`UNKNOWN`,message:`unexpected success in error path`}:{code:`SCHEMA_INVALID`,issues:e.error.issues.map(e=>{let i=e.path.map(e=>typeof e==`symbol`?String(e):e),a=Zu({file:r,source:n,doc:t,path:i});return{path:i,message:e.message,issueCode:e.code,...a===void 0?{}:{source:a}}})}}function FJ(e,t,n){let r=`${e}.invalid-${t.replace(/[:.]/g,`-`)}`;try{return D(e,r),r}catch(t){n(`[config] Could not sideline invalid config file ${e} → ${r}: ${t instanceof Error?t.message:String(t)}. File left in place; using schema defaults.`);return}}function IJ(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||Array.isArray(n))return;n=Reflect.get(n,e)}return n}function zye(e){let t=[],n=[[`maxBatchSize`,1,Ll],[`maxBatchChars`,1,Rl],[`docTimeoutMs`,1,zl]];for(let[r,i,a]of n){let n=[`search`,`semantic`,r],o=IJ(e.rawConfig,n),s=e.config.search.semantic[r];if(o===void 0||o===s)continue;let c=`Expected an integer between ${i} and ${a}; using default ${s}.`,l=Zu({file:e.absPath,source:e.source,doc:e.doc,path:n});t.push({path:n,message:c,...l===void 0?{}:{source:{file:l.file,line:l.line,column:l.column}}})}return t.length>0?[{code:`VALUE_FALLBACK`,issues:t}]:[]}function Bye(e){let t=IJ(e.rawConfig,[`git`,`hosts`]);if(t===void 0)return[];let n=gie.safeParse(t);return n.success?[]:[{code:`VALUE_FALLBACK`,issues:n.error.issues.map(t=>{let n=[`git`,`hosts`,...t.path.map(String)],r=Zu({file:e.absPath,source:e.source,doc:e.doc,path:n});return{path:n,message:`${t.message}; ignoring this git-host declaration.`,...r===void 0?{}:{source:{file:r.file,line:r.line,column:r.column}}}})}]}function Vye(e){let t=IJ(e.rawConfig,[`autolinks`]);if(t===void 0)return[];let n=_ie.safeParse(t);return n.success?[]:[{code:`VALUE_FALLBACK`,issues:n.error.issues.map(t=>{let n=[`autolinks`,...t.path.map(String)],r=Zu({file:e.absPath,source:e.source,doc:e.doc,path:n});return{path:n,message:t.path.length===0?`${t.message}; ignoring autolinks.`:`${t.message}; ignoring this autolink entry.`,...r===void 0?{}:{source:{file:r.file,line:r.line,column:r.column}}}})}]}function LJ(e){let{absPath:t,sideline:n=!0,timestamp:r=new Date().toISOString()}=e,i=e.warn??(e=>console.warn(e)),a=Ul.parse({});if(!g(t))return{valid:!0,value:a,source:void 0,diagnostics:[]};let o;try{o=S(t,`utf-8`)}catch(e){let n=e instanceof Error?e.message:String(e);i(`[config] Could not read ${t}: ${n}. Using schema defaults.`);let r={code:`UNREADABLE`,detail:n};return{valid:!1,value:a,error:r,diagnostics:[{...r}]}}let s=(0,xs.parseDocument)(o);if(s.errors.length>0){let e=s.errors.map(e=>e.message).join(`; `);i(`[config] ${t} contains invalid YAML (${e}). Using schema defaults.`+(n?``:` Pass-through mode: file left in place.`));let o=n?FJ(t,r,i):void 0,c={code:`YAML_PARSE`,detail:e};return{valid:!1,value:a,error:c,diagnostics:[{...c}],...o===void 0?{}:{sidelinedTo:o}}}let c=s.toJSON()??{},l=nd({value:c,file:t,source:o,doc:s}),u=l.length>0?id(c):c,d=[...Bye({rawConfig:u,doc:s,source:o,absPath:t}),...Vye({rawConfig:u,doc:s,source:o,absPath:t})];for(let e of d)for(let n of e.issues)i(`[config] ${t} ${n.path.join(`.`)}: ${n.message}`);let f=Ul.safeParse(u);if(!f.success){let e=Rye(f,s,o,t),c=Ul.shape.git.safeParse(IJ(u,[`git`])).data??a.git,p=Object.keys(c.hosts).length>0?`Using schema defaults while preserving valid git-host declarations.`:`Using schema defaults.`;i(`[config] ${t} fails schema validation (${f.error.issues.length} issue(s)). ${p}`+(n?``:` Pass-through mode: file left in place.`));let m=n?FJ(t,r,i):void 0,h=[...l,...d,...Cd(e)&&e.code===`SCHEMA_INVALID`?[{...e}]:[]];return{valid:!1,value:{...a,git:c},error:e,diagnostics:h,...m===void 0?{}:{sidelinedTo:m}}}let p=[...l,...d,...zye({rawConfig:u,config:f.data,doc:s,source:o,absPath:t})];return{valid:!0,value:f.data,source:t,diagnostics:p}}function RJ(e=_e()){return j(e,ft().userHomeDirName)}const zJ=`.tmp.`,BJ=[8,4,4,4,12];function Hye(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Uye=BJ.map(e=>`[0-9a-f]`.repeat(e)).join(`-`),Wye=BJ.map(e=>`[0-9a-f]{${e}}`).join(`-`),Gye=`*${zJ}${Uye}`;RegExp(`${Hye(zJ)}${Wye}$`);function Kye(e){return`${e}${zJ}${Ee()}`}function qye(e){try{let t=k(e),n=`${ae(e)}${zJ}`,r=Date.now()-3e4;for(let e of w(t)){if(!e.startsWith(n))continue;let i=j(t,e);try{te(i).mtimeMs<r&&ne(i)}catch{}}}catch{}}function VJ(e,t,n={}){qye(e);let r=Kye(e);try{re(r,t,{encoding:`utf-8`,mode:n.mode??420}),D(r,e)}catch(e){try{ne(r)}catch{}throw e}}var HJ=class extends Error{code=`LOCK_TIMEOUT`;lockPath;timeoutMs;constructor(e,t){super(`Could not acquire file lock at ${e} within ${t}ms`),this.name=`FileLockTimeoutError`,this.lockPath=e,this.timeoutMs=t}};async function Jye(e,t,n={}){let r=n.timeoutMs??5e3,i=n.retryIntervalMs??25,a=r*2,o=Date.now()+r,s=!0;for(;;){if(!s&&Date.now()>=o)throw new HJ(e,r);s=!1;let c;try{c=b(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let s;try{let t=te(e);s=Date.now()-t.mtimeMs}catch{continue}let c=!1;if(s>a){n.onWarn?.(`cleared stale file lock`,{lockPath:e,ageMs:s,staleThresholdMs:a});try{ne(e),c=!0}catch{}}if(c)continue;if(Date.now()>=o)throw new HJ(e,r);await Gie(i);continue}try{return await t()}finally{try{f(c)}catch{}try{ne(e)}catch{}}}}function Yye(e){let t=Date.now()+e;for(;Date.now()<t;);}function UJ(e,t,n={}){let r=n.timeoutMs??5e3,i=n.retryIntervalMs??25,a=r*2,o=Date.now()+r,s=!0;for(;;){if(!s&&Date.now()>=o)throw new HJ(e,r);s=!1;let c;try{c=b(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let s;try{let t=te(e);s=Date.now()-t.mtimeMs}catch{continue}let c=!1;if(s>a){n.onWarn?.(`cleared stale file lock`,{lockPath:e,ageMs:s,staleThresholdMs:a});try{ne(e),c=!0}catch{}}if(c)continue;if(Date.now()>=o)throw new HJ(e,r);Yye(i);continue}try{return t()}finally{try{f(c)}catch{}try{ne(e)}catch{}}}}const WJ=`config.yml`;function GJ(e,t,n){if(e===`user`)return N(RJ(n??_e()),`global.yml`);let r=A(t)?t:N(t);return e===`project-local`?N(r,`.ok`,cd,WJ):N(r,`.ok`,WJ)}const Xye=[`LC_ALL`,`LC_MESSAGES`,`LANG`];function KJ(e){let t=e.trim().split(`@`)[0].split(`.`)[0];return t===``||t===`C`||t===`POSIX`?null:jP(t.replaceAll(`_`,`-`))}function Zye(e){for(let t of Xye){let n=e[t]?.trim();if(n!==void 0&&n!==``)return KJ(n)}return null}function Qye(e){let t=e.OK_LANG?.trim();if(t!==void 0&&t!==``)return jP(t)??void 0}function $ye(e=process.env){let t=Qye(e),n=Zye(e);if(n===null)return{override:t,preferenceList:[]};let r=[],i=e.LANGUAGE;if(i!==void 0)for(let e of i.split(`:`)){let t=KJ(e);t!==null&&r.push(t)}return{override:t,preferenceList:[...r,n]}}function qJ(){return pd(ud)}function JJ(){return ft().keyringService}function YJ(e){try{e()}catch{}}var ebe=class{backend=`keyring`;onKeychainRead;constructor(e){this.onKeychainRead=e}async get(e){let{Entry:t}=await import(`@napi-rs/keyring`),n;try{n=new t(JJ(),e).getPassword()}catch(t){return YJ(()=>this.onKeychainRead?.({kind:`read-error`,host:e,error:t instanceof Error?t.name:`unknown`})),null}if(n==null)return YJ(()=>this.onKeychainRead?.({kind:`absent`,host:e})),null;try{return JSON.parse(n)}catch{return YJ(()=>this.onKeychainRead?.({kind:`corrupt-entry`,host:e,error:`corrupt-entry`})),null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(JJ(),e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(JJ(),e).deletePassword()}catch{}}},XJ=class{backend=`file`;authFile;constructor(e){this.authFile=e??j(RJ(),`auth.yml`)}read(){if(!g(this.authFile))return{};try{let e=S(this.authFile,`utf-8`);return(0,xs.parse)(e)??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=k(this.authFile);g(t)||v(t,{recursive:!0,mode:448}),VJ(this.authFile,(0,xs.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}},tbe=class{backend=`keyring`;keychain;file;constructor(e,t){this.keychain=e,this.file=t}async get(e){let t=await this.keychain.get(e);if(t!=null)return t;let n=await this.file.get(e);if(n==null)return null;try{await this.keychain.set(e,n.login,n.token,{gitProtocol:n.gitProtocol,name:n.name,email:n.email}),await this.file.clear(e),process.stderr.write(`[auth] migrated ${e} credential from ${qJ()} to the OS keychain\n`)}catch{}return n}set(e,t,n,r){return this.keychain.set(e,t,n,r)}async clear(e){await this.keychain.clear(e),await this.file.get(e)!=null&&await this.file.clear(e)}};async function ZJ(e,t){try{let{Entry:n}=await import(`@napi-rs/keyring`);return new n(JJ(),`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
|
|
429
|
+
`||e[r]===`\r`;let i=n.after.charCodeAt(0);return Number.isNaN(i)||i===10||i===13}function O_e(e,t){let n=``,r=0;for(;r<e.length;){let i=e.charAt(r);if(i===`\\`){n+=e.slice(r,r+2),r+=2;continue}if(i===`*`||i===`_`||i===`~`||i===`=`){let a=r+1;for(;a<e.length&&e.charAt(a)===i;)a++;let o=r===0?t.before.charCodeAt(t.before.length-1):e.charCodeAt(r-1);if(i===`=`)n+=(Number.isNaN(o)||o===10||o===13)&&D_e(e,a,t)?`\\${e.slice(r,a)}`:e.slice(r,a);else{let s=a<e.length?e.charCodeAt(a):t.after.charCodeAt(0);n+=E_e(i,o,s)?`\\${i}`.repeat(a-r):e.slice(r,a)}r=a;continue}n+=i,r+=1}return n}function Dq(e,t,n){let r=n.startsWith(`_`)?`_`:`*`,i=t.before??``,a=t.after??``,o=e,s=o.charCodeAt(0);Oq(i.charCodeAt(i.length-1),s,r)&&(o=kq(s)+o.slice(1));let c=o.charCodeAt(o.length-1);return Oq(a.charCodeAt(0),c,r)&&(o=o.slice(0,-1)+kq(c)),o}function Oq(e,t,n){return!(Vf(t)!==1||n===`_`&&Vf(e)===void 0)}function kq(e){return`&#x${e.toString(16).toUpperCase()};`}function k_e(e,t,n,r){let i=e.value??``,a=e.data?.sourceDelimiter,o=typeof a==`string`&&/^\$+$/.test(a)?a.length:2;for(o===1&&!j_e(i,r)&&(o=2);RegExp(`(^|[^$])${`\\$`.repeat(o)}([^$]|$)`).test(i);)o++;let s=`$`.repeat(o);/[^ \r\n]/.test(i)&&(/^[ \r\n]/.test(i)&&/[ \r\n]$/.test(i)||/^\$|\$$/.test(i))&&(i=` ${i} `);let c=-1;for(;++c<n.unsafe.length;){let e=n.unsafe[c];if(!e.atBreak)continue;let t=n.compilePattern(e),r;for(;(r=t.exec(i))!==null;){let e=r.index;i.codePointAt(e)===10&&i.codePointAt(e-1)===13&&e--,i=`${i.slice(0,e)} ${i.slice(r.index+1)}`}}return s+i+s}function A_e(e,t,n,r){let i=e.data?.sourceDelimiter===`~`?`~`:`~~`,a=n.createTracker(r),o=n.enter(`strikethrough`),s=a.move(i);return s+=Dq(n.containerPhrasing(e,{...a.current(),before:s,after:`~`}),r,i),s+=a.move(i),o(),s}function j_e(e,t){return!(e.length===0||!/^\S/.test(e)||!/\S$/.test(e)||/[$\r\n]/.test(e)||e.endsWith(`\\`)||/\\[!-/:-@[-`{-~]/.test(e)||/^\d/.test(t.after)||t.before.endsWith(`\\`))}const Aq=[{mode:`protecting`,protect:LH,reservations:FH},{mode:`protecting`,protect:FU,reservations:HH},{mode:`protecting`,protect:jH,reservations:DH},{mode:`serializer-only`,reservations:[{to:``}]}];new Set(Aq.flatMap(({reservations:e})=>e.map(({to:e})=>e)));function M_e(e,t){switch(t.mode){case`protecting`:return t.protect(e);case`serializer-only`:return e}}function jq(e){return Aq.reduce(M_e,e)}function Mq(e){return e.data?.sourceRaw}function N_e(e){return e.type===`text`?e.value===``:e.type===`mdxJsxTextElement`&&Mq(e)===``}function Nq(e){return e.type===`paragraph`&&(e.children??[]).every(N_e)}function Pq(e){let t=e.children??[],n=t[0]?.children?.length??0,r=0;for(let e=1;e<t.length;e++)r=Math.max(r,t[e]?.children?.length??0);let i=e.align??[];return Math.max(n,r,i.length)}function P_e(e){switch(e.type){case`table`:return Pq(e)===0;case`code`:return e.data?.sourceStyle===`indented`&&/^\n*$/.test(e.value??``);case`thematicBreak`:return Mq(e)===``;case`html`:return(e.value??``)===``;case`mdxJsxFlowElement`:return Mq(e)===void 0&&e.data?.htmlBoundary===void 0&&(e.children??[]).length===0&&!e.name;case`list`:return(e.children??[]).length===0;default:return!1}}function F_e(e){let t=[];for(let n of e.children){if(n.type===`table`&&Pq(n)===0){console.warn(JSON.stringify({event:`table-serialize-dropped-empty`,rows:(n.children??[]).length}));continue}P_e(n)||(n.type===`paragraph`&&n.children.length>0&&Nq(n)&&(n.children=[]),t.push(n))}e.children=t}function I_e(e,t){let n=e,r=t;return n.type===`heading`&&n.data?.sourceContiguousNext===!0&&r.type===`paragraph`}const L_e=(e,t)=>{if(Nq(e)||I_e(e,t))return 0;let n=e.position,r=t.position;if(!n||!r)return;let i=r.start.line-n.end.line-1;return i>=1?i:void 0},Fq=/(?<!\\)\$(?=\S)([^$\n]*?[^\s$])\$(?!\d)/g;function R_e(){return(e,t)=>{let n=typeof t.value==`string`?t.value:``;Wf(e,`text`,(e,t,r)=>{if(r===void 0||t==null)return;let i=e.value;if(i.indexOf(`$`)===-1)return;let a=mP(e);Fq.lastIndex=0;let o=[],s;for(;(s=Fq.exec(i))!==null;){let e=s.index,t=e+s[0].length;if(vP(a,e,1)||vP(a,t-1,1)){Fq.lastIndex=e+1;continue}o.push(s)}if(o.length===0)return;let c=[],l=0;for(let t of o){let r=t.index,i=r+t[0].length;r>l&&c.push(_P(n,e,l,r));let a={type:`inlineMath`,value:t[1]},o=xP(n,e,r,i);o&&(a.position=o),c.push(a),l=i}return l<i.length&&c.push(_P(n,e,l,i.length)),r.children.splice(t,1,...c),[yf,t+c.length]})}}const z_e=new Set([`strong`,`emphasis`,`delete`,`link`,`mark`,`comment`]);function B_e(e){if(e?.type!==`break`)return!1;let t=e.data?.sourceRaw;return typeof t!=`string`||t.length===0}function V_e(e){e.data??={},e.data.sourceRaw=`<br />`,e.data.sourceStyle=`html`}function Iq(e){if(e?.type!==`text`)return!1;let t=e.data?.sourceRaw;return typeof t!=`string`||t.length===0}const Lq=/[ \t]+$/,Rq=/^[ \t]*$/;function H_e(e){return e.some(e=>!(Iq(e)&&Rq.test(e.value)))}function zq(e,t=!1){for(;e.length>0;){let n=e[e.length-1];if(B_e(n)){V_e(n);break}if(n&&z_e.has(n.type)&&`children`in n){let t=n.children;if(zq(t,!0),t.length===0){e.pop();continue}}if(!t&&Iq(n)&&Lq.test(n.value)){let t=n.value.replace(Lq,``);if(t.length>0){n.value=t;continue}if(H_e(e.slice(0,-1))){e.pop();continue}if(e.every(e=>Iq(e)&&Rq.test(e.value))){let t=e[0];t.value=t.value.charAt(0),e.splice(1)}}break}}const U_e=new Set([`paragraph`,`heading`,`tableCell`]);function W_e(e){let t=e=>{if(U_e.has(e.type)&&`children`in e&&zq(e.children),`children`in e)for(let n of e.children)t(n)};t(e)}const Bq={handlers:{tag:e=>`#${e.value}`},unsafe:[{character:`#`,inConstruct:[`phrasing`],before:`\\s`,after:`[A-Za-z]|[^\\x00-\\x7F]`}]};function G_e(){let e=this.data();e.toMarkdownExtensions||=[],e.toMarkdownExtensions.some(e=>e===Bq)||e.toMarkdownExtensions.push(Bq)}const K_e=new Set([`u`,`ins`]);function q_e(){return e=>{Wf(e,`mdxJsxTextElement`,(e,t,n)=>{if(n===void 0||t==null||e.name===null||!K_e.has(e.name)||(e.attributes??[]).length>0)return;let r={type:`underline`,children:e.children??[],data:{sourceForm:e.name===`ins`?`ins`:`u`}};return e.position&&(r.position=e.position),n.children.splice(t,1,r),t+1})}}function J_e(e){return e.children.some(e=>{let t=e.type;return t!==`yaml`&&t!==`toml`})?e:{...e,children:[...e.children,{type:`paragraph`,children:[]}]}}const Y_e=[{name:`remark-parse`,plugin:w_},{name:`escape-provenance`,plugin:AK},{name:`remark-mdx-agnostic`,plugin:UU},{name:`remark-gfm`,plugin:Uh},{name:`remark-math`,plugin:qW,options:{singleDollarTextMath:!1}},{name:`remark-wiki-link`,plugin:fW},{name:`remark-github-alerts`,plugin:UW,options:xG},{name:`callout-transformer`,plugin:bG},{name:`restore-from-mdx`,plugin:LU},{name:`void-br-promoter`,plugin:qU},{name:`restore-entity-refs`,plugin:PH},{name:`restore-backslash-escapes`,plugin:RH},{name:`details-accordion-promoter`,plugin:aK},{name:`div-align-promoter`,plugin:mK},{name:`image-promoter`,plugin:RK},{name:`indented-code-promoter`,plugin:WK},{name:`math-promoter`,plugin:eq},{name:`single-dollar-math-promoter`,plugin:R_e},{name:`highlight-promoter`,plugin:LK},{name:`underline-promoter`,plugin:q_e},{name:`mermaid-promoter`,plugin:n_e},{name:`comment-promoter`,plugin:wG},{name:`merged-post-parse-walker`,plugin:e_e},{name:`empty-task-item-unmint`,plugin:xK},{name:`link-reference-destination`,plugin:QK},{name:`non-rendering-context-demote`,plugin:d_e},{name:`ensure-non-empty-doc`,plugin:()=>J_e}];function X_e(e){let t=ug();for(let e of Y_e)t=`options`in e&&e.options!==void 0?t.use(e.plugin,e.options):t.use(e.plugin);return t=t.use(FW,{schema:e.schema,handlers:e.handlers}),t.freeze(),t}function Z_e(e){let t=ug().use(zg,[`yaml`]).use(Uh,{tablePipeAlign:!1}).use(qW,{singleDollarTextMath:!1}).use(UU).use(fW).use(G_e).use(aB,{bullet:`-`,fences:!0,rule:`-`,join:[L_e],...e.toMarkdownHandlers?{handlers:e.toMarkdownHandlers}:{}});return t.freeze(),t}function Vq(e){return e.charCodeAt(0)===65279?{source:e.slice(1),hadBom:!0}:{source:e,hadBom:!1}}const Hq=/^\n+$/,Uq=/^\n{2,}$/;function Wq(e,t,n){let r,i,a=e.children;if(a.length>0){let e=a[0]?.position?.start?.offset;if(typeof e==`number`&&e>0){let n=t.slice(0,e);Hq.test(n)&&(r=n)}let n=a[a.length-1]?.position?.end?.offset;if(typeof n==`number`&&n<=t.length){let e=t.slice(n);Uq.test(e)&&(i=e)}}if(!n&&r===void 0&&i===void 0)return;let o={...n?{bom:!0}:{},...r===void 0?{}:{leading:r},...i===void 0?{}:{trailing:i}};return e.data??={},e.data.sourceDocBoundary=o,o}function Q_e(e){if(typeof e!=`object`||!e)return;let t=e,n={};return t.bom===!0&&(n.bom=!0),typeof t.leading==`string`&&Hq.test(t.leading)&&(n.leading=t.leading),typeof t.trailing==`string`&&Uq.test(t.trailing)&&(n.trailing=t.trailing),n.bom||n.leading||n.trailing?n:void 0}function $_e(e,t){let{source:n,hadBom:r}=Vq(e),i=JG(n),a=new ng(jq(i)),o=t.parse(a);a.value=i;let s=t.runSync(o,a);JK(s,i);let c=Wq(s,i,r),l=c?ws(s,c):void 0,u=t.stringify(s);return l?u.type.create({...u.attrs,sourceDocBoundary:l},u.content,u.marks):u}function eve(e,t){return Gq(e,t,!1)}function tve(e,t){return Gq(e,t,!0)}function Gq(e,t,n){let{source:r,hadBom:i}=Vq(e),a=JG(r),o=new ng(jq(a)),s=t.parse(o);o.value=a;let c=t.runSync(s,o);n&&JK(c,a);let l=Wq(c,a,i);return n&&l&&ws(c,l),c}function nve(e,t,n){let r=LW(e,{schema:n.schema,nodeHandlers:n.pmNodeHandlers,markHandlers:n.pmMarkHandlers});Kq(r),yK(r),W_e(r),F_e(r);let i=Q_e(e.attrs?.sourceDocBoundary),a=String(t.stringify(r));return i?.leading&&(a=i.leading+a),i?.trailing&&(a=a.replace(/\n+$/,``)+i.trailing),i?.bom&&(a=`\uFEFF${a}`),a}function Kq(e){if(!(!(`children`in e)||!Array.isArray(e.children))){for(let t of e.children)Kq(t);for(let t=0;t+1<e.children.length;){let n=e.children[t],r=e.children[t+1],i=n?.data,a=r?.data,o=lP(i)?i.escapedChars:null,s=lP(a)?a.escapedChars:null;if(n?.type!==`text`||r?.type!==`text`||typeof n.data?.sourceRaw==`string`||typeof r.data?.sourceRaw==`string`||o===null&&s===null){t+=1;continue}let c=n.value.length;n.value+=r.value,n.data??={},n.data.escapedChars=[...o??[],...(s??[]).map(e=>({...e,offset:e.offset+c}))],r.data?.entityRefSpans?.length&&(n.data.entityRefSpans=[...n.data.entityRefSpans??[],...r.data.entityRefSpans.map(e=>({...e,offset:e.offset+c}))]),e.children.splice(t+1,1)}}}var rve=class{schema;handlers;pmNodeHandlers;pmMarkHandlers;parseProcessor;serializeProcessor;parseCtx={current:{}};freshnessHolder={checker:void 0};constructor(e){this.schema=yO(e.extensions),this.handlers=cve(this.schema,this.parseCtx),this.freshnessHolder.checker=e.deriveStructuralFreshness?Qs({parse:e=>this.parseWithFallback(e)}):void 0;let{nodeHandlers:t,markHandlers:n}=lve(this.schema,this.freshnessHolder);this.pmNodeHandlers=t,this.pmMarkHandlers=n,this.parseProcessor=X_e({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers}),this.serializeProcessor=Z_e({toMarkdownHandlers:__e})}parse(e,t){if(!e.trim())return{type:`doc`,content:[{type:`paragraph`,content:[]}]};this.parseCtx.current=t??{};try{return $_e(e,this.parseProcessor).toJSON()}finally{this.parseCtx.current={}}}parseToMdast(e){return e.trim()?eve(e,this.parseProcessor):{type:`root`,children:[]}}parseToEditorMdast(e){return e.trim()?tve(e,this.parseProcessor):{type:`root`,children:[]}}parseWithFallback(e,t){return e.trim()?XW(e,{parse:e=>this.parse(e,t)}):{type:`doc`,content:[{type:`paragraph`,content:[]}]}}serialize(e,t){let n;try{n=this.schema.nodeFromJSON(e)}catch(t){let n=`MarkdownManager.serialize() failed: schema rejected JSONContent (type=${e.type}, childCount=${e.content?.length??0})`;throw Error(n,{cause:t})}let r=this.freshnessHolder.checker;t?.skipFreshnessDerive&&(this.freshnessHolder.checker=void 0);try{return nve(n,this.serializeProcessor,{schema:this.schema,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers})}finally{this.freshnessHolder.checker=r}}};const qq=eV();function Jq(e,t){let n=new Map;for(let e of t)n.set(e.name,e);let r={};for(let t of e){if(t.type===`mdxJsxExpressionAttribute`)continue;let e=t.name,i=n.get(e);if(t.value===null||t.value===void 0){r[e]=!0;continue}if(typeof t.value==`string`){if(i?.type===`number`){let n=Number(t.value);r[e]=Number.isNaN(n)?t.value:n}else r[e]=i?.type===`boolean`?t.value===`true`:t.value;continue}let a=t.value.value;try{r[e]=JSON.parse(a)}catch{r[e]=a}}return r}function ive(e){let t=!1;return e.descendants(e=>t?!1:e.type.name===`jsxInline`?(e.attrs.sourceDirty&&(t=!0),!1):e.type.name===`jsxComponent`&&e.attrs.sourceDirty?(t=!0,!1):!0),t}function ave(e,t){return e.attrs.sourceDirty||ive(e)?!0:t?t.isDiverged(e.toJSON()):!1}function ove(e){if(e.type!==`paragraph`)return!1;let t=e.children??[];return t.length===0||t.every(e=>e.type===`text`&&e.value===``)}function Yq(e,t){if(!t)return e;let n={};return t.sourceFenceChar&&(n.sourceFenceChar=t.sourceFenceChar),typeof t.sourceFenceLength==`number`&&(n.sourceFenceLength=t.sourceFenceLength),t.sourcePadded===!0&&(n.sourcePadded=!0),Object.keys(n).length===0?e:{...e,data:n}}function Xq(e,t){if(e.length===0)return Yq({type:`inlineCode`,value:``},t);if(e.every(e=>e.type===`text`))return Yq({type:`inlineCode`,value:e.map(e=>e.value).join(``)},t);if(e.length===1&&`children`in e[0]){let n=e[0];return{...n,children:[Xq(n.children,t)]}}return Yq({type:`inlineCode`,value:Zq(e)},t)}function Zq(e){let t=``;for(let n of e)n.type===`text`?t+=n.value:`children`in n&&Array.isArray(n.children)?t+=Zq(n.children):`value`in n&&typeof n.value==`string`&&(t+=n.value);return t}const sve=Oc;function cve(e,t){let n=e.nodes,r=e.marks,i={};n.paragraph&&(i.paragraph=(e,t,r)=>{let i=r.all(e).flat(),a=i.some(e=>e?.isBlock&&!e?.isInline),o=i.some(e=>e?.isInline||e?.isText||e?.isTextblock);if(a&&!o)return i.length===1?i[0]:i;if(a&&o){let e=i.filter(e=>!e?.isBlock||e?.isInline),t=i.filter(e=>e?.isBlock&&!e?.isInline),r=[],a=n.paragraph.createAndFill(null,e.length>0?e:null);return a&&r.push(a),r.push(...t),r.length===1?r[0]:r}return n.paragraph.createAndFill(null,i.length>0?i:null)}),n.blockquote&&(i.blockquote=MW(n.blockquote,e=>({sourceMarkerSpacings:e.data?.sourceMarkerSpacings??null}))),n.tableCell&&(i.tableCell=(e=>(t,r,i)=>{let a=i.all(t).flat();if(a.length>0&&n.paragraph){let t=n.paragraph.create(null,a);return e.createAndFill(null,[t])}return e.createAndFill(null,null)})(n.tableCell)),n.tableRow&&(i.tableRow=MW(n.tableRow)),n.table&&n.tableRow&&n.tableCell&&(i.table=(e,t,r)=>{let i=e.align??[],a=e.children??[],o=[];for(let e=0;e<a.length;e++){let t=a[e];if(t.type!==`tableRow`)continue;let s=t.children??[],c=[];for(let t=0;t<s.length;t++){let a=s[t];if(a.type!==`tableCell`)continue;let o=r.all(a).flat(),l=o.length>0&&n.paragraph?[n.paragraph.create(null,o)]:null,u=i[t]??null,d=e===0&&n.tableHeader?n.tableHeader:n.tableCell,f=a.data?.sourcePadding??null,p=d.createAndFill({align:u,sourcePadding:f},l);p&&c.push(p)}let l=n.tableRow.createAndFill(null,c.length>0?c:null);l&&o.push(l)}let s=e.data?.sourceDashCounts??null,c=e.data?.sourceOuterPipes??null,l=e.data?.sourceAlignmentPadding??null;return n.table.createAndFill({sourceDashCounts:s,sourceOuterPipes:c,sourceAlignmentPadding:l},o.length>0?o:null)}),n.image&&(i.image=e=>{let r=e.url??``,i=yW(r,t.current.sourcePath);return n.image.createAndFill({src:i,alt:e.alt??null,title:e.title??null,sourceUrl:i===r?null:r,sourceUrlForm:e.data?.sourceUrlForm??null})},i.imageReference=n.imageReference?e=>n.imageReference.createAndFill({alt:e.alt??``,label:e.label??e.identifier??``,identifier:e.identifier??``,referenceType:e.referenceType??`shortcut`}):e=>n.image.createAndFill({src:``,alt:e.alt??null,title:null})),r.escapeMark&&(i.text=t=>{let n=t.value??``,i=typeof t.data?.sourceRaw==`string`?t.data.sourceRaw:null;if(!n&&!i)return null;if(i)return r.sourceLiteral?e.text(n,[r.sourceLiteral.create({sourceRaw:i})]):e.text(n);let a=t.data?.escapedChars,o=t.data?.entityRefSpans;if(!a?.length&&!o?.length)return e.text(n);let s=[...(a??[]).map(e=>({kind:`escape`,offset:e.offset,length:1})),...(o??[]).map(e=>({kind:`entity`,offset:e.offset,length:e.length,raw:e.raw}))];s.sort((e,t)=>e.offset-t.offset);let c=[];for(let e of s){let t=c[c.length-1];e.kind===`entity`&&t?.kind===`entity`&&t.offset+t.length===e.offset&&oc(t.raw)!==null&&rc(e.raw)?c[c.length-1]={kind:`entity`,offset:t.offset,length:t.length+e.length,raw:t.raw+e.raw}:c.push(e)}let l=[],u=0;for(let t of c){if(t.offset>u){let r=n.slice(u,t.offset);r&&l.push(e.text(r))}if(t.offset<n.length){let i=n.slice(t.offset,t.offset+t.length);if(i){if(t.kind===`escape`)l.push(e.text(i,[r.escapeMark.create()]));else if(r.sourceLiteral){let n=oc(t.raw);l.push(e.text(n??i,[r.sourceLiteral.create({sourceRaw:t.raw})]))}else l.push(e.text(i))}u=t.offset+t.length}}if(u<n.length){let t=n.slice(u);t&&l.push(e.text(t))}return l.length===1?l[0]:l}),r.code&&(i.inlineCode=t=>e.text(t.value,[r.code.create({sourceFenceChar:t.data?.sourceFenceChar??"`",sourceFenceLength:typeof t.data?.sourceFenceLength==`number`?t.data.sourceFenceLength:1,sourcePadded:t.data?.sourcePadded===!0})]));let a=r.strike??r.delete;if(a&&(i.delete=NW(a,e=>({sourceDelimiter:e.data?.sourceDelimiter===`~`?`~`:`~~`}))),r.highlight&&(i.mark=NW(r.highlight)),r.underline&&(i.underline=NW(r.underline,e=>({sourceForm:e.data?.sourceForm===`ins`?`ins`:`u`}))),r.comment&&(i.comment=NW(r.comment,e=>({sourceForm:e.data?.sourceForm??`percent`}))),n.commentBlock&&(i.commentBlock=MW(n.commentBlock,e=>({sourceForm:e.data?.sourceForm??`percent`,sourceLayout:e.data?.sourceLayout??`block`}))),r.emphasis&&(i.emphasis=NW(r.emphasis,e=>({sourceDelimiter:e.data?.sourceDelimiter??`*`}))),r.strong&&(i.strong=NW(r.strong,e=>({sourceDelimiter:e.data?.sourceDelimiter??`**`}))),n.heading&&(i.heading=MW(n.heading,e=>({level:e.depth,headingStyle:e.data?.sourceStyle??`atx`,sourceTrailingHashes:e.data?.sourceTrailingHashes??null,sourceUnderlineLength:e.data?.sourceUnderlineLength??null,sourceContiguousNext:e.data?.sourceContiguousNext??!1,sourceLeadingIndent:e.data?.sourceLeadingIndent??null,sourceInteriorSpacing:e.data?.sourceInteriorSpacing??null}))),n.codeBlock&&(i.code=t=>{let r=t.value?[e.text(t.value)]:[];return n.codeBlock.createAndFill({language:t.lang??null,meta:t.meta??null,fenceDelimiter:t.data?.sourceFenceChar??"`",fenceLength:t.data?.sourceFenceLength??3,sourceStyle:t.data?.sourceStyle??`fenced`,sourceClosingFenceLength:t.data?.sourceClosingFenceLength??null,sourceUnclosedFence:t.data?.sourceUnclosedFence??!1,sourceFenceIndent:t.data?.sourceFenceIndent??null,sourceInfoPadding:t.data?.sourceInfoPadding??null,sourceIndents:t.data?.sourceIndents??null},r)}),n.thematicBreak&&(i.thematicBreak=e=>n.thematicBreak.createAndFill({sourceRaw:e.data?.sourceRaw??`---`})),n.hardBreak&&(i.break=e=>n.hardBreak.createAndFill({hardBreakStyle:e.data?.sourceStyle??`spaces`,sourceRaw:e.data?.sourceRaw??null})),n.list&&(i.list=MW(n.list,e=>({ordered:!!e.ordered,start:e.start??1,spread:!!e.spread,bulletMarker:e.data?.bulletMarker??null,listMarkerDelimiter:e.data?.listMarkerDelimiter??null}))),n.listItem&&(i.listItem=MW(n.listItem,e=>({checked:e.checked??null,spread:!!e.spread,sourceMarkerSpacing:e.data?.sourceMarkerSpacing??null,sourceOrdinal:e.data?.sourceOrdinal??null,sourceCheckboxChar:e.data?.sourceCheckboxChar??null,sourceContinuationIndent:e.data?.sourceContinuationIndent??null}))),r.link){let t=r.sourceLiteral;i.link=(n,i,a)=>{if((n.children??[]).length===0){let r=typeof n.data?.sourceRaw==`string`?n.data.sourceRaw:`[](${n.url??``})`;return r?t?e.text(r,[t.create({sourceRaw:r})]):e.text(r):null}let o=a.all(n).flat(),s=r.link.create({href:n.url??``,title:n.title??null,linkStyle:n.data?.sourceStyle??`inline`,refLabel:null,sourceUrlForm:n.data?.sourceUrlForm??null,sourceTitleMarker:n.data?.sourceTitleMarker??null});return o.map(e=>e.mark(s.addToSet(e.marks)))},i.linkReference=(n,i,a)=>{if((n.children??[]).length===0){let r=typeof n.data?.sourceRaw==`string`?n.data.sourceRaw:`[${n.label??``}][${n.identifier??``}]`;return r?t?e.text(r,[t.create({sourceRaw:r})]):e.text(r):null}let o=a.all(n).flat(),s=r.link.create({href:n.data?.resolvedUrl??``,title:n.data?.resolvedTitle??null,linkStyle:n.referenceType??`shortcut`,refLabel:n.label??n.identifier??null});return o.map(e=>e.mark(s.addToSet(e.marks)))}}n.htmlBlock&&(i.html=e=>n.htmlBlock.createAndFill({content:e.value??``}));let o=n.linkDefinition??n.linkRefDef;if(o){let e=!!o.spec.attrs?.url,t=!!o.spec.attrs?.href,n=!!o.spec.attrs?.identifier,r=!!o.spec.attrs?.sourceLayout,a=!!o.spec.attrs?.sourceTitleMarker,s=!!o.spec.attrs?.sourceUrlForm;i.definition=i=>{let c={title:i.title??null};return n&&(c.identifier=i.identifier??``),c.label=i.label??i.identifier??``,e?c.url=i.url??``:t&&(c.href=i.url??``),r&&(c.sourceLayout=i.data?.sourceLayout??null),a&&(c.sourceTitleMarker=i.data?.sourceTitleMarker??null),s&&(c.sourceUrlForm=i.data?.sourceUrlForm??null),o.createAndFill(c)}}if(n.jsxComponent){let r=e=>{if(e&&typeof e==`object`&&`sourceRaw`in e){let t=e.sourceRaw;if(typeof t==`string`)return t}};i.mdxJsxFlowElement=(e,i,a)=>{let o=e.name??``,s=qq.getOrWildcard(o),c=Jq(e.attributes,s.props);if(o===`CommonMarkImage`&&typeof c.src==`string`){let e=c.src,n=yW(e,t.current.sourcePath);n!==e&&(c.src=n,c.sourceUrl=e)}let l=a.all(e).flat();return n.jsxComponent.createAndFill({componentName:o,kind:`element`,attributes:e.attributes,sourceRaw:r(e.data)??``,sourceDirty:!1,props:c},l.length?l:void 0)};let a=(e,t)=>{let n=e.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===t);return n&&typeof n.value==`string`?n.value:null};i.mdxJsxTextElement=t=>{if(t.name===`InlineMath`&&n.mathInline){let e=a(t,`formula`)??``,r=a(t,`id`);return n.mathInline.create({formula:e,id:r??null})}if(t.name===`Tag`&&n.tag){let e=a(t,`value`)??``;return n.tag.create({value:e})}let i=t.name??``,o=i?qq.get(i):void 0;if(o&&n.jsxInline){let e=Jq(t.attributes,o.props),a=r(t.data)??``,s=(t.children??[]).map(e=>e&&typeof e==`object`&&`value`in e?String(e.value??``):``).join(``);return s&&(e.children=s),n.jsxInline.createAndFill({componentName:i,attributes:t.attributes,sourceRaw:a,sourceDirty:!1,props:e})}if(n.jsxInline){let i=r(t.data)??``;return n.jsxInline.createAndFill({},i?[e.text(i)]:null)}return n.jsxComponent.createAndFill({sourceRaw:r(t.data)??``})},i.mdxFlowExpression=e=>{let t=r(e.data)??`{${e.value??``}}`;return n.jsxComponent.createAndFill({kind:`expression`,sourceRaw:t,sourceDirty:!1})},i.mdxTextExpression=t=>{let n=r(t.data)??`{${t.value??``}}`;return e.text(n)}}return n.wikiLink&&(i.wikiLink=e=>n.wikiLink.createAndFill({target:e.data?.target??``,alias:e.data?.alias??null,anchor:e.data?.anchor??null,sourceTarget:e.data?.sourceTarget??null,sourceAnchor:e.data?.sourceAnchor??null,sourceAlias:e.data?.sourceAlias??null})),n.tag&&(i.tag=e=>n.tag.createAndFill({value:e.value})),n.wikiLinkEmbed&&(i.wikiLinkEmbed=(i,a)=>{let o=i.data?.target??``,s=i.data?.alias??null,c=i.data?.anchor??null,l=i.data?.sourceTarget??null,u=i.data?.sourceAnchor??null,d=i.data?.sourceAlias??null,f=sk(o),{resolveEmbed:p,sourcePath:m}=t.current,h=p&&m?p(o,m)??null:null,g=h?`/${h}`:o,_=a?.type===`paragraph`&&Array.isArray(a.children)&&a.children.length===1;if(_&&sve.has(f)&&n.jsxComponent&&qq.has(`WikiEmbedImage`))return n.jsxComponent.createAndFill({componentName:`WikiEmbedImage`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:g,alt:s??o,target:o,anchor:c,alias:s,sourceTarget:l,sourceAnchor:u,sourceAlias:d}});if(_&&kc.has(f)&&n.jsxComponent&&qq.has(`WikiEmbedVideo`))return n.jsxComponent.createAndFill({componentName:`WikiEmbedVideo`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:g,title:s??o,target:o,anchor:c,alias:s,sourceTarget:l,sourceAnchor:u,sourceAlias:d}});if(_&&jc.has(f)&&n.jsxComponent&&qq.has(`WikiEmbedAudio`))return n.jsxComponent.createAndFill({componentName:`WikiEmbedAudio`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:g,title:s??o,target:o,anchor:c,alias:s,sourceTarget:l,sourceAnchor:u,sourceAlias:d}});if(_&&Mc.has(f)&&n.jsxComponent&&qq.has(`WikiEmbedFile`)){let{resolveSize:e}=t.current,r=e&&m?e(o,m)??null:null,i=r===null?null:bW(r);return n.jsxComponent.createAndFill({componentName:`WikiEmbedFile`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:g,target:o,anchor:c,alias:s,size:i,sourceTarget:l,sourceAnchor:u,sourceAlias:d}})}let v=s||(c?`${o}#${c}`:o);if(r.link){let t=r.link.create({href:g,title:null,linkStyle:`inline`,refLabel:null,sourceForm:`wikiembed`,target:o,anchor:c,alias:s,sourceTarget:l,sourceAnchor:u,sourceAlias:d});return e.text(v,[t])}throw Error("[wikiLinkEmbed handler] schema lacks `link` mark — cannot dispatch without violating the STOP rule against emitting PM wikiLinkEmbed server-side")}),n.mathInline&&(i.inlineMath=e=>n.mathInline.create({formula:e.value??``,sourceDelimiter:e.data?.sourceDelimiter??null})),i.math||=t=>{let r=t.value==null?`«unknown:${t.type}»`:t.value;return n.rawMdxFallback?(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled block mdast: ${t.type}`})),n.rawMdxFallback.createAndFill({reason:`Unhandled block mdast: ${t.type}`},r?[e.text(r)]:null)):null},i.inlineMath||=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled inline mdast: ${t.type}`})),t.value==null?e.text(`«unknown:${t.type}»`):e.text(t.value)),n.footnoteReference?i.footnoteReference=e=>n.footnoteReference.create({identifier:e.identifier,label:e.label??e.identifier}):i.footnoteReference||=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:`footnoteReference`,reason:`FootnoteReference extension missing — recovering [^id] source`})),e.text(`[^${t.label??t.identifier}]`)),n.footnoteDefinition?i.footnoteDefinition=MW(n.footnoteDefinition,e=>{let t=e;return{identifier:t.identifier,label:t.label??t.identifier}}):i.footnoteDefinition||=t=>{console.warn(JSON.stringify({event:`unknown-mdast-type`,type:`footnoteDefinition`,reason:`FootnoteDefinition extension missing — recovering [^id]: marker`}));let r=`[^${t.label??t.identifier}]: `;return n.paragraph?n.paragraph.create(null,e.text(r)):null},i.rawMdxFallbackMdast=t=>{if(!n.rawMdxFallback)return null;let r=t.position?{start:t.position.start?.offset??0,end:t.position.end?.offset??0}:{start:0,end:0};return console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.originalType,reason:`Unhandled mdast: ${t.originalType}`,unresolvedPosition:t.unresolvedPosition??!1})),n.rawMdxFallback.createAndFill({reason:`Unhandled mdast: ${t.originalType}`,originalSpan:r},t.value?[e.text(t.value)]:null)},i}function lve(e,t){let n={},r={},i=e.nodes,a=e.marks;i.paragraph&&(n.paragraph=RW(`paragraph`)),i.blockquote&&(n.blockquote=RW(`blockquote`,e=>{let t=e.attrs.sourceMarkerSpacings,n={};return Array.isArray(t)&&t.length>0&&(n.sourceMarkerSpacings=t),Object.keys(n).length>0?{data:n}:{}})),i.heading&&(n.heading=RW(`heading`,e=>({depth:e.attrs.level,data:{sourceStyle:e.attrs.headingStyle,sourceTrailingHashes:e.attrs.sourceTrailingHashes??void 0,sourceUnderlineLength:e.attrs.sourceUnderlineLength??void 0,sourceContiguousNext:e.attrs.sourceContiguousNext===!0||void 0,sourceLeadingIndent:e.attrs.sourceLeadingIndent??void 0,sourceInteriorSpacing:e.attrs.sourceInteriorSpacing??void 0}}))),i.codeBlock&&(n.codeBlock=e=>{let t=e.attrs.sourceStyle===`indented`?`indented`:`fenced`;return{type:`code`,lang:t===`indented`?null:e.attrs.language??null,meta:t===`indented`?null:e.attrs.meta??null,value:e.textContent??``,data:{sourceFenceChar:e.attrs.fenceDelimiter,sourceFenceLength:e.attrs.fenceLength,sourceStyle:t,sourceClosingFenceLength:e.attrs.sourceClosingFenceLength??void 0,sourceUnclosedFence:e.attrs.sourceUnclosedFence===!0||void 0,sourceFenceIndent:e.attrs.sourceFenceIndent??void 0,sourceInfoPadding:e.attrs.sourceInfoPadding??void 0,sourceIndents:e.attrs.sourceIndents??void 0}}}),i.thematicBreak&&(n.thematicBreak=e=>({type:`thematicBreak`,data:{sourceRaw:e.attrs.sourceRaw}})),i.hardBreak&&(n.hardBreak=e=>({type:`break`,data:{sourceStyle:e.attrs.hardBreakStyle,...typeof e.attrs.sourceRaw==`string`&&e.attrs.sourceRaw.length>0?{sourceRaw:e.attrs.sourceRaw}:{}}})),i.list&&(n.list=RW(`list`,e=>({ordered:e.attrs.ordered??!1,start:e.attrs.ordered?e.attrs.start??1:null,spread:e.attrs.spread??!1,data:{bulletMarker:e.attrs.bulletMarker,listMarkerDelimiter:e.attrs.listMarkerDelimiter}}))),i.listItem&&(n.listItem=(e,t,n)=>{let r=n.all(e),i=r.length>1&&ove(r[0])?r.slice(1):r,a={};return typeof e.attrs.sourceMarkerSpacing==`number`&&(a.sourceMarkerSpacing=e.attrs.sourceMarkerSpacing),typeof e.attrs.sourceOrdinal==`number`&&(a.sourceOrdinal=e.attrs.sourceOrdinal),e.attrs.sourceCheckboxChar===`X`&&(a.sourceCheckboxChar=`X`),typeof e.attrs.sourceContinuationIndent==`number`&&(a.sourceContinuationIndent=e.attrs.sourceContinuationIndent),{type:`listItem`,checked:e.attrs.checked??null,spread:e.attrs.spread??!1,...Object.keys(a).length>0?{data:a}:{},children:i}}),i.table&&(n.table=(e,t,n)=>{let r=n.all(e),i=[],a=e.firstChild;a&&a.forEach(e=>{let t=e.attrs.align;i.push(t===`left`||t===`right`||t===`center`?t:null)});let o=r.filter(e=>e.type===`tableRow`),s=e.attrs.sourceDashCounts,c={};Array.isArray(s)&&s.length>0&&(c.sourceDashCounts=s);let l=e.attrs.sourceOuterPipes;typeof l==`object`&&l&&typeof l.leading==`boolean`&&typeof l.trailing==`boolean`&&(c.sourceOuterPipes=l);let u=e.attrs.sourceAlignmentPadding;Array.isArray(u)&&u.length>0&&(c.sourceAlignmentPadding=u);let d=Object.keys(c).length>0?c:void 0,f={type:`table`,align:i,children:o};return d&&(f.data=d),f}),i.tableRow&&(n.tableRow=RW(`tableRow`));let o=(e,t)=>{let n={type:`tableCell`,children:HP(t)},r=e.attrs.sourcePadding;return typeof r==`object`&&r&&typeof r.left==`number`&&typeof r.right==`number`&&(n.data={sourcePadding:r}),n};if(i.tableCell&&(n.tableCell=(e,t,n)=>o(e,n.all(e))),i.tableHeader&&(n.tableHeader=(e,t,n)=>o(e,n.all(e))),i.image&&(n.image=e=>{let t={type:`image`,url:e.attrs.sourceUrl??e.attrs.src,alt:e.attrs.alt,title:e.attrs.title};return e.attrs.sourceUrlForm===`angle-bracketed`&&(t.data={sourceUrlForm:`angle-bracketed`}),t}),i.imageReference&&(n.imageReference=e=>{let t=e.attrs.label??``,n=e.attrs.identifier??t;return{type:`imageReference`,alt:e.attrs.alt??``,identifier:n,label:t||n,referenceType:e.attrs.referenceType??`shortcut`}}),i.htmlBlock&&(n.htmlBlock=e=>({type:`html`,value:e.attrs.content})),i.linkDefinition??i.linkRefDef){let e=i.linkDefinition?`linkDefinition`:`linkRefDef`;n[e]=e=>{let t={},n=e.attrs.sourceLayout;(n===`multiline`||n===`inline`)&&(t.sourceLayout=n);let r=e.attrs.sourceTitleMarker;(r===`single`||r===`double`||r===`paren`)&&(t.sourceTitleMarker=r),e.attrs.sourceUrlForm===`angle-bracketed`&&(t.sourceUrlForm=`angle-bracketed`);let i={type:`definition`,identifier:e.attrs.identifier??e.attrs.label??``,label:e.attrs.label??e.attrs.identifier??``,url:e.attrs.url??e.attrs.href??``,title:e.attrs.title};return Object.keys(t).length>0&&(i.data=t),i}}if(i.jsxComponent&&(n.jsxComponent=(e,n,r)=>{if(e.attrs.kind===`expression`)return{type:`html`,value:e.attrs.sourceRaw??``};let i=e.attrs.componentName||null,a=Array.isArray(e.attrs.attributes)?e.attrs.attributes:[];return!ave(e,t.checker)&&e.attrs.sourceRaw?{type:`mdxJsxFlowElement`,name:i,attributes:a,children:[],data:{sourceRaw:String(e.attrs.sourceRaw)}}:qq.getOrWildcard(i??`*`).serialize(e,{all:e=>r.all(e),registry:qq,serializeChildren:()=>{throw Error(`SerializeContext.serializeChildren is not available in the PM→mdast handler. Compat descriptors that need markdown-byte body rendering must emit a marker mdast node and let the to-markdown handler render the body via state.containerFlow.`)}})}),i.rawMdxFallback&&(n.rawMdxFallback=e=>{let t=e.textContent??``,n=typeof e.attrs.reason==`string`?e.attrs.reason:``,r=e.attrs.originalSpan;return{type:`rawMdxFallback`,value:t,data:{reason:n,originalSpan:r&&typeof r==`object`&&`start`in r&&`end`in r?{start:Number(r.start)||0,end:Number(r.end)||0}:{start:0,end:0}}}}),i.jsxInline&&(n.jsxInline=e=>{let t=e.attrs.componentName||``;if(t&&e.attrs.sourceDirty)return CB(t,e,qq.get(t)?.props);let n=e.attrs.attributes,r=e.attrs.sourceRaw||e.textContent||``;return{type:`mdxJsxTextElement`,name:t||null,attributes:Array.isArray(n)?n:[],children:[],data:{sourceRaw:String(r)}}}),i.mathInline&&(n.mathInline=e=>{let t=e.attrs.formula??``,n=e.attrs.id;if(typeof n==`string`&&n.length>0)return{type:`mdxJsxTextElement`,name:`InlineMath`,attributes:[{type:`mdxJsxAttribute`,name:`formula`,value:t},{type:`mdxJsxAttribute`,name:`id`,value:n}],children:[]};let r=e.attrs.sourceDelimiter;return{type:`inlineMath`,value:t,...typeof r==`string`&&r.length>0?{data:{sourceDelimiter:r}}:{}}}),i.wikiLink&&(n.wikiLink=e=>{let t=e.attrs.target??``,n=e.attrs.anchor??null,r=e.attrs.alias??null,i=r||(n?`${t}#${n}`:t);return{type:`wikiLink`,value:i,data:{target:t,anchor:n,alias:r,sourceTarget:typeof e.attrs.sourceTarget==`string`?e.attrs.sourceTarget:null,sourceAnchor:typeof e.attrs.sourceAnchor==`string`?e.attrs.sourceAnchor:null,sourceAlias:typeof e.attrs.sourceAlias==`string`?e.attrs.sourceAlias:null},children:[{type:`text`,value:i}]}}),i.tag&&(n.tag=e=>({type:`tag`,value:String(e.attrs.value??``)})),i.wikiLinkEmbed&&(n.wikiLinkEmbed=e=>{let t=e.attrs.target??``,n=e.attrs.anchor??null,r=e.attrs.alias??null,i=r||(n?`${t}#${n}`:t);return{type:`wikiLinkEmbed`,value:i,data:{target:t,anchor:n,alias:r},children:[{type:`text`,value:i}]}}),a.emphasis&&(r.emphasis=zW(`emphasis`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),a.strong&&(r.strong=zW(`strong`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),a.code&&(r.code=(e,t,n)=>{let r=e.attrs.sourceFenceChar,i=e.attrs.sourceFenceLength;return Xq(n,{sourceFenceChar:r,sourceFenceLength:i,sourcePadded:e.attrs.sourcePadded===!0||void 0})}),a.strike??a.delete){let e=a.strike?`strike`:`delete`;r[e]=zW(`delete`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter===`~`?`~`:`~~`}}))}return a.highlight&&(r.highlight=zW(`mark`)),a.underline&&(r.underline=zW(`underline`,e=>({data:{sourceForm:e.attrs.sourceForm===`ins`?`ins`:`u`}}))),a.comment&&(r.comment=zW(`comment`,e=>({data:{sourceForm:e.attrs.sourceForm===`html`?`html`:`percent`}}))),i.commentBlock&&(n.commentBlock=RW(`commentBlock`,e=>({data:{sourceForm:e.attrs.sourceForm===`html`?`html`:`percent`,sourceLayout:e.attrs.sourceLayout===`inline`?`inline`:`block`}}))),i.footnoteReference&&(n.footnoteReference=e=>{let t=String(e.attrs.identifier??``);return{type:`footnoteReference`,identifier:t,label:e.attrs.label?String(e.attrs.label):t}}),i.footnoteDefinition&&(n.footnoteDefinition=RW(`footnoteDefinition`,e=>({identifier:String(e.attrs.identifier??``),label:e.attrs.label?String(e.attrs.label):String(e.attrs.identifier??``)}))),a.link&&(r.link=(e,t,n)=>{if(e.attrs.sourceForm===`wikiembed`){let t=typeof e.attrs.target==`string`&&e.attrs.target.length>0?e.attrs.target:e.attrs.href??``,r=typeof e.attrs.anchor==`string`&&e.attrs.anchor.length>0?e.attrs.anchor:null,i=typeof e.attrs.alias==`string`&&e.attrs.alias.length>0?e.attrs.alias:null,a=typeof e.attrs.sourceTarget==`string`?e.attrs.sourceTarget:null,o=typeof e.attrs.sourceAnchor==`string`?e.attrs.sourceAnchor:null,s=typeof e.attrs.sourceAlias==`string`?e.attrs.sourceAlias:null,c=i||(r?`${t}#${r}`:t),l=n.map(e=>`value`in e&&typeof e.value==`string`?e.value:``).join(``);return l!==c&&l.trim().length>0&&!l.includes(`]]`)&&(i=l,c=l),{type:`wikiLinkEmbed`,value:c,data:{target:t,anchor:r,alias:i,sourceTarget:a,sourceAnchor:o,sourceAlias:s},children:[{type:`text`,value:c}]}}let r=e.attrs.linkStyle;if(r===`autolink`)return{type:`link`,url:e.attrs.href??``,title:null,children:n,data:{sourceStyle:`autolink`}};if(r===`gfm-autolink`)return{type:`link`,url:e.attrs.href??``,title:null,children:n,data:{sourceStyle:`gfm-autolink`}};if(r===`inline`||!r){let t={};e.attrs.sourceUrlForm===`angle-bracketed`&&(t.sourceUrlForm=`angle-bracketed`);let r=e.attrs.sourceTitleMarker;return(r===`single`||r===`double`||r===`paren`)&&(t.sourceTitleMarker=r),{type:`link`,url:e.attrs.href??``,title:e.attrs.title??null,children:n,...Object.keys(t).length>0?{data:t}:{}}}return{type:`linkReference`,identifier:(e.attrs.refLabel??``).toLowerCase(),label:e.attrs.refLabel,referenceType:r,children:n}}),a.escapeMark&&(r.escapeMark=(e,t,n)=>{for(let e of n)if(e.type===`text`&&e.value){let t=e;t.data??={},t.data.escapedChars??=[];for(let e=0;e<t.value.length;e++)t.data.escapedChars.push({offset:e,char:t.value[e]})}return n.length===1?n[0]:n}),a.sourceLiteral&&(r.sourceLiteral=(e,t,n)=>{let r=typeof e.attrs.sourceRaw==`string`?e.attrs.sourceRaw:``;if(n.length===1&&n[0]?.type===`text`){let e=n[0],t=r||e.value;return tk(t,e.value)&&(e.data??={},e.data.sourceRaw=t),e}return{type:`text`,value:n.filter(e=>e.type===`text`).map(e=>e.value??``).join(``)||r}}),{nodeHandlers:n,markHandlers:r}}const uve=new Set([`img`,`video`,`audio`,`mark`,`u`,`ins`]);new Map(QB.flatMap(e=>e.surface===`compat`&&uve.has(e.rendersAs)?[[e.name,e]]:[])),Np(`<>`);var Qq={SINGLE_TILDE:0,COMPARISON_OPERATORS:5,HTML_TAGS:10,SETEXT_HEADINGS:15,LINKS:20,BOLD_ITALIC:30,BOLD:35,ITALIC_DOUBLE_UNDERSCORE:40,ITALIC_SINGLE_ASTERISK:41,ITALIC_SINGLE_UNDERSCORE:42,INLINE_CODE:50,STRIKETHROUGH:60,KATEX:70,INLINE_KATEX:75,DEFAULT:100};Qq.SINGLE_TILDE,Qq.COMPARISON_OPERATORS,Qq.HTML_TAGS,Qq.SETEXT_HEADINGS,Qq.LINKS,Qq.BOLD_ITALIC,Qq.BOLD,Qq.ITALIC_DOUBLE_UNDERSCORE,Qq.ITALIC_SINGLE_ASTERISK,Qq.ITALIC_SINGLE_UNDERSCORE,Qq.INLINE_CODE,Qq.STRIKETHROUGH,Qq.KATEX,Qq.INLINE_KATEX,ug().use(w_).use(Uh);const $q=U(bt),dve=U(iee),fve=V({alwaysOn:L().int().nonnegative(),onTrigger:L().int().nonnegative(),onDemand:L().int().nonnegative()}).strict();V({intents:B(V({satisfierId:I().min(1),desired:U([`present`,`absent`])}).loose()),...Ud,summary:Wd}).loose();const pve=V({satisfierId:I(),agentId:I(),piece:I(),scope:I(),kind:I(),pathId:I().optional(),desired:U([`present`,`absent`]),action:U(va),errorId:I().optional()}).loose(),mve=V({kind:I(),satisfierIds:B(I()),agentIds:B(I()),pathId:I().optional(),blockedReason:I().optional()}).loose(),hve=V({state:I(),strictness:B(U(ga)).optional()}).loose(),gve=V({probes:V({env:U([`desktop`,`local-web`,`remote-web`]),satisfiers:H(I(),hve)}).loose(),detection:V({detected:B(I()),probed:R()}).loose()}).loose();V({actions:B(pve),conflicts:B(mve),withheld:B(I()),snapshot:gve}).loose(),V({entries:B(V({level:U([`info`,`warn`,`error`]),message:I().max(8192),event:I().optional(),fields:H(I(),z()).optional(),ts:L().optional(),sourceId:I().optional(),lineNumber:L().optional()}).loose()).max(100),droppedSinceLastFlush:L().int().min(0).optional()}).loose(),V({accepted:L().int().min(0)}).loose();const _ve=V({exact:I().min(1),prefix:I(),suffix:I(),start:L().int().nonnegative(),end:L().int().nonnegative()}),vve=B($i([I(),L().int().nonnegative()])),yve=ea(`kind`,[V({kind:W(`body`)}),V({kind:W(`property`),key:I().min(1),path:vve.default([])})]).default({kind:`body`}),bve=U([`anchored`,`orphaned`,`resolved`]),eJ=V({threadId:I().min(1),docName:I().min(1),target:yve,anchor:_ve.nullable(),state:bve,queued:R(),latestComment:I(),createdBy:I().min(1),createdAt:L(),updatedAt:L().optional()}),tJ=V({docName:I(),instruction:I(),property:I().nullable(),passage:V({exact:I(),prefix:I(),suffix:I()}).nullable(),anchorLost:R(),passageRepeats:R()}).loose(),nJ=V({threadId:I(),ok:W(!0)}),rJ=V({threadId:I(),ok:W(!1),error:W(`not-found`)});V({threads:B(eJ)}).loose(),V({meta:eJ,orphaned:R()}).loose(),V({threadId:I()}).loose(),V({meta:eJ,payload:tJ}).loose(),V({results:B($i([nJ.extend({meta:eJ,payload:tJ}),rJ]))}).loose(),V({results:B($i([nJ.extend({meta:eJ}),rJ]))}).loose();const xve=V({status:I().min(1),reason:I()}).loose();V({docName:I().min(1),content:I(),lifecycle:xve.nullable()}).loose(),V({documents:B(V({kind:U([`document`,`asset`,`folder`,`file`]).default(`document`),docName:I().min(1).optional(),docExt:I().min(1).default(`.md`),size:L().int().nonnegative(),modified:I().min(1),isSymlink:R().default(!1),canonicalDocName:I().nullable().default(null),targetPath:I().nullable().default(null),path:I().min(1).optional(),assetExt:I().min(1).optional(),mediaKind:U([`image`,`video`,`audio`,`pdf`,`text`,`mermaid`,`excalidraw`]).nullable().optional(),referencedBy:B(I().min(1)).optional(),hasChildren:R().optional()}).loose().refine(e=>e.kind===`document`?e.docName!==void 0&&e.path===void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0&&e.hasChildren===void 0:e.kind===`folder`?e.docName===void 0&&e.path!==void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.kind===`file`?e.path!==void 0&&e.mediaKind===void 0&&e.referencedBy===void 0&&e.hasChildren===void 0:e.path!==void 0&&e.assetExt!==void 0&&e.referencedBy!==void 0&&e.hasChildren===void 0,{message:`document/asset/folder/file kind must match its required fields (document → docName; asset → path+assetExt+referencedBy; folder → path only, no docName; file → path, no mediaKind/referencedBy/hasChildren)`})),truncated:R().optional()}).loose();const Sve=V({source:I().min(1),anchor:I().nullable(),title:I(),snippet:I().nullable()}).loose();V({docName:I().min(1),backlinks:B(Sve)}).loose(),V({counts:H(I().min(1),L().int().nonnegative())}).loose(),V({counts:H(I().min(1),L().int().nonnegative())}).loose();const Cve=ea(`kind`,[V({kind:W(`doc`),docName:I().min(1),anchor:I().nullable(),title:I(),snippet:I().nullable()}).loose(),V({kind:W(`external`),url:I().min(1),title:I(),snippet:I().nullable()}).loose()]),wve=V({role:I().min(1),sourceForm:I().min(1),targetKind:I().min(1),href:I(),resolvedTarget:I().nullable(),status:I().min(1),reason:I().nullable(),resolutionMethod:I().min(1),fallbackTarget:I().nullable().default(null),range:V({start:L().int().nonnegative(),end:L().int().nonnegative()}),line:L().int().nonnegative(),column:L().int().nonnegative(),definition:V({label:I(),line:L().int().nonnegative()}).nullable().default(null)}).loose();V({docName:I().min(1),forwardLinks:B(Cve),localTargets:B(wve).optional()}).loose();const Tve=ea(`kind`,[V({id:I().min(1),kind:W(`doc`),docName:I().min(1),anchor:I().nullable(),label:I(),cluster:I().nullable(),category:I().nullable(),tags:B(I()).nullable(),managed:R().optional()}).loose(),V({id:I().min(1),kind:W(`external`),url:I().min(1),label:I()}).loose()]),Eve=V({source:I().min(1),target:I().min(1)}).loose();V({nodes:B(Tve),links:B(Eve)}).loose();const Dve=V({ts:L().int().min(0),url:I(),method:I(),ua:I().optional(),origin:I().optional(),referer:I().optional(),host:I().optional(),remote:I().optional(),secChUa:I().optional(),secChUaMobile:I().optional(),secChUaPlatform:I().optional(),secFetchSite:I().optional(),secFetchDest:I().optional(),secFetchMode:I().optional(),secFetchUser:I().optional()}).loose(),Ove=V({app:$i([W(`cursor`),W(`codex`),W(`claude`),qi()]),signals_fired:B(I())}).loose();V({entries:B(Dve),count:L().int().min(0),detection:Ove}).loose();const iJ=V({path:I().min(1),code:U([`M`,`A`,`D`,`R`,`C`,`U`,`T`,`?`,`!`,` `]),origPath:I().min(1).optional(),syncScoped:R(),open:ea(`kind`,[V({kind:W(`doc`),docName:I().min(1)}),V({kind:W(`asset`),path:I().min(1)})]).optional()}).loose();V({branch:I().nullable(),detached:R(),upstream:I().nullable(),staged:B(iJ),notStaged:B(iJ),untracked:B(iJ),incoming:B(iJ),truncated:R(),readable:R().default(!0)}).loose();const kve=U([`AWAITING_CHECKS`,`LOCKED`,`MERGEABLE`,`QUEUED`,`UNMERGEABLE`]),Ave=U([`BEHIND`,`BLOCKED`,`CLEAN`,`DIRTY`,`DRAFT`,`HAS_HOOKS`,`UNKNOWN`,`UNSTABLE`]),jve=U([`APPROVED`,`CHANGES_REQUESTED`,`REVIEW_REQUIRED`]),Mve=U([`ERROR`,`EXPECTED`,`FAILURE`,`PENDING`,`SUCCESS`]),Nve=V({mergeQueue:V({position:L().int().nonnegative(),state:kve.nullable().catch(null)}).nullable().catch(null),autoMerge:R(),mergeState:Ave.nullable().catch(null),reviewDecision:jve.nullable().catch(null),checks:Mve.nullable().catch(null)}).loose(),Pve=V({kind:U([`pull`,`issue`]),repo:I().min(1),number:L().int().positive(),title:I(),author:I().nullable(),createdAt:I(),lifecycle:U([`open`,`draft`,`merged`,`closed`,`completed`,`not-planned`]),additions:L().int().nonnegative().optional(),deletions:L().int().nonnegative().optional(),status:Nve.optional()}).loose();V({url:I()}).loose(),ea(`ok`,[V({ok:W(!0),preview:Pve}).loose(),V({ok:W(!1),reason:I()}).loose()]),V({writers:B(V({id:I().min(1),name:I().optional(),email:I().optional()}).loose()).optional(),summary:Wd,...Ud}).loose(),V({checkpointRef:I().min(1)}).loose();const Fve=V({v:L().int().optional(),id:I().min(1),name:I().min(1),colorSeed:I().optional(),docs:B(I()),summaries:B(I()).optional()}).loose();V({entries:B(V({sha:I().min(1),timestamp:I().min(1),author:I(),authorEmail:I(),type:U([`checkpoint`,`wip`,`upstream`,`park`]),message:I(),contributors:B(Fve),checkpoint:z().nullable(),parentSha:I().nullable().optional()}).loose()),total:L().int().nonnegative().optional(),truncated:R().optional(),hasMore:R().optional()}).loose(),V({sha:I().regex(/^[0-9a-f]{40}$/i),content:I(),timestamp:I(),author:I()}).loose(),V({contentDir:I().min(1),pathSeparator:U([`/`,`\\`]),symlinkResolved:R()}).loose(),B(ea(`source`,[V({docName:I().min(1),timestamp:I().min(1),size:L().int().nonnegative(),source:W(`flat`)}).loose(),V({docName:I().min(1),timestamp:I().min(1),source:W(`timeline`),sha:I().min(1)}).loose()])).meta({description:"Flat array of rescue buffer entries; discriminated via `source`."});const Ive=V({domain:I().min(1),title:I().optional(),description:I().optional(),siteName:I().optional(),faviconDataUri:I().optional()}).loose();V({url:I()}).loose(),ea(`ok`,[V({ok:W(!0),metadata:Ive}).loose(),V({ok:W(!1),reason:I()}).loose()]),V({orphans:B(V({docName:I().min(1),title:I()}).loose())}).loose(),V({hubs:B(V({docName:I().min(1),title:I(),count:L().int().nonnegative()}).loose())}).loose();const Lve=V({source:I().min(1),title:I(),snippet:I().nullable()}).loose();V({deadLinks:B(V({target:I().min(1),sources:B(Lve)}).loose())}).loose(),V({target:V({docName:I().min(1),title:I(),aliases:B(I())}).loose(),mentions:B(V({source:I().min(1),excerpt:I(),offset:L().int().nonnegative()}).loose()),truncated:R()}).loose(),V({projectPath:I().min(1)}).loose();const Rve=U([`not-a-git-worktree`,`init-failed`]);ea(`ok`,[V({ok:W(!0),projectPath:I().min(1)}).loose(),V({ok:W(!1),reason:Rve,message:I().min(1)}).loose()]),V({host:I().min(1).optional()}).loose(),V({host:I().min(1).optional(),token:I().min(1)}).loose(),V({host:I(),login:I()}).loose(),V({host:I().refine(hc,{message:`Host must be a hostname with an optional :port, with no scheme or path`}),username:I().min(1),token:I().min(1)}).loose(),V({host:I(),login:I()}).loose(),V({key:I().min(1)}).loose(),V({keyPresent:R()}).loose();const zve=U([`no_key`,`invalid_endpoint`,`rate_limit`,`timeout`,`http_error`,`network`,`dims_mismatch`,`malformed_response`]);ea(`ok`,[V({ok:W(!0),endpoint:I().min(1),model:I().min(1),dimensions:L().int().positive()}).loose(),V({ok:W(!1),endpoint:I().min(1),model:I().min(1),reason:zve,status:L().int().optional()}).loose()]),V({name:I().refine(e=>e.trim().length>0,{message:`name must be non-empty`}),email:I().refine(e=>e.trim().length>0,{message:`email must be non-empty`})}).loose(),V({authenticated:R()}).loose(),V({channel:U([`login`,`gh-login`]).default(`login`)}).loose(),V({}).loose();const Bve=V({stackIndex:L().int().min(0),ts:L().int().min(0),additions:L().int().min(0),deletions:L().int().min(0)}).loose(),Vve=V({docName:I().min(1),additionsTotal:L().int().min(0),deletionsTotal:L().int().min(0),lastTs:L().int().min(0),bursts:B(Bve)}).loose(),Hve=V({displayName:I().min(1),color:I().min(1),icon:I().optional(),connectionId:I().min(1)}).loose();V({sessionAlive:R(),agent:Hve.nullable(),files:B(Vve)}).loose(),V({diff:I(),before:I(),after:I(),properties:kP,generatedAt:L().int().min(0)}).loose(),V({}).loose(),V({}).loose(),V({}).loose(),V({}).loose(),V({}).loose(),V({}).loose();const Uve=V({displayName:I().min(1),icon:I(),color:I().min(1),currentDoc:I().nullable(),mode:U([`idle`,`writing`]),ts:L().int().min(0)}).loose();V({presence:H(I().min(1),Uve)}).loose();const Wve=V({sessionId:I().min(1),agentType:I().min(1),ts:L().int().min(0),insertedChars:L().int().min(0),deletedChars:L().int().min(0)}).loose();V({effects:B(V({"doc.name":I().min(1),entries:B(Wve)}).loose())}).loose(),V({decisions:B(V({ts:L().int().min(0),decision:I().min(1),kind:I().min(1),"doc.name":I().min(1),pathRole:I().min(1)}).loose())}).loose(),H(I().min(1),R()).meta({description:`Flat boolean record keyed by agent-scheme name (claude / codex / cursor). True = installed.`}),V({path:I().min(1,`path must be non-empty`)}).loose(),V({}).loose();const Gve=V({fromDocName:I().min(1),toDocName:I().min(1)}).loose(),Kve=V({fromPath:I().min(1),toPath:I().min(1)}).loose();V({}).loose(),V({path:I().min(1),...Ud,summary:Wd}).loose(),V({docName:I().min(1)}).loose(),V({path:I().min(1),...Ud,summary:Wd}).loose(),V({path:I().min(1)}).loose(),V({kind:U([`file`,`folder`]),path:I().min(1),...Ud,summary:Wd}).loose(),V({kind:U([`file`,`folder`]),path:I().min(1),duplicatedDocNames:B(I().min(1))}).loose(),V({pages:B(V({docName:I().min(1),title:I(),docExt:I().min(1),size:L().int().nonnegative(),modified:I().min(1),icon:I().min(1).max(2048).optional()}).loose())}).loose();const qve=V({level:L().int().min(1).max(6),text:I(),slug:I()}).loose();V({docName:I().min(1),headings:B(qve)}).loose();const Jve=V({docName:I().min(1),rewrites:L().int().nonnegative()}).loose();V({kind:U([`file`,`folder`,`asset`]),fromPath:I().min(1),toPath:I().min(1),...Ud,summary:Wd}).loose(),V({renamed:B(Gve),renamedAssets:B(Kve),rewrittenDocs:B(Jve).optional(),summary:Kd.optional()}).loose(),V({kind:U([`file`,`folder`,`asset`]),path:I().min(1),...Ud}).loose(),V({deletedDocNames:B(I().min(1))}).loose(),V({kind:U([`file`,`folder`,`asset`]),path:I().min(1),...Ud,summary:Wd}).loose(),V({deletedDocNames:B(I().min(1))}).loose(),V({docName:I().min(1),commitSha:I().regex(/^[0-9a-f]{40}$/i,{message:`commitSha must be a 40-char git SHA`}),summary:Wd,...Ud}).loose(),V({restoredFrom:I().min(1),timestamp:I().min(1),summary:Kd.optional(),warnings:Zd.optional()}).loose();const Yve=/^#[0-9a-fA-F]{6}$/,Xve=V(Object.fromEntries(el.map(e=>[e,I().regex(Yve,`must be a #rrggbb hex color`)]))),aJ=I().min(1).refine(al,{message:`must contain a non-whitespace character`}),oJ=V({name:aJ,author:aJ.optional(),variant:U([`dark`,`light`]),palette:Xve}).loose();V({name:I().min(1),scheme:oJ,stem:I().min(1).optional(),extension:U([`.yaml`,`.yml`]).optional()}).loose(),V({id:I().min(1),filename:I().min(1)}).loose(),V({id:I().min(1),scheme:oJ}).loose(),V({id:I().min(1),filename:I().min(1)}).loose(),ea(`existed`,[V({existed:W(!1)}).loose(),V({existed:W(!0),filename:I().min(1),scheme:oJ}).loose()]),V({themes:B(ea(`ok`,[V({ok:W(!0),id:I().min(1),filename:I().min(1),scheme:oJ}),V({ok:W(!1),filename:I().min(1),id:I().min(1).optional(),code:I().min(1),conflictingFilenames:B(I().min(1)).min(2).optional()})])),truncated:R()}).loose();function Zve(e){return e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`)}function Qve(e){let t=Zve(e).at(-1);return t!==void 0&&Dd.some(e=>t.toLowerCase().endsWith(e))}V({tags:B(V({name:I().min(1),count:L().int().nonnegative(),isLeaf:R()}).loose())}).loose();const $ve=V({docName:I().min(1),title:I(),matchingTags:B(I().min(1)),snippet:I().nullable()}).loose();V({name:I().min(1),docs:B($ve)}).loose(),V({folder:z(),frontmatter_local:H(I(),z()).nullable(),warnings:B(I()).optional().meta({description:"Non-fatal degradations of this response, one per entry; the field each affects is absent, null, or incomplete — the aligned `warningCodes` entry names which field and how."}),warningCodes:B(U([`symlink-refused`,`malformed-yaml`,`unverifiable`,`templates-symlink-refused`,`templates-unverifiable`])).optional().meta({description:"Machine-readable codes aligned 1:1 with `warnings`; switch on these, never on the English. `symlink-refused` / `malformed-yaml` / `unverifiable`: this folder's own `.ok/frontmatter.yml` (a symlink, malformed YAML, or an lstat failure) — `frontmatter_local` is null. `templates-symlink-refused` / `templates-unverifiable`: the `.ok/templates` directory on this folder, or a `.ok` or `.ok/templates` directory on an ancestor it inherits from — a symlink (wherever it points, dangling included), or a non-ENOTDIR `lstat` failure — `folder.templates_available` omits that directory's templates and may still list others. A non-directory `.ok` / `.ok/templates` (ENOTDIR) is treated as empty and yields no `templates-*` code. This folder's own symlinked `.ok` is a 400, never a warning."})}).loose(),V({path:I(),frontmatter:H(I(),z()).optional()}).loose(),V({applied:z()}).loose();const sJ=H(I(),z()).meta({description:`Free-form frontmatter map embedded in template payloads.`});V({template:V({name:I().min(1),folder:I(),scope:U([`local`,`inherited`]),path:I().min(1),frontmatter:sJ,body:I()}).strict()}).strict(),V({templates:B(V({name:I().min(1),title:I().optional(),description:I().optional(),path:I().min(1),source_folder:I()}).strict()),truncated:R()}).strict(),V({folder:I(),name:I(),body:Bd.optional(),frontmatter:sJ.optional(),...Ud,summary:Wd}).strict(),V({path:I().min(1),created:R(),warnings:B(I())}).strict(),V({sourcePath:I().min(1),targetFolder:I(),name:I().optional(),title:I().optional(),deleteSource:R().optional(),...Ud,summary:Wd}).strict(),V({path:I().min(1),created:R(),warnings:B(I())}).strict(),V({existed:R(),path:I().min(1)}).strict(),V({fromFolder:I(),fromName:I(),toFolder:I(),toName:I(),body:Bd.optional(),frontmatter:sJ.optional(),...Ud,summary:Wd}).strict(),V({from:I().min(1),to:I().min(1),committed:R()}).strict();const cJ=U(Ed),eye=/^[a-z0-9-]+$/,lJ=V({name:I(),description:I(),metadata:V({pack:I()}).strict().optional()}).strict();V({skill:V({name:I().min(1),scope:cJ,path:I().min(1),frontmatter:lJ,body:I(),files:B(V({path:I().min(1),text:I().nullable()})).optional(),managed:R().optional()}).strict()}).strict();const tye=V({source:I().min(1),publisher:I().optional(),skill:I().optional(),marketplaceUrl:I().optional(),importedAt:I().min(1),autoUpdate:R().optional()}).strict(),nye=V({name:I().min(1),description:I().optional(),scope:cJ,path:I().min(1),canonicalPath:I().min(1).optional(),filePaths:B(I()).optional(),absolutePath:I().min(1).optional(),installed:R(),hosts:B(I()),hostQualifier:I().optional().meta({description:"Set on a GLOBAL entry that shares its name with a distinct-content bundle in another host dir AND is not the by-name default: the host id whose root holds THIS bundle. Doc-name builders append it (`__skill__/global/<name>@<host>`) so each same-named bundle keeps its own tab and its own write-back path; the default bundle keeps the stable unqualified name."}),driftPaths:B(I()).optional().meta({description:`Recorded locations whose on-disk form (copy vs symlink) no longer matches what OK last wrote there — evidence another tool rewrote the path.`}),hostAliases:H(I(),I()).optional().meta({description:`Host skills roots that are symlink ALIASES of another location (host id → base-relative target root). An aliased folder is a derived view — no menu row, never a write target; the host's icon rides the target root's row.`}),conflictHosts:B(I()).optional().meta({description:`Hosts whose dir holds a DIFFERENT same-name skill (fork/conflict) — occupied, not this skill.`}),symlinkedHosts:B(I()).optional(),installableEditors:B(I()).optional(),hubOffered:R().optional().meta({description:"Whether the vendor-neutral `.agents/skills` hub is a live destination at this scope on THIS machine — server-computed via the same predicate that filters the Folders surface, so the install menu and Settings cannot disagree. True when the project already uses the hub OR a host that reads it is installed (`HUB_READER_EDITORS`)."}),linkMode:R().optional(),customPlacements:B(V({path:I(),mode:U([`copy`,`link`])}).strict()).optional(),plugin:V({name:I().min(1),marketplace:I().min(1),provider:I().min(1),url:I().optional()}).strict().optional(),managed:R().optional(),origin:tye.optional(),pack:I().optional(),modified:R().optional(),revertable:R().optional(),ignored:R().optional(),size:fve.optional()}).strict();V({name:I().min(1),scope:cJ,apply:R().optional()}).strict(),V({line:I().min(1),gitignorePath:I().min(1),applied:R(),alreadyTracked:R().optional()}).strict(),V({skills:B(nye),truncated:R()}).strict(),V({scope:cJ.default(`project`),name:I().meta({description:`Managed skill name to create or update.`}),body:Bd.optional(),frontmatter:lJ,...Ud,summary:Wd}).strict();const uJ=[`skill-name-vendor-word`,`skill-body-too-long`],dJ=B(U(uJ)).meta({description:"Machine-readable codes aligned 1:1 with `warnings` (`warnings[i]` is the display text for `warningCodes[i]`)."});V({path:I().min(1),created:R(),warnings:B(I()),warningCodes:dJ}).strict(),V({scope:cJ.default(`project`),name:I(),dryRun:R().optional(),setAutoUpdate:R().optional(),...Ud,summary:Wd}).strict(),V({name:I().min(1),updated:R(),source:I().min(1),localBody:I().optional(),upstreamBody:I().optional(),gitTracked:R().optional(),warnings:B(I()),warningCodes:dJ}).strict(),V({scope:cJ.default(`project`),name:I(),...Ud,summary:Wd}).strict(),V({name:I().min(1),baselineRef:I().min(1),restoredFiles:B(I()),warnings:B(I())}).strict();const fJ=`This member also carries the one bookkeeping failure that does not undo the operation: the content change landed, but a state file this server keeps beside it refused to be rewritten because it could not be read, so the install or import records still describe the old state until an operator repairs that file. Absent when there is nothing to report; a server that predates this member omits it, so treat its absence as no warning rather than as an error.`;V({existed:R(),path:I().min(1),warnings:B(I()).optional().meta({description:`Present when this delete removed a directory a retention record ties to a recovery copy an earlier failed move kept, whose source was never verified unchanged — either because this server verified the deleted directory against the copy that record describes, or because it could not read the directory and so could not confirm either way. Each entry says which of the two it is; neither claims more than the check established. ${fJ}`})}).strict(),V({scope:cJ.default(`project`),fromName:I(),toName:I(),body:Bd.optional(),frontmatter:lJ.optional(),...Ud,summary:Wd}).strict(),V({from:I().min(1),to:I().min(1),committed:R(),warnings:B(I()).optional().meta({description:`Present when the rename itself completed but something beside it did not. ${fJ}`})}).strict(),V({name:I(),toName:I().optional().meta({description:"Name for the skill at the destination scope; defaults to `name`. The SKILL.md `name` frontmatter is rewritten to match."}),fromScope:cJ,toScope:cJ,...Ud,summary:Wd}).strict(),V({scope:cJ,path:I().optional(),droppedLocations:B(I()).default([]).meta({description:"Locations the skill occupied at the source that were removed and not re-created at the destination: the `agents` hub and custom roots, which projection does not cover. Entries are install location ids, so they can be passed straight back as an install `add` list with `scope` set to the destination scope; custom roots resolve against that scope's base."}),warnings:B(I()).optional().meta({description:`Present when the move itself completed but something beside it did not. ${fJ}`})}).strict().meta({description:"Scope-move result. Rename paths deliberately do not emit authoring warnings, consistent with same-scope rename and duplicate. Content-authoring and import responses carry those warnings and their codes. The Skills Studio client parses `droppedLocations` off the wire but deliberately does not render it yet; how a human is told what was removed is an open product decision."}),V({scope:cJ,name:I(),toName:I(),...Ud,summary:Wd}).strict(),V({name:I().min(1)}).strict(),V({name:I(),home:I().min(1)}).strict(),V({docName:I().min(1)}).strict();const pJ=U([`reference`,`script`,`file`]);V({scope:cJ.default(`project`),name:I(),path:I().min(1),content:I(),...Ud,summary:Wd}).strict().superRefine((e,t)=>{Qve(e.path)&&zd(e.content,t,[`content`])}),V({path:I().min(1),created:R(),kind:pJ,content:R()}).strict(),V({scope:cJ.default(`project`),name:I(),from:I().min(1),to:I().min(1),...Ud,summary:Wd}).strict(),V({from:I().min(1),to:I().min(1),fromDocName:I().optional(),toDocName:I().optional()}).strict(),V({path:I().min(1),kind:pJ,text:I()}).strict(),V({path:I().min(1),existed:R(),kind:pJ}).strict();const mJ=$i([dve,W(`agents`)]),hJ=I().min(1).refine(e=>!e.startsWith(`/`)&&!e.startsWith(`~`)&&!/^[A-Za-z]:/.test(e),{error:`a custom root is base-relative (e.g. ".tim/skills"), not absolute or ~-prefixed`}).refine(e=>e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`),{error:`a custom root may not contain "..", "." or empty path segments`}).refine(e=>e.includes(`/`),{error:`a custom root is a path (e.g. ".tim/skills") — bare editor names are host ids`}),gJ=$i([mJ,hJ]);V({scope:cJ.default(`project`),name:I(),targets:B(mJ).optional().meta({description:'SET-EXACT install targets (editor ids, plus "agents" for the .agents hub — in-place skills only): the COMPLETE resulting host set. Omit to use project-configured editors; pass [] to uninstall everywhere. Stateless callers should prefer `add`/`remove`.'}),add:B(gJ).optional().meta({description:`Locations to ADD the skill to (everything else untouched). Editor ids fan out a managed copy/symlink; a custom root path (".tim/skills") places the bundle there.`}),remove:B(gJ).optional().meta({description:"Locations to REMOVE the skill from (lossless only — a hand-edited fork is refused, never deleted). The source cannot be removed; move it first with `source`."}),mode:U([`copy`,`link`]).optional().meta({description:`"link": one real folder (the source); every other location becomes a symlink to it. "copy": independent real folders, refreshed from the source until hand-edited (a hand-edit forks that copy). Converts existing locations losslessly. Omit to follow the form the skill already uses.`}),source:gJ.optional().meta({description:`Move the skill's REAL folder to this location (the old source becomes a symlink to it — never a removal). Sticky across rescans.`}),linkMode:R().optional(),setSource:I().min(1).optional(),place:V({dir:I().min(1).meta({description:`Project-relative directory the bundle dir is created under (e.g. ".windsurf/skills").`}),mode:U([`copy`,`link`])}).strict().optional(),convert:V({target:gJ.meta({description:`The installed location to convert — an editor id, "agents", or a recorded custom placement path.`}),mode:U([`copy`,`link`]).meta({description:`"link": replace this location with a symlink to the source. "copy": replace it with an independent real folder.`})}).strict().optional(),unplace:V({path:I().min(1).meta({description:`The recorded placement bundle path (e.g. ".windsurf/skills/my-skill").`})}).strict().optional(),...Ud,summary:Wd,fork:V({editor:I().min(1),action:U([`align`,`make-source`,`rename`]),toName:I().optional()}).strict().optional()}).strict().refine(e=>e.targets===void 0||e.add===void 0&&e.remove===void 0,{error:"`targets` is set-exact; `add`/`remove` are additive — use one style per call"}).refine(e=>e.fork===void 0||e.targets===void 0&&e.add===void 0&&e.remove===void 0&&e.source===void 0&&e.setSource===void 0,{error:"`fork` is its own operation — run it in a separate call"}).refine(e=>e.fork?.action!==`rename`||e.fork.toName!==void 0,{error:"`fork.rename` requires `toName`"}).refine(e=>e.source===void 0||e.add===void 0&&e.remove===void 0,{error:"a `source` move is its own operation — run it in a separate call from `add`/`remove`"}).refine(e=>[e.targets!==void 0||e.add!==void 0||e.remove!==void 0,e.place!==void 0,e.unplace!==void 0,e.convert!==void 0,e.source!==void 0||e.setSource!==void 0,e.fork!==void 0].filter(Boolean).length<=1,{error:"one operation per call — membership (`targets`/`add`/`remove`), `place`, `unplace`, `convert`, `source`, and `fork` are mutually exclusive"});const _J=[`no-targets`,`scripts-present`,`name-conflict`,`no-description`,`skill-fork-name-unpatched`,`place-path-invalid`,`place-fork-refused`,`links-not-permitted`];V({name:I().min(1).meta({description:`Managed skill name installed or uninstalled.`}),hosts:B(I()).meta({description:`Editor ids the skill is projected into after the operation; [] is expected after uninstall.`}),scripts:R().meta({description:`True when the skill ships executable scripts, projected but never run.`}),warnings:B(I()).meta({description:`Non-fatal install/uninstall warnings from target projection.`}),warningCodes:B(U(_J)).meta({description:"Machine-readable warning codes aligned with `warnings`."}),placedAt:I().optional(),sourceMovedTo:I().optional()}).strict(),V({scope:cJ.default(`project`),name:I().meta({description:`Managed skill name to uninstall without deleting source.`})}).strict(),V({name:I().min(1).meta({description:`Managed skill name requested for uninstall.`}),uninstalled:R().meta({description:`True when an install marker existed and was removed; false for an idempotent no-op.`})}).strict(),V({targets:B($q),configured:R(),folders:B(V({scope:cJ,host:I(),root:I(),state:U([`own`,`linked`,`linked-parent`,`absent`]),target:I().optional(),drift:W(!0).optional(),expected:I().optional()}).strict()).optional()}).strict();const vJ=V({action:W(`link`),scope:cJ,root:I().min(1).meta({description:`The folder to link (e.g. ".codex/skills").`}),target:I().min(1).meta({description:`The root it merges into (e.g. ".agents/skills"). Required.`})}),yJ=V({action:W(`unlink`),scope:cJ,root:I().min(1).meta({description:`The linked folder to materialize back.`}),exclude:B(I().min(1)).optional().meta({description:`Skill names to LEAVE OUT when materializing — the folder keeps every other skill it currently sees (as per-skill links) and stops auto-following the target root.`})}).strict(),bJ=V({action:W(`add-root`),scope:cJ,root:hJ.meta({description:`New custom skills root to declare (base-relative, e.g. ".team/skills").`})}).strict(),rye=ea(`action`,[vJ.extend({preview:R().optional().meta({description:`Return the merge plan only (moves, drops, removes, conflicts, strays) — nothing is written.`})}).strict(),yJ,bJ]);ea(`action`,[vJ.strict(),yJ,bJ]),V({folderAction:rye}).strict();const iye=V({moves:B(I()),drops:B(I()),removes:B(I()),replaces:B(I()),conflicts:B(I()),strays:B(I())}).strict();V({targets:B($q),reprojected:B(V({name:I(),hosts:B(I())}).strict()),bundleHosts:B(I()),removedFrom:B(I()),folder:V({moved:B(I()),dropped:B(I()),linked:B(I())}).strict().optional(),preview:iye.optional()}).strict(),V({scope:cJ.default(`project`),name:I(),version:I().regex(/^[0-9a-f]{40}$/i),...Ud,summary:Wd}).strict(),V({name:I().min(1),version:I(),restoredFiles:B(I()),warnings:B(I())}).strict(),V({query:I().optional(),intent:U([`autocomplete`,`full_text`,`omnibar`]).optional(),ranking:U([`navigation`,`relevance`]).optional(),scopes:B(U([`page`,`folder`,`content`,`file`])).optional(),scope:I().optional(),limit:L().int().nonnegative().optional(),semantic:R().optional(),source:U([`omnibar`,`mcp`,`http`]).optional()}).loose();const aye=V({kind:U([`page`,`folder`,`content`,`file`]),path:I().min(1),title:I(),score:L(),signals:H(I(),z()),snippet:I().optional()}).loose(),oye=U([`applied`,`no_match`,`warming`,`incapable`,`provider_error`,`restart_required`,`query_too_short`]),xJ=U([`warm`,`corpus`,`query`,`dimensions`,`configured_dimensions`]),SJ=V({capable:R(),applied:R(),outcome:oye,providerErrorReason:xJ.nullable().optional().catch(null),coverage:V({embedded:L().int().nonnegative(),total:L().int().nonnegative()})}).loose();V({enabled:R(),keyPresent:R(),keyNotRequired:R(),keySource:U([`project`,`file`,`env`]).nullable(),keyHint:I().nullable(),ready:R(),capable:R(),providerError:R().optional(),providerErrorReason:xJ.nullable().optional().catch(null),embedded:L().int().nonnegative(),total:L().int().nonnegative()}).loose(),V({query:I(),intent:U([`autocomplete`,`full_text`,`omnibar`]),results:B(aye),elapsedMs:L().nonnegative(),semantic:SJ.optional(),truncated:R().optional(),ready:R().optional()}).loose();const sye=V({version:I().min(1),recordedAt:I().min(1)}).loose();V({currentVersion:I().min(1),targets:H(I(),sye.nullable())}).loose(),V({scope:cJ.default(`project`),source:I().min(1).meta({description:`External skill source: full skills.sh skill-page URL (https://www.skills.sh/<owner>/<repo>/<skill>, or https://www.skills.sh/site/<hostname>/<skill> for a website catalog), GitHub owner/repo[/subpath], git URL, or local/file path.`}),skill:I().min(1).optional().meta({description:`Specific skill name to import from a multi-skill source.`}),install:R().optional().meta({description:`Pass false to import WITHOUT the default-editor auto-projection (the caller installs explicitly afterwards). Default true.`}),marketplace:R().optional().meta({description:"The source came from a skills.sh listing the user chose (the Explore tab), so the install is reported to skills.sh and counts toward that listing. Off by default: a hand-typed repo must not be announced to skills.sh. Honors the `telemetry.skillInstallReports.enabled` setting and DO_NOT_TRACK."}),...Ud,summary:Wd}).strict(),V({scope:cJ.default(`project`),source:I().min(1).meta({description:`External skill source: full skills.sh skill-page URL, GitHub owner/repo[/subpath], git URL, or local/file path.`}),skills:B(I().min(1)).min(1).max(100).meta({description:`Skill names to import from the source.`}),install:R().optional().meta({description:`Pass false to import WITHOUT the default-editor auto-projection. Default true.`}),marketplace:R().optional().meta({description:"The source came from a skills.sh listing the user chose (a marketplace plugin bundle), so the import is reported to skills.sh as one batched install event and counts toward that listing. Off by default: a hand-typed repo must not be announced to skills.sh. Honors the `telemetry.skillInstallReports.enabled` setting and DO_NOT_TRACK."}),...Ud,summary:Wd}).strict(),V({results:B(V({requested:I(),status:U([`imported`,`already-imported`,`not-found`,`failed`]),name:I().optional(),collisionRenamedFrom:I().optional(),warnings:B(I()),warningCodes:dJ,error:I().optional()}).loose()),imported:L(),alreadyImported:L(),failed:L()}).loose(),V({scope:cJ.default(`project`),names:B(I().min(1)).min(1).max(100).meta({description:`Managed skill names to refresh from their recorded upstreams.`}),...Ud,summary:Wd}).strict(),V({results:B(V({requested:I(),status:U([`updated`,`up-to-date`,`not-found`,`failed`]),source:I().optional(),warnings:B(I()),warningCodes:dJ,error:I().optional()}).loose()),updated:L(),upToDate:L(),failed:L()}).loose();const cye=V({source:I(),ref:I().optional(),contentHash:I(),publisher:I().optional()}).loose();V({name:I().min(1).meta({description:`Managed skill name created or matched.`}),path:I().min(1).meta({description:`Store-relative path to the imported skill source.`}),created:R().meta({description:`True when this request created new source files.`}),alreadyImported:R().meta({description:`True when identical content was already present and no files changed.`}),collisionRenamedFrom:I().optional().meta({description:`Original source name when collision handling renamed the import.`}),provenance:cye,warnings:B(I()).meta({description:`Non-fatal import warnings, such as skipped unsupported files.`}),warningCodes:dJ}).loose();const lye=U([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`,`tags`,`comments`,`lint-config`,`local-targets`]);V({v:W(1),ch:W(`server-info`),seq:L(),serverInstanceId:I().min(1),currentBranch:I().min(1).optional()}).loose(),V({v:W(1),ch:W(`branch-switched`),seq:L(),branch:I().min(1)}).loose(),V({v:W(1),ch:lye,seq:L()}).loose(),V({v:W(1),ch:W(`disk-ack`),seq:L(),docName:I().min(1),sv:I().min(1)}).loose(),V({v:W(1),ch:W(`config-validation-rejected`),seq:L(),docName:I().min(1),error:Qie}).loose(),V({v:W(1),ch:W(`config-ignore-nested-error`),seq:L(),path:I().min(1),error:I().min(1)}).loose(),(()=>{let e=globalThis.Intl.Segmenter;return e?new e(`en`,{granularity:`word`}):null})();const uye=Zi({name:I(),description:I(),files:Zi({skillMd:I(),scripts:B(I()),references:B(I())})}),dye=Zi({pluginProvider:I().optional(),plugin:I().optional(),marketplace:I().optional(),repositoryUrl:I().optional(),version:I().optional(),gitCommitSha:I().optional(),scope:I().optional(),projectPath:I().optional()}),fye=Zi({commands:R(),hooks:R(),mcp:R()}),pye=Zi({...uye.shape,sourceHarness:I(),sourceHarnesses:B(I()),home:I(),provenance:dye,inert:fye,outsideProject:R().optional()}),mye=Zi({schema:W(1),name:I(),version:I(),description:I().optional(),author:Zi({name:I()}).optional(),skills:B(I()),hostCompatibility:B(I()).optional(),capabilities:Zi({scripts:I(),network:I(),inert:B(I())}).optional(),provenance:Zi({source:I(),ref:I(),contentHash:I()}).optional()});V({skills:B(pye),packs:B(mye)}).loose(),V({results:B(V({id:I().min(1),name:I().min(1),source:I().min(1),description:I(),installs:L().int().nonnegative().nullable(),publisher:I().nullable()}).loose()),backend:U([`skills.sh`,`github-fallback`]),degraded:R()}).loose(),V({title:I(),description:I(),image:I().nullable(),skillsUrl:I().nullable(),sourceKind:U([`github`,`site`]),sourceUrl:I()}).loose(),V({skills:B(V({name:I(),description:I().nullable()}).loose())}).loose(),V({kind:U([`local`,`import`,`none`]),scope:U(Ed).optional(),name:I().optional(),dir:I().optional(),source:I().optional(),ref:I().optional(),via:U([`source`,`publisher`]).optional()}).loose();const hye=V({relPath:I(),content:I().nullable()}).loose(),gye=V({provider:I(),plugin:I(),version:I().optional(),marketplace:I().optional(),repositoryUrl:I().optional()}).loose(),_ye=V({provider:I(),plugin:I(),version:I().optional(),description:I().optional(),repositoryUrl:I().optional(),bundledSkills:B(I()),capabilities:V({commands:R(),hooks:R(),mcp:R(),agents:R()}),setupSupported:R()}).loose();V({name:I(),description:I().nullable(),skillMd:I(),files:B(hye),plugin:gye.optional(),pluginBundle:_ye.optional()}).loose();const vye=[`auth-error`,`detached-head`,`dirty-tree`,`diverged-local-commits`,`external-changes-pending`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`no-push-permission`,`non-content-merge-failure`,`protected-branch`,`unsafe-incoming-symlinks`],CJ=e=>e*8+4;CJ(92),CJ(40),(()=>{let e=globalThis.Intl.Segmenter;return e?new e(void 0,{granularity:`grapheme`}):null})(),Array.from({length:256},(e,t)=>(t+256).toString(16).slice(1));const wJ={fileSystem:`File System`,gitUpstream:`Git (upstream)`,service:`OpenKnowledge (service)`,generator:`OpenKnowledge (generated)`},TJ=`state/bug-reports`,yye=Zi({at:I(),transport:I(),outcome:I(),reference:I().optional(),error:I().optional(),errorCode:I().optional()}),bye=Zi({reason:I(),at:I(),errorCode:I().optional()});Zi({version:L().int().catch(1),id:I(),createdAt:I(),bundleLevel:I(),zipBytes:L().int().nonnegative().catch(0),zipDeleted:R().optional(),state:I(),systemWide:R().optional(),projectSlug:I().nullable().optional(),reference:I().optional(),lastError:bye.optional(),attempts:B(yye).optional(),note:I().optional()}),Zi({version:L().int().catch(1),id:I().optional(),sentAt:I().optional(),reference:I().optional()});const xye=new Map([[`PORT`,[`server`,`port`]],[`OK_BIND`,[`server`,`bind`]],[`OK_EXTERNAL_URL`,[`server`,`externalUrl`]],[`OK_ALLOW_EXTERNAL`,[`server`,`allowExternal`]],[`OK_OPEN_BROWSER`,[`server`,`openBrowser`]],[`OK_IDLE_SHUTDOWN`,[`server`,`idleShutdown`]]]);function Sye(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toUpperCase()}function Cye(e){return`OK_${(e[0]===`server`?e.slice(1):e).map(Sye).join(`_`)}`}function wye(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Tye(e){let{value:t,file:n,source:r,doc:i}=e,a=[],o=(e,t)=>{if(t.length>0){let e=Wl(Ul,t);if(e!==void 0){if(e.scope===`project-local`){let e=Cye(t),o;i!=null&&r!=null&&n!=null&&(o=Zu({file:n,source:r,doc:i,path:t})),a.push({path:[...t],...xye.has(e)?{envVar:e}:{},...o===void 0?{}:{source:o}})}return}}if(wye(e))for(let[n,r]of Object.entries(e))o(r,[...t,n])};return o(t,[]),a}const EJ=`(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)`;RegExp(`^127\\.${EJ}\\.${EJ}\\.${EJ}$`);function DJ(e,t){return e===`unix-chain`?`# ok-mcp${t}-v`:`# ok-mcp${t}-win-v`}function OJ(e){return e.replace(/\/+/g,`/`).replace(/\/+$/,``)}function Eye(e){return rt[e].userHomeDirName}function Dye(e,t){return e===`stable`?`${OJ(t)}/Library/Application Support/OpenKnowledge/path-install.json`:`${OJ(t)}/${Eye(e)}/path-install.json`}const Oye=[`.ok`,cd,`installed-skills.json`],kye=U(Ed),Aye=Zi({hosts:B(I()),scope:kye,scripts:R(),installedAt:ki(),projection:U([`symlink`,`copy`]).optional(),contentHash:I().optional()}),jye=Zi({schema:W(1),skills:H(I(),Aye).default({})});function Mye(e){let t;try{t=JSON.parse(e)}catch{return null}let n=jye.safeParse(t);return n.success?n.data:null}function kJ(e){if(e===``)throw Error(`toPathspec: empty path. ":(literal)" is an empty pattern that matches every tracked path; pass "." if you meant the repo root.`);return`:(literal)${e}`}function Nye(e){if(e.length===0)throw Error(`pathspecArgs: empty path list. A bare "--" removes the pathspec restriction rather than selecting nothing.`);return[`--`,...e.map(e=>kJ(e))]}const AJ=[{tagName:`Mirror`,attrName:`src`,resolution:`bare-doc-name`},{tagName:`Excalidraw`,attrName:`src`,resolution:`doc-relative`}];for(let e of AJ){let t=QB.find(t=>t.name===e.tagName);if(!t)throw Error(`JSX_SRC_REF_TAGS: no built-in component descriptor named '${e.tagName}' — the rename-rewrite and backlink passes for this entry would silently never match. Fix the tagName to match a descriptor in builtInComponents.`);if(!t.props.some(t=>t.name===e.attrName))throw Error(`JSX_SRC_REF_TAGS: component '${e.tagName}' declares no prop named '${e.attrName}' — the rename-rewrite and backlink passes for this entry would silently never match. Fix the attrName to match one of the descriptor's props.`)}gH(),PV(),FV();function Pye(){return QB.filter(e=>e.surface===`canonical`&&e.name!==`*`)}function Fye(){return Pye().filter(e=>{let t=Iye(e);return t!==`fence`&&t!==`html`})}function Iye(e){return e.name===`MermaidFence`?`fence`:e.name===`HtmlAlignBlock`?`html`:e.hasChildren?`jsx-block`:`jsx-void`}const jJ=Symbol.for(`@inkeep/open-knowledge/skill-state-field-registry`),MJ=globalThis;MJ[jJ]===void 0&&(MJ[jJ]=sr());const NJ=MJ[jJ],PJ=Zi({version:I().regex(/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/,`version must match /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/`).register(NJ,{description:`Recorded skill version for this target.`}),recordedAt:ki().register(NJ,{description:`ISO 8601 timestamp of the most recent successful write. Updated on every write, including reinstalls of the same version.`}),surface:U([`server-build-and-open`,`electron-build-and-open`,`cli-npx-skills-add`,`desktop-direct`,`cli-start`]).register(NJ,{description:`Install-source surface that recorded this entry.`}).optional()}),Lye=Zi({enabled:R().register(NJ,{description:`Whether this user-global skill bundle is opted in.`}),decidedAt:ki().register(NJ,{description:`ISO 8601 timestamp of the opt-in / opt-out decision.`})});Zi({schema:W(1).register(NJ,{description:`Schema major version. Bumped only on breaking shape changes.`}),targets:Zi({"claude-cowork":PJ.optional(),"cli-hosts":PJ.optional()}).register(NJ,{description:`Per-target install-state entries. Absent target = no recorded install.`}).default({}),bundles:H(I(),Lye).register(NJ,{description:`Per-bundle opt-in decisions keyed by install name. Absent key = no recorded decision.`}).optional(),installsReported:B(I()).register(NJ,{description:"Skill installs already reported to skills.sh from this machine, as `<owner/repo>#<skill>`. Append-only; presence suppresses a re-report."}).optional()});function Rye(e,t,n,r){return e.success?{code:`UNKNOWN`,message:`unexpected success in error path`}:{code:`SCHEMA_INVALID`,issues:e.error.issues.map(e=>{let i=e.path.map(e=>typeof e==`symbol`?String(e):e),a=Zu({file:r,source:n,doc:t,path:i});return{path:i,message:e.message,issueCode:e.code,...a===void 0?{}:{source:a}}})}}function FJ(e,t,n){let r=`${e}.invalid-${t.replace(/[:.]/g,`-`)}`;try{return D(e,r),r}catch(t){n(`[config] Could not sideline invalid config file ${e} → ${r}: ${t instanceof Error?t.message:String(t)}. File left in place; using schema defaults.`);return}}function IJ(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||Array.isArray(n))return;n=Reflect.get(n,e)}return n}function zye(e){let t=[],n=[[`maxBatchSize`,1,Ll],[`maxBatchChars`,1,Rl],[`docTimeoutMs`,1,zl]];for(let[r,i,a]of n){let n=[`search`,`semantic`,r],o=IJ(e.rawConfig,n),s=e.config.search.semantic[r];if(o===void 0||o===s)continue;let c=`Expected an integer between ${i} and ${a}; using default ${s}.`,l=Zu({file:e.absPath,source:e.source,doc:e.doc,path:n});t.push({path:n,message:c,...l===void 0?{}:{source:{file:l.file,line:l.line,column:l.column}}})}return t.length>0?[{code:`VALUE_FALLBACK`,issues:t}]:[]}function Bye(e){let t=IJ(e.rawConfig,[`git`,`hosts`]);if(t===void 0)return[];let n=gie.safeParse(t);return n.success?[]:[{code:`VALUE_FALLBACK`,issues:n.error.issues.map(t=>{let n=[`git`,`hosts`,...t.path.map(String)],r=Zu({file:e.absPath,source:e.source,doc:e.doc,path:n});return{path:n,message:`${t.message}; ignoring this git-host declaration.`,...r===void 0?{}:{source:{file:r.file,line:r.line,column:r.column}}}})}]}function Vye(e){let t=IJ(e.rawConfig,[`autolinks`]);if(t===void 0)return[];let n=_ie.safeParse(t);return n.success?[]:[{code:`VALUE_FALLBACK`,issues:n.error.issues.map(t=>{let n=[`autolinks`,...t.path.map(String)],r=Zu({file:e.absPath,source:e.source,doc:e.doc,path:n});return{path:n,message:t.path.length===0?`${t.message}; ignoring autolinks.`:`${t.message}; ignoring this autolink entry.`,...r===void 0?{}:{source:{file:r.file,line:r.line,column:r.column}}}})}]}function LJ(e){let{absPath:t,sideline:n=!0,timestamp:r=new Date().toISOString()}=e,i=e.warn??(e=>console.warn(e)),a=Ul.parse({});if(!g(t))return{valid:!0,value:a,source:void 0,diagnostics:[]};let o;try{o=S(t,`utf-8`)}catch(e){let n=e instanceof Error?e.message:String(e);i(`[config] Could not read ${t}: ${n}. Using schema defaults.`);let r={code:`UNREADABLE`,detail:n};return{valid:!1,value:a,error:r,diagnostics:[{...r}]}}let s=(0,xs.parseDocument)(o);if(s.errors.length>0){let e=s.errors.map(e=>e.message).join(`; `);i(`[config] ${t} contains invalid YAML (${e}). Using schema defaults.`+(n?``:` Pass-through mode: file left in place.`));let o=n?FJ(t,r,i):void 0,c={code:`YAML_PARSE`,detail:e};return{valid:!1,value:a,error:c,diagnostics:[{...c}],...o===void 0?{}:{sidelinedTo:o}}}let c=s.toJSON()??{},l=nd({value:c,file:t,source:o,doc:s}),u=l.length>0?id(c):c,d=[...Bye({rawConfig:u,doc:s,source:o,absPath:t}),...Vye({rawConfig:u,doc:s,source:o,absPath:t})];for(let e of d)for(let n of e.issues)i(`[config] ${t} ${n.path.join(`.`)}: ${n.message}`);let f=Ul.safeParse(u);if(!f.success){let e=Rye(f,s,o,t),c=Ul.shape.git.safeParse(IJ(u,[`git`])).data??a.git,p=Object.keys(c.hosts).length>0?`Using schema defaults while preserving valid git-host declarations.`:`Using schema defaults.`;i(`[config] ${t} fails schema validation (${f.error.issues.length} issue(s)). ${p}`+(n?``:` Pass-through mode: file left in place.`));let m=n?FJ(t,r,i):void 0,h=[...l,...d,...Cd(e)&&e.code===`SCHEMA_INVALID`?[{...e}]:[]];return{valid:!1,value:{...a,git:c},error:e,diagnostics:h,...m===void 0?{}:{sidelinedTo:m}}}let p=[...l,...d,...zye({rawConfig:u,config:f.data,doc:s,source:o,absPath:t})];return{valid:!0,value:f.data,source:t,diagnostics:p}}function RJ(e=_e()){return j(e,ft().userHomeDirName)}const zJ=`.tmp.`,BJ=[8,4,4,4,12];function Hye(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Uye=BJ.map(e=>`[0-9a-f]`.repeat(e)).join(`-`),Wye=BJ.map(e=>`[0-9a-f]{${e}}`).join(`-`),Gye=`*${zJ}${Uye}`;RegExp(`${Hye(zJ)}${Wye}$`);function Kye(e){return`${e}${zJ}${Ee()}`}function qye(e){try{let t=k(e),n=`${ae(e)}${zJ}`,r=Date.now()-3e4;for(let e of w(t)){if(!e.startsWith(n))continue;let i=j(t,e);try{te(i).mtimeMs<r&&ne(i)}catch{}}}catch{}}function VJ(e,t,n={}){qye(e);let r=Kye(e);try{re(r,t,{encoding:`utf-8`,mode:n.mode??420}),D(r,e)}catch(e){try{ne(r)}catch{}throw e}}var HJ=class extends Error{code=`LOCK_TIMEOUT`;lockPath;timeoutMs;constructor(e,t){super(`Could not acquire file lock at ${e} within ${t}ms`),this.name=`FileLockTimeoutError`,this.lockPath=e,this.timeoutMs=t}};async function Jye(e,t,n={}){let r=n.timeoutMs??5e3,i=n.retryIntervalMs??25,a=r*2,o=Date.now()+r,s=!0;for(;;){if(!s&&Date.now()>=o)throw new HJ(e,r);s=!1;let c;try{c=b(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let s;try{let t=te(e);s=Date.now()-t.mtimeMs}catch{continue}let c=!1;if(s>a){n.onWarn?.(`cleared stale file lock`,{lockPath:e,ageMs:s,staleThresholdMs:a});try{ne(e),c=!0}catch{}}if(c)continue;if(Date.now()>=o)throw new HJ(e,r);await Gie(i);continue}try{return await t()}finally{try{f(c)}catch{}try{ne(e)}catch{}}}}function Yye(e){let t=Date.now()+e;for(;Date.now()<t;);}function UJ(e,t,n={}){let r=n.timeoutMs??5e3,i=n.retryIntervalMs??25,a=r*2,o=Date.now()+r,s=!0;for(;;){if(!s&&Date.now()>=o)throw new HJ(e,r);s=!1;let c;try{c=b(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let s;try{let t=te(e);s=Date.now()-t.mtimeMs}catch{continue}let c=!1;if(s>a){n.onWarn?.(`cleared stale file lock`,{lockPath:e,ageMs:s,staleThresholdMs:a});try{ne(e),c=!0}catch{}}if(c)continue;if(Date.now()>=o)throw new HJ(e,r);Yye(i);continue}try{return t()}finally{try{f(c)}catch{}try{ne(e)}catch{}}}}const WJ=`config.yml`;function GJ(e,t,n){if(e===`user`)return N(RJ(n??_e()),`global.yml`);let r=A(t)?t:N(t);return e===`project-local`?N(r,`.ok`,cd,WJ):N(r,`.ok`,WJ)}const Xye=[`LC_ALL`,`LC_MESSAGES`,`LANG`];function KJ(e){let t=e.trim().split(`@`)[0].split(`.`)[0];return t===``||t===`C`||t===`POSIX`?null:jP(t.replaceAll(`_`,`-`))}function Zye(e){for(let t of Xye){let n=e[t]?.trim();if(n!==void 0&&n!==``)return KJ(n)}return null}function Qye(e){let t=e.OK_LANG?.trim();if(t!==void 0&&t!==``)return jP(t)??void 0}function $ye(e=process.env){let t=Qye(e),n=Zye(e);if(n===null)return{override:t,preferenceList:[]};let r=[],i=e.LANGUAGE;if(i!==void 0)for(let e of i.split(`:`)){let t=KJ(e);t!==null&&r.push(t)}return{override:t,preferenceList:[...r,n]}}function qJ(){return pd(ud)}function JJ(){return ft().keyringService}function YJ(e){try{e()}catch{}}var ebe=class{backend=`keyring`;onKeychainRead;constructor(e){this.onKeychainRead=e}async get(e){let{Entry:t}=await import(`@napi-rs/keyring`),n;try{n=new t(JJ(),e).getPassword()}catch(t){return YJ(()=>this.onKeychainRead?.({kind:`read-error`,host:e,error:t instanceof Error?t.name:`unknown`})),null}if(n==null)return YJ(()=>this.onKeychainRead?.({kind:`absent`,host:e})),null;try{return JSON.parse(n)}catch{return YJ(()=>this.onKeychainRead?.({kind:`corrupt-entry`,host:e,error:`corrupt-entry`})),null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(JJ(),e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(JJ(),e).deletePassword()}catch{}}},XJ=class{backend=`file`;authFile;constructor(e){this.authFile=e??j(RJ(),`auth.yml`)}read(){if(!g(this.authFile))return{};try{let e=S(this.authFile,`utf-8`);return(0,xs.parse)(e)??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=k(this.authFile);g(t)||v(t,{recursive:!0,mode:448}),VJ(this.authFile,(0,xs.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}},tbe=class{backend=`keyring`;keychain;file;constructor(e,t){this.keychain=e,this.file=t}async get(e){let t=await this.keychain.get(e);if(t!=null)return t;let n=await this.file.get(e);if(n==null)return null;try{await this.keychain.set(e,n.login,n.token,{gitProtocol:n.gitProtocol,name:n.name,email:n.email}),await this.file.clear(e),process.stderr.write(`[auth] migrated ${e} credential from ${qJ()} to the OS keychain\n`)}catch{}return n}set(e,t,n,r){return this.keychain.set(e,t,n,r)}async clear(e){await this.keychain.clear(e),await this.file.get(e)!=null&&await this.file.clear(e)}};async function ZJ(e,t){try{let{Entry:n}=await import(`@napi-rs/keyring`);return new n(JJ(),`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
|
|
430
430
|
`),YJ(()=>t?.onBackendSelected?.({backend:`keyring`})),new tbe(new ebe(t?.onKeychainRead),new XJ(e))}catch(n){let r=n instanceof Error?`${n.name}: ${n.message}`:String(n);return process.stderr.write(`[auth] token storage: file (${qJ()}) — OS keychain unavailable: ${r}\n`),YJ(()=>t?.onBackendSelected?.({backend:`file`,reason:r})),new XJ(e)}}function nbe(e){let t=null;return function(){if(t)return t;let n=2e3;return t=(async()=>{let t=null,r=new Promise(r=>{t=setTimeout(()=>{process.stderr.write(`[auth] token storage: keyring init exceeded ${n}ms; falling back to file (${qJ()})\n`),r(new XJ(e))},n)});try{return await Promise.race([ZJ(e),r])}catch{return new XJ(e)}finally{t!==null&&clearTimeout(t)}})(),t}}function rbe(e){let t=nbe(e);return{async get(e){let n=await(await t()).get(e);return n===null?null:{token:n.token,login:n.login}}}}
|
|
431
431
|
/*!
|
|
432
432
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -1114,15 +1114,15 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
|
|
|
1114
1114
|
`),process.exit(2));let s=new Set(n),c={roots:[{uri:t.pathToFileURL(i).href,name:`chat files`}]},l=e.spawn(a,o,{cwd:r,stdio:[`pipe`,`pipe`,`inherit`],windowsHide:!0}),u=l.stdin,d=l.stdout;(u===null||d===null)&&(process.stderr.write(`ok-browser relay: the browser server has no pipes
|
|
1115
1115
|
`),process.exit(1));let f=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:null,p=e=>{u.write(`${JSON.stringify(e)}\n`)},m=e=>{process.stdout.write(`${JSON.stringify(e)}\n`)},h=(e,t)=>{process.stderr.write(`ok-browser relay: dropped a ${e} line that ${t}\n`)},g=(e,t,n)=>{if(e.trim()===``)return null;let r;try{r=JSON.parse(e)}catch{return h(t,`is not JSON`),null}let i=f(r);if(i!==null)return i;if(Array.isArray(r))for(let e of r){let t=f(e);t?.method!==void 0&&t.id!==void 0&&n({jsonrpc:`2.0`,id:t.id,error:{code:-32600,message:`Batched messages are not supported`}})}return h(t,`is not a single JSON-RPC message`),null},_=e=>{let t=g(e,`client`,m);if(t===null||t.method===`notifications/roots/list_changed`)return null;let n=f(t.params),r=n?.name;return t.method===`tools/call`&&(typeof r!=`string`||!s.has(r))?(t.id!==void 0&&m({jsonrpc:`2.0`,id:t.id,error:{code:-32602,message:`Tool ${String(r)} is not available`}}),null):(t.method===`initialize`&&n!==null&&(n.capabilities={...f(n.capabilities),roots:{listChanged:!1}}),JSON.stringify(t))},v=e=>{let t=g(e,`server`,p);if(t===null)return null;if(t.method===`roots/list`)return t.id!==void 0&&p({jsonrpc:`2.0`,id:t.id,result:c}),null;let n=f(t.result),r=n?.tools;if(n===null||!Array.isArray(r))return e;let i=r.filter(e=>{let t=f(e)?.name;return typeof t==`string`&&s.has(t)});for(let e of i){let t=f(f(e)?.annotations);t!==null&&(t.readOnlyHint=!1)}return n.tools=i,JSON.stringify(t)},y=(e,t,n,r)=>{let i=``,a=e=>{let r=n(e);r!==null&&t.write(`${r}\n`)};e.setEncoding(`utf8`),e.on(`data`,e=>{i+=String(e);let t=i.indexOf(`
|
|
1116
1116
|
`);for(;t!==-1;)a(i.slice(0,t)),i=i.slice(t+1),t=i.indexOf(`
|
|
1117
|
-
`)}),e.on(`end`,()=>{i!==``&&a(i),r&&t.end()})};u.on(`error`,()=>{}),y(process.stdin,u,_,!0),y(d,process.stdout,v,!1);for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])process.on(e,()=>l.kill());l.on(`error`,e=>{process.stderr.write(`${e.message}\n`),process.exit(1)}),l.on(`close`,e=>{process.exitCode=e??1,process.stdin.destroy()})}const G8=V({name:I(),version:I().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/)});$i([B(G8),H(I(),G8).transform(e=>Object.values(e))]).pipe(ire([G8])),`${cje.toString()}${JSON.stringify([`browser_click`,`browser_close`,`browser_console_messages`,`browser_drag`,`browser_drop`,`browser_emulate_media`,`browser_evaluate`,`browser_file_upload`,`browser_fill_form`,`browser_find`,`browser_handle_dialog`,`browser_hover`,`browser_navigate`,`browser_navigate_back`,`browser_network_request`,`browser_network_requests`,`browser_press_key`,`browser_resize`,`browser_select_option`,`browser_snapshot`,`browser_tabs`,`browser_take_screenshot`,`browser_type`,`browser_wait_for`])}`,RegExp(`^(?:${`do you mind.i would like you to.i'd like you to.i want you to.i need you to.i would like to.i'd like to.i want to.i need to.we need to.we want to.we should.go ahead and.take a look at.have a look at.look into.look at.help me with.help me to.help me.can you.could you.would you.will you.can we.could we.should we.let's.lets.try to.please.kindly.hello.alright.actually.anyway.also.okay.hey.hi.yo.ok.so.pls.plz.just.maybe`.split(`.`).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})\\b(?:[\\s,:;!.\\-–—]+|$)`,`i`),Fe(x),QX(`agent-registry-apply`),QX(`local-op-security`),new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256),Od.cursor,Od.codex,Od[`claude-desktop`],t8(()=>{}),Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})}),QX(`external-change-attribution`),QX(`mermaid-validator`),QX(`rename-log`),QX(`history`);function K8(e){return St.filter(t=>g(j(e,t.hostDir)))}function q8(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}q8(_t,bS),[...q8(vt,bS)].sort((e,t)=>{let n=b4.indexOf(e.editor),r=b4.indexOf(t.editor);return(n===-1?b4.length:n)-(r===-1?b4.length:r)||e.editor.localeCompare(t.editor)}),QX(`installed-skills-marker`),QX(`skill-import`),QX(`backlinks`),QX(`local-target-inventory`),QX(`tag-index`),EP(),QX(`derived-document-index`);const J8={start:L().int().nonnegative().optional(),end:L().int().nonnegative().optional(),quote:I().min(1).optional(),prefix:I().max(1e3).optional(),suffix:I().max(1e3).optional()};V({docName:I().min(1),...J8,propertyKey:I().min(1).optional(),propertyPath:B($i([I(),L().int().nonnegative()])).optional(),body:I(),queue:R().optional(),summary:I().optional()});const Y8=Hi();ea(`action`,[V({action:W(`edit`),id:Y8,body:I(),summary:I().optional()}),V({action:W(`resolve`),id:Y8,summary:I().optional()}),V({action:W(`reopen`),id:Y8,summary:I().optional()}),V({action:W(`replace`),id:Y8,...J8,summary:I().optional()}),V({action:W(`queue`),id:Y8,summary:I().optional()}),V({action:W(`unqueue`),id:Y8,summary:I().optional()}),V({action:W(`dispatch-prepare`),id:Y8,summary:I().optional()}),V({action:W(`dispatch-complete`),id:Y8,summary:I().optional()}),V({action:W(`dispatch-prepare-batch`),ids:B(Y8).min(1).max(200),summary:I().optional()}),V({action:W(`dispatch-complete-batch`),ids:B(Y8).min(1).max(200),summary:I().optional()})]),QX(`embeddings`),QX(`embeddings`);function lje(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}lje(Nl),QX(`embeddings`),QX(`embeddings`);const uje=/^[A-Za-z0-9-]{8,64}$/;let X8=null;function dje(e){return j(e??_e(),`.ok`,`machine-id`)}function fje(e){if(e===void 0&&X8!==null)return X8;let t=dje(e),n=null;try{let e=S(t,`utf-8`).trim();uje.test(e)&&(n=e)}catch{}if(n===null){n=Ee();try{v(k(t),{recursive:!0}),re(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){QX(`machine-id`).warn({path:t,err:e},`Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(X8=n),n}QX(`process-lock`);function pje(e,t){return N(e,`${t}.lock`)}function mje(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)?t.origin:null}function hje(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=mje(e.url);if(t!==null)return t}if(e.port>0){let n=t?.fallbackHost??`localhost`;return`http://${n===`0.0.0.0`||n===`::`?`localhost`:n.includes(`:`)&&!n.startsWith(`[`)?`[${n}]`:n}:${e.port}`}return null}QX(`asset-references`),QX(`file-ops`),QX(`upload-streaming`);const Z8=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,Q8=`Canonical ids: ${Fye().map(e=>e.name).join(`, `)}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`;I().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),I().length(40).regex(/^[0-9a-f]+$/i).describe("A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three."),I().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),I().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),I().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`);const gje=V({value:I(),truncatedFrom:L().optional(),hint:I().optional()}).describe(`Normalized change-note summary, when one was recorded.`),_je=B(H(I(),z()));H(I(),z()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),B(Qd).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting or busy with other writes. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.'),ef.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.'),gje.optional(),B(Xd).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit. `link-check-deferred` means links were not checked because the server is still starting or busy with other writes — that doc is re-checked only by a later write or edit of it, or an `audit`, which can time out until startup finishes."),B(V({name:I(),description:I().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.");const vje=I().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function $8(e){return{text:vje,...e}}function yje(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}yje(`the server`);function bje(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}bje(`the server`),QX(`git-checkout`),QX(`git-worktree-status`),QX(`managed-artifact-persistence`),QX(`timeline`),QX(`suggest-links`),new Intl.Segmenter(`und`,{granularity:`word`}),QX(`git-context`),QX(`clone-flow`),Fe(o),B8.project,Object.fromEntries(Object.entries(xS).map(([e,t])=>[t,e])),[`These are patterns to adapt to your domain, not a layout to copy verbatim.`,"To build a variant: create your own folders (via `write` or your editor) and reuse only the ideas that fit.","To adopt this pack as-is: re-run without `--dry-run`."].join(`
|
|
1117
|
+
`)}),e.on(`end`,()=>{i!==``&&a(i),r&&t.end()})};u.on(`error`,()=>{}),y(process.stdin,u,_,!0),y(d,process.stdout,v,!1);for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])process.on(e,()=>l.kill());l.on(`error`,e=>{process.stderr.write(`${e.message}\n`),process.exit(1)}),l.on(`close`,e=>{process.exitCode=e??1,process.stdin.destroy()})}const G8=V({name:I(),version:I().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/)});$i([B(G8),H(I(),G8).transform(e=>Object.values(e))]).pipe(ire([G8])),`${cje.toString()}${JSON.stringify([`browser_click`,`browser_close`,`browser_console_messages`,`browser_drag`,`browser_drop`,`browser_emulate_media`,`browser_evaluate`,`browser_file_upload`,`browser_fill_form`,`browser_find`,`browser_handle_dialog`,`browser_hover`,`browser_navigate`,`browser_navigate_back`,`browser_network_request`,`browser_network_requests`,`browser_press_key`,`browser_resize`,`browser_select_option`,`browser_snapshot`,`browser_tabs`,`browser_take_screenshot`,`browser_type`,`browser_wait_for`])}`;const lje=String.raw`(?![\p{L}\p{M}\p{N}_])`;RegExp(`^(?:${`do you mind.i would like you to.i'd like you to.i want you to.i need you to.i would like to.i'd like to.i want to.i need to.we need to.we want to.we should.go ahead and.take a look at.have a look at.look into.look at.help me with.help me to.help me.can you.could you.would you.will you.can we.could we.should we.let's.lets.try to.please.kindly.hello.alright.actually.anyway.also.okay.hey.hi.yo.ok.so.pls.plz.just.maybe`.split(`.`).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})${lje}(?:[\\s,:;!.\\-–—]+|$)`,`iu`),Fe(x),QX(`agent-registry-apply`),QX(`local-op-security`),new class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let n=1;n<=t;n++){let t=(this.writeIndex-n+this.capacity)%this.capacity,r=this.store[t];r!==void 0&&e.push(r)}return e}get size(){return this.filled?this.capacity:this.writeIndex}}(256),Od.cursor,Od.codex,Od[`claude-desktop`],t8(()=>{}),Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})}),QX(`external-change-attribution`),QX(`mermaid-validator`),QX(`rename-log`),QX(`history`);function K8(e){return St.filter(t=>g(j(e,t.hostDir)))}function q8(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}q8(_t,bS),[...q8(vt,bS)].sort((e,t)=>{let n=b4.indexOf(e.editor),r=b4.indexOf(t.editor);return(n===-1?b4.length:n)-(r===-1?b4.length:r)||e.editor.localeCompare(t.editor)}),QX(`installed-skills-marker`),QX(`skill-import`),QX(`backlinks`),QX(`local-target-inventory`),QX(`tag-index`),EP(),QX(`derived-document-index`);const J8={start:L().int().nonnegative().optional(),end:L().int().nonnegative().optional(),quote:I().min(1).optional(),prefix:I().max(1e3).optional(),suffix:I().max(1e3).optional()};V({docName:I().min(1),...J8,propertyKey:I().min(1).optional(),propertyPath:B($i([I(),L().int().nonnegative()])).optional(),body:I(),queue:R().optional(),summary:I().optional()});const Y8=Hi();ea(`action`,[V({action:W(`edit`),id:Y8,body:I(),summary:I().optional()}),V({action:W(`resolve`),id:Y8,summary:I().optional()}),V({action:W(`reopen`),id:Y8,summary:I().optional()}),V({action:W(`replace`),id:Y8,...J8,summary:I().optional()}),V({action:W(`queue`),id:Y8,summary:I().optional()}),V({action:W(`unqueue`),id:Y8,summary:I().optional()}),V({action:W(`dispatch-prepare`),id:Y8,summary:I().optional()}),V({action:W(`dispatch-complete`),id:Y8,summary:I().optional()}),V({action:W(`dispatch-prepare-batch`),ids:B(Y8).min(1).max(200),summary:I().optional()}),V({action:W(`dispatch-complete-batch`),ids:B(Y8).min(1).max(200),summary:I().optional()})]),QX(`embeddings`),QX(`embeddings`);function uje(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}uje(Nl),QX(`embeddings`),QX(`embeddings`);const dje=/^[A-Za-z0-9-]{8,64}$/;let X8=null;function fje(e){return j(e??_e(),`.ok`,`machine-id`)}function pje(e){if(e===void 0&&X8!==null)return X8;let t=fje(e),n=null;try{let e=S(t,`utf-8`).trim();dje.test(e)&&(n=e)}catch{}if(n===null){n=Ee();try{v(k(t),{recursive:!0}),re(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){QX(`machine-id`).warn({path:t,err:e},`Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(X8=n),n}QX(`process-lock`);function mje(e,t){return N(e,`${t}.lock`)}function hje(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)?t.origin:null}function gje(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=hje(e.url);if(t!==null)return t}if(e.port>0){let n=t?.fallbackHost??`localhost`;return`http://${n===`0.0.0.0`||n===`::`?`localhost`:n.includes(`:`)&&!n.startsWith(`[`)?`[${n}]`:n}:${e.port}`}return null}QX(`asset-references`),QX(`file-ops`),QX(`upload-streaming`);const Z8=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,Q8=`Canonical ids: ${Fye().map(e=>e.name).join(`, `)}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`;I().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),I().length(40).regex(/^[0-9a-f]+$/i).describe("A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three."),I().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),I().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),I().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`);const _je=V({value:I(),truncatedFrom:L().optional(),hint:I().optional()}).describe(`Normalized change-note summary, when one was recorded.`),vje=B(H(I(),z()));H(I(),z()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),B(Qd).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting or busy with other writes. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.'),ef.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.'),_je.optional(),B(Xd).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit. `link-check-deferred` means links were not checked because the server is still starting or busy with other writes — that doc is re-checked only by a later write or edit of it, or an `audit`, which can time out until startup finishes."),B(V({name:I(),description:I().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.");const yje=I().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function $8(e){return{text:yje,...e}}function bje(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}bje(`the server`);function xje(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}xje(`the server`),QX(`git-checkout`),QX(`git-worktree-status`),QX(`managed-artifact-persistence`),QX(`timeline`),QX(`suggest-links`),new Intl.Segmenter(`und`,{granularity:`word`}),QX(`git-context`),QX(`clone-flow`),Fe(o),B8.project,Object.fromEntries(Object.entries(xS).map(([e,t])=>[t,e])),[`These are patterns to adapt to your domain, not a layout to copy verbatim.`,"To build a variant: create your own folders (via `write` or your editor) and reuse only the ideas that fit.","To adopt this pack as-is: re-run without `--dry-run`."].join(`
|
|
1118
1118
|
`),QX(`skills-leaderboard`),QX(`handoff-dispatch`),V({target:U(Object.keys({"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}})),url:I().min(1).max(4096),workspacePath:I().optional()}),V({}).loose(),QX(`github-permissions`),QX(`github-reference`),QX(`github-reference`),QX(`link-preview.guarded-fetch`),QX(`link-preview.cache`),QX(`saved-themes`),V({enabled:R(),active:R(),git:V({state:U([`not-applicable`,`ready`,`missing`,`conflict`,`unavailable`]),ownership:U([`open-knowledge`,`existing`]).optional()}),applied:R().optional(),reason:U([`git-conflict`,`git-unavailable`,`config-write`]).optional()}),V({enabled:R()}).strict(),QX(`managed-rename`),Object.assign(fOe,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`,"7z":`application/x-7z-compressed`,tar:`application/x-tar`,rar:`application/vnd.rar`,xls:`application/vnd.ms-excel`,ppt:`application/vnd.ms-powerpoint`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,pages:`application/vnd.apple.pages`,numbers:`application/vnd.apple.numbers`,key:`application/vnd.apple.keynote`,mobi:`application/x-mobipocket-ebook`}),QX(`search`),QX(`skill-install`),QX(`write-advisory`),QX(`api`),V({principalId:I().optional(),tabSessionId:I().optional(),expectedServerInstanceId:I().optional(),expectedBranch:I().optional(),expectedDocLineageEpoch:I().optional(),clientProtocolVersion:L().optional(),clientRuntimeVersion:I().optional(),clientKind:I().optional()}).loose(),new He,t8(()=>{}),[...Aae],["Read-only validation of markdownlint, frontmatter, OKF and broken internal links. Requires the Hocuspocus server. No args scans all in-scope .md/.mdx; `path` narrows to file/folder. `links` is the navigation/graph tool.","ran names selected `markdownlint`, `frontmatter`, `okf`, `links`. A family absent from `ran` was not checked. A selected family remains in ran if degraded; warnings explain why and it may still have contributed findings. okf covers document and project-tree OKF checks here.",`Broken links are reported under the source doc. Default-on validation.suppressLogLinkAdvisories omits links inside lowercase log.md/log.mdx at any depth; LOG.md is ordinary. brokenLinkSuppression reports reason reserved-log-policy and count without paths/hrefs. Logs are append-only history: never rewrite old entries to clear links. links({kind:'dead'}) reads raw state.`,`Diagnostics carry source, code, message, 0-based LSP range (link columns approximate) and severity. Broken links default to warning; validation.links can raise/hide them. Only problematic files are listed; fileCount/errorCount/warningCount reflect full scan. Output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow runtime hints for document lint and raw dead links; project-tree OKF findings remain capped.`,`Nothing is modified. Auto-fix document lint with lint({document,fix:true}); fix broken links with edit/write.`].join(`
|
|
1119
1119
|
`),[`Save a project-wide checkpoint of every document. Requires the Hocuspocus server. Optional summary ≤80 chars defaults to "Checkpoint version"; avoid secrets or PII because it persists in git history. Returns version (40-char SHA). Find it with history and restore one doc with restore_version({document,version}).`].join(`
|
|
1120
1120
|
`),[`Read effective config merged defaults → user → project; no running OK server needed. Optional key is a dotted path (content, appearance.theme); omit for the full config. All fields are readable. Re-read after disk changes or before relying on an old value.`,"Removed server.*, mcp.*, github.*, preview.baseUrl and preview.scriptSrc return exists:false; appearance.preview.autoOpen remains live. This is a pure read. Use `install` skillFolders for folder topology."].join(`
|
|
1121
|
-
`),I().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),I().optional().describe(Z8),$8({value:z().describe(`Resolved config value at the requested path (or full config).`),exists:R().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:I().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)});const
|
|
1121
|
+
`),I().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),I().optional().describe(Z8),$8({value:z().describe(`Resolved config value at the requested path (or full config).`),exists:R().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:I().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)});const Sje=[`lock`],Cje=$i([oo,qi()]),wje=$i([I(),L(),R(),B(z()),H(I(),z()),qi()]);H(I(),wje).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))Cje.safeParse(r).success||t.addIssue({code:`custom`,path:[n],message:`invalid frontmatter value — allowed: a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects; a top-level key may be null to delete it, but nested null is not allowed`})}).describe(`Metadata as a key→value map. Values may be a scalar (string | number | boolean), a scalar array, a nested object, or an array of objects. Merge-patch: include a top-level key to set it, set a top-level key to null to delete it; keys you omit are unchanged. A nested object REPLACES the existing subtree at that key (send the full subtree you want). Example: { title: "Q3 Planning", tags: ["planning"], metadata: { version: "1.0", author: "Inkeep" } }.`),U([`append`,`prepend`,`replace`]).describe(`Where content lands. replace = overwrite the whole body (default for a new doc; required for an existing doc). append / prepend = add to the end / start.`),U(Dd).describe("File format for a NEW doc: `.md` (default) or `.mdx` (Markdown + JSX components). Honored only on create — an existing doc keeps its on-disk extension. Takes precedence over an extension typed into `path`."),U(Ed).describe(`Level: "project" (default — a Project skill: lives in this KB wherever its folder is, shared with teammates via git) or "global" (a Global skill: lives under your user home, available in every project on this machine — not shared, not version-tracked). Pass the literal value "global" for a Global skill.`),new Set(uJ),[`Delete exactly one document, folder, template, skill or asset. Requires the Hocuspocus server. Irreversible; deleting a doc leaves inbound redlinks. Call links({kind:'backlinks',document}) BEFORE deleting.`,`document: path or paths array; folder: recursive folder path; template: {path:'<folder>/<name>'}; asset: {path:'<folder>/<file.ext>'}. skill: {name} deletes the whole bundle, or {name,files:['references/x.md']} deletes selected files. Template/skill deletion is attributed and cleans empty .ok/ directories.`].join(`
|
|
1122
1122
|
`),["Edit exactly one `document`, `folder`, `template`, or `skill`: body find/replace OR metadata, never both in one call. Requires the Hocuspocus server.","`document: {path, find, replace, occurrence?}` edits body only; frontmatter-intersecting finds are rejected. occurrence selects a match (1 = first). `{path, frontmatter}` merge-patches metadata; null deletes a key.","`folder: {path, frontmatter}` patches metadata (no body). `template: {path: '<folder>/<name>', ...}` takes body find/replace/occurrence or frontmatter.","`skill: {name, ...}` takes body find/replace/occurrence OR description (its only metadata leaf). Recorded, unedited copies refresh from the source on watcher/startup sync; links reflect edits immediately. Hand-edited copies are preserved.",`Optional summary: one-line outcome ≤80 chars for any edit, persisted to git history; avoid secrets or PII.`,`Read structuredContent.document.warnings: content-divergence/disk-edit-reconciled means re-read with exec; mermaid-parse-error means the edit landed but fix the fence and re-edit.`,Q8].join(`
|
|
1123
|
-
`);const
|
|
1123
|
+
`);const Tje=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];[...new Set([`-name`,`-iname`,`-path`,`-ipath`,`-regex`,`-iregex`,`-lname`,`-ilname`])],new Set(Tje),QX(`mcp:exec`),["STOP: with `.ok/`, use exec for in-scope .md/.mdx; native Read/Grep/Glob omit wiki context. Native tools are for source code, non-markdown or projects without .ok/. See the open-knowledge skill for the full rule and escape hatch.",`Read-only bash-like command; returns stdout and enrichedPaths with frontmatter, backlinks/forward links, unresolved comments, shadow-repo activity and git history with human/agent attribution. Unresolved comments are open human review requests: consider before editing and report them.`,`Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or pipe per call. No &&, ;, subshells, writes or redirection (including <). Use multiple paths or separate calls.`,`cwd: command paths resolve inside explicit absolute cwd, or the client's sole advertised root. With zero/multiple roots pass cwd; traversal above it is rejected.`,`Stdout provenance: ls <dir>/ labels the directory; single-file cat/head/tail labels its path. Multi-file cat has no header; enrichedPaths still lists files. Piped head/tail preserve upstream provenance.`,`Examples: exec({command:'cat notes/a.md'}); exec({command:'grep -rn oauth notes/ | head -5'}); exec({command:'ls',cwd:'/abs/project'}).`].join(`
|
|
1124
1124
|
`),[`Get the full browser URL for this project or a document/folder/skill, or an absolute markdown file outside the project. Opening is demand: auto-starts OK under the normal OK_MCP_AUTOSTART gate and waits briefly for UI; cold calls can take seconds. Other tools return route-only previewUrl paths; use this tool for an openable URL, never guess ports or hunt via the OpenKnowledge CLI's ps/status.`,`Choose one: document (extension-less), folder (trailing-slash route), skill:{name,scope?} (project default), or file (absolute .md/.mdx in a loose-file/worktree session). file ignores cwd; other targets use current project. Omit targets for UI root.`,`When YOUR host opens URLs, navigate its embedded browser to url; Claude Code Desktop uses preview_start({url}) then navigate({url}). Only a stdio host without a browser tool should open the URL in the system browser. A CLI without a browser can use the OpenKnowledge CLI's open <doc> for OK Desktop. This tool forces browser access even when Desktop is installed.`,`INSIDE OK's terminal/agent panel, use returned okOpenCommand instead; never paste url in the answer. If no UI is reachable, returns url:null, baseUrl:null, running:false, autoOpen plus state-specific recovery text (autostart disabled, no spawn authority or UI timeout). Follow it.`].join(`
|
|
1125
|
-
`),I().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),I().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),V({name:I().min(1).regex(eye,`Skill name must be lowercase letters, digits, and hyphens only.`).describe(`Skill name (the bundle-dir identity, wherever the skill lives).`),scope:U(Ed).optional().describe("Skill scope; defaults to `project`.")}).optional().describe("Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`."),I().optional().describe("Absolute path to a single markdown file to open, including one OUTSIDE any Open Knowledge project. Resolves to the running single-file (or worktree) session whose content directory contains it and returns that session’s `url`. Mutually exclusive with `document` / `folder` / `skill`. When `file` is set, `cwd` is ignored."),I().optional().describe(Z8),$8({url:I().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:I().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:R().describe(`Whether a UI is running for the project.`),autoOpen:R().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`."),okOpenCommand:I().nullable().optional().describe("Machine-readable form of the hosted-agent steer: when the calling agent runs inside an OpenKnowledge surface (the desktop app’s built-in terminal, or its in-app agent panel) AND a doc/folder/skill target was given, the exact OpenKnowledge CLI `open` command to run to bring it up for the user. Run it INSTEAD of navigating `url`, and do not paste `url` into your reply — the user is already in the app it points at. `null`/absent in every other context (navigate `url` per your host instead).")}),V({version:I().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:I().describe(`ISO timestamp of the entry.`),author:I().describe(`Author display name.`),authorEmail:I().describe(`Author email.`),kind:U([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:I().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:
|
|
1125
|
+
`),I().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),I().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),V({name:I().min(1).regex(eye,`Skill name must be lowercase letters, digits, and hyphens only.`).describe(`Skill name (the bundle-dir identity, wherever the skill lives).`),scope:U(Ed).optional().describe("Skill scope; defaults to `project`.")}).optional().describe("Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`."),I().optional().describe("Absolute path to a single markdown file to open, including one OUTSIDE any Open Knowledge project. Resolves to the running single-file (or worktree) session whose content directory contains it and returns that session’s `url`. Mutually exclusive with `document` / `folder` / `skill`. When `file` is set, `cwd` is ignored."),I().optional().describe(Z8),$8({url:I().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:I().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:R().describe(`Whether a UI is running for the project.`),autoOpen:R().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`."),okOpenCommand:I().nullable().optional().describe("Machine-readable form of the hosted-agent steer: when the calling agent runs inside an OpenKnowledge surface (the desktop app’s built-in terminal, or its in-app agent panel) AND a doc/folder/skill target was given, the exact OpenKnowledge CLI `open` command to run to bring it up for the user. Run it INSTEAD of navigating `url`, and do not paste `url` into your reply — the user is already in the app it points at. `null`/absent in every other context (navigate `url` per your host instead).")}),V({version:I().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:I().describe(`ISO timestamp of the entry.`),author:I().describe(`Author display name.`),authorEmail:I().describe(`Author email.`),kind:U([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:I().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:vje.describe(`Per-contributor records parsed from the commit (writer id, name, docs, summaries).`),checkpoint:z().nullable().describe(`Checkpoint metadata when this entry is a checkpoint, else null.`)}),[`Read version history: pass exactly one document, folder or skill. Requires the Hocuspocus server. Returns shadow-repo entries newest first; version is a 40-char SHA for restore_version({document,version}) or restore_version({skill,version}).`,`document accepts optional .md/.mdx. folder lists attributed template/frontmatter activity; empty string is project root. skill is a project-scope name; global skills are unversioned. Optional branch (current default), limit (50 default, 200 max), offset (0), kind (checkpoint/upstream/wip), author and excludeAuthor (name/email).`].join(`
|
|
1126
1126
|
`),[...uJ,..._J],[`Import an external agentskills.io/skills.sh skill as managed content. Requires the Hocuspocus server. source accepts a full skills.sh page URL (including website catalogs), owner/repo[/subpath], git URL, or local/file:// path. skill picks one from a multi-skill source. scope: project (default, versioned/shared) or global (user-wide, unversioned).`,`Writes the .agents/skills/<name>/ hub with provenance in .ok/skills-lock.json. Scripts are NEVER executed. add selects editor locations; import always places the skill somewhere. Use install later to change placement/form/source. Name collisions use <name>-imported, never overwrite; identical content-hash re-import is a no-op.`].join(`
|
|
1127
1127
|
`),new Set(_J),["Manage where a SKILL is available: `{name, add?, remove?, convert?, mode?, source?, scope?}` or `{skillFolders: {...}}` alone. Requires the Hocuspocus server. One real source folder plus managed copies/symlinks; the source still loads with no extra locations. Use delete to remove the skill everywhere.",`name is the bundle identity: lowercase letters/digits/hyphens, ≤64 chars. Locations: claude/cursor/codex/copilot/opencode/pi, agents (.agents/skills), or custom root containing '/' such as .team/skills. Custom roots are project-relative, home-relative at global scope. scope: project (default, shared via git) or global (user-wide).`,`add/remove change membership; omitting both installs to configured editors. remove cannot remove the source; folder aliases unfollow minus this skill and keep others. Differing copies are preserved; editor removal may succeed and leave them in place.`,`mode: link = live symlink for source updates (copy where the OS refuses symlinks); copy = separate folder, refreshed on watcher/startup sync while unedited. Hand-edited copies fork; differing copies are preserved and cannot be converted. Requires add or convert; affects named locations only, no skill-wide default. Omit mode on add to inherit form. convert requires mode and changes form without membership; name all locations for uniformity.`,`source moves the real folder; its old location becomes a symlink. Run alone, not with add/remove. Source SKILL.md with conflict markers, invalid/missing frontmatter, XML in name/description or reserved open-knowledge* names is refused before projection.`,`skillFolders runs alone without name. link: {action:'link', scope, root, target}; target required, merge then symlink root; equal entries deduplicate, differing skills abort, interrupted merges can rerun. unlink: {action:'unlink', scope, root, exclude?}; makes a real directory of per-skill symlinks, excluding named skills and retaining others. add-root: {action:'add-root', scope, root}; declares a custom root for install/link.`].join(`
|
|
1128
1128
|
`),[`Read the wiki-link graph. Requires the Hocuspocus server. kind is one value or an array; results merge, failures go in errors. Use audit for validation.`,"`backlinks`/`forward`/`suggest` require document. suggest finds unlinked prose mentions; excerpt is normalized context, NOT edit-ready text. Re-read with exec, locate the real text using offset, then edit into a wiki-link.","`dead` lists raw unresolved internal targets; sourceDocuments optionally filters with OR semantics. Includes skill docs and lowercase log.md/log.mdx: inspect deliberately, never use as a repair queue or rewrite existing log entries to clear findings.","`orphans` finds disconnected pages; mode incoming/outgoing/both. `hubs` lists most-linked pages; limit defaults 20."].join(`
|
|
@@ -1131,10 +1131,10 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
|
|
|
1131
1131
|
`),[`Read the authoring palette: markdown-native components/examples/guidance, themed html preview embedPatterns (charts, stat cards, SVG, interactive controls), and CSS tokens. No running OK server needed. Optional components:[ids] adds full JSX props in componentDetails plus notFound; ids are case-sensitive, max 32. cwd selects project.`,`Prefer native forms: > [!NOTE], <details>, mermaid fences, $math$. For interactive HTML/JS/CSS use html preview starters and var(--chart-1)/var(--foreground) tokens for light/dark themes. Inside SVG use style="fill: var(--chart-1)", not a fill presentation attribute.`,`Delimiters are live even in ordinary prose: ==highlight==, $inline math$/$$block math$$, %%comment%% and <!-- comment --> (HIDES text), ~~strikethrough~~. Keep literal pairs in an inline code span or backslash-escape either delimiter. For ~~ escape BOTH tildes on both sides; one-sided escaping is rewritten on save.`,`Preview iframes have open network access for external HTTPS resources/fetch/fonts/maps. They are sandboxed null-origin frames and cannot access the knowledge base, cookies or auth.`].join(`
|
|
1132
1132
|
`),B(I().min(1)).max(32).optional().describe("Canonical ids to expand to full JSX-form detail (max 32, case-sensitive). Returns `componentDetails` + `notFound`."),I().optional().describe(Z8),$8({version:W(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:B(V({id:I(),displayName:I(),description:I(),authoring:U([`markdown`,`jsx`]).describe("`markdown` — write the markdown-native form OK auto-promotes; `jsx` — write the JSX tag directly (no markdown-native form exists)."),example:I().describe(`Copy-ready source for the authoring form.`),guidance:I().describe(`One line on when / how to use this construct.`)})).describe(`Canonical authoring constructs, keyed by the form an agent should write.`),embedPatterns:B(V({id:I(),title:I(),description:I(),snippet:I().describe("A complete, theme-wired ```html preview fenced block.")})).describe("Copy-ready themed `html preview` starters."),tokens:B(V({name:I().describe("CSS custom-property name, e.g. `--chart-1`."),light:I(),dark:I()})).describe("Theme tokens injected into every preview iframe — reference with `var(--name)`."),componentDetails:B(H(I(),z())).optional().describe("Full JSX-form prop schema for the requested `components` ids (when provided)."),notFound:B(I()).optional().describe("Requested `components` ids that did not match any canonical.")}),[`Restore exactly one document or skill to version (40-char SHA from history). Requires the Hocuspocus server. document accepts optional .md/.mdx; restore is append-only through CRDT and visible to connected editors. skill is a PROJECT-scope name (global is unversioned); its folder is rewritten. Recorded, unedited copies refresh on watcher/startup sync; links reflect edits immediately. Hand-edited copies are preserved.`,`Optional summary ≤80 chars; avoid secrets or PII, persisted to git history. content-divergence in structuredContent.warnings means restore landed but bytes differ: re-read with exec to see the converged result.`].join(`
|
|
1133
1133
|
`),QX(`mcp:search`),[`Ranked search across ALL non-ignored files and folders. Requires the Hocuspocus server. All file name/path values are indexed; only markdown bodies are indexed. Run in parallel with exec grep for exhaustive literal content search, especially code/config/data.`,`Pass query; intent full_text (default) includes bodies, omnibar searches title/path/folders. scopes: page/folder/file/content; defaults follow intent. limit: 20 default, 100 max. Ranking combines title boost, BM25 and recency; hits include signals, and pages include snippets (other files are name-only).`,`When workspace semantic search is enabled, full_text adds embeddings by default; query and matching content go to the configured provider. Set semantic:false for lexical-only/no embedding egress. Response semantic reports coverage.`,`ready:false means an incomplete cold index, not an authoritative empty result. Wait 2–3 seconds before retrying; after 2–3 retries use exec grep. If the server is down, follow recovery text; exec grep is the server-free search fallback.`].join(`
|
|
1134
|
-
`),I().describe(`Search query — title, path, or body terms.`),U([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),B(U([`page`,`folder`,`content`,`file`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'file', 'content'. Defaults derive from intent.`),L().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),R().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),I().optional().describe(Z8);const
|
|
1135
|
-
`),$8({ok:R().describe(`Success discriminator.`),shareUrl:I().optional().describe(`Marketing share URL (success only).`),sharedUrl:I().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:I().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:U([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),freshness:Pd.optional().describe(`Whether the shared target matches origin (success only): current, stale (unpushed edits), absent (not on origin, a push fixes it), or empty (a folder holding nothing git can track, which no push fixes). Omitted when the probe could not run.`),error:U([...Nd.options,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:I().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:I().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:I().optional().describe(`Internal: preview-URL provenance.`)});const e5="Which level the skill lives at. `project` = lives in this KB (wherever its folder is; shared via git); `global` = user-level under your home dir (available in every project on this machine, not shared).",
|
|
1134
|
+
`),I().describe(`Search query — title, path, or body terms.`),U([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),B(U([`page`,`folder`,`content`,`file`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'file', 'content'. Defaults derive from intent.`),L().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),R().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),I().optional().describe(Z8);const Eje=V({kind:U([`page`,`folder`,`file`]),path:I(),docName:I(),title:I().nullable(),score:L(),signals:V({lexical:L(),fullText:L(),recency:L(),vector:L().optional()}),snippet:I().optional(),previewUrl:I().nullable(),previewUrlSource:U(Sje).optional()});$8({cwd:I(),query:I(),intent:I(),resultCount:L().int(),results:B(Eje),elapsedMs:L().nullable(),semantic:SJ.optional(),ready:W(!1).optional()}),[`Build a shareable GitHub-substrate URL for a teammate to receive a doc/folder subtree in OpenKnowledge, pinned to current branch. Requires the Hocuspocus server. Read-only, no commits/pushes/fetch. Publishing is a user act: agents do NOT publish; a missing remote returns Share-wizard guidance.`,"`path` is content-relative, docs accept .md/.mdx, empty string means root folder. `kind` doc/folder is optional for auto-probe (.mdx → .md → directory); REQUIRED when `path` is empty (use folder). Optional `cwd` selects project. Requires a named branch, GitHub/GH Enterprise origin, and branch already pushed."].join(`
|
|
1135
|
+
`),$8({ok:R().describe(`Success discriminator.`),shareUrl:I().optional().describe(`Marketing share URL (success only).`),sharedUrl:I().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:I().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:U([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),freshness:Pd.optional().describe(`Whether the shared target matches origin (success only): current, stale (unpushed edits), absent (not on origin, a push fixes it), or empty (a folder holding nothing git can track, which no push fixes). Omitted when the probe could not run.`),error:U([...Nd.options,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:I().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:I().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:I().optional().describe(`Internal: preview-URL provenance.`)});const e5="Which level the skill lives at. `project` = lives in this KB (wherever its folder is; shared via git); `global` = user-level under your home dir (available in every project on this machine, not shared).",Dje=V({id:I().describe("Location id — editor host id, `agents`, or a custom root path. Pass to `install`."),path:I().describe('Base-relative bundle dir (e.g. ".claude/skills/x"). INFORMATIONAL — for showing a user where a location lives. Skills are addressed by `name` + `scope`: pass `id` to `install`, and read bundle files with `skills({ name, file })`, never by handing this path to `exec` or a native file tool.'),role:U([`source`,`copy`,`symlink`]).describe(`source = the REAL folder (the skill itself); copy = independent folder, refreshed from the source on watcher/startup sync while unedited (hand edits fork it); symlink = live link to the source.`),audience:B(I()).optional().describe(`Folders that RESOLVE INTO this location (folder-level symlinks) — their agents read what lands here.`),drift:R().optional().describe(`Something outside OK rewrote this path since OK last wrote it.`)});V({name:I().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:U([`project`,`global`]).describe(e5),description:I().optional().describe(`The skill's one-line description (when present).`),installed:R().describe('Always true for a managed skill — its source folder IS the skill, so it is never "not installed". Read `locations[]` for where it actually lives.'),hosts:B(I()).describe(`Flat location ids (locations[].id), SOURCE first — legacy projection.`),locations:B(Dje).describe("Everywhere the skill lives. Exactly one `source` (the skill's real folder); every other entry is a managed copy or symlink of it."),mode:U([`copy`,`link`]).describe("The form a NEW location would take, derived from the ones the skill already uses. Not a stored preference and not a claim about existing locations — read `locations[].role` for those."),conflicts:B(I()).optional().describe(`Host ids where a DIFFERENT skill with this name occupies the slot.`)});const Oje=V({path:I().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:U([`reference`,`script`]).describe("`script` for anything under scripts/; `reference` for every other bundle file.")});V({name:I().describe(`Skill name (its identity).`),scope:U([`project`,`global`]).describe(e5),description:I().describe(`The skill's one-line description (empty if none).`),body:I().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:B(Oje).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),V({path:I().describe(`Skill-relative path read.`),kind:U([`reference`,`script`]).describe("`reference` or `script`."),text:I().describe(`Full text of the bundle file.`)}),V({name:I().describe("Skill name to pass as `skill` to `import`."),source:I().describe("Import-ready repository coordinates or website hostname. Pass this exact value to `import`."),description:I().describe(`Marketplace description for deciding whether the skill matches the task.`),installs:L().int().nonnegative().nullable().describe(`skills.sh install count, if known.`),publisher:I().nullable().describe(`Publisher, website, or GitHub owner, if known.`)}),[`Read-only skill discovery. Requires the Hocuspocus server. query searches the skills.sh marketplace and returns import-ready name/source/description/publisher/install-count rows. Import a chosen row with import({source,skill:name}); external rows are not managed or active editor content until imported/projected.`,`Omit name to list Project and Global managed skills with scope/description/hosts. name reads description/body plus a bundle files list (path/kind, no inline text); name+file reads one reference/script/bundle file. Optional scope; name-only prefers Project. Address skills by name/scope, never raw .ok/ paths or native cat.`,`Built-in open-knowledge* runtime skills are already in your skill list; do not fetch them here. Use write/edit/delete/move/install for changes.`].join(`
|
|
1136
1136
|
`),["Create/replace exactly one `document`, `folder`, `template`, `skill`, or `asset`; use `documents` for an ordered batch. Requires the Hocuspocus server.","Nested paths such as `guides/overview` can be documents; put all requested blocks in one `document.content`. Use `folder` only for separate pages.","`document: {path, content|template, frontmatter?, position?}`: content and template are exclusive. Existing docs require position: replace/append/prepend; new docs default replace. frontmatter with literal content forces replace, even with append/prepend. Recent edits by another writer can refuse replace; follow the recovery response; append/prepend/edit bypass this refusal. Peers are per MCP connection; own writes and writers sharing a connection do not refuse each other; connected editors can. No agentId is needed.","`folder: {path, frontmatter?}` creates NEW folders; edit existing ones. `template: {path: '<folder>/<name>', content, frontmatter: {title, description?, tags?}}` creates reusable doc templates.","`skill: {name, description, body, scope?}` writes agent guidance; lowercase letters/digits/hyphens name is identity, description is when to use it. New skills use the default skill home; existing ones keep their real folder. Use install for editors.","`asset: {path, content|source}` uploads binary image/file: base64 content or local source path. `documents` takes document specs and reports each result.",`Optional summary: one-line outcome ≤80 chars, persisted to git history; avoid secrets or PII. Batches need per-entry summary; top-level is ignored.`,`Read response warnings: content-divergence/disk-edit-reconciled means re-read; mermaid-parse-error means the write landed but fix the fence.`,Q8].join(`
|
|
1137
|
-
`),QX(`config-persistence`),QX(`generated-index-git-attributes`),QX(`head-watcher`),QX(`shadow-gc`),QX(`shadow-maintenance`),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),QX(`mermaid-persistence`),QX(`persistence`),QX(`persistence-staleness`),QX(`recovered-file-target`),QX(`removed-docs-journal`),QX(`server-observers`),QX(`github-account`),QX(`sync-engine`),Fe(o),new Set(vye);const t5=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`];new Set(t5),[...t5],(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();let n5=null;t8(()=>{n5?.disable(),n5=null}),QX(`skill-migrate`);function r5(e){return[{host:`agents`,root:bS},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=b4.indexOf(e.host),r=b4.indexOf(t.host);return(n===-1?b4.length:n)-(r===-1?b4.length:r)||e.host.localeCompare(t.host)})}r5(_t),r5(vt),Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS);const
|
|
1137
|
+
`),QX(`config-persistence`),QX(`generated-index-git-attributes`),QX(`head-watcher`),QX(`shadow-gc`),QX(`shadow-maintenance`),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),QX(`mermaid-persistence`),QX(`persistence`),QX(`persistence-staleness`),QX(`recovered-file-target`),QX(`removed-docs-journal`),QX(`server-observers`),QX(`github-account`),QX(`sync-engine`),Fe(o),new Set(vye);const t5=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`];new Set(t5),[...t5],(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();let n5=null;t8(()=>{n5?.disable(),n5=null}),QX(`skill-migrate`);function r5(e){return[{host:`agents`,root:bS},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=b4.indexOf(e.host),r=b4.indexOf(t.host);return(n===-1?b4.length:n)-(r===-1?b4.length:r)||e.host.localeCompare(t.host)})}r5(_t),r5(vt),Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS);const kje=Ul;yX(),Fe(o),QX(`project-git`);var i5=i((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),a5=i((e=>{let{InvalidArgumentError:t}=i5();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),o5=i((e=>{let{humanReadableArgName:t}=a5();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
|
|
1138
1138
|
`)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
|
|
1139
1139
|
`+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
|
|
1140
1140
|
`)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),s5=i((e=>{let{InvalidArgumentError:t}=i5();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
|
|
@@ -1143,7 +1143,7 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
|
|
|
1143
1143
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
|
|
1144
1144
|
- too many short flags`):i.test(t)?Error(`${n}
|
|
1145
1145
|
- too many long flags`):Error(`${n}
|
|
1146
|
-
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}e.Option=n,e.DualOptions=r})),
|
|
1146
|
+
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}e.Option=n,e.DualOptions=r})),Aje=i((e=>{function t(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a=1;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function n(e,n){if(!n||n.length===0)return``;n=Array.from(new Set(n));let r=e.startsWith(`--`);r&&(e=e.slice(2),n=n.map(e=>e.slice(2)));let i=[],a=3;return n.forEach(n=>{if(n.length<=1)return;let r=t(e,n),o=Math.max(e.length,n.length);(o-r)/o>.4&&(r<a?(a=r,i=[n]):r===a&&i.push(n))}),i.sort((e,t)=>e.localeCompare(t)),r&&(i=i.map(e=>`--${e}`)),i.length>1?`\n(Did you mean one of ${i.join(`, `)}?)`:i.length===1?`\n(Did you mean ${i[0]}?)`:``}e.suggestSimilar=n})),jje=i((e=>{let n=t(`node:events`).EventEmitter,r=t(`node:child_process`),i=t(`node:path`),a=t(`node:fs`),o=t(`node:process`),{Argument:s,humanReadableArgName:c}=a5(),{CommanderError:l}=i5(),{Help:u,stripColor:d}=o5(),{Option:f,DualOptions:p}=s5(),{suggestSimilar:m}=Aje();var h=class e extends n{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>o.stdout.write(e),writeErr:e=>o.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>o.stdout.isTTY?o.stdout.columns:void 0,getErrHelpWidth:()=>o.stderr.isTTY?o.stderr.columns:void 0,getOutHasColors:()=>_()??(o.stdout.isTTY&&o.stdout.hasColors?.()),getErrHasColors:()=>_()??(o.stderr.isTTY&&o.stderr.hasColors?.()),stripColor:e=>d(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new u,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
|
|
1147
1147
|
- specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new s(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
|
|
1148
1148
|
Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new l(e,t,n)),o.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return r[n]=this._storeOptionsAsProperties?this:this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new f(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
1149
1149
|
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(n,e.defaultValue===void 0||e.defaultValue,`default`)}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof f)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){o.versions?.electron&&(t.from=`electron`);let e=o.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=o.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:o.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
@@ -1152,7 +1152,7 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
1152
1152
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1153
1153
|
- ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function c(e,t){let n=i.resolve(e,t);if(a.existsSync(n))return n;if(s.includes(i.extname(t)))return;let r=s.find(e=>a.existsSync(`${n}${e}`));if(r)return`${n}${r}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=a.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=i.resolve(i.dirname(e),d)}if(d){let t=c(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=i.basename(this._scriptPath,i.extname(this._scriptPath));n!==this._name&&(t=c(d,`${n}-${e._name}`))}u=t||u}n=s.includes(i.extname(u));let f;o.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.execPath,t,{stdio:`inherit`})):n?(t.unshift(u),t=g(o.execArgv).concat(t),f=r.spawn(o.argv[0],t,{stdio:`inherit`})):f=r.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{o.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new l(e,`commander.executeSubCommandAsync`,`(close)`)):o.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)o.exit(1);else{let e=new l(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
1154
1154
|
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in o.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,o.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new p(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=m(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${e.length}.`;this.error(r,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=m(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>c(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=i.basename(e,i.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(o.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
1155
|
-
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:
|
|
1155
|
+
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function g(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function _(){if(o.env.NO_COLOR||o.env.FORCE_COLOR===`0`||o.env.FORCE_COLOR===`false`)return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=h,e.useColor=_}));const{program:Mje,createCommand:Nje,createArgument:Pje,createOption:Fje,CommanderError:Ije,InvalidArgumentError:Lje,InvalidOptionArgumentError:Rje,Command:zje,Argument:Bje,Option:Vje,Help:Hje}=e(i((e=>{let{Argument:t}=a5(),{Command:n}=jje(),{CommanderError:r,InvalidArgumentError:i}=i5(),{Help:a}=o5(),{Option:o}=s5();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;function Uje(e){let{projectDir:t,contentDir:n,sampleCap:r=5}=e,i=[],a=[];try{_(n)}catch(e){return{totalCount:0,sample:[],contentDir:n,warnings:[`cannot access content directory ${n}: ${e instanceof Error?e.message:String(e)}`]}}let o;try{o=qAe({projectDir:t,contentDir:n})}catch(e){return{totalCount:0,sample:[],contentDir:n,warnings:[e instanceof Error?e.message:String(e)]}}function s(e){let t;try{t=w(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);i.push(`could not read directory ${M(n,e)||`.`}: ${r}`);return}for(let r of t){let t=j(e,r.name);if(r.isSymbolicLink()){let e;try{e=E(t)}catch(e){let r=e.code;r===`ENOENT`||r===`ELOOP`?i.push(`broken or cyclic symlink: ${M(n,t)}`):i.push(`cannot resolve symlink ${M(n,t)}: ${r??`unknown error`}`);continue}let r;try{r=te(e)}catch{continue}if(r.isDirectory()){let e=M(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=M(n,t);if(o.isExcluded(e))continue;a.push(e)}}else if(r.isDirectory()){let e=M(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=M(n,t);if(o.isExcluded(e))continue;a.push(e)}}}return s(n),{totalCount:a.length,sample:a.slice(0,r),contentDir:n,warnings:i}}function Wje(e){let t=ft(),n=e.split(/\r?\n/,1)[0]??``;if(n===jY(t))return!0;let r=kY(t);return n.startsWith(r)&&/^-v\d+$/.test(n.slice(r.length))}function c5(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command!==`ok-pi-managed-extension`||!Array.isArray(t.args))return!1;let n=t.args[0];return typeof n==`string`&&Wje(n)}function Gje(e){return{command:`ok-pi-managed-extension`,args:[e]}}function l5(e={}){let t=e.mode===`dev`,n=ft(),r=t?jY(n):AY(n),i=`${Tt(n)}_`,a={unix:PY({...e,platformName:`darwin`}),win32:PY({...e,platformName:`win32`})};return`${r}
|
|
1156
1156
|
/**
|
|
1157
1157
|
* Open Knowledge bridge for Pi — MANAGED FILE, written by \`${mt()} init\`.
|
|
1158
1158
|
* Hand edits are overwritten whenever OK re-syncs this project; remove it
|
|
@@ -1495,61 +1495,61 @@ export default function okBridge(pi: {
|
|
|
1495
1495
|
}
|
|
1496
1496
|
});
|
|
1497
1497
|
}
|
|
1498
|
-
`}function
|
|
1498
|
+
`}function Kje(e,t){let n=M(n8(t),n8(e));return n.length>0&&!n.startsWith(`..`)&&!A(n)}const qje=e=>{try{let t=s(`git`,[`rev-parse`,`--show-toplevel`],c8({cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})).trim();return t.length>0?t:null}catch{return null}};function Jje(e,t={}){let n=t.homeDir??_e(),r=t.gitTopLevel??qje,i=N(e),a;try{a=E(i)}catch{a=i}let o=a,s=0;for(;s<30&&o!==n&&o!==`/`&&o!==``;){if(s8(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=k(o);if(e===o)break;o=e,s+=1}let c=r(a);return c!==null&&Kje(c,n)?c===a?{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:{projectRoot:c,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!0}:{projectRoot:i,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}}var u5=class extends Error{name=`ProjectPathSafetyError`;code=`PROJECT_PATH_SAFETY`};function d5(e,t){let n;try{n=_(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(n?.isSymbolicLink())throw new u5(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);f5(e,t)}function Yje(e,t){f5(e,t)}function f5(e,t){p5(e,t)}function p5(e,t){let n=t,r;try{r=E(n)}catch{r=N(n)}let i=k(e);for(;i.length>1&&i!==le;){let t;try{t=E(i)}catch(e){if(e.code===`ENOENT`){i=k(i);continue}throw e}let n=M(r,t);if(n===``||!n.startsWith(`..`)&&!A(n))return;throw new u5(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${r}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function m5(e,t){let n=k(t),r=g(t)?`overwritten`:`written`;if(r===`written`&&g(n))throw Error(`Refusing to replace ${n}: it exists but holds no SKILL.md, so it is not a bundle OpenKnowledge wrote. Move it aside and try again.`);return O(n,{recursive:!0,force:!0}),v(k(n),{recursive:!0}),m(e,n,{recursive:!0}),r}function h5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function g5(e,t,n){try{if(te(n).size>10485760)return!1}catch{return!1}let r;try{r=S(n,`utf-8`)}catch{return!1}let i=[],a=WDe(r.charCodeAt(0)===65279?r.slice(1):r,i,{allowTrailingComma:!0,disallowComments:!1});if(i.length>0||!h5(a))return!1;let o=a[e.topLevelKey];if(!h5(o))return!1;let s=e.serverMapSubKey?o[e.serverMapSubKey]:o;if(!h5(s))return!1;let c=s[e.serverName(t)];return h5(c)&&c.enabled===!1?!1:VY(c)||Rbe(c)}function Xje(e){let t=$a[e]?.satisfiers.find(e=>e.piece===`mcp`&&e.scope===`project`),n=t?.pathId===void 0?null:Oa(t.pathId);return n===null||n.kind!==`editor-project-config`||n.editor===e?null:$Y[n.editor]??null}function Zje(e,t,n={}){if(!oee.includes(e.id))return!0;let r=Xje(e.id),i=r?.projectConfigPath?.(t);if(r!==null&&i!==void 0&&g5(r,t,i))return!0;try{return g5(e,t,e.configPath(t,n.home))}catch{return!1}}function Qje(e){let t=new Set(yt.filter(e=>e.scope===`project`).map(e=>e.editorId));return e.filter(e=>t.has(e))}function $je(e,t){if(Qje(t).length===0)return null;let n=j(e,bS,xt,`SKILL.md`);try{let t=W8(`project`,{checkDesktop:!0});return d5(k(n),e),{editorId:`agents`,label:`.agents hub`,action:m5(t,n),path:n}}catch(e){return{editorId:`agents`,label:`.agents hub`,action:`failed`,path:n,error:e instanceof Error?e.message:String(e)}}}function _5(e,t,n={}){let r=e.projectSkillPath?.(t);if(!r)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};if(!Zje(e,t,n))return{editorId:e.id,label:e.label,action:`skipped-prerequisite`,path:r};try{let n=W8(`project`,{checkDesktop:!0});d5(k(r),t);let i=m5(n,r);return{editorId:e.id,label:e.label,action:i,path:r}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}function eMe(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=k(n);return g(n)?(Yje(r,t),O(r,{recursive:!0,force:!0}),{editorId:e.id,label:e.label,action:`removed`,path:n}):{editorId:e.id,label:e.label,action:`not-present`,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function tMe(){let e=mY();return e&&typeof e.resolveSymlinkWritePath==`function`?e:null}function nMe(e){let t=e,n=new Set;for(;;){let r;try{r=_(t).isSymbolicLink()}catch(n){return n.code===`ENOENT`?{readPath:t,writePath:t}:{readPath:null,writePath:e}}if(!r)return{readPath:t,writePath:t};if(n.has(t))return{readPath:null,writePath:e};n.add(t);let i;try{i=T(t)}catch(t){return pY(`readlinkSync threw during symlink walk`,t),{readPath:null,writePath:e}}t=A(i)?i:j(k(t),i)}}let v5;function rMe(){return v5===void 0&&(v5=tMe()),v5}function y5(e,t=rMe){let n=t();if(n)try{let t=n.resolveSymlinkWritePath(e);return{readPath:t.readPath??null,writePath:t.writePath}}catch(e){pY(`resolveSymlinkWritePath threw`,e)}return nMe(e)}const b5=`**/.ok/*`,x5=`!**/.ok/skills/`;function S5(e){let t=[`.ok/`,`.okignore`];for(let n of vY){let r=$Y[n];r.projectConfigPath&&t.push(dMe(r.projectConfigPath(e),e))}return t.push(`.claude/launch.json`),Array.from(new Set(t))}function C5(e){let t=j(e,...Oye);if(!g(t))return[];try{let e=Mye(S(t,`utf-8`));if(!e)return[];let n=[];for(let[t,r]of Object.entries(e.skills))if(t!==`open-knowledge`)for(let e of r.hosts){let r=_t[e];r&&n.push(`${r}/${t}/`)}return Array.from(new Set(n))}catch{return[]}}function iMe(e,t){let n=w5(e,t).tracked;if(n.length>0)return{kind:`refused-tracked`,tracked:n,remediation:T5(n)};let r=E5(e);if(r.kind!==`ok`)return r.result;let i=g(r.path)?S(r.path,`utf-8`):``,a=new Set(C5(e)),o=[],s=a.size===0?i:i.split(`
|
|
1499
1499
|
`).filter(e=>{let t=e.trim();return!a.has(t)||(o.push(t),!1)}).join(`
|
|
1500
1500
|
`),c=k5(s),l=[],u=[];for(let e of t)O5(c,e)?u.push(e):l.push(e);if(l.length===0&&o.length===0)return{kind:`updated`,appended:l,alreadyPresent:u,removed:[]};let d=l.length===0||s.length===0||s.endsWith(`
|
|
1501
1501
|
`)?``:`
|
|
1502
1502
|
`,f=l.length===0?``:`${l.join(`
|
|
1503
|
-
`)}\n`;try{re(r.path,`${s}${d}${f}`,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:l,alreadyPresent:u,removed:o}}function
|
|
1503
|
+
`)}\n`;try{re(r.path,`${s}${d}${f}`,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:l,alreadyPresent:u,removed:o}}function aMe(e,t){let n=E5(e);if(n.kind!==`ok`)return n.result;if(!g(n.path))return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let r=t.map(e=>D5(e)),i=new Set;for(let e of r)for(let t of e)i.add(t);i.add(b5),i.add(x5);for(let t of C5(e))i.add(t);let a;try{a=S(n.path,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}let o=a.split(`
|
|
1504
1504
|
`),s=new Set,c=[];for(let e of o){let t=e.trim();if(i.has(t)){s.add(t);continue}c.push(e)}let l=[...s];if(s.size===0)return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let u=c.join(`
|
|
1505
|
-
`);if(u!==a)try{re(n.path,u,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:[],alreadyPresent:[],removed:l}}function
|
|
1505
|
+
`);if(u!==a)try{re(n.path,u,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:[],alreadyPresent:[],removed:l}}function oMe(e){let t=E5(e);if(t.kind!==`ok`)return t.result.reason===`no-git`||t.result.reason===`malformed-pointer`||t.result.reason===`inaccessible`?`no-git`:`shared`;if(!g(t.path))return`shared`;let n;try{n=S(t.path,`utf-8`)}catch{return`shared`}let r=k5(n),i=S5(e);for(let e of i)if(O5(r,e))return`local-only`;return r.has(b5)?`local-only`:`shared`}function sMe(e){let t=E5(e);if(t.kind!==`ok`||!g(t.path))return[];let n;try{n=S(t.path,`utf-8`)}catch{return[]}let r=k5(n),i=[...S5(e),...C5(e)].filter(e=>O5(r,e)),a=new Set(i),o=[];for(let e of Object.values(_t))e!==null&&o.push(e);let s=[];for(let e of r){if(a.has(e))continue;if(e===b5||e===x5){s.push(e);continue}let t=e.replace(/^\//,``).replace(/\/$/,``);o.some(e=>t.startsWith(`${e}/`)&&t.length>e.length+1)&&s.push(e)}return[...i,...s]}function w5(e,t){let n=[];for(let r of t){let t=N(e,r);if(g(t))try{s(`git`,[`ls-files`,`--error-unmatch`,...Nye([r])],c8({cwd:e,stdio:[`ignore`,`ignore`,`ignore`]})),n.push(r)}catch{}}return{tracked:n}}const cMe=/^[\w.\-/]+$/;function lMe(e){return process.platform===`win32`?`"${e.replaceAll(`"`,``)}"`:`'${e.replaceAll(`'`,`'\\''`)}'`}function uMe(e){return cMe.test(e)?e:lMe(kJ(e))}function T5(e){let t=[];t.push(`Cannot switch OpenKnowledge to local-only — these OK files are tracked upstream:`),t.push(``);for(let n of e)t.push(` ${n}`);t.push(``),t.push(`.git/info/exclude only hides files that git isn't already tracking. To proceed, untrack them first:`),t.push(``);for(let n of e){let e=n.replace(/\/$/,``),r=n.endsWith(`/`)?`-r `:``;t.push(` git rm --cached ${r}-- ${uMe(e)}`)}return t.push(``),t.push("Then re-run the command. Note: `git rm --cached` removes the files from the index — your teammates will see a deletion on their next pull. If you don't want that, leave sharing mode set to 'shared'."),t.join(`
|
|
1506
1506
|
`)}function E5(e){let t=Wxe(e);switch(t.kind){case`repository`:{let e=t.repository.readCommonDir();if(e.kind===`unreadable`)return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`inaccessible`}};let n=j(e.path,`info`);return g(n)?{kind:`ok`,path:j(n,`exclude`)}:{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`no-info-dir`}}}case`absent`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`no-git`}};case`malformed-pointer`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`malformed-pointer`}};case`inaccessible`:return{kind:`no-exclude`,result:{kind:`no-exclude`,reason:`inaccessible`}}}}function D5(e){let t=e.replace(/\/$/,``);return new Set([e,t,`/${e}`,`/${t}`])}function O5(e,t){for(let n of D5(t))if(e.has(n))return!0;return!1}function k5(e){let t=new Set;for(let n of e.split(`
|
|
1507
|
-
`)){let e=n.trim();e.length!==0&&t.add(e)}return t}function
|
|
1508
|
-
`)){let e=t.trimStart();if(e.length!==0&&e.length!==t.length)return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function M5(e){let t=(e.match(/\r\n/g)??[]).length;return t!==0&&t>=(e.match(/\n/g)??[]).length-t}function N5(e){try{return te(e).mode&511}catch{return}}function
|
|
1507
|
+
`)){let e=n.trim();e.length!==0&&t.add(e)}return t}function dMe(e,t){return fMe(M(t,e))}function fMe(e){return le===`/`?e:e.split(le).join(`/`)}function A5(e){switch(e?.code){case`EACCES`:case`EPERM`:return`permission-denied`;case`ELOOP`:return`unresolved-symlink`;case`EISDIR`:case`ENOTDIR`:return`not-a-file`;case`ENOENT`:return`disappeared`;default:return`unreadable`}}function j5(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions, then retry`;case`missing-symlink-target`:return`the symlink target is missing; restore the target or correct the symlink, then retry`;case`unresolved-symlink`:return`the path or symlink could not be resolved; check path permissions and repair any symlink cycle, then retry`;case`not-a-file`:return`the path is not a regular file; restore the intended configuration file, then retry`;case`disappeared`:return`the file disappeared; retry to check its current state`;case`unreadable`:return`the file could not be read; check that the path is accessible, then retry`;default:throw Error(`unhandled configuration file decline reason: ${e}`)}}function pMe(e){for(let t of e.split(`
|
|
1508
|
+
`)){let e=t.trimStart();if(e.length!==0&&e.length!==t.length)return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function M5(e){let t=(e.match(/\r\n/g)??[]).length;return t!==0&&t>=(e.match(/\n/g)??[]).length-t}function N5(e){try{return te(e).mode&511}catch{return}}function mMe(e,t){let n=e.charCodeAt(0)===65279,r=n?e.slice(1):e,i=r.includes(`\r
|
|
1509
1509
|
`)?`\r
|
|
1510
1510
|
`:`
|
|
1511
|
-
`,a=R4(r,t,void 0,{formattingOptions:{...
|
|
1512
|
-
`)?n:`${n}\n`)}function
|
|
1513
|
-
`)?n:`${n}\n`)}const L5=10485760;function R5(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>R5(e,t[n]));if(dY(e)&&dY(t)){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&R5(e[n],t[n]))}return!1}function
|
|
1514
|
-
`)){let e=t.trimStart();if(e.length!==0&&e.length!==t.length)return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function z5(e,t,n){return t===void 0?[e,n]:[e,t,n]}function B5(e,t,n,r){let i={[n]:r};return{[e]:t===void 0?i:{[t]:i}}}function V5(e,t,n){let r=e[t];return n===void 0?r:dY(r)?r[n]:void 0}function
|
|
1511
|
+
`,a=R4(r,t,void 0,{formattingOptions:{...pMe(r),eol:i}});if(a.length===0)return{text:e,changed:!1};let o=`${n?``:``}${z4(r,a)}`;return{text:o,changed:o!==e}}const hMe={allowTrailingComma:!0,disallowComments:!1};function gMe(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function P5(e){let t=[],n=GDe(e,t,hMe);return t.some(t=>!gMe(t,e))||n?.type!==`object`?null:n}function F5(e,t){let n=0;for(let r of e.children??[]){let e=r.children?.[0];e!==void 0&&L4(e)===t&&(n+=1)}return n}function I5(e,t){VJ(e,`${JSON.stringify(t,null,2)}\n`)}function _Me(e,t){let n=Sbe(t);VJ(e,n.endsWith(`
|
|
1512
|
+
`)?n:`${n}\n`)}function vMe(e,t){let n=(0,xs.stringify)(t);VJ(e,n.endsWith(`
|
|
1513
|
+
`)?n:`${n}\n`)}const L5=10485760;function R5(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>R5(e,t[n]));if(dY(e)&&dY(t)){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&R5(e[n],t[n]))}return!1}function yMe(e,t,n){return dY(e)&&n.every(n=>R5(e[n],t[n]))}function bMe(e){for(let t of e.split(`
|
|
1514
|
+
`)){let e=t.trimStart();if(e.length!==0&&e.length!==t.length)return t.charCodeAt(0)===9?{insertSpaces:!1,tabSize:1}:{insertSpaces:!0,tabSize:t.length-e.length}}return{insertSpaces:!0,tabSize:2}}function z5(e,t,n){return t===void 0?[e,n]:[e,t,n]}function B5(e,t,n,r){let i={[n]:r};return{[e]:t===void 0?i:{[t]:i}}}function V5(e,t,n){let r=e[t];return n===void 0?r:dY(r)?r[n]:void 0}function xMe(e,t,n,r,i,a=!1,o=!1){if(!g(e))return o?{kind:`unchanged`}:(I5(e,B5(t,i,n,r)),{kind:`written`});let s;try{s=S(e,`utf-8`)}catch(e){return pY(`json config read failed`,e),{kind:`declined`,reason:A5(e)}}if(s.trim()===``)return o?{kind:`unchanged`}:(I5(e,B5(t,i,n,r)),{kind:`written`});if(Buffer.byteLength(s,`utf-8`)>L5)return{kind:`declined`,reason:`oversize`};let c=P5(s);if(!c)return{kind:`declined`,reason:`unparseable`};if(F5(c,t)>1)return{kind:`declined`,reason:`duplicate-container`};let l=V5(L4(c),t,i),u=dY(l)?l[n]:void 0,d=u!==void 0,f=HY(r);if(d&&a?FY(u):d&&yMe(u,r,f))return{kind:o?`unchanged`:`overwritten`};let p=s.charCodeAt(0)===65279,m=p?s.slice(1):s,h=m.includes(`\r
|
|
1515
1515
|
`)?`\r
|
|
1516
1516
|
`:`
|
|
1517
|
-
`,_={...
|
|
1518
|
-
`),p,m=!1;try{let t=
|
|
1517
|
+
`,_={...bMe(m),eol:h},v=z5(t,i,n),y=m;if(o)for(let e of d?UY(u,r):[]){let t=R4(y,[...v,e],void 0,{formattingOptions:_});y=z4(y,t)}else if(d&&!a&&VY(u))for(let e of f){let t=R4(y,[...v,e],r[e],{formattingOptions:_});y=z4(y,t)}else{let e=R4(y,v,r,{formattingOptions:_});y=z4(y,e)}let b=`${p?``:``}${y}`;return b!==s&&VJ(e,b,{mode:N5(e)}),o&&b===s?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}function SMe(e,t,n,r,i,a=!1,o=!1){let s=``;if(g(t))try{s=S(t,`utf-8`)}catch(e){return pY(`toml config read failed`,e),{kind:`declined`,reason:A5(e)}}let c=s.trim()===``;if(c&&o)return{kind:`unchanged`};if(e.backend===`fallback`)return c?(_Me(t,{[n]:{[r]:i}}),{kind:`written`}):{kind:`declined`,reason:`no-native-writer`};let l=s.charCodeAt(0)===65279,u=l?s.slice(1):s,d=M5(u),f=c||u.endsWith(`
|
|
1518
|
+
`),p,m=!1;try{let t=CMe(e,u,n,r);if(o){let n=u;for(let a of t===void 0?[]:UY(t,i))n=e.removeEntryKey(n,r,a).text;p={text:n,existed:t!==void 0}}else{let n=wMe(t,i,a);m=n.kind===`replace`;let o=m?e.removeEntry(u,r).text:u;if(n.kind===`merge`)for(let t of n.prune)o=e.removeEntryKey(o,r,t).text;p=e.upsertEntry(o,r,i)}}catch(e){return pY(`upsertEntry failed`,e),{kind:`declined`,reason:`unparseable`}}let h=p.text;f?h.endsWith(`
|
|
1519
1519
|
`)||(h=`${h}\n`):h=h.replace(/\n+$/,``),d&&(h=h.replace(/\r\n/g,`
|
|
1520
1520
|
`).replace(/\n/g,`\r
|
|
1521
|
-
`));let _=`${l?``:``}${h}`;return _!==s&&VJ(t,_,{mode:N5(t)}),o&&_===s?{kind:`unchanged`}:{kind:p.existed||m?`overwritten`:`written`}}function
|
|
1521
|
+
`));let _=`${l?``:``}${h}`;return _!==s&&VJ(t,_,{mode:N5(t)}),o&&_===s?{kind:`unchanged`}:{kind:p.existed||m?`overwritten`:`written`}}function CMe(e,t,n,r){if(t.trim()===``)return;let i=e.parseToObject(t)[n],a=dY(i)?i[r]:void 0;return dY(a)?a:void 0}function wMe(e,t,n){return e===void 0||FY(e)?{kind:`merge`,prune:[]}:n||!VY(e)?{kind:`replace`}:{kind:`merge`,prune:UY(e,t)}}function TMe(e,t,n,r,i=!1,a=!1){let o=``;if(g(e))try{o=S(e,`utf-8`)}catch(e){return pY(`yaml config read failed`,e),{kind:`declined`,reason:A5(e)}}if(o.trim()===``)return a?{kind:`unchanged`}:(vMe(e,{[t]:{[n]:r}}),{kind:`written`});if(Buffer.byteLength(o,`utf-8`)>L5)return{kind:`declined`,reason:`oversize`};let s=o.charCodeAt(0)===65279,c=s?o.slice(1):o,l=(0,xs.parseDocument)(c);if(l.errors.length>0)return{kind:`declined`,reason:`unparseable`};let u=[t,n],d=l.hasIn(u);l.hasIn([t])&&!(0,xs.isCollection)(l.getIn([t],!0))&&l.deleteIn([t]);let f=l.getIn(u,!0),p=d&&(0,xs.isCollection)(f)&&(i?FY(f.toJSON()):VY(f.toJSON()));if(a){if(d&&(0,xs.isCollection)(f))for(let e of UY(f.toJSON(),r))l.deleteIn([...u,e])}else if(p)for(let e of HY(r))r[e]===void 0?l.deleteIn([...u,e]):l.setIn([...u,e],l.createNode(r[e]));else l.setIn(u,l.createNode(r));let m=l.toString(),h=M5(c);c.endsWith(`
|
|
1522
1522
|
`)?m.endsWith(`
|
|
1523
1523
|
`)||(m=`${m}\n`):m=m.replace(/\n+$/,``),h&&(m=m.replace(/\r\n/g,`
|
|
1524
1524
|
`).replace(/\n/g,`\r
|
|
1525
|
-
`));let _=`${s?``:``}${m}`;return _!==o&&VJ(e,_,{mode:N5(e)}),a&&_===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const
|
|
1525
|
+
`));let _=`${s?``:``}${m}`;return _!==o&&VJ(e,_,{mode:N5(e)}),a&&_===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const EMe=`A dev build registers OpenKnowledge MCP in project config only, never in user-level editor config. Run \`${ht} init --dev-mcp\` in the project, or set OK_CHANNEL=stable.`,DMe=`open-knowledge-ui`;function H5(e,t,n){try{let r=e.detectPath?.(t,n)??k(e.configPath(t,n));return g(r)}catch{return!1}}function U5(e,t,n){try{let r=N(k(e.configPath(t,n))),i=N(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+le)}catch{return!1}}function W5(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=n.pruneOnly===!0;if(s&&(e.format===`file`||!g(o)))return{editorId:e.id,label:e.label,action:`skipped-flag`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}};let c=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||U5(e,t,r);if(!i&&c&&!H5(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{d5(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return kMe(e,o,a,n,{isProjectScope:i!==void 0});let l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{s||v(k(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let u={action:`written`},d;try{UJ(`${o}.lock`,()=>{let t=y5(o).writePath;if(s||v(k(t),{recursive:!0}),e.format===`toml`){let r=SMe(_Y(),t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}if(e.format===`yaml`){let r=TMe(t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}let r=xMe(t,e.topLevelKey,a,l,e.serverMapSubKey,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){d=e instanceof Error?e:Error(String(e))}return d?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:d.message,...i===void 0?{}:{configScope:`project`}}:u.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:u.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:u.action===`unchanged`?`skipped-flag`:u.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const OMe={pi:l5};function kMe(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=OMe[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{v(k(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{UJ(`${t}.lock`,()=>{let e=null;try{e=S(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}VJ(t,c,e===null?void 0:{mode:N5(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}async function AMe(e){let t=exe(e.editors).filter(e=>e.scope===`global`);if(ut())return t.map(t=>({editorId:t.id,label:t.label,action:`failed`,configPath:t.configPath(``,e.home),serverName:t.serverName(``),error:EMe}));let n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>W5(t,``,n,e.home))}function G5(e,t,n,r){let i=q5(e,t,n,r);return i.kind===`present`?i.entry:null}function K5(e,t,n,r){let i=V5(e,t,r);if(!dY(i))return{kind:`no-entry`};let a=i[n];return dY(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function q5(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!g(i))return{kind:`absent`};try{if(te(i).size>L5)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:A5(e)}}let a;try{a=S(i,`utf-8`)}catch(e){return{kind:`decline`,reason:A5(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:Gje(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=_Y().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return K5(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,xs.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:K5(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=P5(a);return s?F5(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:K5(L4(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}function jMe(e,t){let n=[];for(let r of vY)r!==`claude-desktop`&&H5($Y[r],e,t)&&n.push(r);return n}function J5(e){return e===`opencode`?Ube:Hbe}function MMe(e,t,n){let r=$Y[e],i=J5(e),a=[],o=r.projectConfigPath?.(t);o!==void 0&&a.push({scope:`project`,configPath:o});try{a.push({scope:`user`,configPath:r.configPath(t,n)})}catch{}for(let o of a){let a=G5(r,t,n,o.configPath);if(a!==null&&i(a))return{editorId:e,scope:o.scope,configPath:o.configPath}}return null}const Y5=8192;function X5(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 NMe(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const PMe=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function FMe(e){return e.replace(PMe,`$1"[REDACTED-DEVICE-ID]"`)}function Z5(e){return FMe(NMe(e))}const IMe=/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(\.\d+)? ([+-]\d{2})(\d{2})$/;function Q5(e){if(typeof e!=`string`)return null;let t=IMe.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 LMe(e){let t=b(e,`r`);try{let e=Buffer.alloc(Y5),n=0,r=!1;for(;n<Y5;){let i=C(t,e,n,Y5-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{f(t)}}function RMe(e){try{let t=LMe(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:Q5(a)}}catch{return{kind:`unreadable`}}}function $5(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function zMe(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=j(e,t.name),r;try{r=te(n).mtimeMs}catch{continue}if(r<i)continue;let c=RMe(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!$5(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 e7=`state/os-termination-evidence.json`,t7=6048e5,n7=`/Library/Logs/DiagnosticReports`,r7=/openknowledge/i,BMe=it.map(e=>at(rt[e]));function VMe(e={}){return(t,n)=>new Promise(r=>{try{o(t,n,{encoding:`utf8`,timeout:e.timeoutMs??15e3,maxBuffer:e.maxBuffer??16777216,windowsHide:!0},(e,t,n)=>{r({...HMe(e),stdout:t,stderr:n})})}catch(e){let t=e.code;r({status:null,stdout:``,stderr:``,errorCode:typeof t==`string`?t:`spawn-failed`})}})}function HMe(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 i7(e){if(e.errorCode!==void 0)return e.errorCode;if(e.signal!==void 0)return`signal ${e.signal}`;let t=(e.stderr.trim().split(`
|
|
1526
1526
|
`)[0]??``).replace(/\S*\/journal\/\S*/g,`<journal path>`).replace(/\b[0-9a-f]{32}\b/gi,`<id>`);return`exit ${e.status}${t===``?``:`: ${t}`}`}function a7(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 o7(e,t){return{...e,outcome:`unavailable`,unavailableReason:t}}function s7(e){return{...e,outcome:e.events.length>0?`collected`:`none-in-window`}}function c7(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function l7(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function u7(e,t){let n=t.indexOf(`
|
|
1527
|
-
`);if(n===-1)return null;let r,i;try{r=l7(JSON.parse(t.slice(0,n))),i=l7(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=l7(e);t===null||typeof t.name!=`string`||!$5(t.name)||a.push({name:t.name,pid:c7(t.pid),killReason:typeof t.reason==`string`?t.reason:null,residentPages:c7(t.rpages),lifetimeMaxPages:c7(t.lifetimeMax)})}let o=Q5(r.timestamp);return{kind:`jetsam`,at:o===null?null:new Date(o).toISOString(),file:e,pageSize:c7(l7(i.memoryStatus)?.pageSize),largestProcessOwned:typeof i.largestProcess==`string`?$5(i.largestProcess):null,ownedProcesses:a}}const d7=/^JetsamEvent-.*\.ips$/;function f7(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
|
|
1528
|
-
`)){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
|
|
1529
|
-
`)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=h7.exec(i);if(e===null){r+=1;continue}let[,a=``,o=``,s=``]=e;if(!r7.test(s)){n+=1;continue}let c=
|
|
1530
|
-
`)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=h7.exec(i);if(e===null){r+=1;continue}let[,a=``,,o=``]=e,s=GMe.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 ZMe(e,t,n){let r=XMe(e);if(r.lines.length===0)return{...r,events:[],unattributed:null};let i=await qMe(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 g7(e){return e.status===0||e.status===1&&/^-- No entries --$/m.test(e.stdout)}async function QMe(e,t,n){let r=a7(`linux`,`linux-journal`,[`journalctl ${p7.join(` `)}`,`journalctl ${m7.join(` `)}`]),[i,a]=await Promise.all([e(`journalctl`,[...p7]),e(`journalctl`,[...m7])]),o=[];if(g7(i)){let e=YMe(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: ${i7(i)}`);if(g7(a)){let e=await ZMe(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: ${i7(a)}`);return o.length===2?o7(r,o.join(`; `)):o.length===1?{...r,outcome:`partial`,unavailableReason:o.join(`; `)}:s7(r)}const $Me={41:`Microsoft-Windows-Kernel-Power`,1074:`User32`,2004:`Microsoft-Windows-Resource-Exhaustion-Detector`,6008:`EventLog`},eNe={1e3:`Application Error`,1001:`Windows Error Reporting`,1002:`Application Hang`};function _7(e){return e===`System`?$Me:eNe}function tNe(e){let t=`System[(${Object.keys(_7(e)).map(e=>`EventID=${e}`).join(` or `)}) and TimeCreated[timediff(@SystemTime) <= ${t7}]]`;return e===`System`?`*[${t}]`:`*[${t} and EventData[${zMe.map(e=>`Data='${e}'`).join(` or `)}]]`}function v7(e){return[`qe`,e,`/q:${tNe(e)}`,`/f:xml`,`/rd:true`,`/c:200`]}function nNe(e){return ue.join(e??`C:\\Windows`,`System32`,`wevtutil.exe`)}function rNe(e){return e.replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/&/g,`&`)}function iNe(e){return/[\\/]/.test(e)||/^[a-z]:/i.test(e)}function y7(e,t){let n=RegExp(`<${t}(?:\\s[^>]*)?>([\\s\\S]*?)</${t}>`,`g`);return[...e.matchAll(n)].map(e=>rNe(e[1]??``).trim())}function aNe(e,t){let n=_7(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=y7(o,`Data`),u=y7(o,`Name`),d=[...l,...u].some(e=>r7.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!==``&&!iNe(e)):[]})}return{events:r,foreignIgnored:i,unparseable:a}}async function oNe(e,t){let n=nNe(t),r=[`System`,`Application`],i=a7(`win32`,`windows-event-log`,r.map(e=>`${n} ${v7(e).join(` `)}`)),a=await Promise.all(r.map(async t=>({log:t,result:await e(n,v7(t))}))),o=[];for(let{log:e,result:t}of a){if(t.status!==0){o.push(`${e}: ${i7(t)}`);continue}let n=aNe(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?o7(i,o.join(`; `)):o.length>0?{...i,outcome:`partial`,unavailableReason:o.join(`; `)}:s7(i)}async function b7(e={}){let t=e.platform??process.platform,n=e.runCommand??BMe(),r=(e.now??(()=>new Date))();switch(t){case`darwin`:return HMe(e.macosReportsDir??n7,r);case`linux`:return QMe(n,r,e.desktopLogsDir??j(RJ(),`logs`));case`win32`:return oNe(n,e.systemRoot??process.env.SystemRoot);default:return{...a7(t,null,[]),outcome:`unsupported`}}}const sNe={schemaVersion:1,outcome:`not-collected`};function x7(e){return`${JSON.stringify(e??sNe,null,2)}\n`}const cNe=rt.stable.appId;function S7(){return j(RJ(),`bug-reports`)}function lNe(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=S7(),r=`${t}-bugreport`,i=j(n,`${r}.zip`);for(let e=2;g(i);e+=1)i=j(n,`${r}-${e}.zip`);return i}function C7(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function w7(e,t){let n=j(e,`.ok`,`config.yml`);if(g(n))try{let e=S(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 g(j(e,`.ok`))?Te(`sha256`).update(N(e)).digest(`hex`).slice(0,12):null}function uNe(){let e={timestamp:new Date().toISOString(),platform:ye(),osType:Ce(),osRelease:be(),hostname:`[redacted]`,uptime:we(),freeMem:ge(),totalMem:Se(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=c(`sw_vers -productVersion 2>/dev/null`,c8({encoding:`utf8`})).trim()}catch{}try{let t=j(__dirname,`..`,`..`,`package.json`);g(t)&&(e.okVersion=JSON.parse(S(t,`utf8`)).version)}catch{}return e}const dNe=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function T7(e){let t=ae(e);return dNe.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function fNe(e,t){return O7(e,t).files}const pNe=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function E7(e,t=cNe){let n=j(e,`${t}.ShipIt`);if(!g(n))return[];let r;try{r=w(n)}catch{return[]}return pNe.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=>j(n,e.entry)))}function D7(e){if(!g(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,-10):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=>j(e,t))}catch{return[]}}function O7(e,t){if(!g(t))return{files:[],excludedByProjectSlug:0};let n=w(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>j(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(T7),i=[],a=r.filter(t=>{try{return S(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=>!T7(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function mNe(e){let t=j(e,`.ok`,`local`);return g(t)?{files:[`server.lock`,`last-spawn-error.log`,sd,ad].map(e=>j(t,e)).filter(e=>g(e))}:{files:[]}}function hNe(e){let t=j(e,`.ok`,`local`,`logs`);return g(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>j(t,e)).filter(e=>g(e))}:{files:[]}}function gNe(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#${Te(`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 k7(e){let t=e.revealDocNames?e.content:gNe(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=BP(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 A7(e){for(let t of e.files)try{let n=S(t,`utf8`);k7({zipfile:e.zipfile,name:`${e.prefix}/${ae(t)}`,content:t.endsWith(`.ips`)?Z5(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 _Ne(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??j(RJ(),`logs`),s=t.projectDir?w7(t.projectDir,i):null;v(k(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=uNe();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=O7(s,o),{files:d}=t.projectDir?mNe(t.projectDir):{files:[]},{files:f}=t.projectDir?hNe(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let g=[],_=[],{ZipFile:y}=await Promise.resolve().then(()=>e(v4(),1)),b=new y;A7({zipfile:b,files:[...l,...p],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),A7({zipfile:b,files:d,prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),A7({zipfile:b,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),A7({zipfile:b,files:t.bugReportLedgerFiles??[],prefix:TJ,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),A7({zipfile:b,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i});for(let e of t.extraFiles??[])try{let t=S(e.sourcePath),n=`extra/${e.zipName??ae(e.sourcePath)}`;b.addBuffer(t,n),_.push(n);let r=C7(e,n);r!==null&&g.push(r)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&k7({zipfile:b,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:_,redactions:g});let x=new Set(m.map(e=>`diagnostic-reports/${ae(e)}`)),C=_.filter(e=>x.has(e)),w=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:X5(t.diagnosticReports,C.length);b.addBuffer(Buffer.from(`${w}\n`,`utf8`),`state/diagnostic-reports-status.txt`),_.push(`state/diagnostic-reports-status.txt`),k7({zipfile:b,name:e7,content:x7(t.osTerminationEvidence),redact:n,revealDocNames:!0,bundleFiles:_,redactions:g});let T=JSON.stringify(c,null,2);b.addBuffer(Buffer.from(T,`utf8`),`sysinfo.json`),_.push(`sysinfo.json`);let E={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:_,redactions:g,sysinfo:c};b.addBuffer(Buffer.from(JSON.stringify(E,null,2),`utf8`),`MANIFEST.json`);let D=g.reduce((e,t)=>e+t.lineCount,0),O=new Set(p.map(e=>`logs/${ae(e)}`)),ee=_.filter(e=>O.has(e)),te=new Set((t.bugReportLedgerFiles??[]).map(e=>`${TJ}/${ae(e)}`)),ne=_.filter(e=>te.has(e)),re=s?_.filter(e=>e.startsWith(`logs/`)&&!T7(e)&&!O.has(e)):[],ie=C.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.`]:[],oe=ie.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...ie]:[`Redaction was disabled for this bundle; file contents are unmodified.`],A=[`# Bug Report Bundle`,``,`Generated: ${E.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${E.disciplineVersion}`,``,`## Contents`,``,..._.map(e=>`- ${e}`),``,`## Privacy`,``,...re.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:`,...re.map(e=>`- ${e}`),``]:[],...ee.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:`,...ee.map(e=>`- ${e}`),``]:[],...C.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:`,...C.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:`,`- ${e7}`,``]:[],...ne.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:`,...ne.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${zP.join(`, `)}`,D>0?`${D} line(s) were scrubbed across ${g.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...ie,``,`This bundle is safe to attach to a GitHub issue.`]:oe].join(`
|
|
1531
|
-
`);b.addBuffer(Buffer.from(A,`utf8`),`README.md`),b.end();let se=h(r);return b.outputStream.pipe(se),await new Promise((e,t)=>{se.on(`close`,e),se.on(`error`,t)}),i?.info({bundlePath:r,fileCount:_.length,redactionCount:D},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:_,redactions:g,redactedLineCount:D,generatedAt:E.generatedAt}}}function j7(e){return e.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\u200b\ufeff]/gu,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function M7(e){return Te(`sha256`).update(e).digest(`hex`)}function N7(e){return j(RJ(N(e)),`pi-trust`)}function P7(e,t){return j(N7(e),M7(N(t)))}function F7(e,t,n){return j(P7(e,t),`${M7(n)}.json`)}var I7=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${j7(e)} ${j7(t)}; ${j7(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function L7(e,t,n){let r=n.code,i=n instanceof Error?n.message:String(n),a;switch(r){case`EACCES`:case`EPERM`:a=`check receipt and parent-directory permissions, then retry`;break;case`ENOENT`:a=`the location no longer exists; restore access to its expected location, then retry`;break;default:a=`check the path and available storage, then retry`}return new I7(e,`could not ${t}: ${i}`,a,n)}function R7(e){let t;try{t=_(e)}catch(t){if(t.code===`ENOENT`)return!1;throw L7(e,`be inspected`,t)}if(!t.isDirectory())throw new I7(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function z7(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function B7(e,t){if(!dY(e)||!z7(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==N(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==N(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==N(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!dY(e.previous))throw new I7(t,`has invalid contents`,`restore a valid ownership record from a backup without guessing its trust decision, then retry`);let n;if(e.previous.present===!1&&z7(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&z7(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new I7(t,`has an invalid previous decision`,`restore the recorded previous decision from a backup without guessing its value, then retry`);return{version:1,cwd:e.cwd,configuredTrustPath:e.configuredTrustPath,canonicalTrustPath:e.canonicalTrustPath,state:e.state,previous:n}}function V7(e,t,n){let r;try{r=_(n)}catch(e){throw L7(n,`be inspected`,e)}if(!r.isFile())throw new I7(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=S(n,`utf8`)}catch(e){throw L7(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new I7(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=B7(a,n);if(o.cwd!==N(t)||n!==F7(e,t,o.canonicalTrustPath))throw new I7(n,`does not match its project or trust-store location`,`restore the ownership record to its original project and trust-store location, then retry`);return{path:n,record:o}}function H7(e,t){let{record:n,path:r}=t;for(let t of[N7(e),P7(e,n.cwd)])if(!R7(t))throw new I7(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=V7(e,n.cwd,r);if(!Pe(i.record,n))throw new I7(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function vNe(e,t,n,r,i){let a={version:1,cwd:N(t),configuredTrustPath:N(n),canonicalTrustPath:N(r),state:`pending`,previous:i},o=F7(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!Pe(B7(JSON.parse(s),o),a))throw new I7(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);R7(N7(e)),R7(k(o));try{v(k(o),{recursive:!0,mode:448})}catch(e){throw L7(k(o),`be created`,e)}let c;try{c=_(o,{throwIfNoEntry:!1})}catch(e){throw L7(o,`be inspected`,e)}if(c)throw new I7(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{VJ(o,s,{mode:384})}catch(e){throw L7(o,`be written`,e)}return{path:o,record:a}}function yNe(e,t){let n=H7(e,t);if(n.record.state!==`pending`)throw new I7(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{VJ(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw L7(n.path,`be committed`,e)}return{path:n.path,record:r}}function U7(e,t){if(!R7(N7(e)))return[];let n=P7(e,t);if(!R7(n))return[];let r;try{r=w(n).sort()}catch(e){throw L7(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>V7(e,t,j(n,r)))}function W7(e,t){let n=H7(e,t);try{ne(n.path)}catch(e){throw L7(n.path,`be removed after reconciling its grant`,e)}for(let t of[k(n.path),N7(e)])try{ee(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw L7(t,`be removed after reconciling its grant`,e)}}var bNe=i(((e,n)=>{var r=t(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),xNe=i(((e,n)=>{var r=t(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),SNe=i(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),G7=i(((e,n)=>{var r=t(`fs`),i=bNe(),a=xNe(),o=SNe(),s=t(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
|
|
1532
|
-
GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),t(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=T,e.createWriteStream=E;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);x=g.ReadStream,C=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=S);var v=e.WriteStream;v&&(C.prototype=Object.create(v.prototype),C.prototype.open=w),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return C},set:function(e){C=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=C;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function C(e,t){return this instanceof C?(v.apply(this,arguments),this):C.apply(Object.create(C.prototype),arguments)}function w(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function T(t,n){return new e.ReadStream(t,n)}function E(t,n){return new e.WriteStream(t,n)}var D=e.open;e.open=O;function O(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return D(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function m(e){f(`ENQUEUE`,e[0].name,e[1]),r[c].push(e),_()}var h;function g(){for(var e=Date.now(),t=0;t<r[c].length;++t)r[c][t].length>2&&(r[c][t][3]=e,r[c][t][4]=e);_()}function _(){if(clearTimeout(h),h=void 0,r[c].length!==0){var e=r[c].shift(),t=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)f(`RETRY`,t.name,n),t.apply(null,n);else if(Date.now()-a>=6e4){f(`TIMEOUT`,t.name,n);var s=n.pop();typeof s==`function`&&s.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(f(`RETRY`,t.name,n),t.apply(null,n.concat([a]))):r[c].push(e)}h===void 0&&(h=setTimeout(_,0))}}})),CNe=i(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),wNe=i((e=>{var t=CNe();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),TNe=i(((e,t)=>{t.exports=wNe()})),ENe=i(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),DNe=i(((e,n)=>{var r=global.process;let i=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!i(r))n.exports=function(){return function(){}};else{var a=t(`assert`),o=ENe(),s=/^win/i.test(r.platform),c=t(`events`);typeof c!=`function`&&(c=c.EventEmitter);var l;r.__signal_exit_emitter__?l=r.__signal_exit_emitter__:(l=r.__signal_exit_emitter__=new c,l.count=0,l.emitted={}),l.infinite||(l.setMaxListeners(1/0),l.infinite=!0),n.exports=function(e,t){if(!i(global.process))return function(){};a.equal(typeof e,`function`,`a callback must be provided for exit handler`),p===!1&&m();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),l.on(n,e),function(){l.removeListener(n,e),l.listeners(`exit`).length===0&&l.listeners(`afterexit`).length===0&&u()}};var u=function(){!p||!i(global.process)||(p=!1,o.forEach(function(e){try{r.removeListener(e,f[e])}catch{}}),r.emit=_,r.reallyExit=h,--l.count)};n.exports.unload=u;var d=function(e,t,n){l.emitted[e]||(l.emitted[e]=!0,l.emit(e,t,n))},f={};o.forEach(function(e){f[e]=function(){i(global.process)&&r.listeners(e).length===l.count&&(u(),d(`exit`,null,e),d(`afterexit`,null,e),s&&e===`SIGHUP`&&(e=`SIGINT`),r.kill(r.pid,e))}}),n.exports.signals=function(){return o};var p=!1,m=function(){p||!i(global.process)||(p=!0,l.count+=1,o=o.filter(function(e){try{return r.on(e,f[e]),!0}catch{return!1}}),r.emit=v,r.reallyExit=g)};n.exports.load=m;var h=r.reallyExit,g=function(e){i(global.process)&&(r.exitCode=e||0,d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),h.call(r,r.exitCode))},_=r.emit,v=function(e,t){if(e===`exit`&&i(global.process)){t!==void 0&&(r.exitCode=t);var n=_.apply(this,arguments);return d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),n}return _.apply(this,arguments)}}})),ONe=i(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),kNe=i(((e,n)=>{let r=t(`path`),i=G7(),a=TNe(),o=DNe(),s=ONe(),c={};function l(e,t){return t.lockfilePath||`${e}.lock`}function u(e,t,n){if(!t.realpath)return n(null,r.resolve(e));t.fs.realpath(e,n)}function d(e,t,n){let r=l(e,t);t.fs.mkdir(r,i=>{if(!i)return s.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?d(e,{...t,stale:0},n):n(r);if(!f(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));p(e,t,r=>{if(r)return n(r);d(e,{...t,stale:0},n)})})})}function f(e,t){return e.mtime.getTime()<Date.now()-t.stale}function p(e,t,n){t.fs.rmdir(l(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function m(e,t){let n=c[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return h(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let o=s.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,o,o,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));n.mtime=o,n.lastUpdate=Date.now(),n.updateDelay=null,m(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function h(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),c[e]===t&&delete c[e],t.options.onCompromised(n)}function g(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),u(e,t,(e,r)=>{if(e)return n(e);let i=a.operation(t.retries);i.attempt(()=>{d(r,t,(e,a,o)=>{if(i.retry(e))return;if(e)return n(i.mainError());let s=c[r]={lockfilePath:l(r,t),mtime:a,mtimePrecision:o,options:t,lastUpdate:Date.now()};m(r,t),n(null,e=>{if(s.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));_(r,{...t,realpath:!1},e)})})})})}function _(e,t,n){t={fs:i,realpath:!0,...t},u(e,t,(e,r)=>{if(e)return n(e);let i=c[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete c[r],p(r,t,n)})}function v(e,t,n){t={stale:1e4,realpath:!0,fs:i,...t},t.stale=Math.max(t.stale||0,2e3),u(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(l(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!f(r,t)))})}function y(){return c}o(()=>{for(let e in c){let t=c[e].options;try{t.fs.rmdirSync(l(e,t))}catch{}}}),n.exports.lock=g,n.exports.unlock=_,n.exports.check=v,n.exports.getLocks=y})),ANe=i(((e,t)=>{let n=G7();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),K7=e(i(((e,t)=>{let n=kNe(),{toPromise:r,toSync:i,toSyncOptions:a}=ANe();async function o(e,t){let i=await r(n.lock)(e,t);return r(i)}function s(e,t){let r=i(n.lock)(e,a(t));return i(r)}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1);const q7=5e3;function J7(e,t,n){if(!(e instanceof Error)||!(`code`in e)||e.code!==`ELOCKED`)throw e;let r=t-performance.now();if(r<=0)throw Object.assign(Error(`Could not acquire Pi trust lock at ${n}.lock within ${q7}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function Y7(e,t){}function X7(e,t){if(e.length===0)return;if(e.length===1)throw e[0];let[n,r]=e,i=n instanceof Error?n.message:String(n),a=r instanceof Error?r.message:String(r);throw AggregateError(e,`Pi trust update failed: ${i}\nReleasing Pi trust lock ${t}.lock also failed: ${a}`)}async function jNe(e,t,n){await Jye(`${t}.ok.lock`,async()=>{let t=performance.now()+q7,r;for(;;)try{r=await K7.default.lock(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await Ve(J7(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}X7(i,e)},{onWarn:Y7})}function MNe(e,t,n){UJ(`${t}.ok.lock`,()=>{let t=performance.now()+q7,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=K7.default.lockSync(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,J7(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}X7(a,e)},{onWarn:Y7})}const NNe=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var Z7=class extends Error{name=`PiResourceInspectionError`};function Q7(e){let t;try{t=_(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=te(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new Z7(j5(`missing-symlink-target`),{cause:e}):e}return d(e,p.R_OK|(n.isDirectory()?p.X_OK:0)),!0}function PNe(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function FNe(e,t,n){let r=e;try{let i=E(e),a;r=t;try{a=E(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=N(t)}let o=j(a,`.agents`,`skills`),s=[];for(let e of NNe)r=j(i,`.pi`,e),Q7(r)&&s.push(r);if(r=j(i,`.pi`,`extensions`),Q7(r))for(let t of w(r).sort()){let i=j(r,t);N(n)!==j(N(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[j(i,`.pi`,`skills`),j(i,`.agents`,`skills`)])if(e!==o&&(r=e,Q7(e)))for(let t of w(e).sort())PNe(t)||s.push(j(e,t));let c=k(i);for(;c!==i;){r=j(c,`.agents`,`skills`),r!==o&&Q7(r)&&s.push(r);let e=k(c);if(e===c)break;c=e}return s.length===0?{kind:`none`}:{kind:`shared`,paths:s.sort()}}catch(e){return{kind:`unreadable`,error:`Could not inspect Pi project resources at ${j7(r)}: ${e instanceof Z7?e.message:j5(A5(e))}`}}}function $7(e){let t;try{t=_(e).isSymbolicLink()}catch(e){return e.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:A5(e)}}let n=y5(e);if(n.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!te(n.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(e){return{kind:`declined`,reason:t&&e.code===`ENOENT`?`missing-symlink-target`:A5(e)}}return{kind:`ready`,path:n.writePath,symlink:t}}function e9(e,t,n){let r=N(e),i=ZY({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:$Y.pi.projectConfigPath(r),trustPath:j(i,`trust.json`)}}function t9(e){try{let t=E(e);return te(t).isDirectory()?(d(t,p.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${j7(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${j7(e)} could not be resolved or accessed: ${j7(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function n9(e){let t=t9(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${j7(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function r9(e,t,n){let r=q5($Y.pi,e,n,t);if(r.kind===`absent`)return{state:`absent`,text:null};if(r.kind!==`present`)return{state:`unreadable`,text:null};let i=r.entry,a=Array.isArray(i.args)&&typeof i.args[0]==`string`?i.args[0]:null;return MY(i)?{state:`own-current`,text:a}:c5(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function i9(e,t){let n;try{n=S(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:A5(t)}}if(n.trim()===``)return{state:`untrusted`,entries:{},trailingNewline:!1};let r;try{r=JSON.parse(n)}catch{return{state:`unreadable`,reason:`invalid-json`}}return dY(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
|
|
1533
|
-
`)}:{state:`unreadable`,reason:`invalid-json`}}function
|
|
1534
|
-
`:``),f=N5(s.path);VJ(s.path,d,f===void 0?void 0:{mode:f}),l9(n,()=>
|
|
1527
|
+
`);if(n===-1)return null;let r,i;try{r=l7(JSON.parse(t.slice(0,n))),i=l7(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=l7(e);t===null||typeof t.name!=`string`||!$5(t.name)||a.push({name:t.name,pid:c7(t.pid),killReason:typeof t.reason==`string`?t.reason:null,residentPages:c7(t.rpages),lifetimeMaxPages:c7(t.lifetimeMax)})}let o=Q5(r.timestamp);return{kind:`jetsam`,at:o===null?null:new Date(o).toISOString(),file:e,pageSize:c7(l7(i.memoryStatus)?.pageSize),largestProcessOwned:typeof i.largestProcess==`string`?$5(i.largestProcess):null,ownedProcesses:a}}const d7=/^JetsamEvent-.*\.ips$/;function f7(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 UMe(e,t){let n=a7(`darwin`,`macos-jetsam`,[j(e,`JetsamEvent-*.ips`)]),r;try{r=await ke(e)}catch(e){return o7(n,e.code??`unknown`)}let i=f7(await Promise.all(r.filter(e=>d7.test(e)).map(async t=>{try{return{file:t,mtimeMs:(await Me(j(e,t))).mtimeMs}}catch{return{file:t,mtimeMs:null}}})),t.getTime()-t7,50,`newest-first`);n.unparseable+=i.statFailed,n.droppedOverCap=i.droppedOverCap;for(let t of i.files){let r=null;try{r=u7(t,await Oe(j(e,t),`utf8`))}catch{}r===null?n.unparseable+=1:r.ownedProcesses.length===0?n.foreignIgnored+=1:n.events.push(r)}return s7(n)}const WMe=new Set([`vm-pageshortage`,`vm-compressor-thrashing`,`vm-pageout-starvation`,`low-swap`,`sustained-memory-pressure`]);function GMe(e,t=n7){let n;try{n=w(t)}catch(e){return{outcome:`unavailable`,unavailableReason:e.code??`unknown`}}let r=e.fromMs-1e3,i=null,a=n.filter(e=>d7.test(e)).map(e=>{try{return{file:e,mtimeMs:te(j(t,e)).mtimeMs}}catch(t){return i??=t.code??`unknown`,{file:e,mtimeMs:null}}}),o=f7(a,r,5,`oldest-first`),s=0,c=o.statFailed,l=0,u=null;for(let n of o.files){let i;try{i=S(j(t,n),`utf8`)}catch(e){c+=1,u??=e.code??`unknown`;continue}s+=1;let a=u7(n,i);if(a===null){l+=1;continue}let o=a.at===null?null:Date.parse(a.at);if(o!==null&&(o<r||o>e.toMs))continue;let d=a.ownedProcesses.find(t=>t.pid===e.pid&&t.killReason!==null);if(d!==void 0&&d.killReason!==null)return{outcome:`killed`,source:`macos-jetsam`,at:a.at,killReason:d.killReason,victimChosenByPriority:WMe.has(d.killReason),largestProcessOwned:a.largestProcessOwned,residentBytes:d.residentPages===null||a.pageSize===null?null:d.residentPages*a.pageSize,reportsRead:s}}if(i!==null&&o.statFailed===a.length)return{outcome:`unavailable`,unavailableReason:i};if(s===0&&u!==null)return{outcome:`unavailable`,unavailableReason:u};let d=o.droppedOverCap;return c===0&&l===0&&d===0?{outcome:`not-killed`,reportsRead:s,unreadable:0,unparseable:0,skippedNewerOverCap:0}:{outcome:`inconclusive`,reportsRead:s,unreadable:c,unparseable:l,skippedNewerOverCap:d}}const p7=[`--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`],m7=[`--user`,`--no-pager`,`--output=short-iso-precise`,`--since=-7d`,`--grep=Fatal Wayland communication error|Wayland protocol error|X IO error|Missing X server`],h7=/^(\S+) \S+ ([^:\s[]+)(?:\[\d+\])?: (.*)$/,KMe=/\[(\d+)(?::\d+)?:\d{4}\/\d{6}\.\d+:[A-Z0-9]+:[^\]]*\]\s*(.*)$/,qMe=/^desktop\.\d{4}-\d{2}-\d{2}\.log$/;async function JMe(e,t){let n=new Set,r;try{r=await ke(e)}catch{return{pids:n,unreadable:!0}}let i=!1;for(let a of r){if(!qMe.test(a))continue;let r=j(e,a);try{if(t.getTime()-(await Me(r)).mtimeMs>t7)continue;for(let e of(await Oe(r,`utf8`)).split(`
|
|
1528
|
+
`)){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 YMe(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:r7.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 XMe(e){let t=[],n=0,r=0;for(let i of e.split(`
|
|
1529
|
+
`)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=h7.exec(i);if(e===null){r+=1;continue}let[,a=``,o=``,s=``]=e;if(!r7.test(s)){n+=1;continue}let c=YMe(o,s);if(c===null){r+=1;continue}t.push({kind:`journal`,at:a,...c})}return{events:t,foreignIgnored:n,unparseable:r}}function ZMe(e){let t=[],n=0,r=0;for(let i of e.split(`
|
|
1530
|
+
`)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=h7.exec(i);if(e===null){r+=1;continue}let[,a=``,,o=``]=e,s=KMe.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 QMe(e,t,n){let r=ZMe(e);if(r.lines.length===0)return{...r,events:[],unattributed:null};let i=await JMe(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 g7(e){return e.status===0||e.status===1&&/^-- No entries --$/m.test(e.stdout)}async function $Me(e,t,n){let r=a7(`linux`,`linux-journal`,[`journalctl ${p7.join(` `)}`,`journalctl ${m7.join(` `)}`]),[i,a]=await Promise.all([e(`journalctl`,[...p7]),e(`journalctl`,[...m7])]),o=[];if(g7(i)){let e=XMe(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: ${i7(i)}`);if(g7(a)){let e=await QMe(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: ${i7(a)}`);return o.length===2?o7(r,o.join(`; `)):o.length===1?{...r,outcome:`partial`,unavailableReason:o.join(`; `)}:s7(r)}const eNe={41:`Microsoft-Windows-Kernel-Power`,1074:`User32`,2004:`Microsoft-Windows-Resource-Exhaustion-Detector`,6008:`EventLog`},tNe={1e3:`Application Error`,1001:`Windows Error Reporting`,1002:`Application Hang`};function _7(e){return e===`System`?eNe:tNe}function nNe(e){let t=`System[(${Object.keys(_7(e)).map(e=>`EventID=${e}`).join(` or `)}) and TimeCreated[timediff(@SystemTime) <= ${t7}]]`;return e===`System`?`*[${t}]`:`*[${t} and EventData[${BMe.map(e=>`Data='${e}'`).join(` or `)}]]`}function v7(e){return[`qe`,e,`/q:${nNe(e)}`,`/f:xml`,`/rd:true`,`/c:200`]}function rNe(e){return ue.join(e??`C:\\Windows`,`System32`,`wevtutil.exe`)}function iNe(e){return e.replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/&/g,`&`)}function aNe(e){return/[\\/]/.test(e)||/^[a-z]:/i.test(e)}function y7(e,t){let n=RegExp(`<${t}(?:\\s[^>]*)?>([\\s\\S]*?)</${t}>`,`g`);return[...e.matchAll(n)].map(e=>iNe(e[1]??``).trim())}function oNe(e,t){let n=_7(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=y7(o,`Data`),u=y7(o,`Name`),d=[...l,...u].some(e=>r7.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!==``&&!aNe(e)):[]})}return{events:r,foreignIgnored:i,unparseable:a}}async function sNe(e,t){let n=rNe(t),r=[`System`,`Application`],i=a7(`win32`,`windows-event-log`,r.map(e=>`${n} ${v7(e).join(` `)}`)),a=await Promise.all(r.map(async t=>({log:t,result:await e(n,v7(t))}))),o=[];for(let{log:e,result:t}of a){if(t.status!==0){o.push(`${e}: ${i7(t)}`);continue}let n=oNe(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?o7(i,o.join(`; `)):o.length>0?{...i,outcome:`partial`,unavailableReason:o.join(`; `)}:s7(i)}async function b7(e={}){let t=e.platform??process.platform,n=e.runCommand??VMe(),r=(e.now??(()=>new Date))();switch(t){case`darwin`:return UMe(e.macosReportsDir??n7,r);case`linux`:return $Me(n,r,e.desktopLogsDir??j(RJ(),`logs`));case`win32`:return sNe(n,e.systemRoot??process.env.SystemRoot);default:return{...a7(t,null,[]),outcome:`unsupported`}}}const cNe={schemaVersion:1,outcome:`not-collected`};function x7(e){return`${JSON.stringify(e??cNe,null,2)}\n`}const lNe=rt.stable.appId;function S7(){return j(RJ(),`bug-reports`)}function uNe(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=S7(),r=`${t}-bugreport`,i=j(n,`${r}.zip`);for(let e=2;g(i);e+=1)i=j(n,`${r}-${e}.zip`);return i}function C7(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function w7(e,t){let n=j(e,`.ok`,`config.yml`);if(g(n))try{let e=S(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 g(j(e,`.ok`))?Te(`sha256`).update(N(e)).digest(`hex`).slice(0,12):null}function dNe(){let e={timestamp:new Date().toISOString(),platform:ye(),osType:Ce(),osRelease:be(),hostname:`[redacted]`,uptime:we(),freeMem:ge(),totalMem:Se(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=c(`sw_vers -productVersion 2>/dev/null`,c8({encoding:`utf8`})).trim()}catch{}try{let t=j(__dirname,`..`,`..`,`package.json`);g(t)&&(e.okVersion=JSON.parse(S(t,`utf8`)).version)}catch{}return e}const fNe=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function T7(e){let t=ae(e);return fNe.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function pNe(e,t){return O7(e,t).files}const mNe=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function E7(e,t=lNe){let n=j(e,`${t}.ShipIt`);if(!g(n))return[];let r;try{r=w(n)}catch{return[]}return mNe.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=>j(n,e.entry)))}function D7(e){if(!g(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,-10):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=>j(e,t))}catch{return[]}}function O7(e,t){if(!g(t))return{files:[],excludedByProjectSlug:0};let n=w(t).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>j(t,e));if(!e)return{files:n,excludedByProjectSlug:0};let r=n.filter(T7),i=[],a=r.filter(t=>{try{return S(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=>!T7(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function hNe(e){let t=j(e,`.ok`,`local`);return g(t)?{files:[`server.lock`,`last-spawn-error.log`,sd,ad].map(e=>j(t,e)).filter(e=>g(e))}:{files:[]}}function gNe(e){let t=j(e,`.ok`,`local`,`logs`);return g(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>j(t,e)).filter(e=>g(e))}:{files:[]}}function _Ne(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#${Te(`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 k7(e){let t=e.revealDocNames?e.content:_Ne(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=BP(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 A7(e){for(let t of e.files)try{let n=S(t,`utf8`);k7({zipfile:e.zipfile,name:`${e.prefix}/${ae(t)}`,content:t.endsWith(`.ips`)?Z5(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 vNe(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??j(RJ(),`logs`),s=t.projectDir?w7(t.projectDir,i):null;v(k(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=dNe();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=O7(s,o),{files:d}=t.projectDir?hNe(t.projectDir):{files:[]},{files:f}=t.projectDir?gNe(t.projectDir):{files:[]},p=t.shipItLogFiles??[],m=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length,localSinkFileCount:f.length,shipItLogFileCount:p.length,diagnosticReportCount:m.length},`files collected`);let g=[],_=[],{ZipFile:y}=await Promise.resolve().then(()=>e(v4(),1)),b=new y;A7({zipfile:b,files:[...l,...p],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),A7({zipfile:b,files:d,prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),A7({zipfile:b,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),A7({zipfile:b,files:t.bugReportLedgerFiles??[],prefix:TJ,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i}),A7({zipfile:b,files:m,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:_,redactions:g,logger:i});for(let e of t.extraFiles??[])try{let t=S(e.sourcePath),n=`extra/${e.zipName??ae(e.sourcePath)}`;b.addBuffer(t,n),_.push(n);let r=C7(e,n);r!==null&&g.push(r)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&k7({zipfile:b,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:_,redactions:g});let x=new Set(m.map(e=>`diagnostic-reports/${ae(e)}`)),C=_.filter(e=>x.has(e)),w=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:X5(t.diagnosticReports,C.length);b.addBuffer(Buffer.from(`${w}\n`,`utf8`),`state/diagnostic-reports-status.txt`),_.push(`state/diagnostic-reports-status.txt`),k7({zipfile:b,name:e7,content:x7(t.osTerminationEvidence),redact:n,revealDocNames:!0,bundleFiles:_,redactions:g});let T=JSON.stringify(c,null,2);b.addBuffer(Buffer.from(T,`utf8`),`sysinfo.json`),_.push(`sysinfo.json`);let E={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:_,redactions:g,sysinfo:c};b.addBuffer(Buffer.from(JSON.stringify(E,null,2),`utf8`),`MANIFEST.json`);let D=g.reduce((e,t)=>e+t.lineCount,0),O=new Set(p.map(e=>`logs/${ae(e)}`)),ee=_.filter(e=>O.has(e)),te=new Set((t.bugReportLedgerFiles??[]).map(e=>`${TJ}/${ae(e)}`)),ne=_.filter(e=>te.has(e)),re=s?_.filter(e=>e.startsWith(`logs/`)&&!T7(e)&&!O.has(e)):[],ie=C.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.`]:[],oe=ie.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...ie]:[`Redaction was disabled for this bundle; file contents are unmodified.`],A=[`# Bug Report Bundle`,``,`Generated: ${E.generatedAt}`,`Project: ${s??`(unscoped)`}`,`Discipline version: ${E.disciplineVersion}`,``,`## Contents`,``,..._.map(e=>`- ${e}`),``,`## Privacy`,``,...re.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:`,...re.map(e=>`- ${e}`),``]:[],...ee.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:`,...ee.map(e=>`- ${e}`),``]:[],...C.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:`,...C.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:`,`- ${e7}`,``]:[],...ne.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:`,...ne.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${zP.join(`, `)}`,D>0?`${D} line(s) were scrubbed across ${g.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...ie,``,`This bundle is safe to attach to a GitHub issue.`]:oe].join(`
|
|
1531
|
+
`);b.addBuffer(Buffer.from(A,`utf8`),`README.md`),b.end();let se=h(r);return b.outputStream.pipe(se),await new Promise((e,t)=>{se.on(`close`,e),se.on(`error`,t)}),i?.info({bundlePath:r,fileCount:_.length,redactionCount:D},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:_,redactions:g,redactedLineCount:D,generatedAt:E.generatedAt}}}function j7(e){return e.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\u200b\ufeff]/gu,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function M7(e){return Te(`sha256`).update(e).digest(`hex`)}function N7(e){return j(RJ(N(e)),`pi-trust`)}function P7(e,t){return j(N7(e),M7(N(t)))}function F7(e,t,n){return j(P7(e,t),`${M7(n)}.json`)}var I7=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${j7(e)} ${j7(t)}; ${j7(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function L7(e,t,n){let r=n.code,i=n instanceof Error?n.message:String(n),a;switch(r){case`EACCES`:case`EPERM`:a=`check receipt and parent-directory permissions, then retry`;break;case`ENOENT`:a=`the location no longer exists; restore access to its expected location, then retry`;break;default:a=`check the path and available storage, then retry`}return new I7(e,`could not ${t}: ${i}`,a,n)}function R7(e){let t;try{t=_(e)}catch(t){if(t.code===`ENOENT`)return!1;throw L7(e,`be inspected`,t)}if(!t.isDirectory())throw new I7(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function z7(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function B7(e,t){if(!dY(e)||!z7(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==N(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==N(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==N(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!dY(e.previous))throw new I7(t,`has invalid contents`,`restore a valid ownership record from a backup without guessing its trust decision, then retry`);let n;if(e.previous.present===!1&&z7(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&z7(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new I7(t,`has an invalid previous decision`,`restore the recorded previous decision from a backup without guessing its value, then retry`);return{version:1,cwd:e.cwd,configuredTrustPath:e.configuredTrustPath,canonicalTrustPath:e.canonicalTrustPath,state:e.state,previous:n}}function V7(e,t,n){let r;try{r=_(n)}catch(e){throw L7(n,`be inspected`,e)}if(!r.isFile())throw new I7(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=S(n,`utf8`)}catch(e){throw L7(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new I7(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=B7(a,n);if(o.cwd!==N(t)||n!==F7(e,t,o.canonicalTrustPath))throw new I7(n,`does not match its project or trust-store location`,`restore the ownership record to its original project and trust-store location, then retry`);return{path:n,record:o}}function H7(e,t){let{record:n,path:r}=t;for(let t of[N7(e),P7(e,n.cwd)])if(!R7(t))throw new I7(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=V7(e,n.cwd,r);if(!Pe(i.record,n))throw new I7(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function yNe(e,t,n,r,i){let a={version:1,cwd:N(t),configuredTrustPath:N(n),canonicalTrustPath:N(r),state:`pending`,previous:i},o=F7(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!Pe(B7(JSON.parse(s),o),a))throw new I7(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);R7(N7(e)),R7(k(o));try{v(k(o),{recursive:!0,mode:448})}catch(e){throw L7(k(o),`be created`,e)}let c;try{c=_(o,{throwIfNoEntry:!1})}catch(e){throw L7(o,`be inspected`,e)}if(c)throw new I7(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{VJ(o,s,{mode:384})}catch(e){throw L7(o,`be written`,e)}return{path:o,record:a}}function bNe(e,t){let n=H7(e,t);if(n.record.state!==`pending`)throw new I7(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{VJ(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw L7(n.path,`be committed`,e)}return{path:n.path,record:r}}function U7(e,t){if(!R7(N7(e)))return[];let n=P7(e,t);if(!R7(n))return[];let r;try{r=w(n).sort()}catch(e){throw L7(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>V7(e,t,j(n,r)))}function W7(e,t){let n=H7(e,t);try{ne(n.path)}catch(e){throw L7(n.path,`be removed after reconciling its grant`,e)}for(let t of[k(n.path),N7(e)])try{ee(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw L7(t,`be removed after reconciling its grant`,e)}}var xNe=i(((e,n)=>{var r=t(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!e||e.code===`ENOSYS`||(!process.getuid||process.getuid()!==0)&&(e.code===`EINVAL`||e.code===`EPERM`)}}})),SNe=i(((e,n)=>{var r=t(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),CNe=i(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),G7=i(((e,n)=>{var r=t(`fs`),i=xNe(),a=SNe(),o=CNe(),s=t(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
|
|
1532
|
+
GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),t(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=T,e.createWriteStream=E;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);x=g.ReadStream,C=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=S);var v=e.WriteStream;v&&(C.prototype=Object.create(v.prototype),C.prototype.open=w),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return C},set:function(e){C=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=C;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function C(e,t){return this instanceof C?(v.apply(this,arguments),this):C.apply(Object.create(C.prototype),arguments)}function w(){var e=this;O(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function T(t,n){return new e.ReadStream(t,n)}function E(t,n){return new e.WriteStream(t,n)}var D=e.open;e.open=O;function O(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return D(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function m(e){f(`ENQUEUE`,e[0].name,e[1]),r[c].push(e),_()}var h;function g(){for(var e=Date.now(),t=0;t<r[c].length;++t)r[c][t].length>2&&(r[c][t][3]=e,r[c][t][4]=e);_()}function _(){if(clearTimeout(h),h=void 0,r[c].length!==0){var e=r[c].shift(),t=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)f(`RETRY`,t.name,n),t.apply(null,n);else if(Date.now()-a>=6e4){f(`TIMEOUT`,t.name,n);var s=n.pop();typeof s==`function`&&s.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(f(`RETRY`,t.name,n),t.apply(null,n.concat([a]))):r[c].push(e)}h===void 0&&(h=setTimeout(_,0))}}})),wNe=i(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),TNe=i((e=>{var t=wNe();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),ENe=i(((e,t)=>{t.exports=TNe()})),DNe=i(((e,t)=>{t.exports=[`SIGABRT`,`SIGALRM`,`SIGHUP`,`SIGINT`,`SIGTERM`],process.platform!==`win32`&&t.exports.push(`SIGVTALRM`,`SIGXCPU`,`SIGXFSZ`,`SIGUSR2`,`SIGTRAP`,`SIGSYS`,`SIGQUIT`,`SIGIOT`),process.platform===`linux`&&t.exports.push(`SIGIO`,`SIGPOLL`,`SIGPWR`,`SIGSTKFLT`,`SIGUNUSED`)})),ONe=i(((e,n)=>{var r=global.process;let i=function(e){return e&&typeof e==`object`&&typeof e.removeListener==`function`&&typeof e.emit==`function`&&typeof e.reallyExit==`function`&&typeof e.listeners==`function`&&typeof e.kill==`function`&&typeof e.pid==`number`&&typeof e.on==`function`};if(!i(r))n.exports=function(){return function(){}};else{var a=t(`assert`),o=DNe(),s=/^win/i.test(r.platform),c=t(`events`);typeof c!=`function`&&(c=c.EventEmitter);var l;r.__signal_exit_emitter__?l=r.__signal_exit_emitter__:(l=r.__signal_exit_emitter__=new c,l.count=0,l.emitted={}),l.infinite||(l.setMaxListeners(1/0),l.infinite=!0),n.exports=function(e,t){if(!i(global.process))return function(){};a.equal(typeof e,`function`,`a callback must be provided for exit handler`),p===!1&&m();var n=`exit`;return t&&t.alwaysLast&&(n=`afterexit`),l.on(n,e),function(){l.removeListener(n,e),l.listeners(`exit`).length===0&&l.listeners(`afterexit`).length===0&&u()}};var u=function(){!p||!i(global.process)||(p=!1,o.forEach(function(e){try{r.removeListener(e,f[e])}catch{}}),r.emit=_,r.reallyExit=h,--l.count)};n.exports.unload=u;var d=function(e,t,n){l.emitted[e]||(l.emitted[e]=!0,l.emit(e,t,n))},f={};o.forEach(function(e){f[e]=function(){i(global.process)&&r.listeners(e).length===l.count&&(u(),d(`exit`,null,e),d(`afterexit`,null,e),s&&e===`SIGHUP`&&(e=`SIGINT`),r.kill(r.pid,e))}}),n.exports.signals=function(){return o};var p=!1,m=function(){p||!i(global.process)||(p=!0,l.count+=1,o=o.filter(function(e){try{return r.on(e,f[e]),!0}catch{return!1}}),r.emit=v,r.reallyExit=g)};n.exports.load=m;var h=r.reallyExit,g=function(e){i(global.process)&&(r.exitCode=e||0,d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),h.call(r,r.exitCode))},_=r.emit,v=function(e,t){if(e===`exit`&&i(global.process)){t!==void 0&&(r.exitCode=t);var n=_.apply(this,arguments);return d(`exit`,r.exitCode,null),d(`afterexit`,r.exitCode,null),n}return _.apply(this,arguments)}}})),kNe=i(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),ANe=i(((e,n)=>{let r=t(`path`),i=G7(),a=ENe(),o=ONe(),s=kNe(),c={};function l(e,t){return t.lockfilePath||`${e}.lock`}function u(e,t,n){if(!t.realpath)return n(null,r.resolve(e));t.fs.realpath(e,n)}function d(e,t,n){let r=l(e,t);t.fs.mkdir(r,i=>{if(!i)return s.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?d(e,{...t,stale:0},n):n(r);if(!f(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));p(e,t,r=>{if(r)return n(r);d(e,{...t,stale:0},n)})})})}function f(e,t){return e.mtime.getTime()<Date.now()-t.stale}function p(e,t,n){t.fs.rmdir(l(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function m(e,t){let n=c[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return h(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let o=s.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,o,o,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));n.mtime=o,n.lastUpdate=Date.now(),n.updateDelay=null,m(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function h(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),c[e]===t&&delete c[e],t.options.onCompromised(n)}function g(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),u(e,t,(e,r)=>{if(e)return n(e);let i=a.operation(t.retries);i.attempt(()=>{d(r,t,(e,a,o)=>{if(i.retry(e))return;if(e)return n(i.mainError());let s=c[r]={lockfilePath:l(r,t),mtime:a,mtimePrecision:o,options:t,lastUpdate:Date.now()};m(r,t),n(null,e=>{if(s.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));_(r,{...t,realpath:!1},e)})})})})}function _(e,t,n){t={fs:i,realpath:!0,...t},u(e,t,(e,r)=>{if(e)return n(e);let i=c[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete c[r],p(r,t,n)})}function v(e,t,n){t={stale:1e4,realpath:!0,fs:i,...t},t.stale=Math.max(t.stale||0,2e3),u(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(l(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!f(r,t)))})}function y(){return c}o(()=>{for(let e in c){let t=c[e].options;try{t.fs.rmdirSync(l(e,t))}catch{}}}),n.exports.lock=g,n.exports.unlock=_,n.exports.check=v,n.exports.getLocks=y})),jNe=i(((e,t)=>{let n=G7();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),K7=e(i(((e,t)=>{let n=ANe(),{toPromise:r,toSync:i,toSyncOptions:a}=jNe();async function o(e,t){let i=await r(n.lock)(e,t);return r(i)}function s(e,t){let r=i(n.lock)(e,a(t));return i(r)}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))(),1);const q7=5e3;function J7(e,t,n){if(!(e instanceof Error)||!(`code`in e)||e.code!==`ELOCKED`)throw e;let r=t-performance.now();if(r<=0)throw Object.assign(Error(`Could not acquire Pi trust lock at ${n}.lock within ${q7}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function Y7(e,t){}function X7(e,t){if(e.length===0)return;if(e.length===1)throw e[0];let[n,r]=e,i=n instanceof Error?n.message:String(n),a=r instanceof Error?r.message:String(r);throw AggregateError(e,`Pi trust update failed: ${i}\nReleasing Pi trust lock ${t}.lock also failed: ${a}`)}async function MNe(e,t,n){await Jye(`${t}.ok.lock`,async()=>{let t=performance.now()+q7,r;for(;;)try{r=await K7.default.lock(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await Ve(J7(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}X7(i,e)},{onWarn:Y7})}function NNe(e,t,n){UJ(`${t}.ok.lock`,()=>{let t=performance.now()+q7,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=K7.default.lockSync(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,J7(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}X7(a,e)},{onWarn:Y7})}const PNe=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var Z7=class extends Error{name=`PiResourceInspectionError`};function Q7(e){let t;try{t=_(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=te(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new Z7(j5(`missing-symlink-target`),{cause:e}):e}return d(e,p.R_OK|(n.isDirectory()?p.X_OK:0)),!0}function FNe(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function INe(e,t,n){let r=e;try{let i=E(e),a;r=t;try{a=E(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=N(t)}let o=j(a,`.agents`,`skills`),s=[];for(let e of PNe)r=j(i,`.pi`,e),Q7(r)&&s.push(r);if(r=j(i,`.pi`,`extensions`),Q7(r))for(let t of w(r).sort()){let i=j(r,t);N(n)!==j(N(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[j(i,`.pi`,`skills`),j(i,`.agents`,`skills`)])if(e!==o&&(r=e,Q7(e)))for(let t of w(e).sort())FNe(t)||s.push(j(e,t));let c=k(i);for(;c!==i;){r=j(c,`.agents`,`skills`),r!==o&&Q7(r)&&s.push(r);let e=k(c);if(e===c)break;c=e}return s.length===0?{kind:`none`}:{kind:`shared`,paths:s.sort()}}catch(e){return{kind:`unreadable`,error:`Could not inspect Pi project resources at ${j7(r)}: ${e instanceof Z7?e.message:j5(A5(e))}`}}}function $7(e){let t;try{t=_(e).isSymbolicLink()}catch(e){return e.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:A5(e)}}let n=y5(e);if(n.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!te(n.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(e){return{kind:`declined`,reason:t&&e.code===`ENOENT`?`missing-symlink-target`:A5(e)}}return{kind:`ready`,path:n.writePath,symlink:t}}function e9(e,t,n){let r=N(e),i=ZY({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:$Y.pi.projectConfigPath(r),trustPath:j(i,`trust.json`)}}function t9(e){try{let t=E(e);return te(t).isDirectory()?(d(t,p.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${j7(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${j7(e)} could not be resolved or accessed: ${j7(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function n9(e){let t=t9(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${j7(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function r9(e,t,n){let r=q5($Y.pi,e,n,t);if(r.kind===`absent`)return{state:`absent`,text:null};if(r.kind!==`present`)return{state:`unreadable`,text:null};let i=r.entry,a=Array.isArray(i.args)&&typeof i.args[0]==`string`?i.args[0]:null;return MY(i)?{state:`own-current`,text:a}:c5(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function i9(e,t){let n;try{n=S(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:A5(t)}}if(n.trim()===``)return{state:`untrusted`,entries:{},trailingNewline:!1};let r;try{r=JSON.parse(n)}catch{return{state:`unreadable`,reason:`invalid-json`}}return dY(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
|
|
1533
|
+
`)}:{state:`unreadable`,reason:`invalid-json`}}function LNe(e){switch(e){case`invalid-json`:return`the file is not a valid JSON object; repair its JSON, then retry`;case`path-changed`:return`the path changed while waiting for its lock; retry to check its current state`;case`unavailable-root`:return`the filesystem root is unavailable; reconnect the drive or network share, then retry`;default:return j5(e)}}function a9(e,t){return{kind:`refused`,error:`trust store ${j7(e)}: ${LNe(t)}`}}function o9(e){let t=$7(e);try{switch(t.kind){case`declined`:return a9(e,t.reason);case`ready`:return{kind:`ready`,path:E(t.path)};case`not-present`:break;default:throw Error(`unhandled trust file resolution: ${t}`)}let n=k(e),r=[ae(e)],i=_(n,{throwIfNoEntry:!1});for(;!i;){let t=k(n);if(t===n)return a9(e,`unavailable-root`);r.unshift(ae(n)),n=t,i=_(n,{throwIfNoEntry:!1})}try{return{kind:`missing`,path:j(E(n),...r)}}catch(t){return a9(e,i.isSymbolicLink()&&t.code===`ENOENT`?`missing-symlink-target`:A5(t))}}catch(t){return a9(e,A5(t))}}function s9(e,t){let n=o9(e);return n.kind===`refused`?n:n.path!==t.path||t.kind===`ready`&&n.kind===`missing`?a9(e,`path-changed`):n}function RNe(e,t,n){let r=e9(e,t,n),i=t9(r.cwd);if(i.kind===`refused`)return{...r,project:`unavailable`,error:i.error};let a=r9(r.cwd,r.bridgePath,t).state,o=o9(r.trustPath),s=o.kind===`refused`?`unreadable`:o.kind===`missing`?`untrusted`:i9(o,i.project.canonical).state;return{...r,project:`ready`,canonicalCwd:i.project.canonical,bridge:a,trust:s,bridgeLoadable:(a===`own-current`||a===`own-stale`)&&s===`trusted`,otherExtensions:zNe(r.bridgePath).displayNames}}function zNe(e){let t=k(e),n=ae(e);try{return{displayNames:w(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort().map(e=>j7(JSON.stringify(e)))}}catch{return{displayNames:[]}}}async function BNe(e,t={mode:`published`},n,r,i){let a=e9(e,n,r),o=t9(a.cwd);if(o.kind===`refused`)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:o.error};if(i!==void 0&&o.project.canonical!==i)return{...a,ok:!1,bridge:`refused-project-path`,trust:`skipped`,error:`The approved Pi project directory ${j7(i)} no longer matches the current directory ${j7(o.project.canonical)}. Reopen the intended project and approve the Pi integration again; no bridge or trust settings were changed.`};let s=r9(a.cwd,a.bridgePath,n);if(s.state===`foreign`)return{...a,ok:!1,bridge:`refused-foreign`,trust:`skipped`};if(s.state===`unreadable`)return{...a,ok:!1,bridge:`refused-unreadable`,trust:`skipped`};let c;if(s.state===`absent`)c=`written`;else{let e;try{e=l5(t)}catch{e=void 0}c=e!==void 0&&s.text===e?`unchanged`:`refreshed`}if(c!==`unchanged`){let e=W5($Y.pi,a.cwd,t,n,a.bridgePath);if(e.action!==`written`&&e.action!==`overwritten`)return{...a,ok:!1,bridge:`failed`,trust:`skipped`,error:e.error===void 0?`bridge write ${e.action}`:j7(e.error)}}let l=await VNe(a.trustPath,o.project,n??_e());return{...a,ok:l.action===`already-trusted`||l.action===`added`,bridge:c,trust:l.action,...l.error===void 0?{}:{error:l.error}}}async function VNe(e,t,n){let r=t.canonical,i=o9(e);if(i.kind===`refused`)return{action:`refused-unreadable`,error:i.error};try{v(k(i.path),{recursive:!0})}catch(e){return{action:`failed`,error:j7(e instanceof Error?e.message:String(e))}}let a={action:`added`};try{await MNe(e,i.path,()=>{let o=n9(t);if(o){a.action=`refused-unreadable`,a.error=o;return}let s=s9(e,i);if(s.kind===`refused`){a.action=`refused-unreadable`,a.error=s.error;return}let c=i9(s,r);if(c.state===`trusted`){a.action=`already-trusted`;return}if(c.state===`unreadable`){a.action=`refused-unreadable`,a.error=a9(e,c.reason).error;return}let l=l9(n,()=>{let t=U7(n,r).find(e=>e.record.canonicalTrustPath===s.path);return t&&W7(n,t),yNe(n,r,e,s.path,Object.hasOwn(c.entries,r)?{present:!0,value:c.entries[r]}:{present:!1})}),u={...c.entries,[r]:!0},d=JSON.stringify(u,null,2)+(c.trailingNewline?`
|
|
1534
|
+
`:``),f=N5(s.path);VJ(s.path,d,f===void 0?void 0:{mode:f}),l9(n,()=>bNe(n,l)),a.action=`added`})}catch(e){return{action:`failed`,error:j7(e instanceof Error?e.message:String(e))}}return a}function HNe(e){let t=[],n=e;try{for(;;){if(_(n,{throwIfNoEntry:!1})){if(t.length===0)return;let e=E(n);return te(e).isDirectory()?(d(e,p.X_OK),j(e,...t)):void 0}let e=k(n);if(e===n)return;t.unshift(ae(n)),n=e}}catch{return}}function c9(e){let t={"not-present":0,removed:1,"kept-unowned":2,"kept-shared":3,"kept-unverified":4,"refused-unreadable":5,failed:6},n=e.reduce((e,n)=>t[n.action]>t[e.action]?n:e,{action:`not-present`}),r=e.flatMap(e=>e.error??[]),i=e.flatMap(e=>e.detail??[]);return r.length>0?{action:n.error===void 0?`failed`:n.action,error:[...r,...i].join(`
|
|
1535
1535
|
`)}:n.detail===void 0?n:{...n,detail:i.join(`
|
|
1536
|
-
`)}}function
|
|
1537
|
-
`)}}let u=
|
|
1538
|
-
`:``),p=N5(r);VJ(r,f,p===void 0?void 0:{mode:p}),i.entries=d,l9(t,()=>W7(t,l)),s.result={action:`removed`}}function
|
|
1536
|
+
`)}}function UNe(e,t,n,r={}){let i=e9(e,t,n),a=t??_e(),o=t9(i.cwd),s=o.kind===`refused`&&r.recordedOnly?HNe(i.cwd):void 0,c=o.kind===`ready`?o.project.canonical:s,l;try{l=l9(a,()=>{let e=U7(a,i.cwd);return c===void 0||c===i.cwd?e:[...U7(a,c),...e]})}catch(e){return{action:`failed`,error:j7(e instanceof Error?e.message:String(e))}}if(l.length===0&&r.recordedOnly)return o.kind===`ready`||s!==void 0?{action:`not-present`}:{action:`kept-unverified`,error:`${o.error}. OpenKnowledge could not verify whether this path refers to a project with recorded Pi trust; cleanup was left pending. Retry once the project path can be resolved to check again.`};if(o.kind===`refused`){if(l.length===0)return{action:`kept-unverified`,error:o.error};let e=l.map(({path:e,record:t})=>`key ${j7(JSON.stringify(t.cwd))}; configured store ${j7(JSON.stringify(t.configuredTrustPath))}; recorded destination ${j7(JSON.stringify(t.canonicalTrustPath))}; ownership record ${j7(JSON.stringify(e))} (${t.state})`);return{action:`kept-unverified`,error:[`${o.error}. OpenKnowledge kept these Pi trust ownership records; current trust decisions were not checked:`,...e,`To review manually, close Pi, verify the intended store against its recorded destination, and inspect only the exact key. A pending record does not prove setup completed or ownership of a current grant. If you choose to undo a current true decision, restore the recorded previous value, or remove that key only when no previous entry was recorded. Preserve other current decisions; parent-folder and global trust settings still apply.`].join(`
|
|
1537
|
+
`)}}let u=INe(o.project.canonical,a,$Y.pi.projectConfigPath(o.project.canonical));if(u.kind===`unreadable`)return{action:`kept-unverified`,error:u.error};let d=u.kind===`shared`?u.paths:[],f=[],p=new Map,m=(e,t)=>{let n=p.get(e);if(!n){let t=o9(e);if(t.kind===`refused`){f.push({action:`refused-unreadable`,error:t.error});return}n={trustPath:e,resolved:t,keys:new Map},p.set(e,n)}if(t){if(n.resolved.path!==t.record.canonicalTrustPath){f.push({action:`refused-unreadable`,error:`Pi trust store ${j7(e)} no longer points to its recorded destination ${j7(t.record.canonicalTrustPath)}; restore the intended file location or symlink, then retry`});return}n.keys.set(t.record.cwd,{cwd:t.record.cwd,mode:`recorded`,receipt:t})}};for(let e of l)m(e.record.configuredTrustPath,e);m(i.trustPath);for(let e of p.values()){for(let t of[o.project.canonical,i.cwd])e.keys.has(t)||e.keys.set(t,{cwd:t,mode:`inspect`,receipt:l.find(n=>n.record.cwd===t&&n.record.canonicalTrustPath===e.resolved.path)});f.push(WNe(e,a,d,o.project))}return c9(f)}function l9(e,t){try{return t()}catch(t){throw t instanceof I7?t:Error(`Could not access OpenKnowledge's Pi trust ownership records at ${j7(j(RJ(e),`pi-trust`))}: ${j7(t instanceof Error?t.message:String(t))}. Check the records and their permissions, then retry.`,{cause:t})}}function WNe(e,t,n,r){let{trustPath:i,resolved:a}=e,o=[...e.keys.values()];if(!o.some(e=>e.mode===`recorded`)&&a.kind===`missing`)return{action:`not-present`};if(a.kind===`missing`)try{_(k(a.path))}catch(e){return{action:`failed`,error:`The recorded Pi trust directory ${j7(k(a.path))} is unavailable: ${j7(e instanceof Error?e.message:String(e))}. Restore access to its parent directory or mounted drive, then retry; the ownership record was kept.`}}let s=[],c={result:{action:`not-present`}};try{NNe(i,a.path,()=>{let e=n9(r);if(e){c.result={action:`kept-unverified`,error:e};return}let l=s9(i,a);if(l.kind===`refused`){c.result={action:`refused-unreadable`,error:l.error};return}let u=i9(l,r.canonical);if(u.state===`unreadable`){c.result={action:`refused-unreadable`,error:a9(i,u.reason).error};return}let d=o.map(e=>({cwd:e.cwd,mode:e.mode,expectedConfiguredPath:e.receipt?.record.configuredTrustPath,receipt:l9(t,()=>U7(t,e.cwd).find(e=>e.record.canonicalTrustPath===l.path))}));if(d.some(e=>e.receipt&&e.receipt.record.configuredTrustPath!==e.expectedConfiguredPath)){c.result={action:`failed`,error:`The Pi trust ownership record changed during cleanup; retry to read its current location.`};return}for(let e of d){try{GNe(e,t,i,l.path,u,n,r,c)}catch(t){let n=j7(t instanceof Error?t.message:String(t)),r=t instanceof I7?``:`; retry to check its current state.`;s.push({action:`failed`,error:`Pi trust entry ${j7(JSON.stringify(e.cwd))} in ${j7(i)} could not be reconciled: ${n}${r}`})}s.push(c.result),c.result={action:`not-present`}}})}catch(e){s.push({action:`failed`,error:j7(e instanceof Error?e.message:String(e))})}return c9([...s,c.result])}function GNe(e,t,n,r,i,a,o,s){let{cwd:c,receipt:l}=e;if(i.entries[c]!==!0){l&&e.mode===`recorded`&&l9(t,()=>W7(t,l)),s.result={action:`not-present`};return}let u=`To remove this grant manually, close Pi and remove only the ${j7(JSON.stringify(c))} entry from ${j7(n)}; parent-folder and global trust settings still apply.`;if(a.length>0&&c===o.canonical){let n=`kept Pi's folder trust because other resources still need it: ${a.slice(0,3).map(e=>j7(JSON.stringify(e))).join(`, `)}${a.length>3?` (+${a.length-3} more)`:``}. ${u} Removing this grant may stop Pi from loading those resources, including any not listed here.`;s.result={action:`kept-shared`,detail:n},l&&e.mode===`recorded`&&l9(t,()=>W7(t,l)),s.result={action:`kept-shared`,detail:`${n} ${l?e.mode===`recorded`?`OpenKnowledge has relinquished this grant and will not revoke it on later cleanup runs.`:`OpenKnowledge kept the existing ownership record; cleanup of its recorded location remains incomplete.`:`OpenKnowledge has no ownership record for this grant and will not revoke it on later cleanup runs.`}`};return}if(e.mode===`inspect`||!l||l.record.state===`pending`){let e=l?l.record.state===`pending`?`its ownership record is pending after an interrupted setup; completion cannot be verified. Re-running setup or cleanup does not reconcile this record while the folder remains trusted.`:`OpenKnowledge must reconcile its recorded location at ${j7(l.record.configuredTrustPath)} before removing it.`:`no OpenKnowledge ownership record exists; this includes every grant made before ownership recording was introduced.`;s.result={action:`kept-unowned`,detail:`${c===o.canonical?`kept Pi's folder trust because ${e}`:`kept a Pi trust entry under a non-canonical project path because ${e} Pi uses the real project directory instead of this key.`} ${u}`};return}let d={...i.entries};l.record.previous.present?d[c]=l.record.previous.value:delete d[c];let f=JSON.stringify(d,null,2)+(i.trailingNewline?`
|
|
1538
|
+
`:``),p=N5(r);VJ(r,f,p===void 0?void 0:{mode:p}),i.entries=d,l9(t,()=>W7(t,l)),s.result={action:`removed`}}function KNe(e){return MY(e)||FY(e)||c5(e)}const u9=10485760;function d9(e,t,n,r=!1){let i=UNe(e,t,n,{recordedOnly:r});switch(i.action){case`removed`:case`not-present`:return{trust:i.action};case`kept-shared`:case`kept-unowned`:return{trust:i.action,trustDetail:i.detail};case`failed`:case`refused-unreadable`:case`kept-unverified`:{let e=r?`Trust cleanup remains incomplete`:`The bridge file was left untouched`;throw Error(`Pi trust cleanup failed (${i.action}):\n${i.error}\n${e} so cleanup can be retried.`)}default:throw Error(`unhandled Pi trust cleanup result: ${i}`)}}function f9(e,t,n,r){if(e.id!==`pi`)return{kind:`not-present`};let i=d9(t,n,r,!0);return i.trust===`not-present`?{kind:`not-present`}:{kind:`removed`,...i}}function qNe(e,t,n,r,i){let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=$7(a);if(o.kind===`not-present`)return f9(e,t,n,i);if(o.kind===`declined`)return o;let s=q5(e,t,n,o.path);if(s.kind===`absent`||s.kind===`no-entry`)return f9(e,t,n,i);if(s.kind===`decline`)return{kind:`declined`,reason:s.reason};if(!KNe(s.entry))return{kind:`left-foreign`};let c=e.serverName(t);if(e.format===`file`){let e=d9(t,n,i);try{O(a,{force:!0})}catch(t){throw e.trustDetail?Error(`${t instanceof Error?t.message:String(t)}\n${e.trustDetail}`,{cause:t}):t}return{kind:`removed`,...e}}return e.format===`toml`?XNe(o.path,c):e.format===`yaml`?YNe(o.path,e.topLevelKey,c):JNe(o.path,e.topLevelKey,e.serverMapSubKey,c)}function JNe(e,t,n,r){let i;try{i=S(e,`utf-8`)}catch(e){return{kind:`declined`,reason:A5(e)}}if(Buffer.byteLength(i,`utf-8`)>u9)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=mMe(i,z5(t,n,r));return o?(VJ(e,a,{mode:N5(e)}),{kind:`removed`}):{kind:`not-present`}}function YNe(e,t,n){let r;try{r=S(e,`utf-8`)}catch(e){return{kind:`declined`,reason:A5(e)}}if(Buffer.byteLength(r,`utf-8`)>u9)return{kind:`declined`,reason:`oversize`};let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=(0,xs.parseDocument)(a);if(o.errors.length>0)return{kind:`declined`,reason:`unparseable`};let s=[t,n];if(!o.hasIn(s))return{kind:`not-present`};o.deleteIn(s);let c=o.toString(),l=M5(a);a.trim()===``||a.endsWith(`
|
|
1539
1539
|
`)?c.endsWith(`
|
|
1540
1540
|
`)||(c=`${c}\n`):c=c.replace(/\n+$/,``),l&&(c=c.replace(/\r\n/g,`
|
|
1541
1541
|
`).replace(/\n/g,`\r
|
|
1542
|
-
`));let u=`${i?``:``}${c}`;return u!==r&&VJ(e,u,{mode:N5(e)}),{kind:`removed`}}function
|
|
1542
|
+
`));let u=`${i?``:``}${c}`;return u!==r&&VJ(e,u,{mode:N5(e)}),{kind:`removed`}}function XNe(e,t){let n=_Y();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=S(e,`utf-8`)}catch(e){return{kind:`declined`,reason:A5(e)}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=M5(a),s=a.trim()===``||a.endsWith(`
|
|
1543
1543
|
`),c;try{c=n.removeEntry(a,t)}catch{return{kind:`declined`,reason:`unparseable`}}if(!c.existed)return{kind:`not-present`};let l=c.text;s?l.endsWith(`
|
|
1544
1544
|
`)||(l=`${l}\n`):l=l.replace(/\n+$/,``),o&&(l=l.replace(/\r\n/g,`
|
|
1545
1545
|
`).replace(/\n/g,`\r
|
|
1546
|
-
`));let u=`${i?``:``}${l}`;return u!==r&&VJ(e,u,{mode:N5(e)}),{kind:`removed`}}function XNe(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}function ZNe(e){let{priorCommand:t,priorArgs:n}=p9(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function p9(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function m9(e,t,n={}){let r=pje(e,t),i;try{i=S(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??fje()):`hostname`in o&&typeof o.hostname==`string`&&o.hostname!==(n.host??ve());if(!a||typeof a!=`object`||!mAe(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??r8)(c)?l?{status:`alive`,lockPath:r,lock:a}:{status:`unverified-owner`,lockPath:r,pid:c}:{status:`dead-pid`,lockPath:r,lock:a}}async function QNe(e,t=void 0){let n=m9(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=hje(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 $Ne(e,t={}){return{targets:nPe(e,t.isAlive??r8)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}function ePe(e){try{return dt()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function tPe(e){let t=e.inspect??(()=>m9(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??QNe,o=e.logger??void 0,s=t(),c=$Ne(s,{isAlive:e.isAlive});if(c.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 l=s.status===`alive`||s.status===`foreign-host`?s.lock.channel:void 0;if(e.force!==!0&&typeof l==`string`&&l.length>0){let t=e.selfChannel??ePe(o);if(t!==void 0&&l!==t)return i(`Not stopping: the server at ${e.lockDir} belongs to ${eee(l)}. `+(l===`dev`?`Stop it from that dev build, or run \`${ht} 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:l,selfChannel:t,pids:c.targets.map(e=>e.pid)},`stop declined: server belongs to another channel`),{stopped:[],failed:[],hadTargets:!0,declined:{otherChannel:l}}}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:c.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}let u=[],d=[];for(let e of c.targets)try{n(e.pid,`SIGTERM`),u.push(e)}catch(t){d.push({target:e,error:t instanceof Error?t.message:String(t)})}return u.length>0&&r(`Stopped: ${u.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),o?.info({lockDir:e.lockDir,signalled:u.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:d.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),d.length>0&&i(`Failed to stop: ${d.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:u,failed:d,hadTargets:!0}}function nPe(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}function h9(e){if(!g(e))return{value:null,path:e,source:null,doc:null};let t;try{t=S(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,xs.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return dY(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function rPe(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=Zu({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function iPe(e){let t=e??process.cwd(),n=[],r=[],i=[],a=[],o=GJ(`user`,t),s=LJ({absPath:o});r.push(...s.diagnostics),!s.valid&&s.sidelinedTo!==void 0&&i.push({from:o,to:s.sidelinedTo}),s.valid&&s.source!==void 0&&n.push(o);let c=(e,t=!1)=>{let i=h9(e);if(i.diagnostic!==void 0&&r.push(i.diagnostic),i.value===null)return{};let o=nd({value:i.value,file:i.path,source:i.source,doc:i.doc});r.push(...o),n.push(e);let s=o.length>0?id(i.value):i.value;return t&&a.push(...Tye({value:s,file:i.path,source:i.source,doc:i.doc})),s},l=N(t,`.ok`,`config.yml`),u=c(l,!0),d=c(GJ(`project-local`,t)),f=tae(s.value,u,d),p=Oje.safeParse(f);if(!p.success){let e=h9(l),t={code:`SCHEMA_INVALID`,issues:rPe(p.error.issues,e)};throw Error(eae(t))}return{config:p.data,sources:n,diagnostics:r,sidelined:i,ignoredCommittedKeys:a}}function g9(e){return e.replace(/:\d+$/,``)}function _9(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:g9(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:g9(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:g9(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}function v9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=gc(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`).filter(e=>e.length>0);if(r.length<5||r[2]!==`blob`)return null;let i,a,o,s;try{i=decodeURIComponent(r[0]),a=decodeURIComponent(r[1]),o=decodeURIComponent(r[3]),s=r.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.length===0||s.some(e=>e.length===0)?null:{host:n,owner:i,repo:a,branch:o,path:s.join(`/`)}}function y9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=gc(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`);if(r.length<5||r[0]!==``||r[3]!==`tree`)return null;let i=r.slice(5);i.length===1&&i[0]===``&&i.pop();let a,o,s,c;try{a=decodeURIComponent(r[1]),o=decodeURIComponent(r[2]),s=decodeURIComponent(r[4]),c=i.map(e=>decodeURIComponent(e))}catch{return null}return!a||!o||!s||c.some(e=>e.length===0)?null:{host:n,owner:a,repo:o,branch:s,path:c.join(`/`)}}function aPe(e){let t=v9(e);if(t)return{kind:`doc`,...t};let n=y9(e);return n?{kind:`folder`,...n}:null}async function oPe(e,t){let n,r;try{n=await Ae(N(e)),r=await Ae(N(k(e)))}catch{return{kind:`not-git`}}if(!b9(n,r))return{kind:`symlink-escape`};let i=j(n,`.git`),a;try{a=te(i)}catch{return{kind:`not-git`}}if(a.isDirectory()){let e;try{e=await Ae(i)}catch{return{kind:`not-git`}}if(!b9(e,n))return{kind:`symlink-escape`}}else if(!a.isFile())return{kind:`not-git`};let o=Uxe(n);if(o.kind!==`repository`)return{kind:`not-git`};let s=o.repository.readRemoteUrl(`origin`);if(s.kind===`unreadable`)return{kind:`not-git`};if(s.kind===`absent`)return s.reason===`config-missing`?{kind:`not-git`}:{kind:`no-origin`};let c=s.url,l=_9(c);if(l===null)return{kind:`non-github`};let u=gc(l.hostname);if(u===null)return{kind:`non-github`};let d=u===t.host.toLowerCase(),f=l.owner.toLowerCase()===t.owner.toLowerCase(),p=l.name.toLowerCase()===t.repo.toLowerCase();return!d&&f&&p?{kind:`wrong-host`,actualHost:u}:!d||!f||!p?{kind:`wrong-repo`,actualOwner:l.owner,actualRepo:l.name}:{kind:`ok`,gitRemoteUrl:`https://${u}/${l.owner}/${l.name}.git`}}function b9(e,t){if(e===t)return!0;let n=M(t,e);return n.length>0&&!n.startsWith(`..`)&&!A(n)}const sPe=`# >>> open-knowledge cli >>>`,cPe=`# <<< open-knowledge cli <<<`,lPe=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function uPe(e){return Dye(dt(),e)}function x9(e,t,n=[]){let r=g(j(e,B8[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function dPe(e,t){let n=vY.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=yt.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:bS}));return[...n,...r]}function S9(e,t,n,r){let i=dOe(e,dPe(t,r)),a=i.find(e=>e.host===n);if(a===void 0||a.state===`absent`)return[];let o=a.real;return i.filter(e=>e.host!==n&&e.state!==`absent`&&e.real===o).map(e=>e.host)}function fPe(e,t){let n=(t??_e()).replace(/[\\/]+$/,``);if(!n.includes(`\\`))return e.startsWith(`${n}/`)?`~/${e.slice(n.length+1)}`:e;let r=e=>e.replace(/\\/g,`/`),i=r(n),a=r(e);return a.startsWith(`${i}/`)?`~/${a.slice(i.length+1)}`:e}function pPe(e,t){let n=$Y[e];return U5(n,``,t)&&!H5(n,``,t)}function C9(e,t,n,r,i){let a=$Y[e],o;if(i===void 0)try{o=a.configPath(n,r)}catch{return{state:`structural-na`}}else o=i;let s=i===void 0?fPe(o,r):void 0,c=q5(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&pPe(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];MY(r)&&i.push(`reclaim-permissive`),FY(r)&&i.push(`pre-approval-exact`),J5(e)(r)&&i.push(`injection-functional`);let o=WY(a,n);return i.length>0&&(o!==null&&Vbe(r,o)||t.includes(`pre-approval-exact`)&&i.includes(`reclaim-permissive`)&&!i.includes(`pre-approval-exact`))?{state:`drifted`,strictness:i,path:s}:i.length>0?{state:`satisfied`,strictness:i,path:s}:Ibe(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function mPe(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let r=Oa(e.pathId);if(r===null)return null;if(r.kind===`central-skill-store`)return n===void 0?null:x9(j(n,bS),`discovery`,S9(n,vt,e.agent,`global`));let i=r.editor;switch(r.kind){case`editor-user-skill-root`:{let e=vt[i];return e===null||n===void 0?null:K8(n).some(e=>e.editorId===i)?x9(j(n,e),`discovery`,S9(n,vt,i,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=_t[i];return e===null?null:x9(j(t,e),`project`,S9(t,_t,i,`project`))}case`editor-user-config`:return C9(i,e.strictness,t,n);case`editor-project-config`:{let r=$Y[i].projectConfigPath?.(t);return r===void 0?null:C9(i,e.strictness,t,n,r)}}}}[...V8.map(e=>B8[e])];function hPe(e){if(!A(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=N(e);if(t===le||k(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function w9(e){let t=hPe(e),n=[];for(let e of V8){let r=B8[e];n.push({path:j(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of St)n.push({path:j(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function gPe(e,t){let n=[];for(let r of w9(e))if(r.bundleId===t)try{O(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}`)}const _Pe=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=W5(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let r=_5(e,t,{home:n.home});return{integration:`project-skill`,editorId:e.id,action:r.action,...r.path?{path:r.path}:{},...r.error?{error:r.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function vPe(e,t,n={},r=_Pe){let i=[];for(let a of t){let t=$Y[a];for(let a of r)i.push(a.write(t,e,n))}let a=Qje(e,t);return a&&i.push({integration:`project-skill`,editorId:a.editorId,action:a.action,...a.path?{path:a.path}:{},...a.error?{error:a.error}:{}}),i}function yPe(e,t,n={}){return{integrations:vPe(e,t,n)}}function T9(e,t){let n=vt[e];return n===null?null:j(t,...n.split(`/`),B8.discovery,`SKILL.md`)}function bPe(e,t){let n=T9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!K8(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=W8(`discovery`,{checkDesktop:!0});return p5(k(n),t),{editorId:e,label:e,action:m5(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function xPe(e){return g(j(e,...`.agents/skills`.split(`/`),B8.discovery))?!0:gt.some(t=>{let n=T9(t,e);return n!==null&&g(k(n))})}function SPe(e,t){let n=T9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=k(n);try{return g(n)?(p5(r,t),O(r,{recursive:!0,force:!0}),{editorId:e,label:e,action:`removed`,path:n}):{editorId:e,label:e,action:`not-present`,path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function CPe(e){return LJ({absPath:GJ(`user`,e,e),sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function E9({home:e=_e(),env:t=process.env}={}){let n=CPe(e),{override:r,preferenceList:i}=$ye(t),{locale:a,source:o}=PP({override:r,storedPreference:n,supportedLocales:Kc,preferenceList:i,autoDetectableLocales:Jc});return{preference:n,locale:a,source:o,systemLanguages:i}}function D9(e){let t=new Set([e]);try{t.add(E.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 O9(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function wPe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function k9(e,t){if(typeof e==`string`)return O9(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>k9(e,t));if(!wPe(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=k9(i,t);return n}function A9(e,t){let n=S(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
|
|
1546
|
+
`));let u=`${i?``:``}${l}`;return u!==r&&VJ(e,u,{mode:N5(e)}),{kind:`removed`}}function ZNe(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}function QNe(e){let{priorCommand:t,priorArgs:n}=p9(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function p9(e){return{priorCommand:typeof e.command==`string`?e.command.slice(0,200):null,priorArgs:Array.isArray(e.args)?e.args.slice(0,10).map(e=>typeof e==`string`?e.slice(0,200):e):null}}function m9(e,t,n={}){let r=mje(e,t),i;try{i=S(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??pje()):`hostname`in o&&typeof o.hostname==`string`&&o.hostname!==(n.host??ve());if(!a||typeof a!=`object`||!mAe(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??r8)(c)?l?{status:`alive`,lockPath:r,lock:a}:{status:`unverified-owner`,lockPath:r,pid:c}:{status:`dead-pid`,lockPath:r,lock:a}}async function $Ne(e,t=void 0){let n=m9(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=gje(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 ePe(e,t={}){return{targets:rPe(e,t.isAlive??r8)?[{name:`server`,pid:e.lock.pid,port:e.lock.port}]:[]}}function tPe(e){try{return dt()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function nPe(e){let t=e.inspect??(()=>m9(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??$Ne,o=e.logger??void 0,s=t(),c=ePe(s,{isAlive:e.isAlive});if(c.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 l=s.status===`alive`||s.status===`foreign-host`?s.lock.channel:void 0;if(e.force!==!0&&typeof l==`string`&&l.length>0){let t=e.selfChannel??tPe(o);if(t!==void 0&&l!==t)return i(`Not stopping: the server at ${e.lockDir} belongs to ${eee(l)}. `+(l===`dev`?`Stop it from that dev build, or run \`${ht} 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:l,selfChannel:t,pids:c.targets.map(e=>e.pid)},`stop declined: server belongs to another channel`),{stopped:[],failed:[],hadTargets:!0,declined:{otherChannel:l}}}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:c.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}let u=[],d=[];for(let e of c.targets)try{n(e.pid,`SIGTERM`),u.push(e)}catch(t){d.push({target:e,error:t instanceof Error?t.message:String(t)})}return u.length>0&&r(`Stopped: ${u.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),o?.info({lockDir:e.lockDir,signalled:u.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:d.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),d.length>0&&i(`Failed to stop: ${d.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:u,failed:d,hadTargets:!0}}function rPe(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}function h9(e){if(!g(e))return{value:null,path:e,source:null,doc:null};let t;try{t=S(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,xs.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return dY(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function iPe(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=Zu({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function aPe(e){let t=e??process.cwd(),n=[],r=[],i=[],a=[],o=GJ(`user`,t),s=LJ({absPath:o});r.push(...s.diagnostics),!s.valid&&s.sidelinedTo!==void 0&&i.push({from:o,to:s.sidelinedTo}),s.valid&&s.source!==void 0&&n.push(o);let c=(e,t=!1)=>{let i=h9(e);if(i.diagnostic!==void 0&&r.push(i.diagnostic),i.value===null)return{};let o=nd({value:i.value,file:i.path,source:i.source,doc:i.doc});r.push(...o),n.push(e);let s=o.length>0?id(i.value):i.value;return t&&a.push(...Tye({value:s,file:i.path,source:i.source,doc:i.doc})),s},l=N(t,`.ok`,`config.yml`),u=c(l,!0),d=c(GJ(`project-local`,t)),f=tae(s.value,u,d),p=kje.safeParse(f);if(!p.success){let e=h9(l),t={code:`SCHEMA_INVALID`,issues:iPe(p.error.issues,e)};throw Error(eae(t))}return{config:p.data,sources:n,diagnostics:r,sidelined:i,ignoredCommittedKeys:a}}function g9(e){return e.replace(/:\d+$/,``)}function _9(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:g9(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:g9(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:g9(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}function v9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=gc(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`).filter(e=>e.length>0);if(r.length<5||r[2]!==`blob`)return null;let i,a,o,s;try{i=decodeURIComponent(r[0]),a=decodeURIComponent(r[1]),o=decodeURIComponent(r[3]),s=r.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.length===0||s.some(e=>e.length===0)?null:{host:n,owner:i,repo:a,branch:o,path:s.join(`/`)}}function y9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=gc(t.hostname);if(n===null)return null;let r=t.pathname.split(`/`);if(r.length<5||r[0]!==``||r[3]!==`tree`)return null;let i=r.slice(5);i.length===1&&i[0]===``&&i.pop();let a,o,s,c;try{a=decodeURIComponent(r[1]),o=decodeURIComponent(r[2]),s=decodeURIComponent(r[4]),c=i.map(e=>decodeURIComponent(e))}catch{return null}return!a||!o||!s||c.some(e=>e.length===0)?null:{host:n,owner:a,repo:o,branch:s,path:c.join(`/`)}}function oPe(e){let t=v9(e);if(t)return{kind:`doc`,...t};let n=y9(e);return n?{kind:`folder`,...n}:null}async function sPe(e,t){let n,r;try{n=await Ae(N(e)),r=await Ae(N(k(e)))}catch{return{kind:`not-git`}}if(!b9(n,r))return{kind:`symlink-escape`};let i=j(n,`.git`),a;try{a=te(i)}catch{return{kind:`not-git`}}if(a.isDirectory()){let e;try{e=await Ae(i)}catch{return{kind:`not-git`}}if(!b9(e,n))return{kind:`symlink-escape`}}else if(!a.isFile())return{kind:`not-git`};let o=Uxe(n);if(o.kind!==`repository`)return{kind:`not-git`};let s=o.repository.readRemoteUrl(`origin`);if(s.kind===`unreadable`)return{kind:`not-git`};if(s.kind===`absent`)return s.reason===`config-missing`?{kind:`not-git`}:{kind:`no-origin`};let c=s.url,l=_9(c);if(l===null)return{kind:`non-github`};let u=gc(l.hostname);if(u===null)return{kind:`non-github`};let d=u===t.host.toLowerCase(),f=l.owner.toLowerCase()===t.owner.toLowerCase(),p=l.name.toLowerCase()===t.repo.toLowerCase();return!d&&f&&p?{kind:`wrong-host`,actualHost:u}:!d||!f||!p?{kind:`wrong-repo`,actualOwner:l.owner,actualRepo:l.name}:{kind:`ok`,gitRemoteUrl:`https://${u}/${l.owner}/${l.name}.git`}}function b9(e,t){if(e===t)return!0;let n=M(t,e);return n.length>0&&!n.startsWith(`..`)&&!A(n)}const cPe=`# >>> open-knowledge cli >>>`,lPe=`# <<< open-knowledge cli <<<`,uPe=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function dPe(e){return Dye(dt(),e)}function x9(e,t,n=[]){let r=g(j(e,B8[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function fPe(e,t){let n=vY.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=yt.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:bS}));return[...n,...r]}function S9(e,t,n,r){let i=dOe(e,fPe(t,r)),a=i.find(e=>e.host===n);if(a===void 0||a.state===`absent`)return[];let o=a.real;return i.filter(e=>e.host!==n&&e.state!==`absent`&&e.real===o).map(e=>e.host)}function pPe(e,t){let n=(t??_e()).replace(/[\\/]+$/,``);if(!n.includes(`\\`))return e.startsWith(`${n}/`)?`~/${e.slice(n.length+1)}`:e;let r=e=>e.replace(/\\/g,`/`),i=r(n),a=r(e);return a.startsWith(`${i}/`)?`~/${a.slice(i.length+1)}`:e}function mPe(e,t){let n=$Y[e];return U5(n,``,t)&&!H5(n,``,t)}function C9(e,t,n,r,i){let a=$Y[e],o;if(i===void 0)try{o=a.configPath(n,r)}catch{return{state:`structural-na`}}else o=i;let s=i===void 0?pPe(o,r):void 0,c=q5(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&mPe(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];MY(r)&&i.push(`reclaim-permissive`),FY(r)&&i.push(`pre-approval-exact`),J5(e)(r)&&i.push(`injection-functional`);let o=WY(a,n);return i.length>0&&(o!==null&&Vbe(r,o)||t.includes(`pre-approval-exact`)&&i.includes(`reclaim-permissive`)&&!i.includes(`pre-approval-exact`))?{state:`drifted`,strictness:i,path:s}:i.length>0?{state:`satisfied`,strictness:i,path:s}:Ibe(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function hPe(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let r=Oa(e.pathId);if(r===null)return null;if(r.kind===`central-skill-store`)return n===void 0?null:x9(j(n,bS),`discovery`,S9(n,vt,e.agent,`global`));let i=r.editor;switch(r.kind){case`editor-user-skill-root`:{let e=vt[i];return e===null||n===void 0?null:K8(n).some(e=>e.editorId===i)?x9(j(n,e),`discovery`,S9(n,vt,i,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=_t[i];return e===null?null:x9(j(t,e),`project`,S9(t,_t,i,`project`))}case`editor-user-config`:return C9(i,e.strictness,t,n);case`editor-project-config`:{let r=$Y[i].projectConfigPath?.(t);return r===void 0?null:C9(i,e.strictness,t,n,r)}}}}[...V8.map(e=>B8[e])];function gPe(e){if(!A(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=N(e);if(t===le||k(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function w9(e){let t=gPe(e),n=[];for(let e of V8){let r=B8[e];n.push({path:j(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of St)n.push({path:j(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function _Pe(e,t){let n=[];for(let r of w9(e))if(r.bundleId===t)try{O(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}`)}const vPe=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=W5(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let r=_5(e,t,{home:n.home});return{integration:`project-skill`,editorId:e.id,action:r.action,...r.path?{path:r.path}:{},...r.error?{error:r.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function yPe(e,t,n={},r=vPe){let i=[];for(let a of t){let t=$Y[a];for(let a of r)i.push(a.write(t,e,n))}let a=$je(e,t);return a&&i.push({integration:`project-skill`,editorId:a.editorId,action:a.action,...a.path?{path:a.path}:{},...a.error?{error:a.error}:{}}),i}function bPe(e,t,n={}){return{integrations:yPe(e,t,n)}}function T9(e,t){let n=vt[e];return n===null?null:j(t,...n.split(`/`),B8.discovery,`SKILL.md`)}function xPe(e,t){let n=T9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!K8(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=W8(`discovery`,{checkDesktop:!0});return p5(k(n),t),{editorId:e,label:e,action:m5(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function SPe(e){return g(j(e,...`.agents/skills`.split(`/`),B8.discovery))?!0:gt.some(t=>{let n=T9(t,e);return n!==null&&g(k(n))})}function CPe(e,t){let n=T9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=k(n);try{return g(n)?(p5(r,t),O(r,{recursive:!0,force:!0}),{editorId:e,label:e,action:`removed`,path:n}):{editorId:e,label:e,action:`not-present`,path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function wPe(e){return LJ({absPath:GJ(`user`,e,e),sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function E9({home:e=_e(),env:t=process.env}={}){let n=wPe(e),{override:r,preferenceList:i}=$ye(t),{locale:a,source:o}=PP({override:r,storedPreference:n,supportedLocales:Kc,preferenceList:i,autoDetectableLocales:Jc});return{preference:n,locale:a,source:o,systemLanguages:i}}function D9(e){let t=new Set([e]);try{t.add(E.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 O9(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function TPe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function k9(e,t){if(typeof e==`string`)return O9(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>k9(e,t));if(!TPe(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=k9(i,t);return n}function A9(e,t){let n=S(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
|
|
1547
1547
|
`),i=n.split(`
|
|
1548
1548
|
`),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=k9(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}let o=r?`${a.join(`
|
|
1549
1549
|
`)}\n`:a.join(`
|
|
1550
1550
|
`);re(e,o)}function j9(e,t){let n=S(e,`utf-8`);if(n.trim().length!==0)try{let r=k9(JSON.parse(n),t),i=n.endsWith(`
|
|
1551
1551
|
`)?`
|
|
1552
|
-
`:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=O9(n,t.contentDirSpellings);r!==n&&re(e,r)}}function M9(e,t){let n=S(e,`utf-8`),r=O9(n,t.contentDirSpellings);r!==n&&re(e,r)}function N9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>j(e,t.name))}catch{return[]}}const
|
|
1553
|
-
`)}\n`:null}catch{return null}}function
|
|
1554
|
-
`:`not-running (${w})\n`;re(j(_,`state`,`server-status.txt`),oe);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:X5(e.diagnosticReports,y);if(re(j(_,`state`,`diagnostic-reports-status.txt`),`${A}\n`),re(j(_,e7),x7(e.osTerminationEvidence)),e.processDir&&g(e.processDir)){let t=j(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let se=e.redact===!0;se&&
|
|
1552
|
+
`:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=O9(n,t.contentDirSpellings);r!==n&&re(e,r)}}function M9(e,t){let n=S(e,`utf-8`),r=O9(n,t.contentDirSpellings);r!==n&&re(e,r)}function N9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>j(e,t.name))}catch{return[]}}const EPe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function P9(e){return/\.log\.\d+$/.test(e)}function DPe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||P9(e)}const OPe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function kPe(e){let t={contentDirSpellings:D9(e.contentDir)};for(let n of OPe)for(let r of N9(j(e.stagingDir,n)))DPe(r)?A9(r,t):r.endsWith(`.json`)?j9(r,t):M9(r,t);for(let n of N9(j(e.stagingDir,`state`))){let e=ae(n);n.endsWith(`.jsonl`)?A9(n,t):EPe.has(e)?j9(n,t):M9(n,t)}}const F9=[`.ok`,`local`,`telemetry`],I9=[`.ok`,`local`,`logs`],L9=[`.ok`,`local`,`loss-capture`],R9=`spans-current.jsonl`,z9=`spans-prev.jsonl`,B9=`server-current.jsonl`,V9=`server-prev.jsonl`,H9=`loss-current.jsonl`,U9=`loss-prev.jsonl`;function APe(e){return j(e,...F9,R9)}function jPe(e){return j(e,...F9,z9)}function MPe(e){return j(e,...I9,B9)}function NPe(e){return j(e,...I9,V9)}function PPe(e){return j(e,...L9,H9)}function FPe(e){return j(e,...L9,U9)}const W9=1e3;async function IPe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}async function LPe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}async function RPe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(W9)});return t.ok?await t.text():null}catch{return null}}function zPe(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(`
|
|
1553
|
+
`)}\n`:null}catch{return null}}function BPe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],c8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function VPe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],c8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function G9(){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 HPe(){return{nodeVersion:process.version,platform:ye(),arch:me()}}function UPe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!g(e))return{};let t;try{t=(0,xs.parse)(S(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(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function WPe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return WPe(e.maxBytes)}function GPe(e){let t=q9(GJ(`project`,e)),n=q9(GJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function KPe(e){return Te(`sha256`).update(e).digest(`hex`)}function qPe(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const JPe=[`"doc.name"`,`"docName"`];function X9(e){let t=S(e,`utf-8`),n=0;for(let e of JPe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(k(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,Z5(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const YPe=new Set([`.jsonl`]);function XPe(e){let t=e.lastIndexOf(`.`);return t!==-1&&YPe.has(e.slice(t))}const ZPe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function QPe(e){if(P9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&ZPe.has(e.slice(t))}function $Pe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!QPe(r))continue;let{redacted:i,patterns:a,lineCount:o}=BP(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return M(e,t).split(le).join(`/`)}async function eFe(e){let t=N(e.contentDir),n=N(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??IPe,a=r.fetchAgentEffects??LPe,o=r.fetchWatcherRecent??RPe,s=r.readShadowHead??BPe,c=r.readCheckpointRefs??VPe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.86.13-beta.12`),d=r.readDesktopEnv??G9,f=r.readLanguage??E9,p=r.readRuntime??HPe,h=r.isOtlpPushEnabled??UPe,_=y(j(xe(),`ok-bundle-`));try{v(j(_,`telemetry`),{recursive:!0}),v(j(_,`logs`),{recursive:!0}),v(j(_,`state`),{recursive:!0}),Z9(APe(n),j(_,`telemetry`,R9)),Z9(jPe(n),j(_,`telemetry`,z9)),Z9(MPe(n),j(_,`logs`,B9)),Z9(NPe(n),j(_,`logs`,V9));for(let t of e.userLogFiles??[])Z9(t,j(_,`logs`,ae(t)));for(let t of e.userStateFiles??[])Z9(t,j(_,TJ,ae(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,j(_,`diagnostic-reports`,ae(t)))&&(y+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,j(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(j(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(j(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=zPe(n);e!==null&&re(j(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(j(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(j(_,`state`,`checkpoint-refs.txt`),D),Z9(PPe(n),j(_,`state`,H9)),Z9(FPe(n),j(_,`state`,U9)),Z9(j(b,`last-spawn-error.log`),j(_,`state`,`last-spawn-error.log`)),Z9(j(b,od),j(_,`state`,od)),Z9(j(b,sd),j(_,`state`,sd)),Z9(j(b,ad),j(_,`state`,ad));let ee=p(),ne=d(),ie=f(),k={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(j(_,`state`,`runtime.json`),`${JSON.stringify(k,null,2)}\n`);let oe=C===`running`?`running
|
|
1554
|
+
`:`not-running (${w})\n`;re(j(_,`state`,`server-status.txt`),oe);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:X5(e.diagnosticReports,y);if(re(j(_,`state`,`diagnostic-reports-status.txt`),`${A}\n`),re(j(_,e7),x7(e.osTerminationEvidence)),e.processDir&&g(e.processDir)){let t=j(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let se=e.redact===!0;se&&kPe({stagingDir:_,contentDir:t}),e.note&&re(j(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=$Pe(_));for(let t of e.extraFiles??[]){let e=t.zipName??ae(t.sourcePath);if(!Z9(t.sourcePath,j(_,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=C7(t,`extra/${e}`);n!==null&&(ce??={redactions:[],redactedLineCount:0},ce.redactions.push(n),ce.redactedLineCount+=n.lineCount)}let M=GPe(n),N=Q9(_),le=[],ue=0,de=0;for(let e of N){let t=$9(_,e),n=te(e).size,r=XPe(t)?qPe(e):0;le.push({path:t,bytes:n,lines:r}),ue+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=X9(e))}let fe={applied:se};ce!==null&&(fe.secretScrub=ce);let P={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie},contentDir:{pathSha256:KPe(t),absolutePath:se?`<CONTENT_DIR>`:t},telemetry:{localSink:M,otlpPushEnabled:h()},redaction:fe,serverStatus:C,files:le};re(j(_,`manifest.json`),`${JSON.stringify(P,null,2)}\n`);let pe=D9(t),me=N.some(e=>{try{let t=S(e,`utf-8`);return pe.some(e=>t.includes(e))}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:ue,fileCount:le.length,docNameCount:de,contentDirVisible:me,redacted:se},ge=!1;return{stagingDir:_,manifest:P,summary:he,cleanup:()=>{ge||(ge=!0,O(_,{recursive:!0,force:!0}))}}}catch(e){throw O(_,{recursive:!0,force:!0}),e}}async function tFe(e){let{collected:t,outputPath:n}=e,r=k(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new TDe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(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 nFe(e,t){let n=j(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,xs.parse)(S(n,`utf-8`)),r=dY(t)?t.content:void 0,i=dY(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return N(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 N(e)}async function rFe(e,t,n,r,i,a){let o=w7(t,e.logger),s=await eFe({contentDir:nFe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...pNe(o,e.userLogsDir??j(RJ(),`logs`)),...E7(e.cachesDir??j(_e(),`Library`,`Caches`))],userStateFiles:D7(e.bugReportsDir??S7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(k(e.outputPath),{recursive:!0}),await tFe({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 iFe(e){let{projectDir:t}=e,n=e.readDesktopEnv??G9,r=e.readLanguage??E9,i=()=>zMe(e.diagnosticReportsDir??j(_e(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return rFe(e,t,n,r,i(),await b7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await vNe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:E7(e.cachesDir??j(_e(),`Library`,`Caches`)),bugReportLedgerFiles:D7(e.bugReportsDir??S7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await b7(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}}}export{vY as ALL_EDITOR_IDS,yY as EDITOR_LABELS,$Y as EDITOR_TARGETS,Mbe as HOSTS_WITH_USER_SKILL_DIR,DMe as LAUNCH_CONFIG_NAME,cPe as PATH_SHIM_BEGIN,uPe as PATH_SHIM_BLOCK_RE,lPe as PATH_SHIM_END,u5 as ProjectPathSafetyError,iMe as addOkPathsToGitExclude,d5 as assertProjectPathSafe,PY as buildManagedServerEntry,ZNe as buildMcpConfigDeclineEvent,QNe as buildMcpConfigMigrateEvent,WY as canonicalEntryFor,q5 as classifyExistingMcpEntry,iFe as collectReportBundle,hPe as createCliProbeResolver,ZJ as createTokenStore,uNe as defaultBugReportZipPath,Ke as detectGh,Ye as detectGhAccounts,jMe as detectInstalledEditors,UY as droppedManagedKeys,$be as editorConfigPathDisplay,Qbe as editorEntryLocator,BNe as ensurePiBridge,GMe as findJetsamKillSync,T5 as formatTrackedRemediation,sMe as getExcludedOkPaths,C5 as getInstalledSkillProjectionPaths,jbe as getNativeTomlMcpEditor,S5 as getOkArtifactPaths,MY as isEntryUpToDate,FY as isOwnManagedEntry,aPe as loadConfig,rbe as makeLazyProbeTokenStore,S7 as okBugReportsDir,v9 as parseGitHubBlobUrl,oPe as parseGitHubShareUrl,y9 as parseGitHubTreeUrl,_9 as parseGitUrl,dPe as pathInstallMarkerPath,Uje as previewContent,MMe as probeOwnManagedEditorMcpEntry,RNe as probePiBridgeState,w5 as probeTrackedOkPaths,G5 as readExistingMcpEntry,oMe as readSharingMode,BP as redactContent,aMe as removeOkPathsFromGitExclude,qNe as removeOwnMcpEntry,eMe as removeProjectSkill,_Pe as removeUserGlobalSkillBundle,CPe as removeUserSkill,Jje as resolveProjectRoot,nPe as runStop,p9 as truncatePriorEntry,w9 as userGlobalSkillBundleTargets,SPe as userSkillPresentAnywhere,sPe as validateLocalFolderForShare,W5 as writeEditorMcpConfig,bPe as writeProjectAiIntegrations,_5 as writeProjectSkill,AMe as writeUserMcpConfigs,xPe as writeUserSkill};
|
|
1555
1555
|
//# sourceMappingURL=index.mjs.map
|