@inkeep/open-knowledge 0.88.3-beta.5 → 0.88.3-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD_PARTY_NOTICES.md +2 -1
- package/dist/chunk-3H6UQG3A-Doth9YS5.mjs +9 -0
- package/dist/cli.mjs +65 -65
- package/dist/constants-DGmgdngk.mjs +1 -0
- package/dist/{dist-BniR5KN1.mjs → dist-BBGeY6nr.mjs} +481 -481
- package/dist/dist-YE1QUVK6.mjs +1 -0
- package/dist/{flag-coverage-6JEX67RU-Byy8DkC9.mjs → flag-coverage-6JEX67RU-CvfAS1f3.mjs} +1 -1
- package/dist/{grep-2HUTXO5U-Bu-1kF3P.mjs → grep-2HUTXO5U-CoGVhBxG.mjs} +1 -1
- package/dist/grep-2HUTXO5U-q3hMkiyQ.mjs +10 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +39 -39
- package/dist/{init-UZr9GVxw.mjs → init-DOXvXRFd.mjs} +12 -12
- package/dist/init-Davt24-h.mjs +1 -0
- package/dist/{launch-json-removal-DdasfWvu.mjs → launch-json-removal-D568oYtW.mjs} +1 -1
- package/dist/loader-BldgWyXM.mjs +1 -0
- package/dist/{loader-Dbq_EWV8.mjs → loader-jiqwkC6p.mjs} +1 -1
- package/dist/{open-browser-CDTeL9eY.mjs → open-browser-BuqG6kOx.mjs} +1 -1
- package/dist/{preview-BRJmRFNY.mjs → preview-CdW8V4pn.mjs} +1 -1
- package/dist/preview-DQpU-n3d.mjs +1 -0
- package/dist/public/assets/{AccountSection-B7HfUudL.js → AccountSection-Bsy01fhm.js} +1 -1
- package/dist/public/assets/{ActivityModeContent-CmhZGNsW.js → ActivityModeContent-HMfBEczJ.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-BT2D84aD.js → AddPropertiesButton-DCMIMF11.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-CHF9pABO.js → AgentDiffPane-DBpovpL0.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-ByGVMvG9.js → AttachmentsSection-C_-B9OiW.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-DR1N5trk.js → CodeMirrorPropInput-q-tW9iPZ.js} +1 -1
- package/dist/public/assets/{ContentRulesSection-C9Req4oF.js → ContentRulesSection-CRs7Z-Kl.js} +1 -1
- package/dist/public/assets/{DocumentContext-CSDucywQ.js → DocumentContext-BXz9ZRMm.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-gpcNAVY7.js → EditorModeToggle-piRgg3g6.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-Cgmhgars.js → ExcalidrawDocEditor-D5ttK_rE.js} +1 -1
- package/dist/public/assets/FeedbackForm-6NZf17Jy.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-D_sEyaYd.js → ImportSkillDialog-Clp9S3Jl.js} +1 -1
- package/dist/public/assets/{LinkPreviewsSection-9BI_Ve7c.js → LinkPreviewsSection-Da1V4LmQ.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-Cd7vchN2.js → LintConfigEditor-CSPu-w3E.js} +1 -1
- package/dist/public/assets/{LintingSection-CYt6Mzbc.js → LintingSection-C4cJfXpY.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-DD9uK5we.js → ManagedArtifactProperties-D_WTySM9.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-SqB6slOf.js +1 -0
- package/dist/public/assets/{MermaidDocEditor-C_HMHLXm.js → MermaidDocEditor-CiCVU3u0.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-BrbkXzyJ.js → NetworkAccessSection-kXV9kK5k.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-DrvArJ_K.js → PropertyDisplayRow-Dbo635Sc.js} +1 -1
- package/dist/public/assets/{PublishToGitHubDialog-D0GzPYlL.js → PublishToGitHubDialog-CWbMkbgX.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-Cxv9ZBLk.js → SchemaConfigEditor-GlcE6Ken.js} +1 -1
- package/dist/public/assets/{SearchSection-B2hY3rln.js → SearchSection-DtOslpNY.js} +1 -1
- package/dist/public/assets/{SessionsHost-Dhya-YYl.js → SessionsHost-BiN9T1mN.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-BqSzx5Tb.js → SettingsDialogBody-DC0-Bfjz.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-BIVMX9w3.js → ShareReceiveMissDialog-_IcdwjYa.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-F1L2HGgN.js → SkillToolbarControls-B4dJ-1Q9.js} +1 -1
- package/dist/public/assets/{SourceEditor-KucnhTGF.js → SourceEditor-DZCnayw_.js} +1 -1
- package/dist/public/assets/{SyncSection-B5pv2M0p.js → SyncSection-CABw_upt.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-emJ3GW6F.js → SyncStatusBadge-Prz62chl.js} +1 -1
- package/dist/public/assets/{TerminalSection-BTwUAO1z.js → TerminalSection-ctDA6BD7.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-DqRB0Vv9.js → TerminalWindowApp-CwcBaNfV.js} +1 -1
- package/dist/public/assets/{TextDocEditor-DI35AumM.js → TextDocEditor-BCy8_o0Z.js} +1 -1
- package/dist/public/assets/{ThreadView-Dykd2VWP.js → ThreadView-AytNA8Bn.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-BMkb_oht.js → TimelineDiffPane-dvUHHFfb.js} +1 -1
- package/dist/public/assets/{client-version-BLwdND1C.js → client-version-CoGrP1hT.js} +1 -1
- package/dist/public/assets/{comment-chips-CvYUezma.js → comment-chips-Duzwlzbj.js} +1 -1
- package/dist/public/assets/{config-provider-DW_79HvK.js → config-provider-CPQaUJ2E.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-CLhgkmvC.js → doc-undo-manager-CXLOMLbE.js} +1 -1
- package/dist/public/assets/{index-X807k4xA.js → index-kFULVhS4.js} +7 -7
- package/dist/public/assets/{lint-plugins-Czjcu-H_.js → lint-plugins-b7FrH_AL.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-C-OIVRCW.js → pending-receive-nav-store-CFrqb1MB.js} +1 -1
- package/dist/public/assets/{preferred-session-events-BNgqIkFZ.js → preferred-session-events-4J_b3j5a.js} +1 -1
- package/dist/public/assets/{progress-CWeTZaVu.js → progress-BNjrCWFP.js} +1 -1
- package/dist/public/assets/{selection-context-BdQZZ1HB.js → selection-context-DipqNj-A.js} +1 -1
- package/dist/public/assets/{src-DO7J3WVu.js → src-DuMojl-j.js} +1 -1
- package/dist/public/assets/{telemetry-impl-BTJogCD2.js → telemetry-impl-DrxqLHsh.js} +1 -1
- package/dist/public/assets/{telemetry-startup-CjA9BXC1.js → telemetry-startup-ZZdRZz3R.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-fQQTAQsm.js → typing-burst-detector-BtG6uGfS.js} +1 -1
- package/dist/public/assets/{use-activity-panel-D2QIpezB.js → use-activity-panel-v2L1525I.js} +1 -1
- package/dist/public/assets/{use-open-skill-CkTZwt2b.js → use-open-skill-B8ph57uc.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-CZCtVTgy.js → use-terminal-enabled-C36hPJ7F.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-BwKzDqXd.js → use-timeline-entry-diff-Cy2jCDnm.js} +1 -1
- package/dist/public/index.html +19 -19
- package/dist/registry-probes-BLEPNl5j.mjs +17 -0
- package/dist/{removal-file-path-Yisg-4PO.mjs → removal-file-path-8NjPowxA.mjs} +1 -1
- package/dist/{repair-launch-json-ByHbUrvl.mjs → repair-launch-json-BfqRZk56.mjs} +1 -1
- package/dist/{repair-mcp-configs-Cz7RUmn9.mjs → repair-mcp-configs-DckwMDwh.mjs} +1 -1
- package/dist/src-2k-YFR8o.mjs +16 -0
- package/dist/src-BPq8I0PL.mjs +1 -0
- package/dist/start-Bgay2g8t.mjs +1 -0
- package/dist/{start-0pD-b-lJ.mjs → start-Cy1P5w3F.mjs} +3 -3
- package/package.json +4 -4
- package/dist/chunk-3H6UQG3A-BTZuQ7ja.mjs +0 -8
- package/dist/constants-BrQxqUNL.mjs +0 -1
- package/dist/dist-D5Ry9hFU.mjs +0 -1
- package/dist/grep-2HUTXO5U-Bvpc71YZ.mjs +0 -9
- package/dist/init-CxYfudet.mjs +0 -1
- package/dist/loader-iVVo3m-3.mjs +0 -1
- package/dist/preview-ca3pkl9K.mjs +0 -1
- package/dist/public/assets/FeedbackForm-ZahAS6z-.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-BBtQ0jlN.js +0 -1
- package/dist/registry-probes-DA_47MnL.mjs +0 -17
- package/dist/src--qjAZ5fK.mjs +0 -16
- package/dist/src-ue3sSI-I.mjs +0 -1
- package/dist/start-r-TtnKpy.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -746,7 +746,7 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
|
|
|
746
746
|
`.indexOf(e.charAt(t))!==-1}var i4;(function(e){e.DEFAULT={allowTrailingComma:!1}})(i4||={});function YOe(e,t=[],n=i4.DEFAULT){let r=null,i=[],a=[];function o(e){Array.isArray(i)?i.push(e):r!==null&&(i[r]=e)}return c4(e,{onObjectBegin:()=>{let e={};o(e),a.push(i),i=e,r=null},onObjectProperty:e=>{r=e},onObjectEnd:()=>{i=a.pop()},onArrayBegin:()=>{let e=[];o(e),a.push(i),i=e,r=null},onArrayEnd:()=>{i=a.pop()},onLiteralValue:o,onError:(e,n,r)=>{t.push({error:e,offset:n,length:r})}},n),i[0]}function a4(e,t=[],n=i4.DEFAULT){let r={type:`array`,offset:-1,length:-1,children:[],parent:void 0};function i(e){r.type===`property`&&(r.length=e-r.offset,r=r.parent)}function a(e){return r.children.push(e),e}c4(e,{onObjectBegin:e=>{r=a({type:`object`,offset:e,length:-1,parent:r,children:[]})},onObjectProperty:(e,t,n)=>{r=a({type:`property`,offset:t,length:-1,parent:r,children:[]}),r.children.push({type:`string`,value:e,offset:t,length:n,parent:r})},onObjectEnd:(e,t)=>{i(e+t),r.length=e+t-r.offset,r=r.parent,i(e+t)},onArrayBegin:(e,t)=>{r=a({type:`array`,offset:e,length:-1,parent:r,children:[]})},onArrayEnd:(e,t)=>{r.length=e+t-r.offset,r=r.parent,i(e+t)},onLiteralValue:(e,t,n)=>{a({type:XOe(e),offset:t,length:n,parent:r,value:e}),i(t+n)},onSeparator:(e,t,n)=>{r.type===`property`&&(e===`:`?r.colonOffset=t:e===`,`&&i(t))},onError:(e,n,r)=>{t.push({error:e,offset:n,length:r})}},n);let o=r.children[0];return o&&delete o.parent,o}function o4(e,t){if(!e)return;let n=e;for(let e of t)if(typeof e==`string`){if(n.type!==`object`||!Array.isArray(n.children))return;let t=!1;for(let r of n.children)if(Array.isArray(r.children)&&r.children[0].value===e&&r.children.length===2){n=r.children[1],t=!0;break}if(!t)return}else{let t=e;if(n.type!==`array`||t<0||!Array.isArray(n.children)||t>=n.children.length)return;n=n.children[t]}return n}function s4(e){switch(e.type){case`array`:return e.children.map(s4);case`object`:let t=Object.create(null);for(let n of e.children){let e=n.children[1];e&&(t[n.children[0].value]=s4(e))}return t;case`null`:case`string`:case`number`:case`boolean`:return e.value;default:return}}function c4(e,t,n=i4.DEFAULT){let r=X2(e,!1),i=[],a=0;function o(e){return e?()=>a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function s(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function c(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice()):()=>!0}function l(e){return e?()=>{a>0?a++:e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice())===!1&&(a=1)}:()=>!0}function u(e){return e?()=>{a>0&&a--,a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter())}:()=>!0}let d=l(t.onObjectBegin),f=c(t.onObjectProperty),p=u(t.onObjectEnd),m=l(t.onArrayBegin),h=u(t.onArrayEnd),g=c(t.onLiteralValue),_=s(t.onSeparator),v=o(t.onComment),y=s(t.onError),b=n&&n.disallowComments,x=n&&n.allowTrailingComma;function S(){for(;;){let e=r.scan();switch(r.getTokenError()){case 4:C(14);break;case 5:C(15);break;case 3:C(13);break;case 1:b||C(11);break;case 2:C(12);break;case 6:C(16)}switch(e){case 12:case 13:b?C(10):v();break;case 16:C(1);break;case 15:case 14:break;default:return e}}}function C(e,t=[],n=[]){if(y(e),t.length+n.length>0){let e=r.getToken();for(;e!==17;){if(t.indexOf(e)!==-1){S();break}if(n.indexOf(e)!==-1)break;e=S()}}}function w(e){let t=r.getTokenValue();return e?g(t):(f(t),i.push(t)),S(),!0}function T(){switch(r.getToken()){case 11:let e=r.getTokenValue(),t=Number(e);isNaN(t)&&(C(2),t=0),g(t);break;case 7:g(null);break;case 8:g(!0);break;case 9:g(!1);break;default:return!1}return S(),!0}function E(){return r.getToken()===10?(w(!1),r.getToken()===6?(_(`:`),S(),te()||C(4,[],[2,5])):C(5,[],[2,5]),i.pop(),!0):(C(3,[],[2,5]),!1)}function D(){d(),S();let e=!1;for(;r.getToken()!==2&&r.getToken()!==17;){if(r.getToken()===5){if(e||C(4,[],[]),_(`,`),S(),r.getToken()===2&&x)break}else e&&C(6,[],[]);E()||C(4,[],[2,5]),e=!0}return p(),r.getToken()===2?S():C(7,[2],[]),!0}function ee(){m(),S();let e=!0,t=!1;for(;r.getToken()!==4&&r.getToken()!==17;){if(r.getToken()===5){if(t||C(4,[],[]),_(`,`),S(),r.getToken()===4&&x)break}else t&&C(6,[],[]);e?(i.push(0),e=!1):i[i.length-1]++,te()||C(4,[],[4,5]),t=!0}return h(),e||i.pop(),r.getToken()===4?S():C(8,[4],[]),!0}function te(){switch(r.getToken()){case 3:return ee();case 1:return D();case 10:return w(!0);default:return T()}}return S(),r.getToken()===17?n.allowEmptyContent?!0:(C(4,[],[]),!1):te()?(r.getToken()!==17&&C(9,[],[]),!0):(C(4,[],[]),!1)}function XOe(e){switch(typeof e){case`boolean`:return`boolean`;case`number`:return`number`;case`string`:return`string`;case`object`:return e?Array.isArray(e)?`array`:`object`:`null`;default:return`null`}}function ZOe(e,t,n,r){let i=t.slice(),a=a4(e,[]),o,s;for(;i.length>0&&(s=i.pop(),o=o4(a,i),o===void 0&&n!==void 0);)n=typeof s==`string`?{[s]:n}:[n];if(!o){if(n===void 0)throw Error(`Can not delete in empty document`);return l4(e,{offset:a?a.offset:0,length:a?a.length:0,content:JSON.stringify(n)},r)}if(o.type===`object`&&typeof s==`string`&&Array.isArray(o.children)){let t=o4(o,[s]);if(t!==void 0){if(n===void 0){if(!t.parent)throw Error(`Malformed AST`);let n=o.children.indexOf(t.parent),i,a=t.parent.offset+t.parent.length;if(n>0){let e=o.children[n-1];i=e.offset+e.length}else i=o.offset+1,o.children.length>1&&(a=o.children[1].offset);return l4(e,{offset:i,length:a-i,content:``},r)}return l4(e,{offset:t.offset,length:t.length,content:JSON.stringify(n)},r)}{if(n===void 0)return[];let t=`${JSON.stringify(s)}: ${JSON.stringify(n)}`,i=r.getInsertionIndex?r.getInsertionIndex(o.children.map(e=>e.children[0].value)):o.children.length,a;if(i>0){let e=o.children[i-1];a={offset:e.offset+e.length,length:0,content:`,`+t}}else a=o.children.length===0?{offset:o.offset+1,length:0,content:t}:{offset:o.offset+1,length:0,content:t+`,`};return l4(e,a,r)}}if(o.type===`array`&&typeof s==`number`&&Array.isArray(o.children)){let t=s;if(t===-1){let t=`${JSON.stringify(n)}`,i;if(o.children.length===0)i={offset:o.offset+1,length:0,content:t};else{let e=o.children[o.children.length-1];i={offset:e.offset+e.length,length:0,content:`,`+t}}return l4(e,i,r)}if(n===void 0&&o.children.length>=0){let t=s,n=o.children[t],i;if(o.children.length===1)i={offset:o.offset+1,length:o.length-2,content:``};else if(o.children.length-1===t){let e=o.children[t-1],n=e.offset+e.length;i={offset:n,length:o.offset+o.length-2-n,content:``}}else i={offset:n.offset,length:o.children[t+1].offset-n.offset,content:``};return l4(e,i,r)}if(n!==void 0){let t,i=`${JSON.stringify(n)}`;if(!r.isArrayInsertion&&o.children.length>s){let e=o.children[s];t={offset:e.offset,length:e.length,content:i}}else if(o.children.length===0||s===0)t={offset:o.offset+1,length:0,content:o.children.length===0?i:i+`,`};else{let e=s>o.children.length?o.children.length:s,n=o.children[e-1];t={offset:n.offset+n.length,length:0,content:`,`+i}}return l4(e,t,r)}throw Error(`Can not ${n===void 0?`remove`:r.isArrayInsertion?`insert`:`modify`} Array index ${t} as length is not sufficient`)}throw Error(`Can not add ${typeof s==`number`?`property`:`index`} to parent of type ${o.type}`)}function l4(e,t,n){if(!n.formattingOptions)return[t];let r=u4(e,t),i=t.offset,a=t.offset+t.content.length;if(t.length===0||t.content.length===0){for(;i>0&&!r4(r,i-1);)i--;for(;a<r.length&&!r4(r,a);)a++}let o=KOe(r,{offset:i,length:a-i},{...n.formattingOptions,keepLines:!1});for(let e=o.length-1;e>=0;e--){let t=o[e];r=u4(r,t),i=Math.min(i,t.offset),a=Math.max(a,t.offset+t.length),a+=t.content.length-t.length}let s=e.length-(r.length-a)-i;return[{offset:i,length:s,content:r.substring(i,a)}]}function u4(e,t){return e.substring(0,t.offset)+t.content+e.substring(t.offset+t.length)}var QOe;(function(e){e[e.None=0]=`None`,e[e.UnexpectedEndOfComment=1]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=2]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=3]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=4]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=5]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=6]=`InvalidCharacter`})(QOe||={});var $Oe;(function(e){e[e.OpenBraceToken=1]=`OpenBraceToken`,e[e.CloseBraceToken=2]=`CloseBraceToken`,e[e.OpenBracketToken=3]=`OpenBracketToken`,e[e.CloseBracketToken=4]=`CloseBracketToken`,e[e.CommaToken=5]=`CommaToken`,e[e.ColonToken=6]=`ColonToken`,e[e.NullKeyword=7]=`NullKeyword`,e[e.TrueKeyword=8]=`TrueKeyword`,e[e.FalseKeyword=9]=`FalseKeyword`,e[e.StringLiteral=10]=`StringLiteral`,e[e.NumericLiteral=11]=`NumericLiteral`,e[e.LineCommentTrivia=12]=`LineCommentTrivia`,e[e.BlockCommentTrivia=13]=`BlockCommentTrivia`,e[e.LineBreakTrivia=14]=`LineBreakTrivia`,e[e.Trivia=15]=`Trivia`,e[e.Unknown=16]=`Unknown`,e[e.EOF=17]=`EOF`})($Oe||={});const eke=YOe,tke=a4,d4=s4;var nke;(function(e){e[e.InvalidSymbol=1]=`InvalidSymbol`,e[e.InvalidNumberFormat=2]=`InvalidNumberFormat`,e[e.PropertyNameExpected=3]=`PropertyNameExpected`,e[e.ValueExpected=4]=`ValueExpected`,e[e.ColonExpected=5]=`ColonExpected`,e[e.CommaExpected=6]=`CommaExpected`,e[e.CloseBraceExpected=7]=`CloseBraceExpected`,e[e.CloseBracketExpected=8]=`CloseBracketExpected`,e[e.EndOfFileExpected=9]=`EndOfFileExpected`,e[e.InvalidCommentToken=10]=`InvalidCommentToken`,e[e.UnexpectedEndOfComment=11]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=12]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=13]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=14]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=15]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=16]=`InvalidCharacter`})(nke||={});function f4(e,t,n,r){return ZOe(e,t,n,r)}function p4(e,t){let n=t.slice(0).sort((e,t)=>{let n=e.offset-t.offset;return n===0?e.length-t.length:n}),r=e.length;for(let t=n.length-1;t>=0;t--){let i=n[t];if(i.offset+i.length<=r)e=u4(e,i);else throw Error(`Overlapping edit`);r=i.offset}return e}const rke=global.Request;var m4=class extends rke{constructor(e,t){if(typeof e==`object`&&S4 in e){let n=t!==void 0&&`body`in t&&t.body!=null;if(e[j4]&&!n)throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);e=e[S4]()}t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}};const h4=e=>{let t=[],n=e.rawHeaders;for(let e=0,r=n.length;e<r;e+=2){let r=n[e];r.charCodeAt(0)!==58&&t.push([r,n[e+1]])}return new Headers(t)},ike=Symbol(`wrapBodyStream`),ake=new Set([`latin1`,`binary`,`hex`,`base64`,`base64url`]),oke=e=>e===null||ake.has(e),g4=Symbol(`bodyBufferedBeforeDisconnect`),_4=Symbol(`bodyBufferedLengthBeforeDisconnect`),v4=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??`utf8`),y4=e=>!(e instanceof We)&&!!e.complete&&!!e.readableAborted&&typeof e.read==`function`&&oke(e.readableEncoding),b4=(e,t)=>{if(e.readableDidRead&&!t||!y4(e))return;let n=e;if(n[g4]!==void 0)return n[g4];let r,i=e.errored;if(i&&i.code!==`ECONNRESET`)r=i;else if(n[_4]!==void 0&&e.readableLength!==n[_4])r=P4();else{let n=t??[],i=e.read();i!==null&&n.push(v4(i,e.readableEncoding));let a=n.length===1?n[0]:Buffer.concat(n);r=a;let o=e.headers[`content-length`];if(typeof o==`string`&&/^\d+$/.test(o)){let e=Number(o);Number.isSafeInteger(e)&&a.length!==e&&(r=P4())}}return n[g4]=r,r},x4=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},ske=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new m4(t,a);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[ike]){let e;a.body=new ReadableStream({async pull(t){try{if(!e){let e=b4(r);if(e!==void 0){x4(t,e);return}}e||=Le.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else{let e=b4(r);a.body=e===void 0?Le.toWeb(r):new ReadableStream({start(t){x4(t,e)}})}}return new m4(t,a)},S4=Symbol(`getRequestCache`),C4=Symbol(`requestCache`),w4=Symbol(`incomingKey`),T4=Symbol(`urlKey`),cke=Symbol(`methodKey`),E4=Symbol(`headersKey`),D4=Symbol(`abortControllerKey`),O4=Symbol(`getAbortController`),lke=Symbol(`abortRequest`),k4=Symbol(`bodyBuffer`),A4=Symbol(`bodyReadPromise`),j4=Symbol(`bodyConsumedDirectly`),M4=Symbol(`bodyLockReader`),N4=Symbol(`abortReason`),P4=()=>TypeError(`Body is unusable`),F4=()=>Promise.reject(P4()),uke=new TextDecoder,dke=e=>{if(e[j4])return F4();e[j4]=!0},fke=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),pke=e=>(e[E4]||=h4(e[w4])).get(`content-type`)||``,mke=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,hke=e=>{if(!mke.test(e))return TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t===`CONNECT`||t===`TRACK`||t===`TRACE`&&e!==`TRACE`)return TypeError(`'${e}' HTTP method is unsupported.`)},I4=(e,t,n)=>{if(e[j4])return F4();let r=e.method;if(r===`GET`||r===`HEAD`)return e[S4]()[t]();let i=hke(r);if(i)return Promise.reject(i);if(e[C4]&&r!==`TRACE`)return e[C4][t]();let a=dke(e);if(a)return a;let o=gke(e);if(o){let t=Promise.resolve(n(o,e));return e[k4]=void 0,t}return _ke(e).then(t=>{let r=n(t,e);return e[k4]=void 0,r})},gke=e=>{let t=e[w4];if(`rawBody`in t&&t.rawBody instanceof Buffer)return t.rawBody},L4=(e,t)=>{if(t.errored)return t.errored;let n=e[N4];return n===void 0?Error(`Client connection prematurely closed.`):n instanceof Error?n:Error(String(n))},_ke=e=>{if(e[k4])return Promise.resolve(e[k4]);if(e[A4])return e[A4];let t=e[w4];if(t.readableDidRead)return F4();let n=b4(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[k4]=n,Promise.resolve(n));let r=new Promise((n,r)=>{let i=[],a=!1,o=e=>{a||(a=!0,f(),e())},s=a=>{let s=t.errored??a;return!y4(t)||s&&s.code!==`ECONNRESET`?!1:(o(()=>{let o=b4(t,i);o instanceof Error?r(o):o===void 0?r(a??L4(e,t)):(e[k4]=o,n(o))}),!0)},c=e=>{i.push(v4(e,t.readableEncoding))},l=()=>{o(()=>{let t=i.length===1?i[0]:Buffer.concat(i);e[k4]=t,n(t)})},u=e=>{s(e)||o(()=>{r(e)})},d=()=>{if(t.readableEnded){l();return}s()||o(()=>{r(L4(e,t))})},f=()=>{t.off(`data`,c),t.off(`end`,l),t.off(`error`,u),t.off(`close`,d),e[A4]=void 0};t.on(`data`,c),t.on(`end`,l),t.on(`error`,u),t.on(`close`,d),queueMicrotask(()=>{a||(t.readableEnded?l():t.errored?u(t.errored):t.destroyed&&d())})});return e[A4]=r,r},R4={get method(){return this[cke]},get url(){return this[T4]},get headers(){return this[E4]||=h4(this[w4])},[lke](e){this[N4]===void 0&&(this[N4]=e);let t=this[D4];t&&!t.signal.aborted&&t.abort(e)},[O4](){return this[D4]||=new AbortController,this[N4]!==void 0&&!this[D4].signal.aborted&&this[D4].abort(this[N4]),this[D4]},[S4](){let e=this[O4]();if(this[C4])return this[C4];let t=this.method;if(this[j4]&&t!==`GET`&&t!==`HEAD`){this[k4]=void 0;let n={method:t===`TRACE`?`GET`:t,headers:this.headers,signal:e.signal};t!==`TRACE`&&(n.body=new ReadableStream({start(e){e.close()}}),n.duplex=`half`);let r=new m4(this[T4],n);return t===`TRACE`&&Object.defineProperty(r,"method",{get(){return`TRACE`}}),this[C4]=r}return this[C4]=ske(this.method,this[T4],this.headers,this[w4],e)},get body(){if(!this[j4])return this[S4]().body;let e=this[S4]();return!this[M4]&&e.body&&(this[M4]=e.body.getReader()),e.body},get bodyUsed(){return this[j4]?!0:this[C4]?this[C4].bodyUsed:!1}};Object.defineProperty(R4,"signal",{get(){return this[O4]().signal}}),[`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`keepalive`].forEach(e=>{Object.defineProperty(R4,e,{get(){return this[S4]()[e]}})}),[`clone`,`formData`].forEach(e=>{Object.defineProperty(R4,e,{value:function(){if(this[j4]){if(e===`clone`)throw P4();return F4()}return this[S4]()[e]()}})}),Object.defineProperty(R4,"text",{value:function(){return I4(this,`text`,e=>uke.decode(e))}}),Object.defineProperty(R4,"arrayBuffer",{value:function(){return I4(this,`arrayBuffer`,e=>fke(e))}}),Object.defineProperty(R4,"blob",{value:function(){return I4(this,`blob`,(e,t)=>{let n=pke(t);return new Response(e,n?{headers:{"content-type":n}}:void 0).blob()})}}),Object.defineProperty(R4,"json",{value:function(){return this[j4]?F4():this.text().then(JSON.parse)}}),Object.defineProperty(R4,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[C4]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(R4,m4.prototype);const z4=Symbol(`responseCache`),B4=Symbol(`getResponseCache`),V4=Symbol(`cache`),H4=global.Response;var U4=class e{#e;#t;[B4](){let e=this[V4],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[V4],this[z4]||=new H4(this.#e,t?{status:this.#t?.status,statusText:this.#t?.statusText,headers:t}:this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof H4){let t=n[z4];if(t){this.#t=t,this[B4]();return}this.#t=n instanceof e?n.#t:n,r=new Headers(n.headers)}else this.#t=n;(t==null||typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[V4]=[n?.status||200,t??null,r||n?.headers])}get headers(){let e=this[V4];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":`text/plain; charset=UTF-8`}))),e[2]):this[B4]().headers}get status(){return this[V4]?.[0]??this[B4]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(U4.prototype,e,{get(){return this[B4]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(U4.prototype,e,{value:function(){return this[B4]()[e]()}})}),Object.defineProperty(U4.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[z4]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(U4,H4),Object.setPrototypeOf(U4.prototype,H4.prototype);const vke=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,yke=e=>e instanceof URL?e.href:vke.test(e)?e:new URL(e).href,bke=new Set([301,302,303,307,308]);Object.defineProperty(U4,"redirect",{value:function(e,t=302){if(!bke.has(t))throw RangeError(`Invalid status code`);return new U4(null,{status:t,headers:{location:yke(e)}})},writable:!0,configurable:!0}),Object.defineProperty(U4,"json",{value:function(e,t){let n=JSON.stringify(e);if(n===void 0)throw TypeError(`The data is not JSON serializable`);let r=t?.headers,i;return r?(i=new Headers(r),i.has(`content-type`)||i.set(`content-type`,`application/json`)):i={"content-type":`application/json`},new U4(n,{status:t?.status??200,statusText:t?.statusText,headers:i})},writable:!0,configurable:!0}),globalThis.CloseEvent,globalThis.ErrorEvent,new Response(null,{headers:{"x-hono-already-sent":`true`}});function xke(e,t){let n;try{n=D(e)}catch{return t.map(({editor:e,root:t})=>({host:e,root:t,state:`absent`}))}let r=e=>{let t=N(n,e);if(!(t===``||t.startsWith(`..`)||se(t)))return t.split(ue).join(`/`)};return t.map(({editor:t,root:i})=>{let a=j(e,i),o;try{o=v(a)}catch{return{host:t,root:i,state:`absent`}}let s;try{s=D(a)}catch{return{host:t,root:i,state:`absent`}}if(o.isSymbolicLink()){let e=r(s);return{host:t,root:i,state:`linked`,real:s,...e?{target:e}:{}}}if(s!==j(n,i)){let e=r(s);return{host:t,root:i,state:`linked-parent`,real:s,...e?{target:e}:{}}}return{host:t,root:i,state:`own`,real:s}})}i(((e,t)=>{(function(e){let n=`(0?\\d+|0x[a-f0-9]+)`,r={fourOctet:RegExp(`^${n}\\.${n}\\.${n}\\.${n}$`,`i`),threeOctet:RegExp(`^${n}\\.${n}\\.${n}$`,`i`),twoOctet:RegExp(`^${n}\\.${n}$`,`i`),longValue:RegExp(`^${n}$`,`i`)},i=RegExp(`^0[0-7]+$`,`i`),a=RegExp(`^0x[a-f0-9]+$`,`i`),o=`%[0-9a-z]{1,}`,s=`(?:[0-9a-f]+::?)+`,c={zoneIndex:RegExp(o,`i`),native:RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,`i`),deprecatedTransitional:RegExp(`^(?:::)(${n}\\.${n}\\.${n}\\.${n}(${o})?)$`,`i`),transitional:RegExp(`^((?:${s})|(?:::)(?:${s})?)${n}\\.${n}\\.${n}\\.${n}(${o})?$`,`i`)};function l(e,t){if(e.indexOf(`::`)!==e.lastIndexOf(`::`))return null;let n=0,r=-1,i=(e.match(c.zoneIndex)||[])[0],a,o;for(i&&(i=i.substring(1),e=e.replace(/%.+$/,``));(r=e.indexOf(`:`,r+1))>=0;)n++;if(e.substr(0,2)===`::`&&n--,e.substr(-2,2)===`::`&&n--,n>t)return null;for(o=t-n,a=`:`;o--;)a+=`0:`;return e=e.replace(`::`,a),e[0]===`:`&&(e=e.slice(1)),e[e.length-1]===`:`&&(e=e.slice(0,-1)),t=(function(){let t=e.split(`:`),n=[];for(let e=0;e<t.length;e++)n.push(parseInt(t[e],16));return n})(),{parts:t,zoneId:i}}function u(e,t,n,r){if(e.length!==t.length)throw Error(`ipaddr: cannot match CIDR for objects with different lengths`);let i=0,a;for(;r>0;){if(a=n-r,a<0&&(a=0),e[i]>>a!==t[i]>>a)return!1;r-=n,i+=1}return!0}function d(e){if(a.test(e))return parseInt(e,16);if(e[0]===`0`&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function f(e,t){for(;e.length<t;)e=`0${e}`;return e}let p={};p.IPv4=(function(){function e(e){if(e.length!==4)throw Error(`ipaddr: ipv4 octet count should be 4`);let t,n;for(t=0;t<e.length;t++)if(n=e[t],!(0<=n&&n<=255))throw Error(`ipaddr: ipv4 octet should fit in 8 bits`);this.octets=e}return e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,18,0,0]),15],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]],as112:[[new e([192,175,48,0]),24],[new e([192,31,196,0]),24]],amt:[[new e([192,52,193,0]),24]]},e.prototype.kind=function(){return`ipv4`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv4`)throw Error(`ipaddr: cannot match ipv4 address with non-ipv4 one`);return u(this.octets,e.octets,8,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r,i,a;for(r=3;r>=0;--r)if(i=this.octets[r],i in n){if(a=n[i],t&&a!==0)return null;a!==8&&(t=!0),e+=a}else return null;return 32-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return p.IPv6.parse(`::ffff:${this.toString()}`)},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(`.`)},e})(),p.IPv4.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<4;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.isIPv4=function(e){return this.parser(e)!==null},p.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch{return!1}},p.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv4.isValidFourPartDecimal=function(e){return!!(p.IPv4.isValid(e)&&e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},p.IPv4.isValidCIDRFourPartDecimal=function(e){let t=e.match(/^(.+)\/(\d+)$/);return!p.IPv4.isValidCIDR(e)||!t?!1:p.IPv4.isValidFourPartDecimal(t[1])},p.IPv4.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv4 Address`);return new this(t)},p.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){let e=parseInt(t[2]);if(e>=0&&e<=32){let n=[this.parse(t[1]),e];return Object.defineProperty(n,"toString",{value:function(){return this.join(`/`)}}),n}}throw Error(`ipaddr: string is not formatted like an IPv4 CIDR range`)},p.IPv4.parser=function(e){let t,n,i;if(t=e.match(r.fourOctet))return(function(){let e=t.slice(1,6),r=[];for(let t=0;t<e.length;t++)n=e[t],r.push(d(n));return r})();if(t=e.match(r.longValue)){if(i=d(t[1]),i>4294967295||i<0)throw Error(`ipaddr: address outside defined range`);return(function(){let e=[],t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e})().reverse()}return(t=e.match(r.twoOctet))?(function(){let e=t.slice(1,4),n=[];if(i=d(e[1]),i>16777215||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(i>>16&255),n.push(i>>8&255),n.push(i&255),n})():(t=e.match(r.threeOctet))?(function(){let e=t.slice(1,5),n=[];if(i=d(e[2]),i>65535||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(d(e[1])),n.push(i>>8&255),n.push(i&255),n})():null},p.IPv4.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>32)throw Error(`ipaddr: invalid IPv4 prefix length`);let t=[0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<4&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.IPv6=(function(){function e(e,t){let n,r;if(e.length===16)for(this.parts=[],n=0;n<=14;n+=2)this.parts.push(e[n]<<8|e[n+1]);else if(e.length===8)this.parts=e;else throw Error(`ipaddr: ipv6 part count should be 8 or 16`);for(n=0;n<this.parts.length;n++)if(r=this.parts[n],!(0<=r&&r<=65535))throw Error(`ipaddr: ipv6 part should fit in 16 bits`);t&&(this.zoneId=t)}return e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new e([65216,0,0,0,0,0,0,0]),10],discard:[new e([256,0,0,0,0,0,0,0]),64],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new e([100,65435,0,0,0,0,0,0]),96],[new e([100,65435,1,0,0,0,0,0]),48]],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],benchmarking:[new e([8193,2,0,0,0,0,0,0]),48],amt:[new e([8193,3,0,0,0,0,0,0]),32],as112v6:[[new e([8193,4,274,0,0,0,0,0]),48],[new e([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new e([8193,16,0,0,0,0,0,0]),28],orchid2:[new e([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new e([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new e([24320,0,0,0,0,0,0,0]),16],reserved:[[new e([8193,0,0,0,0,0,0,0]),23],[new e([8193,3512,0,0,0,0,0,0]),32],[new e([16383,0,0,0,0,0,0,0]),20]]},e.prototype.isIPv4MappedAddress=function(){return this.range()===`ipv4Mapped`},e.prototype.kind=function(){return`ipv6`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv6`)throw Error(`ipaddr: cannot match ipv6 address with non-ipv6 one`);return u(this.parts,e.parts,16,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r,i;for(let a=7;a>=0;--a)if(r=this.parts[a],r in n){if(i=n[r],t&&i!==0)return null;i!==16&&(t=!0),e+=i}else return null;return 128-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e,t=[],n=this.parts;for(let r=0;r<n.length;r++)e=n[r],t.push(e>>8),t.push(e&255);return t},e.prototype.toFixedLengthString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(f(this.parts[t].toString(16),4));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error(`ipaddr: trying to convert a generic ipv6 address to ipv4`);let e=this.parts.slice(-2),t=e[0],n=e[1];return new p.IPv4([t>>8,t&255,n>>8,n&255])},e.prototype.toNormalizedString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toRFC5952String=function(){let e=/((^|:)(0(:|$)){2,})/g,t=this.toNormalizedString(),n=0,r=-1,i;for(;i=e.exec(t);)i[0].length>r&&(n=i.index,r=i[0].length);return r<0?t:`${t.substring(0,n)}::${t.substring(n+r)}`},e.prototype.toString=function(){return this.toRFC5952String()},e})(),p.IPv6.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<16;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.isIPv6=function(e){return this.parser(e)!==null},p.IPv6.isValid=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{let t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch{return!1}},p.IPv6.isValidCIDR=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv6.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<16;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.parse=function(e){let t=this.parser(e);if(t.parts===null)throw Error(`ipaddr: string is not formatted like an IPv6 Address`);return new this(t.parts,t.zoneId)},p.IPv6.parseCIDR=function(e){let t,n,r;if((n=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&t<=128))return r=[this.parse(n[1]),t],Object.defineProperty(r,"toString",{value:function(){return this.join(`/`)}}),r;throw Error(`ipaddr: string is not formatted like an IPv6 CIDR range`)},p.IPv6.parser=function(e){let t,n,r,i,a,o;if(r=e.match(c.deprecatedTransitional))return this.parser(`::ffff:${r[1]}`);if(c.native.test(e))return l(e,8);if((r=e.match(c.transitional))&&(o=r[6]||``,t=r[1],r[1].endsWith(`::`)||(t=t.slice(0,-1)),t=l(t+o,6),t.parts)){for(a=[parseInt(r[2]),parseInt(r[3]),parseInt(r[4]),parseInt(r[5])],n=0;n<a.length;n++)if(i=a[n],!(0<=i&&i<=255))return null;return t.parts.push(a[0]<<8|a[1]),t.parts.push(a[2]<<8|a[3]),{parts:t.parts,zoneId:t.zoneId}}return null},p.IPv6.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>128)throw Error(`ipaddr: invalid IPv6 prefix length`);let t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<16&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.fromByteArray=function(e){let t=e.length;if(t===4)return new p.IPv4(e);if(t===16)return new p.IPv6(e);throw Error(`ipaddr: the binary input is neither an IPv6 nor IPv4 address`)},p.isValid=function(e){return p.IPv6.isValid(e)||p.IPv4.isValid(e)},p.isValidCIDR=function(e){return p.IPv6.isValidCIDR(e)||p.IPv4.isValidCIDR(e)},p.parse=function(e){if(p.IPv6.isValid(e))return p.IPv6.parse(e);if(p.IPv4.isValid(e))return p.IPv4.parse(e);throw Error(`ipaddr: the address has neither IPv6 nor IPv4 format`)},p.parseCIDR=function(e){try{return p.IPv6.parseCIDR(e)}catch{try{return p.IPv4.parseCIDR(e)}catch{throw Error(`ipaddr: the address has neither IPv6 nor IPv4 CIDR format`)}}},p.process=function(e){let t=this.parse(e);return t.kind()===`ipv6`&&t.isIPv4MappedAddress()?t.toIPv4Address():t},p.subnetMatch=function(e,t,n){let r,i,a,o;for(i in n??=`unicast`,t)if(Object.prototype.hasOwnProperty.call(t,i)){for(a=t[i],a[0]&&!(a[0]instanceof Array)&&(a=[a]),r=0;r<a.length;r++)if(o=a[r],e.kind()===o[0].kind()&&e.match.apply(e,o))return i}return n},t!==void 0&&t.exports?t.exports=p:e.ipaddr=p})(e)}))();const Ske={"3g2":`video/3gpp2`,"3gp":`video/3gpp`,"3gpp":`video/3gpp`,"3mf":`model/3mf`,aac:`audio/aac`,ac:`application/pkix-attr-cert`,adp:`audio/adpcm`,adts:`audio/aac`,ai:`application/postscript`,aml:`application/automationml-aml+xml`,amlx:`application/automationml-amlx+zip`,amr:`audio/amr`,apng:`image/apng`,appcache:`text/cache-manifest`,appinstaller:`application/appinstaller`,appx:`application/appx`,appxbundle:`application/appxbundle`,asc:`application/pgp-keys`,atom:`application/atom+xml`,atomcat:`application/atomcat+xml`,atomdeleted:`application/atomdeleted+xml`,atomsvc:`application/atomsvc+xml`,au:`audio/basic`,avci:`image/avci`,avcs:`image/avcs`,avif:`image/avif`,aw:`application/applixware`,bdoc:`application/bdoc`,bin:`application/octet-stream`,bmp:`image/bmp`,bpk:`application/octet-stream`,btf:`image/prs.btif`,btif:`image/prs.btif`,buffer:`application/octet-stream`,ccxml:`application/ccxml+xml`,cdfx:`application/cdfx+xml`,cdmia:`application/cdmi-capability`,cdmic:`application/cdmi-container`,cdmid:`application/cdmi-domain`,cdmio:`application/cdmi-object`,cdmiq:`application/cdmi-queue`,cer:`application/pkix-cert`,cgm:`image/cgm`,cjs:`application/node`,class:`application/java-vm`,coffee:`text/coffeescript`,conf:`text/plain`,cpl:`application/cpl+xml`,cpt:`application/mac-compactpro`,crl:`application/pkix-crl`,css:`text/css`,csv:`text/csv`,cu:`application/cu-seeme`,cwl:`application/cwl`,cww:`application/prs.cww`,davmount:`application/davmount+xml`,dbk:`application/docbook+xml`,deb:`application/octet-stream`,def:`text/plain`,deploy:`application/octet-stream`,dib:`image/bmp`,"disposition-notification":`message/disposition-notification`,dist:`application/octet-stream`,distz:`application/octet-stream`,dll:`application/octet-stream`,dmg:`application/octet-stream`,dms:`application/octet-stream`,doc:`application/msword`,dot:`application/msword`,dpx:`image/dpx`,drle:`image/dicom-rle`,dsc:`text/prs.lines.tag`,dssc:`application/dssc+der`,dtd:`application/xml-dtd`,dump:`application/octet-stream`,dwd:`application/atsc-dwd+xml`,ear:`application/java-archive`,ecma:`application/ecmascript`,elc:`application/octet-stream`,emf:`image/emf`,eml:`message/rfc822`,emma:`application/emma+xml`,emotionml:`application/emotionml+xml`,eps:`application/postscript`,epub:`application/epub+zip`,exe:`application/octet-stream`,exi:`application/exi`,exp:`application/express`,exr:`image/aces`,ez:`application/andrew-inset`,fdf:`application/fdf`,fdt:`application/fdt+xml`,fits:`image/fits`,g3:`image/g3fax`,gbr:`application/rpki-ghostbusters`,geojson:`application/geo+json`,gif:`image/gif`,glb:`model/gltf-binary`,gltf:`model/gltf+json`,gml:`application/gml+xml`,gpx:`application/gpx+xml`,gram:`application/srgs`,grxml:`application/srgs+xml`,gxf:`application/gxf`,gz:`application/gzip`,h261:`video/h261`,h263:`video/h263`,h264:`video/h264`,heic:`image/heic`,heics:`image/heic-sequence`,heif:`image/heif`,heifs:`image/heif-sequence`,hej2:`image/hej2k`,held:`application/atsc-held+xml`,hjson:`application/hjson`,hlp:`application/winhlp`,hqx:`application/mac-binhex40`,hsj2:`image/hsj2`,htm:`text/html`,html:`text/html`,ics:`text/calendar`,ief:`image/ief`,ifb:`text/calendar`,iges:`model/iges`,igs:`model/iges`,img:`application/octet-stream`,in:`text/plain`,ini:`text/plain`,ink:`application/inkml+xml`,inkml:`application/inkml+xml`,ipfix:`application/ipfix`,iso:`application/octet-stream`,its:`application/its+xml`,jade:`text/jade`,jar:`application/java-archive`,jhc:`image/jphc`,jls:`image/jls`,jp2:`image/jp2`,jpe:`image/jpeg`,jpeg:`image/jpeg`,jpf:`image/jpx`,jpg:`image/jpeg`,jpg2:`image/jp2`,jpgm:`image/jpm`,jpgv:`video/jpeg`,jph:`image/jph`,jpm:`image/jpm`,jpx:`image/jpx`,js:`text/javascript`,json:`application/json`,json5:`application/json5`,jsonld:`application/ld+json`,jsonml:`application/jsonml+json`,jsx:`text/jsx`,jt:`model/jt`,jxl:`image/jxl`,jxr:`image/jxr`,jxra:`image/jxra`,jxrs:`image/jxrs`,jxs:`image/jxs`,jxsc:`image/jxsc`,jxsi:`image/jxsi`,jxss:`image/jxss`,kar:`audio/midi`,ktx:`image/ktx`,ktx2:`image/ktx2`,less:`text/less`,lgr:`application/lgr+xml`,list:`text/plain`,litcoffee:`text/coffeescript`,log:`text/plain`,lostxml:`application/lost+xml`,lrf:`application/octet-stream`,m1v:`video/mpeg`,m21:`application/mp21`,m2a:`audio/mpeg`,m2t:`video/mp2t`,m2ts:`video/mp2t`,m2v:`video/mpeg`,m3a:`audio/mpeg`,m4a:`audio/mp4`,m4p:`application/mp4`,m4s:`video/iso.segment`,ma:`application/mathematica`,mads:`application/mads+xml`,maei:`application/mmt-aei+xml`,man:`text/troff`,manifest:`text/cache-manifest`,map:`application/json`,mar:`application/octet-stream`,markdown:`text/markdown`,mathml:`application/mathml+xml`,mb:`application/mathematica`,mbox:`application/mbox`,md:`text/markdown`,mdx:`text/mdx`,me:`text/troff`,mesh:`model/mesh`,meta4:`application/metalink4+xml`,metalink:`application/metalink+xml`,mets:`application/mets+xml`,mft:`application/rpki-manifest`,mid:`audio/midi`,midi:`audio/midi`,mime:`message/rfc822`,mj2:`video/mj2`,mjp2:`video/mj2`,mjs:`text/javascript`,mml:`text/mathml`,mods:`application/mods+xml`,mov:`video/quicktime`,mp2:`audio/mpeg`,mp21:`application/mp21`,mp2a:`audio/mpeg`,mp3:`audio/mpeg`,mp4:`video/mp4`,mp4a:`audio/mp4`,mp4s:`application/mp4`,mp4v:`video/mp4`,mpd:`application/dash+xml`,mpe:`video/mpeg`,mpeg:`video/mpeg`,mpf:`application/media-policy-dataset+xml`,mpg:`video/mpeg`,mpg4:`video/mp4`,mpga:`audio/mpeg`,mpp:`application/dash-patch+xml`,mrc:`application/marc`,mrcx:`application/marcxml+xml`,ms:`text/troff`,mscml:`application/mediaservercontrol+xml`,msh:`model/mesh`,msi:`application/octet-stream`,msix:`application/msix`,msixbundle:`application/msixbundle`,msm:`application/octet-stream`,msp:`application/octet-stream`,mtl:`model/mtl`,mts:`video/mp2t`,musd:`application/mmt-usd+xml`,mxf:`application/mxf`,mxmf:`audio/mobile-xmf`,mxml:`application/xv+xml`,n3:`text/n3`,nb:`application/mathematica`,nq:`application/n-quads`,nt:`application/n-triples`,obj:`model/obj`,oda:`application/oda`,oga:`audio/ogg`,ogg:`audio/ogg`,ogv:`video/ogg`,ogx:`application/ogg`,omdoc:`application/omdoc+xml`,onepkg:`application/onenote`,onetmp:`application/onenote`,onetoc:`application/onenote`,onetoc2:`application/onenote`,opf:`application/oebps-package+xml`,opus:`audio/ogg`,otf:`font/otf`,owl:`application/rdf+xml`,oxps:`application/oxps`,p10:`application/pkcs10`,p7c:`application/pkcs7-mime`,p7m:`application/pkcs7-mime`,p7s:`application/pkcs7-signature`,p8:`application/pkcs8`,pdf:`application/pdf`,pfr:`application/font-tdpfr`,pgp:`application/pgp-encrypted`,pkg:`application/octet-stream`,pki:`application/pkixcmp`,pkipath:`application/pkix-pkipath`,pls:`application/pls+xml`,png:`image/png`,prc:`model/prc`,prf:`application/pics-rules`,provx:`application/provenance+xml`,ps:`application/postscript`,pskcxml:`application/pskc+xml`,pti:`image/prs.pti`,qt:`video/quicktime`,raml:`application/raml+yaml`,rapd:`application/route-apd+xml`,rdf:`application/rdf+xml`,relo:`application/p2p-overlay+xml`,rif:`application/reginfo+xml`,rl:`application/resource-lists+xml`,rld:`application/resource-lists-diff+xml`,rmi:`audio/midi`,rnc:`application/relax-ng-compact-syntax`,rng:`application/xml`,roa:`application/rpki-roa`,roff:`text/troff`,rq:`application/sparql-query`,rs:`application/rls-services+xml`,rsat:`application/atsc-rsat+xml`,rsd:`application/rsd+xml`,rsheet:`application/urc-ressheet+xml`,rss:`application/rss+xml`,rtf:`text/rtf`,rtx:`text/richtext`,rusd:`application/route-usd+xml`,s3m:`audio/s3m`,sbml:`application/sbml+xml`,scq:`application/scvp-cv-request`,scs:`application/scvp-cv-response`,sdp:`application/sdp`,senmlx:`application/senml+xml`,sensmlx:`application/sensml+xml`,ser:`application/java-serialized-object`,setpay:`application/set-payment-initiation`,setreg:`application/set-registration-initiation`,sgi:`image/sgi`,sgm:`text/sgml`,sgml:`text/sgml`,shex:`text/shex`,shf:`application/shf+xml`,shtml:`text/html`,sieve:`application/sieve`,sig:`application/pgp-signature`,sil:`audio/silk`,silo:`model/mesh`,siv:`application/sieve`,slim:`text/slim`,slm:`text/slim`,sls:`application/route-s-tsid+xml`,smi:`application/smil+xml`,smil:`application/smil+xml`,snd:`audio/basic`,so:`application/octet-stream`,spdx:`text/spdx`,spp:`application/scvp-vp-response`,spq:`application/scvp-vp-request`,spx:`audio/ogg`,sql:`application/sql`,sru:`application/sru+xml`,srx:`application/sparql-results+xml`,ssdl:`application/ssdl+xml`,ssml:`application/ssml+xml`,stk:`application/hyperstudio`,stl:`model/stl`,stpx:`model/step+xml`,stpxz:`model/step-xml+zip`,stpz:`model/step+zip`,styl:`text/stylus`,stylus:`text/stylus`,svg:`image/svg+xml`,svgz:`image/svg+xml`,swidtag:`application/swid+xml`,t:`text/troff`,t38:`image/t38`,td:`application/urc-targetdesc+xml`,tei:`application/tei+xml`,teicorpus:`application/tei+xml`,text:`text/plain`,tfi:`application/thraud+xml`,tfx:`image/tiff-fx`,tif:`image/tiff`,tiff:`image/tiff`,toml:`application/toml`,tr:`text/troff`,trig:`application/trig`,ts:`video/mp2t`,tsd:`application/timestamped-data`,tsv:`text/tab-separated-values`,ttc:`font/collection`,ttf:`font/ttf`,ttl:`text/turtle`,ttml:`application/ttml+xml`,txt:`text/plain`,u3d:`model/u3d`,u8dsn:`message/global-delivery-status`,u8hdr:`message/global-headers`,u8mdn:`message/global-disposition-notification`,u8msg:`message/global`,ubj:`application/ubjson`,uri:`text/uri-list`,uris:`text/uri-list`,urls:`text/uri-list`,vcard:`text/vcard`,vrml:`model/vrml`,vtt:`text/vtt`,vxml:`application/voicexml+xml`,war:`application/java-archive`,wasm:`application/wasm`,wav:`audio/wav`,weba:`audio/webm`,webm:`video/webm`,webmanifest:`application/manifest+json`,webp:`image/webp`,wgsl:`text/wgsl`,wgt:`application/widget`,wif:`application/watcherinfo+xml`,wmf:`image/wmf`,woff:`font/woff`,woff2:`font/woff2`,wrl:`model/vrml`,wsdl:`application/wsdl+xml`,wspolicy:`application/wspolicy+xml`,x3d:`model/x3d+xml`,x3db:`model/x3d+fastinfoset`,x3dbz:`model/x3d+binary`,x3dv:`model/x3d-vrml`,x3dvz:`model/x3d+vrml`,x3dz:`model/x3d+xml`,xaml:`application/xaml+xml`,xav:`application/xcap-att+xml`,xca:`application/xcap-caps+xml`,xcs:`application/calendar+xml`,xdf:`application/xcap-diff+xml`,xdssc:`application/dssc+xml`,xel:`application/xcap-el+xml`,xenc:`application/xenc+xml`,xer:`application/patch-ops-error+xml`,xfdf:`application/xfdf`,xht:`application/xhtml+xml`,xhtml:`application/xhtml+xml`,xhvml:`application/xv+xml`,xlf:`application/xliff+xml`,xm:`audio/xm`,xml:`text/xml`,xns:`application/xcap-ns+xml`,xop:`application/xop+xml`,xpl:`application/xproc+xml`,xsd:`application/xml`,xsf:`application/prs.xsf+xml`,xsl:`application/xml`,xslt:`application/xml`,xspf:`application/xspf+xml`,xvm:`application/xv+xml`,xvml:`application/xv+xml`,yaml:`text/yaml`,yang:`application/yang`,yin:`application/yin+xml`,yml:`text/yaml`,zip:`application/zip`},W4=ma(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),G4=ea([I(),L().int()]),K4=I();Qi({ttl:L().optional(),pollInterval:L().optional()});const Cke=V({ttl:L().optional()}),wke=V({taskId:I()}),q4=Qi({progressToken:G4.optional(),"io.modelcontextprotocol/related-task":wke.optional()}),J4=V({_meta:q4.optional()}),Y4=J4.extend({task:Cke.optional()}),X4=V({method:I(),params:J4.loose().optional()}),Z4=V({_meta:q4.optional()}),Q4=V({method:I(),params:Z4.loose().optional()}),$4=Qi({_meta:q4.optional()}),e3=ea([I(),L().int()]),Tke=V({jsonrpc:W(`2.0`),id:e3,...X4.shape}).strict(),Eke=V({jsonrpc:W(`2.0`),...Q4.shape}).strict(),t3=V({jsonrpc:W(`2.0`),id:e3,result:$4}).strict();var Dke;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Dke||={});const n3=V({jsonrpc:W(`2.0`),id:e3.optional(),error:V({code:L().int(),message:I(),data:z().optional()})}).strict();ea([Tke,Eke,t3,n3]),ea([t3,n3]);const r3=$4.strict(),Oke=Z4.extend({requestId:e3.optional(),reason:I().optional()}),i3=Q4.extend({method:W(`notifications/cancelled`),params:Oke}),a3=V({icons:B(V({src:I(),mimeType:I().optional(),sizes:B(I()).optional(),theme:U([`light`,`dark`]).optional()})).optional()}),o3=V({name:I(),title:I().optional()}),s3=o3.extend({...o3.shape,...a3.shape,version:I(),websiteUrl:I().optional(),description:I().optional()}),kke=ha(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,na(V({form:na(V({applyDefaults:R().optional()}),H(I(),z())).optional(),url:W4.optional()}),H(I(),z()).optional())),Ake=Qi({list:W4.optional(),cancel:W4.optional(),requests:Qi({sampling:Qi({createMessage:W4.optional()}).optional(),elicitation:Qi({create:W4.optional()}).optional()}).optional()}),jke=Qi({list:W4.optional(),cancel:W4.optional(),requests:Qi({tools:Qi({call:W4.optional()}).optional()}).optional()}),Mke=V({experimental:H(I(),W4).optional(),sampling:V({context:W4.optional(),tools:W4.optional()}).optional(),elicitation:kke.optional(),roots:V({listChanged:R().optional()}).optional(),tasks:Ake.optional(),extensions:H(I(),W4).optional()}),Nke=J4.extend({protocolVersion:I(),capabilities:Mke,clientInfo:s3}),Pke=X4.extend({method:W(`initialize`),params:Nke}),Fke=V({experimental:H(I(),W4).optional(),logging:W4.optional(),completions:W4.optional(),prompts:V({listChanged:R().optional()}).optional(),resources:V({subscribe:R().optional(),listChanged:R().optional()}).optional(),tools:V({listChanged:R().optional()}).optional(),tasks:jke.optional(),extensions:H(I(),W4).optional()}),Ike=$4.extend({protocolVersion:I(),capabilities:Fke,serverInfo:s3,instructions:I().optional()}),Lke=Q4.extend({method:W(`notifications/initialized`),params:Z4.optional()}),c3=X4.extend({method:W(`ping`),params:J4.optional()}),Rke=V({progress:L(),total:sa(L()),message:sa(I())}),zke=V({...Z4.shape,...Rke.shape,progressToken:G4}),l3=Q4.extend({method:W(`notifications/progress`),params:zke}),Bke=J4.extend({cursor:K4.optional()}),u3=X4.extend({params:Bke.optional()}),d3=$4.extend({nextCursor:K4.optional()}),Vke=U([`working`,`input_required`,`completed`,`failed`,`cancelled`]),f3=V({taskId:I(),status:Vke,ttl:ea([L(),Ji()]),createdAt:I(),lastUpdatedAt:I(),pollInterval:sa(L()),statusMessage:sa(I())}),p3=$4.extend({task:f3}),Hke=Z4.merge(f3),m3=Q4.extend({method:W(`notifications/tasks/status`),params:Hke}),h3=X4.extend({method:W(`tasks/get`),params:J4.extend({taskId:I()})}),g3=$4.merge(f3),_3=X4.extend({method:W(`tasks/result`),params:J4.extend({taskId:I()})});$4.loose();const v3=u3.extend({method:W(`tasks/list`)}),y3=d3.extend({tasks:B(f3)}),b3=X4.extend({method:W(`tasks/cancel`),params:J4.extend({taskId:I()})});$4.merge(f3);const x3=V({uri:I(),mimeType:sa(I()),_meta:H(I(),z()).optional()}),S3=x3.extend({text:I()}),C3=I().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),w3=x3.extend({blob:C3}),T3=U([`user`,`assistant`]),E3=V({audience:B(T3).optional(),priority:L().min(0).max(1).optional(),lastModified:Di({offset:!0}).optional()}),D3=V({...o3.shape,...a3.shape,uri:I(),description:sa(I()),mimeType:sa(I()),size:sa(L()),annotations:E3.optional(),_meta:sa(Qi({}))}),Uke=V({...o3.shape,...a3.shape,uriTemplate:I(),description:sa(I()),mimeType:sa(I()),annotations:E3.optional(),_meta:sa(Qi({}))}),Wke=u3.extend({method:W(`resources/list`)}),Gke=d3.extend({resources:B(D3)}),Kke=u3.extend({method:W(`resources/templates/list`)}),qke=d3.extend({resourceTemplates:B(Uke)}),O3=J4.extend({uri:I()}),Jke=O3,Yke=X4.extend({method:W(`resources/read`),params:Jke}),Xke=$4.extend({contents:B(ea([S3,w3]))}),Zke=Q4.extend({method:W(`notifications/resources/list_changed`),params:Z4.optional()}),Qke=O3,$ke=X4.extend({method:W(`resources/subscribe`),params:Qke}),eAe=O3,tAe=X4.extend({method:W(`resources/unsubscribe`),params:eAe}),nAe=Z4.extend({uri:I()}),rAe=Q4.extend({method:W(`notifications/resources/updated`),params:nAe}),iAe=V({name:I(),description:sa(I()),required:sa(R())}),aAe=V({...o3.shape,...a3.shape,description:sa(I()),arguments:sa(B(iAe)),_meta:sa(Qi({}))}),oAe=u3.extend({method:W(`prompts/list`)}),sAe=d3.extend({prompts:B(aAe)}),cAe=J4.extend({name:I(),arguments:H(I(),I()).optional()}),lAe=X4.extend({method:W(`prompts/get`),params:cAe}),k3=V({type:W(`text`),text:I(),annotations:E3.optional(),_meta:H(I(),z()).optional()}),A3=V({type:W(`image`),data:C3,mimeType:I(),annotations:E3.optional(),_meta:H(I(),z()).optional()}),j3=V({type:W(`audio`),data:C3,mimeType:I(),annotations:E3.optional(),_meta:H(I(),z()).optional()}),uAe=V({type:W(`tool_use`),name:I(),id:I(),input:H(I(),z()),_meta:H(I(),z()).optional()}),dAe=V({type:W(`resource`),resource:ea([S3,w3]),annotations:E3.optional(),_meta:H(I(),z()).optional()}),M3=ea([k3,A3,j3,D3.extend({type:W(`resource_link`)}),dAe]),fAe=V({role:T3,content:M3}),pAe=$4.extend({description:I().optional(),messages:B(fAe)}),mAe=Q4.extend({method:W(`notifications/prompts/list_changed`),params:Z4.optional()}),hAe=V({title:I().optional(),readOnlyHint:R().optional(),destructiveHint:R().optional(),idempotentHint:R().optional(),openWorldHint:R().optional()}),gAe=V({taskSupport:U([`required`,`optional`,`forbidden`]).optional()}),N3=V({...o3.shape,...a3.shape,description:I().optional(),inputSchema:V({type:W(`object`),properties:H(I(),W4).optional(),required:B(I()).optional()}).catchall(z()),outputSchema:V({type:W(`object`),properties:H(I(),W4).optional(),required:B(I()).optional()}).catchall(z()).optional(),annotations:hAe.optional(),execution:gAe.optional(),_meta:H(I(),z()).optional()}),_Ae=u3.extend({method:W(`tools/list`)}),vAe=d3.extend({tools:B(N3)}),P3=$4.extend({content:B(M3).default([]),structuredContent:H(I(),z()).optional(),isError:R().optional()});P3.or($4.extend({toolResult:z()}));const yAe=Y4.extend({name:I(),arguments:H(I(),z()).optional()}),bAe=X4.extend({method:W(`tools/call`),params:yAe}),xAe=Q4.extend({method:W(`notifications/tools/list_changed`),params:Z4.optional()});V({autoRefresh:R().default(!0),debounceMs:L().int().nonnegative().default(300)});const F3=U([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),SAe=J4.extend({level:F3}),CAe=X4.extend({method:W(`logging/setLevel`),params:SAe}),wAe=Z4.extend({level:F3,logger:I().optional(),data:z()}),TAe=Q4.extend({method:W(`notifications/message`),params:wAe}),EAe=V({hints:B(V({name:I().optional()})).optional(),costPriority:L().min(0).max(1).optional(),speedPriority:L().min(0).max(1).optional(),intelligencePriority:L().min(0).max(1).optional()}),DAe=V({mode:U([`auto`,`required`,`none`]).optional()}),OAe=V({type:W(`tool_result`),toolUseId:I().describe(`The unique identifier for the corresponding tool call.`),content:B(M3).default([]),structuredContent:V({}).loose().optional(),isError:R().optional(),_meta:H(I(),z()).optional()}),kAe=ta(`type`,[k3,A3,j3]),I3=ta(`type`,[k3,A3,j3,uAe,OAe]),AAe=V({role:T3,content:ea([I3,B(I3)]),_meta:H(I(),z()).optional()}),jAe=Y4.extend({messages:B(AAe),modelPreferences:EAe.optional(),systemPrompt:I().optional(),includeContext:U([`none`,`thisServer`,`allServers`]).optional(),temperature:L().optional(),maxTokens:L().int(),stopSequences:B(I()).optional(),metadata:W4.optional(),tools:B(N3).optional(),toolChoice:DAe.optional()}),MAe=X4.extend({method:W(`sampling/createMessage`),params:jAe}),NAe=$4.extend({model:I(),stopReason:sa(U([`endTurn`,`stopSequence`,`maxTokens`]).or(I())),role:T3,content:kAe}),PAe=$4.extend({model:I(),stopReason:sa(U([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(I())),role:T3,content:ea([I3,B(I3)])}),FAe=V({type:W(`boolean`),title:I().optional(),description:I().optional(),default:R().optional()}),IAe=V({type:W(`string`),title:I().optional(),description:I().optional(),minLength:L().optional(),maxLength:L().optional(),format:U([`email`,`uri`,`date`,`date-time`]).optional(),default:I().optional()}),LAe=V({type:U([`number`,`integer`]),title:I().optional(),description:I().optional(),minimum:L().optional(),maximum:L().optional(),default:L().optional()}),RAe=V({type:W(`string`),title:I().optional(),description:I().optional(),enum:B(I()),default:I().optional()}),zAe=V({type:W(`string`),title:I().optional(),description:I().optional(),oneOf:B(V({const:I(),title:I()})),default:I().optional()}),BAe=ea([ea([V({type:W(`string`),title:I().optional(),description:I().optional(),enum:B(I()),enumNames:B(I()).optional(),default:I().optional()}),ea([RAe,zAe]),ea([V({type:W(`array`),title:I().optional(),description:I().optional(),minItems:L().optional(),maxItems:L().optional(),items:V({type:W(`string`),enum:B(I())}),default:B(I()).optional()}),V({type:W(`array`),title:I().optional(),description:I().optional(),minItems:L().optional(),maxItems:L().optional(),items:V({anyOf:B(V({const:I(),title:I()}))}),default:B(I()).optional()})])]),FAe,IAe,LAe]),VAe=ea([Y4.extend({mode:W(`form`).optional(),message:I(),requestedSchema:V({type:W(`object`),properties:H(I(),BAe),required:B(I()).optional()})}),Y4.extend({mode:W(`url`),message:I(),elicitationId:I(),url:I().url()})]),HAe=X4.extend({method:W(`elicitation/create`),params:VAe}),UAe=Z4.extend({elicitationId:I()}),WAe=Q4.extend({method:W(`notifications/elicitation/complete`),params:UAe}),GAe=$4.extend({action:U([`accept`,`decline`,`cancel`]),content:ha(e=>e===null?void 0:e,H(I(),ea([I(),L(),R(),B(I())])).optional())}),KAe=V({type:W(`ref/resource`),uri:I()}),qAe=V({type:W(`ref/prompt`),name:I()}),JAe=J4.extend({ref:ea([qAe,KAe]),argument:V({name:I(),value:I()}),context:V({arguments:H(I(),I()).optional()}).optional()}),YAe=X4.extend({method:W(`completion/complete`),params:JAe}),XAe=$4.extend({completion:Qi({values:B(I()).max(100),total:sa(L().int()),hasMore:sa(R())})}),ZAe=V({uri:I().startsWith(`file://`),name:I().optional(),_meta:H(I(),z()).optional()}),QAe=X4.extend({method:W(`roots/list`),params:J4.optional()}),$Ae=$4.extend({roots:B(ZAe)}),eje=Q4.extend({method:W(`notifications/roots/list_changed`),params:Z4.optional()});ea([c3,Pke,YAe,CAe,lAe,oAe,Wke,Kke,Yke,$ke,tAe,bAe,_Ae,h3,_3,v3,b3]),ea([i3,l3,Lke,eje,m3]),ea([r3,NAe,PAe,GAe,$Ae,g3,y3,p3]),ea([c3,MAe,HAe,QAe,h3,_3,v3,b3]),ea([i3,l3,TAe,rAe,Zke,xAe,mAe,m3,WAe]),ea([r3,Ike,XAe,pAe,sAe,Gke,qke,Xke,P3,vAe,g3,y3,p3]);var tje;(function(e){e.Completable=`McpCompletable`})(tje||={});var nje=global.Request,L3=class extends nje{constructor(e,t){typeof e==`object`&&R3 in e&&(e=e[R3]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},rje=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},ije=Symbol(`wrapBodyStream`),aje=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new L3(t,a);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[ije]){let e;a.body=new ReadableStream({async pull(t){try{e||=Be.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=Be.toWeb(r)}return new L3(t,a)},R3=Symbol(`getRequestCache`),z3=Symbol(`requestCache`),B3=Symbol(`incomingKey`),V3=Symbol(`urlKey`),oje=Symbol(`headersKey`),H3=Symbol(`abortControllerKey`),U3={get method(){return this[B3].method||`GET`},get url(){return this[V3]},get headers(){return this[oje]||=rje(this[B3])},[Symbol(`getAbortController`)](){return this[R3](),this[H3]},[R3](){return this[H3]||=new AbortController,this[z3]||=aje(this.method,this[V3],this.headers,this[B3],this[H3])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(U3,e,{get(){return this[R3]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(U3,e,{value:function(){return this[R3]()[e]()}})}),Object.defineProperty(U3,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[z3]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(U3,L3.prototype);var W3=Symbol(`responseCache`),G3=Symbol(`getResponseCache`),K3=Symbol(`cache`),q3=global.Response,J3=class e{#e;#t;[G3](){return delete this[K3],this[W3]||=new q3(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[W3];if(e){this.#t=e,this[G3]();return}this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[K3]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[K3];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[G3]().headers}get status(){return this[K3]?.[0]??this[G3]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(J3.prototype,e,{get(){return this[G3]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(J3.prototype,e,{value:function(){return this[G3]()[e]()}})}),Object.defineProperty(J3.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[W3]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(J3,q3),Object.setPrototypeOf(J3.prototype,q3.prototype),global.crypto===void 0&&(global.crypto=ze);var sje=i(((e,t)=>{var n=[`||`,`&&`,`;;`,`|&`,`<(`,`<<<`,`>>`,`>&`,`<&`,`&`,`;`,`(`,`)`,`|`,`<`,`>`],r=/[\n\r\u2028\u2029]/,i=/[\s#!"$&'():;<=>@\\^`|]/g;t.exports=function(e){return e.map(function(e){if(e===``)return`''`;if(e&&typeof e==`object`){if(`op`in e&&e.op===`glob`){if(typeof e.pattern!=`string`)throw TypeError("glob token requires a string `pattern`");if(r.test(e.pattern))throw TypeError("glob `pattern` must not contain line terminators");return e.pattern.replace(i,`\\$&`)}if(`op`in e&&typeof e.op==`string`){if(n.indexOf(e.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(e.op));return e.op.replace(/[\s\S]/g,`\\$&`)}if(`comment`in e&&typeof e.comment==`string`){if(r.test(e.comment))throw TypeError("`comment` must not contain line terminators");return`#`+e.comment}throw TypeError(`unrecognized object token shape`)}return/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,`$1\\$2`)}).join(` `)}})),cje=i(((e,t)=>{for(var n=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,r=RegExp(`^`+n+`$`),i=`|&;()<> \\t`,a=`'([^']*?)'`,o=`"((\\\\"|[^"])*?)"`,s=/^#$/,c=`'`,l=`"`,u=`$`,d=``,f=4294967296,p=0;p<4;p++)d+=(f*Math.random()).toString(16);var m=RegExp(`^`+d);function h(e,t){for(var n=t.lastIndex,r=[],i;i=t.exec(e);)r[r.length]=i,t.lastIndex===i.index&&(t.lastIndex+=1);return t.lastIndex=n,r}function g(e,t,n){var r=typeof e==`function`?e(n):e[n];return r===void 0&&n!=``?r=``:r===void 0&&(r=`$`),typeof r==`object`?t+d+JSON.stringify(r)+d:t+r}function _(e,t,d){d||={};var f=d.escape||`\\`,p=d.splitUnquoted===!0?`
|
|
747
747
|
`:typeof d.splitUnquoted==`string`?d.splitUnquoted:``,m=`(\\`+f+`['"`+i+`]|[^\\s'"`+i+`])+`,_=h(e,new RegExp([`(`+n+`)`,`(`+m+`|`+o+`|`+a+`)+`].join(`|`),`g`));if(_.length===0)return[];t||={};var v=!1;return _.map(function(n){var i=n[0];if(!i||v)return;if(r.test(i))return{op:i};var a=!1,o=!1,d=``,m=[],h=!1,_=null,y=!1,b;function x(){b+=1;var e,n,r=i.charAt(b);if(r===`{`){if(b+=1,i.charAt(b)===`}`)throw Error(`Bad substitution: `+i.slice(b-2,b+1));var a=1;for(e=b;a>0&&e<i.length;)i.charAt(e)===`{`&&i.charAt(e-1)===`$`?a+=1:i.charAt(e)===`}`&&--a,e+=1;if(a!==0)throw Error(`Bad substitution: `+i.slice(b));--e,n=i.slice(b,e),b=e}else if(/[*@#?$!_-]/.test(r))n=r,b+=1;else{var o=i.slice(b);e=o.match(/[^\w\d_]/),e?(n=o.slice(0,e.index),b+=e.index-1):(n=o,b=i.length)}return g(t,``,n)}function S(){if(_!==null){if(_===0)d!==``&&(m[m.length]=d,d=``);else{m[m.length]=d,d=``;for(var e=1;e<_;e+=1)m[m.length]=``}_=null}}for(b=0;b<i.length;b++){var C=i.charAt(b);if(p&&C!==u&&S(),y||=!a&&(C===`*`||C===`?`),o)d+=C,o=!1;else if(a)C===a?a=!1:a==c?d+=C:C===f?(b+=1,C=i.charAt(b),d+=C===l||C===f||C===u?C:f+C):d+=C===u?x():C;else if(C===l||C===c)a=C,h=!0;else if(r.test(C))return{op:i};else if(s.test(C)){v=!0;var w={comment:e.slice(n.index+b+1)};return d.length?[d,w]:[w]}else if(C===f)o=!0;else if(C===u){var T=x();if(!p)d+=T;else for(var E=0;E<T.length;E+=1){var D=T.charAt(E);p.indexOf(D)<0?(S(),d+=D):_===null?_=D===` `||D===` `||D===`
|
|
748
748
|
`?0:1:D!==` `&&D!==` `&&D!==`
|
|
749
|
-
`&&(_+=1)}}else d+=C}if(y)return{op:`glob`,pattern:d};if(p){if(_!==null&&_>0){m[m.length]=d,d=``;for(var ee=1;ee<_;ee+=1)m[m.length]=``}return(d!==``||h&&m.length===0)&&(m[m.length]=d),m}return d}).reduce(function(e,t){return t===void 0||[].concat(t).forEach(function(t){e[e.length]=t}),e},[])}t.exports=function(e,t,n){var r=_(e,t,n);return typeof t==`function`?r.reduce(function(e,t){if(typeof t==`object`)return e[e.length]=t,e;var n=t.split(RegExp(`(`+d+`.*?`+d+`)`,`g`));return n.length===1?(e[e.length]=n[0],e):(n.filter(Boolean).forEach(function(t){e[e.length]=m.test(t)?JSON.parse(t.split(d)[1]):t}),e)},[]):r}}));i((e=>{e.quote=sje(),e.parse=cje()}))();var Y3;(function(e){e.EOF=`EOF`,e.NEWLINE=`NEWLINE`,e.SEMICOLON=`SEMICOLON`,e.AMP=`AMP`,e.PIPE=`PIPE`,e.PIPE_AMP=`PIPE_AMP`,e.AND_AND=`AND_AND`,e.OR_OR=`OR_OR`,e.BANG=`BANG`,e.LESS=`LESS`,e.GREAT=`GREAT`,e.DLESS=`DLESS`,e.DGREAT=`DGREAT`,e.LESSAND=`LESSAND`,e.GREATAND=`GREATAND`,e.LESSGREAT=`LESSGREAT`,e.DLESSDASH=`DLESSDASH`,e.CLOBBER=`CLOBBER`,e.TLESS=`TLESS`,e.AND_GREAT=`AND_GREAT`,e.AND_DGREAT=`AND_DGREAT`,e.LPAREN=`LPAREN`,e.RPAREN=`RPAREN`,e.LBRACE=`LBRACE`,e.RBRACE=`RBRACE`,e.DSEMI=`DSEMI`,e.SEMI_AND=`SEMI_AND`,e.SEMI_SEMI_AND=`SEMI_SEMI_AND`,e.DBRACK_START=`DBRACK_START`,e.DBRACK_END=`DBRACK_END`,e.DPAREN_START=`DPAREN_START`,e.DPAREN_END=`DPAREN_END`,e.IF=`IF`,e.THEN=`THEN`,e.ELSE=`ELSE`,e.ELIF=`ELIF`,e.FI=`FI`,e.FOR=`FOR`,e.WHILE=`WHILE`,e.UNTIL=`UNTIL`,e.DO=`DO`,e.DONE=`DONE`,e.CASE=`CASE`,e.ESAC=`ESAC`,e.IN=`IN`,e.FUNCTION=`FUNCTION`,e.SELECT=`SELECT`,e.TIME=`TIME`,e.COPROC=`COPROC`,e.WORD=`WORD`,e.NAME=`NAME`,e.NUMBER=`NUMBER`,e.ASSIGNMENT_WORD=`ASSIGNMENT_WORD`,e.FD_VARIABLE=`FD_VARIABLE`,e.COMMENT=`COMMENT`,e.HEREDOC_CONTENT=`HEREDOC_CONTENT`})(Y3||={}),Y3.IF,Y3.THEN,Y3.ELSE,Y3.ELIF,Y3.FI,Y3.FOR,Y3.WHILE,Y3.UNTIL,Y3.DO,Y3.DONE,Y3.CASE,Y3.ESAC,Y3.IN,Y3.FUNCTION,Y3.SELECT,Y3.TIME,Y3.COPROC,Y3.SEMI_SEMI_AND,Y3.TLESS,Y3.AND_DGREAT,Y3.DBRACK_START,Y3.DBRACK_END,Y3.DPAREN_START,Y3.DPAREN_END,Y3.AND_AND,Y3.OR_OR,Y3.DSEMI,Y3.SEMI_AND,Y3.PIPE_AMP,Y3.DGREAT,Y3.LESSAND,Y3.GREATAND,Y3.LESSGREAT,Y3.CLOBBER,Y3.AND_GREAT,Y3.PIPE,Y3.AMP,Y3.SEMICOLON,Y3.LPAREN,Y3.RPAREN,Y3.LESS,Y3.GREAT,Y3.LESS,Y3.GREAT,Y3.DLESS,Y3.DGREAT,Y3.LESSAND,Y3.GREATAND,Y3.LESSGREAT,Y3.DLESSDASH,Y3.CLOBBER,Y3.TLESS,Y3.AND_GREAT,Y3.AND_DGREAT,Y3.LESS,Y3.GREAT,Y3.DLESS,Y3.DGREAT,Y3.LESSAND,Y3.GREATAND,Y3.LESSGREAT,Y3.DLESSDASH,Y3.CLOBBER,Y3.TLESS,Y3.LESS,Y3.GREAT,Y3.DLESS,Y3.DGREAT,Y3.LESSAND,Y3.GREATAND,Y3.LESSGREAT,Y3.DLESSDASH,Y3.CLOBBER,Y3.TLESS,Y3.AND_GREAT,Y3.AND_DGREAT,Y3.AMP,Y3.PIPE,Y3.PIPE_AMP,Y3.SEMICOLON,Y3.AND_AND,Y3.OR_OR,Y3.DSEMI,Y3.SEMI_AND,Y3.SEMI_SEMI_AND;var X3=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-DGiwQF55.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-m8-l0dJv.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-Br1Ug2Ut.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-CDtp05HC.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-uC_QraB2.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-Cw3ocqh1.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-uq_8eRY4.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-BnOWGONG.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-D42CslL1.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-B9PTkiG2.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-C2NklMBi.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-DTlWPHuG.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-P0N9Gpk_.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-wDvdfdV7.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-9R__Yy5p.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-CnLzyp7W.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-CKtInFV_.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-DTts8oaN.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-2HUTXO5U-Bvpc71YZ.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-2HUTXO5U-Bvpc71YZ.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-2HUTXO5U-Bvpc71YZ.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-XNF3R3II-DKI4o3y8.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-JAPPVBEU-y4kzwh-U.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-BBAGSFUB-wDlbOPdF.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-BRNZXaM9.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-C_dQux5r.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-B160yVYr.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-DyTb922x.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-BbuyICrx.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-BjPZn8n7.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-DJ7MH0ty.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-BioDr4pn.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-DzcV-vp8.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-Bpnv4ghU.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-kHLFypbk.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-DcSwox5x.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-CXEcy-ww.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-DL3_07Lu.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-B2crRcrv.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-CPDtNjnw.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-DH2ALKQS-CVRGx4iG.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-CZ6ADlYI.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-DuDN0dhi.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-CIx1Kfia.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-DZrvHJqf.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-Cbpw0Lim.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-Cbpw0Lim.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-DXCJ-qLD.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-DXCJ-qLD.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-Co6e9xUo.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-BxxszDkV.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-w3ayCUR8.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-w3ayCUR8.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-BIhQHuOh.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-DcYpwzkU.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-DcYpwzkU.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-LYZFFBZB-BMLmD0PS.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-DWBbgBRj.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-DmTjb9f0.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-BSrLXaCI.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-DPmPUpYL.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-G3DVszag.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-CdVsJ04Z.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-PVf-rQ-S.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-YYCVMXE3-BDOVRayn.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-CRDOz6nr.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-BU98q8gr.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-CeL32a6r.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-IGDTDPLG-CUqZAlKT.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-BDXFAacx.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-Defr0Q9g.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-BpfGDIeg.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-vsCjLe3q.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-CL_ll-mo.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-CbRRBIk3.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-DcvNzw_D.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-DkFr6f8Z.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-DkFr6f8Z.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-DkFr6f8Z.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(X3.push({name:`tar`,load:async()=>(await import(`./tar-MZQD7NO4-BRGDcHqv.mjs`)).tarCommand}),X3.push({name:`yq`,load:async()=>(await import(`./yq-OAKYHSXH-KGmxWF1Q.mjs`)).yqCommand}),X3.push({name:`xan`,load:async()=>(await import(`./xan-UD7JYIL2-DmdWvgSg.mjs`)).xanCommand}),X3.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-TE5AIOTF-DVwda1Ow.mjs`)).sqlite3Command}));var Z3=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Z3.push({name:`python3`,load:async()=>(await import(`./python3-DNGS4G3E-CixyRGKv.mjs`)).python3Command}),Z3.push({name:`python`,load:async()=>(await import(`./python3-DNGS4G3E-CixyRGKv.mjs`)).pythonCommand}));var Q3=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Q3.push({name:`js-exec`,load:async()=>(await import(`./js-exec-VXN6TZ7U-Z8_USGOo.mjs`)).jsExecCommand}),Q3.push({name:`node`,load:async()=>(await import(`./js-exec-VXN6TZ7U-Z8_USGOo.mjs`)).nodeStubCommand})),new TextEncoder,Object.freeze({stdout:``,stderr:``,exitCode:0}),[...new Map([[`:`,[`: [arguments]`,`Null command.
|
|
749
|
+
`&&(_+=1)}}else d+=C}if(y)return{op:`glob`,pattern:d};if(p){if(_!==null&&_>0){m[m.length]=d,d=``;for(var ee=1;ee<_;ee+=1)m[m.length]=``}return(d!==``||h&&m.length===0)&&(m[m.length]=d),m}return d}).reduce(function(e,t){return t===void 0||[].concat(t).forEach(function(t){e[e.length]=t}),e},[])}t.exports=function(e,t,n){var r=_(e,t,n);return typeof t==`function`?r.reduce(function(e,t){if(typeof t==`object`)return e[e.length]=t,e;var n=t.split(RegExp(`(`+d+`.*?`+d+`)`,`g`));return n.length===1?(e[e.length]=n[0],e):(n.filter(Boolean).forEach(function(t){e[e.length]=m.test(t)?JSON.parse(t.split(d)[1]):t}),e)},[]):r}}));i((e=>{e.quote=sje(),e.parse=cje()}))();var Y3;(function(e){e.EOF=`EOF`,e.NEWLINE=`NEWLINE`,e.SEMICOLON=`SEMICOLON`,e.AMP=`AMP`,e.PIPE=`PIPE`,e.PIPE_AMP=`PIPE_AMP`,e.AND_AND=`AND_AND`,e.OR_OR=`OR_OR`,e.BANG=`BANG`,e.LESS=`LESS`,e.GREAT=`GREAT`,e.DLESS=`DLESS`,e.DGREAT=`DGREAT`,e.LESSAND=`LESSAND`,e.GREATAND=`GREATAND`,e.LESSGREAT=`LESSGREAT`,e.DLESSDASH=`DLESSDASH`,e.CLOBBER=`CLOBBER`,e.TLESS=`TLESS`,e.AND_GREAT=`AND_GREAT`,e.AND_DGREAT=`AND_DGREAT`,e.LPAREN=`LPAREN`,e.RPAREN=`RPAREN`,e.LBRACE=`LBRACE`,e.RBRACE=`RBRACE`,e.DSEMI=`DSEMI`,e.SEMI_AND=`SEMI_AND`,e.SEMI_SEMI_AND=`SEMI_SEMI_AND`,e.DBRACK_START=`DBRACK_START`,e.DBRACK_END=`DBRACK_END`,e.DPAREN_START=`DPAREN_START`,e.DPAREN_END=`DPAREN_END`,e.IF=`IF`,e.THEN=`THEN`,e.ELSE=`ELSE`,e.ELIF=`ELIF`,e.FI=`FI`,e.FOR=`FOR`,e.WHILE=`WHILE`,e.UNTIL=`UNTIL`,e.DO=`DO`,e.DONE=`DONE`,e.CASE=`CASE`,e.ESAC=`ESAC`,e.IN=`IN`,e.FUNCTION=`FUNCTION`,e.SELECT=`SELECT`,e.TIME=`TIME`,e.COPROC=`COPROC`,e.WORD=`WORD`,e.NAME=`NAME`,e.NUMBER=`NUMBER`,e.ASSIGNMENT_WORD=`ASSIGNMENT_WORD`,e.FD_VARIABLE=`FD_VARIABLE`,e.COMMENT=`COMMENT`,e.HEREDOC_CONTENT=`HEREDOC_CONTENT`})(Y3||={}),Y3.IF,Y3.THEN,Y3.ELSE,Y3.ELIF,Y3.FI,Y3.FOR,Y3.WHILE,Y3.UNTIL,Y3.DO,Y3.DONE,Y3.CASE,Y3.ESAC,Y3.IN,Y3.FUNCTION,Y3.SELECT,Y3.TIME,Y3.COPROC,Y3.SEMI_SEMI_AND,Y3.TLESS,Y3.AND_DGREAT,Y3.DBRACK_START,Y3.DBRACK_END,Y3.DPAREN_START,Y3.DPAREN_END,Y3.AND_AND,Y3.OR_OR,Y3.DSEMI,Y3.SEMI_AND,Y3.PIPE_AMP,Y3.DGREAT,Y3.LESSAND,Y3.GREATAND,Y3.LESSGREAT,Y3.CLOBBER,Y3.AND_GREAT,Y3.PIPE,Y3.AMP,Y3.SEMICOLON,Y3.LPAREN,Y3.RPAREN,Y3.LESS,Y3.GREAT,Y3.LESS,Y3.GREAT,Y3.DLESS,Y3.DGREAT,Y3.LESSAND,Y3.GREATAND,Y3.LESSGREAT,Y3.DLESSDASH,Y3.CLOBBER,Y3.TLESS,Y3.AND_GREAT,Y3.AND_DGREAT,Y3.LESS,Y3.GREAT,Y3.DLESS,Y3.DGREAT,Y3.LESSAND,Y3.GREATAND,Y3.LESSGREAT,Y3.DLESSDASH,Y3.CLOBBER,Y3.TLESS,Y3.LESS,Y3.GREAT,Y3.DLESS,Y3.DGREAT,Y3.LESSAND,Y3.GREATAND,Y3.LESSGREAT,Y3.DLESSDASH,Y3.CLOBBER,Y3.TLESS,Y3.AND_GREAT,Y3.AND_DGREAT,Y3.AMP,Y3.PIPE,Y3.PIPE_AMP,Y3.SEMICOLON,Y3.AND_AND,Y3.OR_OR,Y3.DSEMI,Y3.SEMI_AND,Y3.SEMI_SEMI_AND;var X3=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-DGiwQF55.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-m8-l0dJv.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-Br1Ug2Ut.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-CDtp05HC.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-uC_QraB2.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-Cw3ocqh1.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-uq_8eRY4.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-BnOWGONG.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-D42CslL1.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-B9PTkiG2.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-C2NklMBi.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-DTlWPHuG.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-P0N9Gpk_.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-wDvdfdV7.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-9R__Yy5p.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-CnLzyp7W.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-CKtInFV_.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-DTts8oaN.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-2HUTXO5U-q3hMkiyQ.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-2HUTXO5U-q3hMkiyQ.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-2HUTXO5U-q3hMkiyQ.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-XNF3R3II-DKI4o3y8.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-JAPPVBEU-y4kzwh-U.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-BBAGSFUB-wDlbOPdF.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-BRNZXaM9.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-C_dQux5r.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-B160yVYr.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-DyTb922x.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-BbuyICrx.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-BjPZn8n7.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-DJ7MH0ty.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-BioDr4pn.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-DzcV-vp8.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-Bpnv4ghU.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-kHLFypbk.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-DcSwox5x.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-CXEcy-ww.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-DL3_07Lu.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-B2crRcrv.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-CPDtNjnw.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-DH2ALKQS-CVRGx4iG.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-CZ6ADlYI.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-DuDN0dhi.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-CIx1Kfia.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-DZrvHJqf.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-Cbpw0Lim.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-Cbpw0Lim.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-DXCJ-qLD.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-DXCJ-qLD.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-Co6e9xUo.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-BxxszDkV.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-w3ayCUR8.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-w3ayCUR8.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-BIhQHuOh.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-DcYpwzkU.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-DcYpwzkU.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-LYZFFBZB-BMLmD0PS.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-DWBbgBRj.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-DmTjb9f0.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-BSrLXaCI.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-DPmPUpYL.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-G3DVszag.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-CdVsJ04Z.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-PVf-rQ-S.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-YYCVMXE3-BDOVRayn.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-CRDOz6nr.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-BU98q8gr.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-CeL32a6r.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-IGDTDPLG-CUqZAlKT.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-BDXFAacx.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-Defr0Q9g.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-BpfGDIeg.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-vsCjLe3q.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-CL_ll-mo.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-CbRRBIk3.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-DcvNzw_D.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-DkFr6f8Z.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-DkFr6f8Z.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-DkFr6f8Z.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(X3.push({name:`tar`,load:async()=>(await import(`./tar-MZQD7NO4-BRGDcHqv.mjs`)).tarCommand}),X3.push({name:`yq`,load:async()=>(await import(`./yq-OAKYHSXH-KGmxWF1Q.mjs`)).yqCommand}),X3.push({name:`xan`,load:async()=>(await import(`./xan-UD7JYIL2-DmdWvgSg.mjs`)).xanCommand}),X3.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-TE5AIOTF-DVwda1Ow.mjs`)).sqlite3Command}));var Z3=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Z3.push({name:`python3`,load:async()=>(await import(`./python3-DNGS4G3E-CixyRGKv.mjs`)).python3Command}),Z3.push({name:`python`,load:async()=>(await import(`./python3-DNGS4G3E-CixyRGKv.mjs`)).pythonCommand}));var Q3=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Q3.push({name:`js-exec`,load:async()=>(await import(`./js-exec-VXN6TZ7U-Z8_USGOo.mjs`)).jsExecCommand}),Q3.push({name:`node`,load:async()=>(await import(`./js-exec-VXN6TZ7U-Z8_USGOo.mjs`)).nodeStubCommand})),new TextEncoder,Object.freeze({stdout:``,stderr:``,exitCode:0}),[...new Map([[`:`,[`: [arguments]`,`Null command.
|
|
750
750
|
No effect; the command does nothing.
|
|
751
751
|
Exit Status:
|
|
752
752
|
Always succeeds.`]],[`.`,[`. filename [arguments]`,`Execute commands from a file in the current shell.
|
|
@@ -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
|
`)}},async rebuildIgnorePatterns(){let t=e=>(te=e().finally(()=>{te=null}),te),s=async()=>{if(l.reset(),e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs(a),o.succeeded()}catch(e){o.failed(e)}let t=f,s=p,c=m,u=h,d=g,_=v,C=y,w=Date.now();return Pje(`config.ignore.rebuild`,{attributes:{}},async e=>{try{let t=b();x.clear(),i===void 0&&await dMe(n,S,x);let a=Date.now()-w;if(e.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),B6.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a},`content-filter rebuild succeeded`),r)try{r()}catch(e){B6.warn({err:e instanceof Error?e:Error(String(e))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a}}catch(e){f=t,p=s,m=c,h=u,g=d,v=_,y=C,x.clear();try{E()}catch(e){B6.warn({err:e instanceof Error?e:Error(String(e))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let n=e instanceof Error?e.message:String(e);return B6.warn({err:e instanceof Error?e:Error(n)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:n}}}})};return te===null?t(s):(ne===null&&(ne=te.catch(()=>null).then(()=>(ne=null,t(s)))),ne)}}}async function dMe(e,t,n){let r=[{dir:e,relPath:``}],i=0;for(;r.length>0;){let{dir:e,relPath:a}=r.pop();i+=1,i>=50&&(i=0,await new Promise(e=>setImmediate(e)));let o;try{o=T(e,{withFileTypes:!0})}catch(t){B6.warn({dir:e,err:t},`Failed to read directory for dir-count: ${e}`);continue}for(let i of o){let o=a?`${a}/${i.name}`:i.name;if(i.isDirectory()){if(G6(i.name)||t(o)||t(`${o}/`))continue;r.push({dir:j(e,i.name),relPath:o})}else i.isFile()&&P6(i.name)&&!t(o)&&n.set(a,(n.get(a)??0)+1)}}}function o8(e,t,n,r){let i;try{i=T(e,{withFileTypes:!0})}catch(t){B6.warn({dir:e,err:t},`Failed to read directory for dir-count: ${e}`);return}for(let a of i){let i=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){if(G6(a.name)||n(i)||n(`${i}/`))continue;o8(j(e,a.name),i,n,r)}else a.isFile()&&P6(a.name)&&!n(i)&&r.set(t,(r.get(t)??0)+1)}}function s8(e){return e.split(`
|
|
1115
1115
|
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function c8(e,t){let n=e.startsWith(`!`),r=n?e.slice(1):e,i=r.startsWith(`/`)?r.slice(1):r,a=i.endsWith(`/`)?i.slice(0,-1):i,o=r.startsWith(`/`)||a.includes(`/`)?`${t}/${i}`:`${t}/**/${i}`;return n?`!${o}`:o}function l8(e,t,n,r,i){let a;try{a=T(e,{withFileTypes:!0})}catch(t){return B6.warn({dir:e,err:t},`Failed to read directory ${e}`),0}let o=0;for(let s of a){if(!s.isDirectory()||G6(s.name))continue;let a=j(e,s.name),c=R6(N(t,a));if(!c.startsWith(`..`)&&!(n.ignores(c)||n.ignores(`${c}/`))){for(let e of i8){let t=j(a,e);if(_(t))try{let a=C(t,`utf-8`);i.value+=a.length;let s=s8(a).map(e=>c8(e,c));n.add(s),e===`.okignore`&&r.add(s),o++}catch(n){B6.warn({path:t,err:n},`Failed to read nested ${e} at ${t}`)}}o+=l8(a,t,n,r,i)}}return o}new class{_tail=Promise.resolve();enqueue(e){let t=this._tail.then(()=>e());return this._tail=t.catch(()=>void 0),t}};const fMe=/[\u200C-\u200F\u202A-\u202E\u206A-\u206F\uFEFF]/gu;function u8(e){return e.replace(fMe,``).normalize(`NFC`).toUpperCase().toLowerCase().normalize(`NFC`)}function d8(e){let t=u8(e);for(let e=0;e<4;e++){let e=u8(t);if(e===t)break;t=e}return t.replace(/[. ]+$/u,(e,t)=>t===0?e:``)}const pMe=new Set([`.ok`,`.open-knowledge`,`.openknowledge`,...Object.values(it).map(({userHomeDirName:e})=>e)].map(d8));new Set([...wd,...xd,...rae].map(d8));function mMe(e){let t=new Set;for(let n of e){let e=n.replace(/^\.+/u,``);if(!/^[a-z0-9-]+$/u.test(e))throw Error(`cannot derive 8.3 short names for config dir "${n}"`);e.length<=2?t.add(`${e}[0-9a-f]{4}`):(t.add(e.slice(0,6)),t.add(`${e.slice(0,2)}[0-9a-f]{4}`))}return RegExp(`^(?:${[...t].join(`|`)})~\\d+$`,`u`)}mMe(pMe);const f8=I().min(1).refine(e=>!e.includes(`\0`)&&se(e)&&ce(e)===e);ta(`kind`,[V({kind:W(`file`),path:f8}),V({kind:W(`tree`),path:f8,excluded:B(f8)}).refine(({path:e,excluded:t})=>t.every(t=>N(e,t)!==``&&hMe(e,t)))]),V({server_instance_id:I().min(1),owner_token:Ui(),pid:L().int().positive(),lease_protocol:I().min(1),project_dir:f8,scope_json:I(),started_at:Di()});function hMe(e,t){let n=N(e,t);return n===``||n!==`..`&&!n.startsWith(`..${ue}`)&&!se(n)}const gMe=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(`|`)})${gMe}(?:[\\s,:;!.\\-–—]+|$)`,`iu`),EX(`loss-capture`),V({ts:L(),schemaVersion:L(),seq:L(),event:I(),docName:I(),writerId:I().nullable(),site:I().optional(),direction:I().optional(),lostLen:L().optional(),digest:I().optional(),checkpointSha:I().optional(),which:I().optional(),witnessAvailable:R().optional(),connections:L().optional()}),EX(`checkpoint-chain`);function p8(e){try{return D.native(e)}catch{return e}}`${aae.map(e=>`${e}/`).join(`
|
|
1116
1116
|
`)}${xd.join(`
|
|
1117
|
-
`)}`;function _Me(e){try{return process.kill(e,0),`signalable`}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`EPERM`?`foreign`:`absent`}}function m8(e){return _Me(e)!==`absent`}function vMe(e){return!(typeof e!=`number`||!Number.isInteger(e)||e<2||e>2147483647)}const yMe=/^[A-Za-z0-9-]{8,64}$/;let h8=null;function g8(e){return j(e??ve(),`.ok`,`machine-id`)}function bMe(e){if(e===void 0&&h8!==null)return h8;let t=g8(e),n=null;try{let e=C(t,`utf-8`).trim();yMe.test(e)&&(n=e)}catch{}if(n===null){n=De();try{y(k(t),{recursive:!0}),O(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){EX(`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&&(h8=n),n}const xMe=EX(`process-identity`),_8=5e3,SMe=/^\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4}$/,v8=Symbol.for(`@inkeep/open-knowledge/native-process-start-reader`),y8=globalThis;let b8,x8,S8=!1;function C8(e){return Number.isSafeInteger(e)&&e>0&&e<=4294967295}function w8(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function T8(e){return typeof e==`string`&&e.length>0&&e.length<=64}function E8(e){return C(e,`utf8`)}function CMe(e,t={}){if(!C8(e))return null;let n=t.env??process.env,r=t.run??s,i=I6({encoding:`utf8`,...Fje,timeout:_8,env:{...n,LC_ALL:`C`,TZ:`UTC0`}});try{let t=r(`ps`,[`-p`,String(e),`-o`,`lstart=`],i).trim();if(!SMe.test(t))return null;let n=Date.parse(`${t} UTC`);return Number.isFinite(n)?n:null}catch{return null}}function wMe(e){return y8[v8]=e,()=>{y8[v8]===e&&(delete y8[v8],S8=!1)}}function TMe(e){let t=e.lastIndexOf(`)`);if(t<0)return null;let n=e.slice(t+1).trim().split(/\s+/)[19];if(n===void 0||!/^\d+$/.test(n))return null;let r=Number(n);return Number.isSafeInteger(r)?r:null}function EMe(e){let t=/^btime\s+(\d+)\s*$/m.exec(e);if(!t?.[1])return null;let n=Number(t[1]);return Number.isSafeInteger(n)?n:null}function DMe(e){let t=e===E8;if(t&&x8!==void 0)return x8;let n;try{n=e(`/proc/sys/kernel/random/boot_id`).trim()}catch{return}if(T8(n))return t&&(x8=n),n}function OMe(e,t){let n=TMe(t(`/proc/${e}/stat`));if(n===null)return null;let r=EMe(t(`/proc/stat`));if(r===null)return null;let i={startedAtMs:r*1e3+n*10,clock:`boot-derived`,startTicks:n},a=DMe(t);return a===void 0?i:{...i,bootId:a}}function kMe(e,t){let n=t??y8[v8];if(n===void 0)return S8||(S8=!0,xMe.warn({event:`process-start-reader-missing`},`[process-identity] no Windows process-start reader is registered, so lock holders cannot be verified; later reads are not recorded again while it stays missing`)),null;let r=n(e);return w8(r)?{startedAtMs:r,clock:`creation`}:null}function AMe(e,t,n,r){try{if(t===`linux`)return OMe(e,n);if(t===`darwin`){let t=CMe(e);return t===null?null:{startedAtMs:t,clock:`creation`}}return t===`win32`?kMe(e,r):null}catch{return null}}function D8(e,t={}){if(!C8(e))return null;let n=t.platform===void 0&&t.readFile===void 0&&t.readNative===void 0;if(n&&e===process.pid&&b8!==void 0)return b8;let r=AMe(e,t.platform??process.platform,t.readFile??E8,t.readNative);return n&&e===process.pid&&r!==null&&(b8=r),r}function jMe(e){let t=e.read??D8,n=e.now??(()=>performance.now()),r=Math.max(e.maxAgeMs,_8),i=new Map;return a=>{let o=n();for(let[e,t]of i)o>=t.expiresAtMs&&i.delete(e);let s=i.get(a);if(s!==void 0)return s.start;let c=t(a),l=c===null?r:e.maxAgeMs;return i.set(a,{expiresAtMs:n()+l,start:c}),c}}function O8(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let{bootId:t,startTicks:n,startedAtMs:r}=e;if(T8(t)&&w8(n))return{bootId:t,startTicks:n};if(w8(r))return{startedAtMs:r}}function k8(e){return typeof e.machineId==`string`||typeof e.hostname==`string`}function A8(e,t={}){return typeof e.machineId==`string`?e.machineId===(t.machineId??bMe()):typeof e.hostname==`string`&&e.hostname===(t.host??ye())}const j8={verdict:`unverified`,cause:`process-start-incomparable`},M8={verdict:`unverified`,cause:`process-start-mismatch`},MMe={verdict:`unverified`,cause:`recorded-start-in-future`},NMe={verdict:`unverified`,cause:`writer-identity-unrecorded`},PMe={verdict:`unverified`,cause:`process-started-after-lock`};function FMe(e,t,n){let r=typeof e==`string`?Date.parse(e):NaN;if(!Number.isFinite(r))return j8;let i=t.clock===`creation`?1e4:3e5;if(r-Date.now()>i)return MMe;let a=t.startedAtMs-r;return a>i?{verdict:`replaced`}:n&&a>0?PMe:{verdict:`writer`}}function IMe(e,t,n){if(t===null)return{verdict:`unverified`,cause:`process-start-unreadable`};let r=O8(e.processStart);if(r===void 0)return FMe(e.startedAt,t,n);if(`bootId`in r)return t.bootId===void 0||t.startTicks===void 0?j8:r.bootId===t.bootId?t.startTicks===r.startTicks?{verdict:`writer`}:t.startTicks>r.startTicks?{verdict:`replaced`}:M8:{verdict:`replaced`};if(t.clock!==`creation`)return j8;let i=t.startedAtMs-r.startedAtMs;return Math.abs(i)<=1e3?{verdict:`writer`}:i>0?{verdict:`replaced`}:M8}function N8(e){return O8(e.processStart)!==void 0}function P8(e,t={}){let n=t.isAlive??m8;if(!n(e.pid))return{verdict:`gone`};let r=t.sameMachine??A8(e);if(!r&&!k8(e))return{verdict:`unverified`,cause:`unverified-owner`};let i=(t.readProcessStart??D8)(e.pid);if(i===null&&!n(e.pid))return{verdict:`gone`};let a=IMe(e,i,t.refuseHolderStartedAfterLock??!1);return r?a.verdict===`writer`&&(t.formatRecordsMachineId??!0)&&!N8(e)&&typeof e.machineId!=`string`?NMe:a:a.verdict===`writer`&&N8(e)?a:{verdict:`unverified`,cause:`foreign-host`}}EX(`shadow-lock`),EX(`shadow-op-gate`),EX(`shadow-repo`),(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_GC_TIMEOUT_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),(()=>{let e=process.env.OK_SHADOW_STAGE_TIMEOUT_MS;if(!e)return 3e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e5})();const LMe=wd.map(e=>`.ok/${e}/`),RMe=xd.map(e=>`.ok/${e}`);[...LMe.map(e=>`**/${e}`),...RMe.map(e=>`**/${e}`)],Jq.fileSystem,Jq.gitUpstream,Jq.service,Jq.generator,EX(`bridge-loss-detector`),EX(`checkpoint`),RegExp(`<(${eJ.map(e=>e.tagName).join(`|`)})\\b([^>]*)\\/>`,`y`);const zMe=String.raw`\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]`,BMe=String.raw`\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)`,F8=String.raw`([^\]\n]*)`,I8=String.raw`([^\]\n]*(?:\][^[\]\n]*)?)`,L8=e=>RegExp(`(!?)${zMe}`,e),R8=(e,t)=>RegExp(`(!?)\\[${e}\\]${BMe}`,t);L8(`y`),L8(`g`),R8(F8,`y`),R8(I8,`y`),R8(F8,`g`),R8(I8,`g`);const VMe=String.raw`(!?)\[([^\]\n]*)\](?:\[([^\]\n]*)\])?`;new RegExp(VMe,`y`),EX(`watcher-freshness`),EX(`file-watcher`),EX(`conflict-authority`),EX(`parse-pool`),Math.max(1,Math.min(4,ge()-1)),F6(()=>{}),EX(`bridge-watchdog`),F6(()=>{}),EX(`server-observers`),EX(`server-observers`),EX(`agent-sessions`),new class{writes=new WeakMap;record(e,t,n){let r=this.writes.get(e)??new Map;for(let[e,t]of r)HMe(t,n)||r.delete(e);r.set(t,n),this.writes.set(e,r)}hasRecentPeer(e,t,n){let r=this.writes.get(e);if(r===void 0)return!1;for(let[e,i]of r){let a=n-i;if(Math.abs(a)>=2e3){r.delete(e);continue}if(e!==t)return!0}return!1}};function HMe(e,t){return e!==void 0&&Math.abs(t-e)<2e3}Ie(S),EX(`agent-registry-apply`),EX(`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),Bd.cursor,Bd.codex,Bd[`claude-desktop`],F6(()=>{}),Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})}),EX(`external-change-attribution`),EX(`mermaid-validator`),EX(`rename-log`),EX(`history`),V({docName:I().min(1),file:I().min(1),markdown:I(),extension:U(zd).optional(),agentId:I().optional(),agentName:I().optional(),clientName:I().optional()}).strict(),V({...af,timestamp:I().min(1)}).strict();function z8(e){return Ct.filter(t=>_(j(e,t.hostDir)))}function B8(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}B8(vt,gS),[...B8(yt,gS)].sort((e,t)=>{let n=J2.indexOf(e.editor),r=J2.indexOf(t.editor);return(n===-1?J2.length:n)-(r===-1?J2.length:r)||e.editor.localeCompare(t.editor)}),EX(`installed-skills-marker`),EX(`skill-import`),EX(`backlinks`),EX(`local-target-inventory`),EX(`tag-index`),sP(),EX(`derived-document-index`);const V8={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),...V8,propertyKey:I().min(1).optional(),propertyPath:B(ea([I(),L().int().nonnegative()])).optional(),body:I(),queue:R().optional(),summary:I().optional()});const H8=Ui();ta(`action`,[V({action:W(`edit`),id:H8,body:I(),summary:I().optional()}),V({action:W(`resolve`),id:H8,summary:I().optional()}),V({action:W(`reopen`),id:H8,summary:I().optional()}),V({action:W(`replace`),id:H8,...V8,summary:I().optional()}),V({action:W(`queue`),id:H8,summary:I().optional()}),V({action:W(`unqueue`),id:H8,summary:I().optional()}),V({action:W(`dispatch-prepare`),id:H8,summary:I().optional()}),V({action:W(`dispatch-complete`),id:H8,summary:I().optional()}),V({action:W(`dispatch-prepare-batch`),ids:B(H8).min(1).max(200),summary:I().optional()}),V({action:W(`dispatch-complete-batch`),ids:B(H8).min(1).max(200),summary:I().optional()})]),EX(`embeddings`),EX(`embeddings`);function UMe(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}UMe(Ul),EX(`embeddings`),EX(`embeddings`),EX(`process-lock`);function WMe(e,t){return le(e,`${t}.lock`)}jMe({maxAgeMs:1e3});function GMe(e){let{processStart:t,...n}=e,r=O8(t);return{...n,...r!==void 0&&{processStart:r}}}function KMe(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 qMe(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=KMe(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}EX(`asset-references`),EX(`file-ops`),EX(`upload-streaming`);const U8=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,W8=`Canonical ids: ${Ube().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 JMe=V({value:I(),truncatedFrom:L().optional(),hint:I().optional()}).describe(`Normalized change-note summary, when one was recorded.`),YMe=B(H(I(),z()));H(I(),z()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),B(ff).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.'),mf.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.'),JMe.optional(),B(uf).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 XMe=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 G8(e){return{text:XMe,...e}}function ZMe(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.`}ZMe(`the server`);function QMe(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".`}QMe(`the server`),EX(`git-checkout`),EX(`git-worktree-status`),EX(`edit-backups`),EX(`managed-artifact-persistence`),EX(`timeline`),EX(`suggest-links`),new Intl.Segmenter(`und`,{granularity:`word`}),EX(`git-context`),EX(`clone-flow`),Ie(o),k6.project,Object.fromEntries(Object.entries(_S).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
|
+
`)}`;function _Me(e){try{return process.kill(e,0),`signalable`}catch(e){return e&&typeof e==`object`&&`code`in e&&e.code===`EPERM`?`foreign`:`absent`}}function m8(e){return _Me(e)!==`absent`}function vMe(e){return!(typeof e!=`number`||!Number.isInteger(e)||e<2||e>2147483647)}const yMe=/^[A-Za-z0-9-]{8,64}$/;let h8=null;function g8(e){return j(e??ve(),`.ok`,`machine-id`)}function bMe(e){if(e===void 0&&h8!==null)return h8;let t=g8(e),n=null;try{let e=C(t,`utf-8`).trim();yMe.test(e)&&(n=e)}catch{}if(n===null){n=De();try{y(k(t),{recursive:!0}),O(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){EX(`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&&(h8=n),n}const xMe=EX(`process-identity`),_8=5e3,SMe=/^\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4}$/,v8=Symbol.for(`@inkeep/open-knowledge/native-process-start-reader`),y8=globalThis;let b8,x8,S8=!1;function C8(e){return Number.isSafeInteger(e)&&e>0&&e<=4294967295}function w8(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function T8(e){return typeof e==`string`&&e.length>0&&e.length<=64}function E8(e){return C(e,`utf8`)}function CMe(e,t={}){if(!C8(e))return null;let n=t.env??process.env,r=t.run??s,i=I6({encoding:`utf8`,...Fje,timeout:_8,env:{...n,LC_ALL:`C`,TZ:`UTC0`}});try{let t=r(`ps`,[`-p`,String(e),`-o`,`lstart=`],i).trim();if(!SMe.test(t))return null;let n=Date.parse(`${t} UTC`);return Number.isFinite(n)?n:null}catch{return null}}function wMe(e){return y8[v8]=e,()=>{y8[v8]===e&&(delete y8[v8],S8=!1)}}function TMe(e){let t=e.lastIndexOf(`)`);if(t<0)return null;let n=e.slice(t+1).trim().split(/\s+/)[19];if(n===void 0||!/^\d+$/.test(n))return null;let r=Number(n);return Number.isSafeInteger(r)?r:null}function EMe(e){let t=/^btime\s+(\d+)\s*$/m.exec(e);if(!t?.[1])return null;let n=Number(t[1]);return Number.isSafeInteger(n)?n:null}function DMe(e){let t=e===E8;if(t&&x8!==void 0)return x8;let n;try{n=e(`/proc/sys/kernel/random/boot_id`).trim()}catch{return}if(T8(n))return t&&(x8=n),n}function OMe(e,t){let n=TMe(t(`/proc/${e}/stat`));if(n===null)return null;let r=EMe(t(`/proc/stat`));if(r===null)return null;let i={startedAtMs:r*1e3+n*10,clock:`boot-derived`,startTicks:n},a=DMe(t);return a===void 0?i:{...i,bootId:a}}function kMe(e,t){let n=t??y8[v8];if(n===void 0)return S8||(S8=!0,xMe.warn({event:`process-start-reader-missing`},`[process-identity] no Windows process-start reader is registered, so lock holders cannot be verified; later reads are not recorded again while it stays missing`)),null;let r=n(e);return w8(r)?{startedAtMs:r,clock:`creation`}:null}function AMe(e,t,n,r){try{if(t===`linux`)return OMe(e,n);if(t===`darwin`){let t=CMe(e);return t===null?null:{startedAtMs:t,clock:`creation`}}return t===`win32`?kMe(e,r):null}catch{return null}}function D8(e,t={}){if(!C8(e))return null;let n=t.platform===void 0&&t.readFile===void 0&&t.readNative===void 0;if(n&&e===process.pid&&b8!==void 0)return b8;let r=AMe(e,t.platform??process.platform,t.readFile??E8,t.readNative);return n&&e===process.pid&&r!==null&&(b8=r),r}function jMe(e){let t=e.read??D8,n=e.now??(()=>performance.now()),r=Math.max(e.maxAgeMs,_8),i=new Map;return a=>{let o=n();for(let[e,t]of i)o>=t.expiresAtMs&&i.delete(e);let s=i.get(a);if(s!==void 0)return s.start;let c=t(a),l=c===null?r:e.maxAgeMs;return i.set(a,{expiresAtMs:n()+l,start:c}),c}}function O8(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let{bootId:t,startTicks:n,startedAtMs:r}=e;if(T8(t)&&w8(n))return{bootId:t,startTicks:n};if(w8(r))return{startedAtMs:r}}function k8(e){return typeof e.machineId==`string`||typeof e.hostname==`string`}function A8(e,t={}){return typeof e.machineId==`string`?e.machineId===(t.machineId??bMe()):typeof e.hostname==`string`&&e.hostname===(t.host??ye())}const j8={verdict:`unverified`,cause:`process-start-incomparable`},M8={verdict:`unverified`,cause:`process-start-mismatch`},MMe={verdict:`unverified`,cause:`recorded-start-in-future`},NMe={verdict:`unverified`,cause:`writer-identity-unrecorded`},PMe={verdict:`unverified`,cause:`process-started-after-lock`};function FMe(e,t,n){let r=typeof e==`string`?Date.parse(e):NaN;if(!Number.isFinite(r))return j8;let i=t.clock===`creation`?1e4:3e5;if(r-Date.now()>i)return MMe;let a=t.startedAtMs-r;return a>i?{verdict:`replaced`}:n&&a>0?PMe:{verdict:`writer`}}function IMe(e,t,n){if(t===null)return{verdict:`unverified`,cause:`process-start-unreadable`};let r=O8(e.processStart);if(r===void 0)return FMe(e.startedAt,t,n);if(`bootId`in r)return t.bootId===void 0||t.startTicks===void 0?j8:r.bootId===t.bootId?t.startTicks===r.startTicks?{verdict:`writer`}:t.startTicks>r.startTicks?{verdict:`replaced`}:M8:{verdict:`replaced`};if(t.clock!==`creation`)return j8;let i=t.startedAtMs-r.startedAtMs;return Math.abs(i)<=1e3?{verdict:`writer`}:i>0?{verdict:`replaced`}:M8}function LMe(e=Date.now(),t=Te){try{let n=t();return!Number.isFinite(n)||n<=0?null:e-Math.round(n*1e3)}catch{return null}}function RMe(e){let t=O8(e.processStart),n=[t!==void 0&&`startedAtMs`in t?t.startedAtMs:NaN,typeof e.startedAt==`string`?Date.parse(e.startedAt):NaN].filter(Number.isFinite);return n.length===0?null:Math.max(...n)}function zMe(e,t){let n=RMe(e);if(n===null)return!1;let r=t();return r!==null&&r-n>3e5}function N8(e){return O8(e.processStart)!==void 0}function P8(e,t={}){let n=t.isAlive??m8;if(!n(e.pid))return{verdict:`gone`};let r=t.sameMachine??A8(e);if(!r&&!k8(e))return{verdict:`unverified`,cause:`unverified-owner`};let i=(t.readProcessStart??D8)(e.pid);if(i===null&&!n(e.pid))return{verdict:`gone`};if(i===null&&r&&(t.platform??process.platform)===`win32`&&zMe(e,t.readBootInstant??(()=>LMe())))return{verdict:`replaced`};let a=IMe(e,i,t.refuseHolderStartedAfterLock??!1);return r?a.verdict===`writer`&&(t.formatRecordsMachineId??!0)&&!N8(e)&&typeof e.machineId!=`string`?NMe:a:a.verdict===`writer`&&N8(e)?a:{verdict:`unverified`,cause:`foreign-host`}}EX(`shadow-lock`),EX(`shadow-op-gate`),EX(`shadow-repo`),(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})(),(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_GC_TIMEOUT_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})(),(()=>{let e=process.env.OK_SHADOW_STAGE_TIMEOUT_MS;if(!e)return 3e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e5})();const BMe=wd.map(e=>`.ok/${e}/`),VMe=xd.map(e=>`.ok/${e}`);[...BMe.map(e=>`**/${e}`),...VMe.map(e=>`**/${e}`)],Jq.fileSystem,Jq.gitUpstream,Jq.service,Jq.generator,EX(`bridge-loss-detector`),EX(`checkpoint`),RegExp(`<(${eJ.map(e=>e.tagName).join(`|`)})\\b([^>]*)\\/>`,`y`);const HMe=String.raw`\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]`,UMe=String.raw`\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)`,F8=String.raw`([^\]\n]*)`,I8=String.raw`([^\]\n]*(?:\][^[\]\n]*)?)`,L8=e=>RegExp(`(!?)${HMe}`,e),R8=(e,t)=>RegExp(`(!?)\\[${e}\\]${UMe}`,t);L8(`y`),L8(`g`),R8(F8,`y`),R8(I8,`y`),R8(F8,`g`),R8(I8,`g`);const WMe=String.raw`(!?)\[([^\]\n]*)\](?:\[([^\]\n]*)\])?`;new RegExp(WMe,`y`),EX(`watcher-freshness`),EX(`file-watcher`),EX(`conflict-authority`),EX(`parse-pool`),Math.max(1,Math.min(4,ge()-1)),F6(()=>{}),EX(`bridge-watchdog`),F6(()=>{}),EX(`server-observers`),EX(`server-observers`),EX(`agent-sessions`),new class{writes=new WeakMap;record(e,t,n){let r=this.writes.get(e)??new Map;for(let[e,t]of r)GMe(t,n)||r.delete(e);r.set(t,n),this.writes.set(e,r)}hasRecentPeer(e,t,n){let r=this.writes.get(e);if(r===void 0)return!1;for(let[e,i]of r){let a=n-i;if(Math.abs(a)>=2e3){r.delete(e);continue}if(e!==t)return!0}return!1}};function GMe(e,t){return e!==void 0&&Math.abs(t-e)<2e3}Ie(S),EX(`agent-registry-apply`),EX(`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),Bd.cursor,Bd.codex,Bd[`claude-desktop`],F6(()=>{}),Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})}),EX(`external-change-attribution`),EX(`mermaid-validator`),EX(`rename-log`),EX(`history`),V({docName:I().min(1),file:I().min(1),markdown:I(),extension:U(zd).optional(),agentId:I().optional(),agentName:I().optional(),clientName:I().optional()}).strict(),V({...af,timestamp:I().min(1)}).strict();function z8(e){return Ct.filter(t=>_(j(e,t.hostDir)))}function B8(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}B8(vt,gS),[...B8(yt,gS)].sort((e,t)=>{let n=J2.indexOf(e.editor),r=J2.indexOf(t.editor);return(n===-1?J2.length:n)-(r===-1?J2.length:r)||e.editor.localeCompare(t.editor)}),EX(`installed-skills-marker`),EX(`skill-import`),EX(`backlinks`),EX(`local-target-inventory`),EX(`tag-index`),sP(),EX(`derived-document-index`);const V8={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),...V8,propertyKey:I().min(1).optional(),propertyPath:B(ea([I(),L().int().nonnegative()])).optional(),body:I(),queue:R().optional(),summary:I().optional()});const H8=Ui();ta(`action`,[V({action:W(`edit`),id:H8,body:I(),summary:I().optional()}),V({action:W(`resolve`),id:H8,summary:I().optional()}),V({action:W(`reopen`),id:H8,summary:I().optional()}),V({action:W(`replace`),id:H8,...V8,summary:I().optional()}),V({action:W(`queue`),id:H8,summary:I().optional()}),V({action:W(`unqueue`),id:H8,summary:I().optional()}),V({action:W(`dispatch-prepare`),id:H8,summary:I().optional()}),V({action:W(`dispatch-complete`),id:H8,summary:I().optional()}),V({action:W(`dispatch-prepare-batch`),ids:B(H8).min(1).max(200),summary:I().optional()}),V({action:W(`dispatch-complete-batch`),ids:B(H8).min(1).max(200),summary:I().optional()})]),EX(`embeddings`),EX(`embeddings`);function KMe(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}KMe(Ul),EX(`embeddings`),EX(`embeddings`),EX(`process-lock`);function qMe(e,t){return le(e,`${t}.lock`)}jMe({maxAgeMs:1e3});function JMe(e){let{processStart:t,...n}=e,r=O8(t);return{...n,...r!==void 0&&{processStart:r}}}function YMe(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 XMe(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=YMe(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}EX(`asset-references`),EX(`file-ops`),EX(`upload-streaming`);const U8=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,W8=`Canonical ids: ${Ube().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 ZMe=V({value:I(),truncatedFrom:L().optional(),hint:I().optional()}).describe(`Normalized change-note summary, when one was recorded.`),QMe=B(H(I(),z()));H(I(),z()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),B(ff).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.'),mf.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.'),ZMe.optional(),B(uf).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 $Me=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 G8(e){return{text:$Me,...e}}function eNe(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.`}eNe(`the server`);function tNe(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".`}tNe(`the server`),EX(`git-checkout`),EX(`git-worktree-status`),EX(`edit-backups`),EX(`managed-artifact-persistence`),EX(`timeline`),EX(`suggest-links`),new Intl.Segmenter(`und`,{granularity:`word`}),EX(`git-context`),EX(`clone-flow`),Ie(o),k6.project,Object.fromEntries(Object.entries(_S).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
|
`),EX(`skills-leaderboard`),EX(`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(),EX(`github-permissions`),EX(`github-reference`),EX(`github-reference`),EX(`link-preview.guarded-fetch`),EX(`link-preview.cache`),EX(`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(),EX(`managed-rename`),EX(`reconcile`),Object.assign(Ske,{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`}),EX(`search`),EX(`skill-install`),EX(`write-advisory`),EX(`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 Ve,F6(()=>{}),[...Gae],["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.`,"Large project scans can exceed host or transport timeouts. If a scan times out, narrow `path` to a file or folder and retry.",`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(U8),G8({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(U8),G8({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 nNe=[`lock`],rNe=ea([fo,Ji()]);co(ea([I(),L(),R(),B(z()),H(I(),z()),Ji()])).superRefine((e,t)=>{for(let[n,r]of Object.entries(e))rNe.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(zd).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(Rd).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.`);function K8(e){return Object.entries(e).map(([e,t])=>`\`${e}\`: ${t}`).join(`; `)}U(zae).optional().describe(`What happened to this write, present on every write result the server answered, success or not. ${K8(Vae)}. A value this tool version does not know is reported as merged-first when saved, else refused, with nextStep re-read.`),R().optional().describe("Whether the write's bytes were in the document's file when the server answered. Not the same as the move result's `committed` (git history)."),U(Bae).optional().describe(`What to do next about this write. ${K8(Hae)}. Never retry a write whose outcome is merged-first, both-kept or projection-held: it landed.`),new Set(Pq),[`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.`,`Follow nextStep (retry|re-read|none). merged-first, both-kept and projection-held landed: re-read, never retry. mermaid-parse-error: the edit landed; fix the fence.`,W8].join(`
|
|
1123
|
-
`);const
|
|
1123
|
+
`);const iNe=[`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(iNe),EX(`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(cbe,`Skill name must be lowercase letters, digits, and hyphens only.`).describe(`Skill name (the bundle-dir identity, wherever the skill lives).`),scope:U(Rd).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(U8),G8({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(cbe,`Skill name must be lowercase letters, digits, and hyphens only.`).describe(`Skill name (the bundle-dir identity, wherever the skill lives).`),scope:U(Rd).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(U8),G8({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:QMe.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
|
`),[...Pq,...Vq],[`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(Vq),["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(U8),G8({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
|
`),EX(`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(U8);const
|
|
1135
|
-
`),G8({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:Kd.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([...Gd.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 q8="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(U8);const aNe=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(nNe).optional()});G8({cwd:I(),query:I(),intent:I(),resultCount:L().int(),results:B(aNe),elapsedMs:L().nullable(),semantic:Kq.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
|
+
`),G8({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:Kd.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([...Gd.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 q8="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).",oNe=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(q8),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(oNe).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 sNe=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(q8),description:I().describe(`The skill's one-line description (empty if none).`),body:I().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:B(sNe).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.`,`Follow nextStep: retry|re-read|none. Outcomes merged-first, both-kept, projection-held landed: never retry. mermaid-parse-error: fix the fence.`,W8].join(`
|
|
1137
|
-
`),new Set(Object.values(gd)),EX(`config-persistence`),EX(`generated-index-git-attributes`),EX(`doc-notices`),V({branch:I().min(1),notice:Dq}),V({version:W(1),notices:B(z())}),EX(`document-refresh`),EX(`head-watcher`),EX(`shadow-gc`),EX(`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})(),EX(`mermaid-persistence`),EX(`persistence`),EX(`store-compare`);const J8={"pending-unreadable":`its file could not be read for the compare before the write`,"pending-exhausted":`its file kept changing while it was being saved`,"pending-base-moved":`its acknowledged version kept moving while it was being saved`,"pending-no-intake":`its file changed and this persistence has no intake to merge it`,"pending-intake-failed":`its file changed and merging the outside version into it failed`,"pending-intake-failed-no-base":`its file changed and taking the outside version in failed, with no agreed version to merge against`,"pending-conflict":`its file changed and could not be merged, so a conflict was raised`};J8[`pending-unreadable`],J8[`pending-exhausted`],EX(`persistence-staleness`),EX(`recovered-file-target`),EX(`removed-docs-journal`),EX(`server-observers`),EX(`github-account`),EX(`sync-engine`),Ie(o),new Set(Ebe);const Y8=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`];new Set(Y8),[...Y8],Rje(``),(()=>{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 X8=null;F6(()=>{X8?.disable(),X8=null}),EX(`skill-migrate`);function Z8(e){return[{host:`agents`,root:gS},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=J2.indexOf(e.host),r=J2.indexOf(t.host);return(n===-1?J2.length:n)-(r===-1?J2.length:r)||e.host.localeCompare(t.host)})}Z8(vt),Z8(yt),Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS);const
|
|
1137
|
+
`),new Set(Object.values(gd)),EX(`config-persistence`),EX(`generated-index-git-attributes`),EX(`doc-notices`),V({branch:I().min(1),notice:Dq}),V({version:W(1),notices:B(z())}),EX(`document-refresh`),EX(`head-watcher`),EX(`shadow-gc`),EX(`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})(),EX(`mermaid-persistence`),EX(`persistence`),EX(`store-compare`);const J8={"pending-unreadable":`its file could not be read for the compare before the write`,"pending-exhausted":`its file kept changing while it was being saved`,"pending-base-moved":`its acknowledged version kept moving while it was being saved`,"pending-no-intake":`its file changed and this persistence has no intake to merge it`,"pending-intake-failed":`its file changed and merging the outside version into it failed`,"pending-intake-failed-no-base":`its file changed and taking the outside version in failed, with no agreed version to merge against`,"pending-conflict":`its file changed and could not be merged, so a conflict was raised`};J8[`pending-unreadable`],J8[`pending-exhausted`],EX(`persistence-staleness`),EX(`recovered-file-target`),EX(`removed-docs-journal`),EX(`server-observers`),EX(`github-account`),EX(`sync-engine`),Ie(o),new Set(Ebe);const Y8=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`];new Set(Y8),[...Y8],Rje(``),(()=>{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 X8=null;F6(()=>{X8?.disable(),X8=null}),EX(`skill-migrate`);function Z8(e){return[{host:`agents`,root:gS},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=J2.indexOf(e.host),r=J2.indexOf(t.host);return(n===-1?J2.length:n)-(r===-1?J2.length:r)||e.host.localeCompare(t.host)})}Z8(vt),Z8(yt),Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS);const cNe=$l;KY(),Ie(o),EX(`project-git`);var Q8=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})),$8=i((e=>{let{InvalidArgumentError:t}=Q8();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})),e5=i((e=>{let{humanReadableArgName:t}=$8();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})),t5=i((e=>{let{InvalidArgumentError:t}=Q8();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})),lNe=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})),uNe=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}=$8(),{CommanderError:l}=Q8(),{Help:u,stripColor:d}=e5(),{Option:f,DualOptions:p}=t5(),{suggestSimilar:m}=lNe();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:dNe,createCommand:fNe,createArgument:pNe,createOption:mNe,CommanderError:hNe,InvalidArgumentError:gNe,InvalidOptionArgumentError:_Ne,Command:vNe,Argument:yNe,Option:bNe,Help:xNe}=e(i((e=>{let{Argument:t}=$8(),{Command:n}=uNe(),{CommanderError:r,InvalidArgumentError:i}=Q8(),{Help:a}=e5(),{Option:o}=t5();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 SNe(e){let{projectDir:t,contentDir:n,sampleCap:r=5}=e,i=[],a=[];try{v(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=uMe({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=T(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);i.push(`could not read directory ${N(n,e)||`.`}: ${r}`);return}for(let r of t){let t=j(e,r.name);if(r.isSymbolicLink()){let e;try{e=D(t)}catch(e){let r=e.code;r===`ENOENT`||r===`ELOOP`?i.push(`broken or cyclic symlink: ${N(n,t)}`):i.push(`cannot resolve symlink ${N(n,t)}: ${r??`unknown error`}`);continue}let r;try{r=re(e)}catch{continue}if(r.isDirectory()){let e=N(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=N(n,t);if(o.isExcluded(e))continue;a.push(e)}}else if(r.isDirectory()){let e=N(n,t);if(o.isDirExcluded(e))continue;s(t)}else if(r.isFile()){let e=N(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 CNe(e){let t=pt(),n=e.split(/\r?\n/,1)[0]??``;if(n===iY(t))return!0;let r=nY(t);return n.startsWith(r)&&/^-v\d+$/.test(n.slice(r.length))}function n5(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`&&CNe(n)}function wNe(e){return{command:`ok-pi-managed-extension`,args:[e]}}function r5(e={}){let t=e.mode===`dev`,n=pt(),r=t?iY(n):rY(n),i=`${Et(n)}_`,a={unix:sY({...e,platformName:`darwin`}),win32:sY({...e,platformName:`win32`})};return`${r}
|
|
1156
1156
|
/**
|
|
1157
1157
|
* Open Knowledge bridge for Pi — MANAGED FILE, written by \`${ht()} 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 TNe(e,t){let n=N(p8(t),p8(e));return n.length>0&&!n.startsWith(`..`)&&!se(n)}const ENe=e=>{try{let t=s(`git`,[`rev-parse`,`--show-toplevel`],I6({cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})).trim();return t.length>0?t:null}catch{return null}};function DNe(e,t={}){let n=t.homeDir??ve(),r=t.gitTopLevel??ENe,i=le(e),a;try{a=D(i)}catch{a=i}let o=a,s=0;for(;s<30&&o!==n&&o!==`/`&&o!==``;){if(z6(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&&TNe(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}}function i5(e,t){let n=k(t),r=_(t)?`overwritten`:`written`;if(r===`written`&&_(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 te(n,{recursive:!0,force:!0}),y(k(n),{recursive:!0}),a5(e,n),r}function a5(e,t){y(t,{recursive:!0});for(let n of T(e,{withFileTypes:!0})){let r=j(e,n.name),i=j(t,n.name);n.isDirectory()?a5(r,i):m(r,i)}}var o5=class extends Error{name=`ProjectPathSafetyError`;code=`PROJECT_PATH_SAFETY`};function s5(e,t){let n;try{n=v(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(n?.isSymbolicLink())throw new o5(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);c5(e,t)}function ONe(e,t){c5(e,t)}function c5(e,t){l5(e,t)}function l5(e,t){let n=t,r;try{r=D(n)}catch{r=le(n)}let i=k(e);for(;i.length>1&&i!==ue;){let t;try{t=D(i)}catch(e){if(e.code===`ENOENT`){i=k(i);continue}throw e}let n=N(r,t);if(n===``||!n.startsWith(`..`)&&!se(n))return;throw new o5(`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 u5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function d5(e,t,n){try{if(re(n).size>10485760)return!1}catch{return!1}let r;try{r=C(n,`utf-8`)}catch{return!1}let i=[],a=eke(r.charCodeAt(0)===65279?r.slice(1):r,i,{allowTrailingComma:!0,disallowComments:!1});if(i.length>0||!u5(a))return!1;let o=a[e.topLevelKey];if(!u5(o))return!1;let s=e.serverMapSubKey?o[e.serverMapSubKey]:o;if(!u5(s))return!1;let c=s[e.serverName(t)];return u5(c)&&c.enabled===!1?!1:mY(c)||qxe(c)}function kNe(e){let t=eo[e]?.satisfiers.find(e=>e.piece===`mcp`&&e.scope===`project`),n=t?.pathId===void 0?null:ka(t.pathId);return n===null||n.kind!==`editor-project-config`||n.editor===e?null:EY[n.editor]??null}function ANe(e,t,n={}){if(!oee.includes(e.id))return!0;let r=kNe(e.id),i=r?.projectConfigPath?.(t);if(r!==null&&i!==void 0&&d5(r,t,i))return!0;try{return d5(e,t,e.configPath(t,n.home))}catch{return!1}}function jNe(e){let t=new Set(bt.filter(e=>e.scope===`project`).map(e=>e.editorId));return e.filter(e=>t.has(e))}function MNe(e,t){if(jNe(t).length===0)return null;let n=j(e,gS,St,`SKILL.md`);try{let t=N6(`project`,{checkDesktop:!0});return s5(k(n),e),{editorId:`agents`,label:`.agents hub`,action:i5(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 f5(e,t,n={}){let r=e.projectSkillPath?.(t);if(!r)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};if(!ANe(e,t,n))return{editorId:e.id,label:e.label,action:`skipped-prerequisite`,path:r};try{let n=N6(`project`,{checkDesktop:!0});s5(k(r),t);let i=i5(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 NNe(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 _(n)?(ONe(r,t),te(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 PNe(){let e=VJ();return e&&typeof e.resolveSymlinkWritePath==`function`?e:null}function FNe(e){let t=e,n=new Set;for(;;){let r;try{r=v(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=E(t)}catch(t){return BJ(`readlinkSync threw during symlink walk`,t),{readPath:null,writePath:e}}t=se(i)?i:j(k(t),i)}}let p5;function INe(){return p5===void 0&&(p5=PNe()),p5}function m5(e,t=INe){let n=t();if(n)try{let t=n.resolveSymlinkWritePath(e);return{readPath:t.readPath??null,writePath:t.writePath}}catch(e){BJ(`resolveSymlinkWritePath threw`,e)}return FNe(e)}const h5=`**/.ok/*`,g5=`!**/.ok/skills/`;function _5(e){let t=[`.ok/`,`.okignore`];for(let n of GJ){let r=EY[n];r.projectConfigPath&&t.push(WNe(r.projectConfigPath(e),e))}return t.push(`.claude/launch.json`),Array.from(new Set(t))}function v5(e){let t=j(e,...Ibe);if(!_(t))return[];try{let e=Bbe(C(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=vt[e];r&&n.push(`${r}/${t}/`)}return Array.from(new Set(n))}catch{return[]}}function LNe(e,t){let n=y5(e,t).tracked;if(n.length>0)return{kind:`refused-tracked`,tracked:n,remediation:b5(n)};let r=x5(e);if(r.kind!==`ok`)return r.result;let i=_(r.path)?C(r.path,`utf-8`):``,a=new Set(v5(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=w5(s),l=[],u=[];for(let e of t)C5(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{O(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{O(r.path,`${s}${d}${f}`,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:l,alreadyPresent:u,removed:o}}function RNe(e,t){let n=x5(e);if(n.kind!==`ok`)return n.result;if(!_(n.path))return{kind:`updated`,appended:[],alreadyPresent:[],removed:[]};let r=t.map(e=>S5(e)),i=new Set;for(let e of r)for(let t of e)i.add(t);i.add(h5),i.add(g5);for(let t of v5(e))i.add(t);let a;try{a=C(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{O(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{O(n.path,u,`utf-8`)}catch{return{kind:`no-exclude`,reason:`inaccessible`}}return{kind:`updated`,appended:[],alreadyPresent:[],removed:l}}function zNe(e){let t=x5(e);if(t.kind!==`ok`)return t.result.reason===`no-git`||t.result.reason===`malformed-pointer`||t.result.reason===`inaccessible`?`no-git`:`shared`;if(!_(t.path))return`shared`;let n;try{n=C(t.path,`utf-8`)}catch{return`shared`}let r=w5(n),i=_5(e);for(let e of i)if(C5(r,e))return`local-only`;return r.has(h5)?`local-only`:`shared`}function BNe(e){let t=x5(e);if(t.kind!==`ok`||!_(t.path))return[];let n;try{n=C(t.path,`utf-8`)}catch{return[]}let r=w5(n),i=[..._5(e),...v5(e)].filter(e=>C5(r,e)),a=new Set(i),o=[];for(let e of Object.values(vt))e!==null&&o.push(e);let s=[];for(let e of r){if(a.has(e))continue;if(e===h5||e===g5){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 y5(e,t){let n=[];for(let r of t){let t=le(e,r);if(_(t))try{s(`git`,[`ls-files`,`--error-unmatch`,...Vbe([r])],I6({cwd:e,stdio:[`ignore`,`ignore`,`ignore`]})),n.push(r)}catch{}}return{tracked:n}}const VNe=/^[\w.\-/]+$/;function HNe(e){return process.platform===`win32`?`"${e.replaceAll(`"`,``)}"`:`'${e.replaceAll(`'`,`'\\''`)}'`}function UNe(e){return VNe.test(e)?e:HNe($q(e))}function b5(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}-- ${UNe(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 x5(e){let t=$Se(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 _(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 S5(e){let t=e.replace(/\/$/,``);return new Set([e,t,`/${e}`,`/${t}`])}function C5(e,t){for(let n of S5(t))if(e.has(n))return!0;return!1}function w5(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 D5(e){let t=(e.match(/\r\n/g)??[]).length;return t!==0&&t>=(e.match(/\n/g)??[]).length-t}function O5(e){try{return re(e).mode&511}catch{return}}function
|
|
1507
|
+
`)){let e=n.trim();e.length!==0&&t.add(e)}return t}function WNe(e,t){return GNe(N(t,e))}function GNe(e){return ue===`/`?e:e.split(ue).join(`/`)}function T5(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 E5(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 KNe(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 D5(e){let t=(e.match(/\r\n/g)??[]).length;return t!==0&&t>=(e.match(/\n/g)??[]).length-t}function O5(e){try{return re(e).mode&511}catch{return}}function qNe(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=f4(r,t,void 0,{formattingOptions:{...
|
|
1512
|
-
`)?n:`${n}\n`)}function
|
|
1513
|
-
`)?n:`${n}\n`)}const M5=10485760;function N5(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)=>N5(e,t[n]));if(IJ(e)&&IJ(t)){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&N5(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 P5(e,t,n){return t===void 0?[e,n]:[e,t,n]}function F5(e,t,n,r){let i={[n]:r};return{[e]:t===void 0?i:{[t]:i}}}function I5(e,t,n){let r=e[t];return n===void 0?r:IJ(r)?r[n]:void 0}function
|
|
1511
|
+
`,a=f4(r,t,void 0,{formattingOptions:{...KNe(r),eol:i}});if(a.length===0)return{text:e,changed:!1};let o=`${n?``:``}${p4(r,a)}`;return{text:o,changed:o!==e}}const JNe={allowTrailingComma:!0,disallowComments:!1};function YNe(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function k5(e){let t=[],n=tke(e,t,JNe);return t.some(t=>!YNe(t,e))||n?.type!==`object`?null:n}function A5(e,t){let n=0;for(let r of e.children??[]){let e=r.children?.[0];e!==void 0&&d4(e)===t&&(n+=1)}return n}function j5(e,t){dJ(e,`${JSON.stringify(t,null,2)}\n`)}function XNe(e,t){let n=Nxe(t);dJ(e,n.endsWith(`
|
|
1512
|
+
`)?n:`${n}\n`)}function ZNe(e,t){let n=(0,Ts.stringify)(t);dJ(e,n.endsWith(`
|
|
1513
|
+
`)?n:`${n}\n`)}const M5=10485760;function N5(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)=>N5(e,t[n]));if(IJ(e)&&IJ(t)){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&N5(e[n],t[n]))}return!1}function QNe(e,t,n){return IJ(e)&&n.every(n=>N5(e[n],t[n]))}function $Ne(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 P5(e,t,n){return t===void 0?[e,n]:[e,t,n]}function F5(e,t,n,r){let i={[n]:r};return{[e]:t===void 0?i:{[t]:i}}}function I5(e,t,n){let r=e[t];return n===void 0?r:IJ(r)?r[n]:void 0}function ePe(e,t,n,r,i,a=!1,o=!1){if(!_(e))return o?{kind:`unchanged`}:(j5(e,F5(t,i,n,r)),{kind:`written`});let s;try{s=C(e,`utf-8`)}catch(e){return BJ(`json config read failed`,e),{kind:`declined`,reason:T5(e)}}if(s.trim()===``)return o?{kind:`unchanged`}:(j5(e,F5(t,i,n,r)),{kind:`written`});if(Buffer.byteLength(s,`utf-8`)>M5)return{kind:`declined`,reason:`oversize`};let c=k5(s);if(!c)return{kind:`declined`,reason:`unparseable`};if(A5(c,t)>1)return{kind:`declined`,reason:`duplicate-container`};let l=I5(d4(c),t,i),u=IJ(l)?l[n]:void 0,d=u!==void 0,f=hY(r);if(d&&a?cY(u):d&&QNe(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
|
-
`,g={
|
|
1518
|
-
`),p,m=!1;try{let t
|
|
1517
|
+
`,g={...$Ne(m),eol:h},v=P5(t,i,n),y=m;if(o)for(let e of d?gY(u,r):[]){let t=f4(y,[...v,e],void 0,{formattingOptions:g});y=p4(y,t)}else if(d&&!a&&mY(u))for(let e of f){let t=f4(y,[...v,e],r[e],{formattingOptions:g});y=p4(y,t)}else{let e=f4(y,v,r,{formattingOptions:g});y=p4(y,e)}let b=`${p?``:``}${y}`;return b!==s&&dJ(e,b,{mode:O5(e)}),o&&b===s?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}function tPe(e,t,n,r,i,a=!1,o=!1){let s=``;if(_(t))try{s=C(t,`utf-8`)}catch(e){return BJ(`toml config read failed`,e),{kind:`declined`,reason:T5(e)}}let c=s.trim()===``;if(c&&o)return{kind:`unchanged`};if(e.backend===`fallback`)return c?(XNe(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=D5(u),f=c||u.endsWith(`
|
|
1518
|
+
`),p,m=!1;try{let t=nPe(e,u,n,r);if(o){let n=u;for(let a of t===void 0?[]:gY(t,i))n=e.removeEntryKey(n,r,a).text;p={text:n,existed:t!==void 0}}else{let n=rPe(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 BJ(`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 g=`${l?``:``}${h}`;return g!==s&&dJ(t,g,{mode:O5(t)}),o&&g===s?{kind:`unchanged`}:{kind:p.existed||m?`overwritten`:`written`}}function
|
|
1521
|
+
`));let g=`${l?``:``}${h}`;return g!==s&&dJ(t,g,{mode:O5(t)}),o&&g===s?{kind:`unchanged`}:{kind:p.existed||m?`overwritten`:`written`}}function nPe(e,t,n,r){if(t.trim()===``)return;let i=e.parseToObject(t)[n],a=IJ(i)?i[r]:void 0;return IJ(a)?a:void 0}function rPe(e,t,n){return e===void 0||cY(e)?{kind:`merge`,prune:[]}:n||!mY(e)?{kind:`replace`}:{kind:`merge`,prune:gY(e,t)}}function iPe(e,t,n,r,i=!1,a=!1){let o=``;if(_(e))try{o=C(e,`utf-8`)}catch(e){return BJ(`yaml config read failed`,e),{kind:`declined`,reason:T5(e)}}if(o.trim()===``)return a?{kind:`unchanged`}:(ZNe(e,{[t]:{[n]:r}}),{kind:`written`});if(Buffer.byteLength(o,`utf-8`)>M5)return{kind:`declined`,reason:`oversize`};let s=o.charCodeAt(0)===65279,c=s?o.slice(1):o,l=(0,Ts.parseDocument)(c);if(l.errors.length>0)return{kind:`declined`,reason:`unparseable`};let u=[t,n],d=l.hasIn(u);l.hasIn([t])&&!(0,Ts.isCollection)(l.getIn([t],!0))&&l.deleteIn([t]);let f=l.getIn(u,!0),p=d&&(0,Ts.isCollection)(f)&&(i?cY(f.toJSON()):mY(f.toJSON()));if(a){if(d&&(0,Ts.isCollection)(f))for(let e of gY(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=D5(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 g=`${s?``:``}${m}`;return g!==o&&dJ(e,g,{mode:O5(e)}),a&&g===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const
|
|
1525
|
+
`));let g=`${s?``:``}${m}`;return g!==o&&dJ(e,g,{mode:O5(e)}),a&&g===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const aPe=`A dev build registers OpenKnowledge MCP in project config only, never in user-level editor config. Run \`${gt} init --dev-mcp\` in the project, or set OK_CHANNEL=stable.`,oPe=`open-knowledge-ui`;function L5(e,t,n){try{let r=e.detectPath?.(t,n)??k(e.configPath(t,n));return _(r)}catch{return!1}}function R5(e,t,n){try{let r=le(k(e.configPath(t,n))),i=le(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+ue)}catch{return!1}}function z5(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`||!_(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||R5(e,t,r);if(!i&&c&&!L5(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{s5(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 cPe(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||y(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{pJ(`${o}.lock`,()=>{let t=m5(o).writePath;if(s||y(k(t),{recursive:!0}),e.format===`toml`){let r=tPe(WJ(),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=iPe(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=ePe(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 sPe={pi:r5};function cPe(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=sPe[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{y(k(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{pJ(`${t}.lock`,()=>{let e=null;try{e=C(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}dJ(t,c,e===null?void 0:{mode:O5(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 lPe(e){let t=lSe(e.editors).filter(e=>e.scope===`global`);if(dt())return t.map(t=>({editorId:t.id,label:t.label,action:`failed`,configPath:t.configPath(``,e.home),serverName:t.serverName(``),error:aPe}));let n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>z5(t,``,n,e.home))}function B5(e,t,n,r){let i=H5(e,t,n,r);return i.kind===`present`?i.entry:null}function V5(e,t,n,r){let i=I5(e,t,r);if(!IJ(i))return{kind:`no-entry`};let a=i[n];return IJ(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function H5(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!_(i))return{kind:`absent`};try{if(re(i).size>M5)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:T5(e)}}let a;try{a=C(i,`utf-8`)}catch(e){return{kind:`decline`,reason:T5(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:wNe(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=WJ().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return V5(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,Ts.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:V5(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=k5(a);return s?A5(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:V5(d4(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}function uPe(e,t){let n=[];for(let r of GJ)r!==`claude-desktop`&&L5(EY[r],e,t)&&n.push(r);return n}function U5(e){return e===`opencode`?Qxe:Zxe}function dPe(e,t,n){let r=EY[e],i=U5(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=B5(r,t,n,o.configPath);if(a!==null&&i(a))return{editorId:e,scope:o.scope,configPath:o.configPath}}return null}const W5=8192;function G5(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 fPe(e){return e.replace(/\\+\/?/g,e=>{if(!e.endsWith(`/`))return e;let t=e.length-1;return`${`\\`.repeat(t-t%2)}/`})}const pPe=RegExp(`("(?:${[`crashReporterKey`,`bootSessionUUID`,`deviceIdentifierForVendor`].join(`|`)})"\\s*:\\s*)"[^"]*"`,`g`);function mPe(e){return e.replace(pPe,`$1"[REDACTED-DEVICE-ID]"`)}function K5(e){return mPe(fPe(e))}const hPe=/^(\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=hPe.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 gPe(e){let t=x(e,`r`);try{let e=Buffer.alloc(W5),n=0,r=!1;for(;n<W5;){let i=w(t,e,n,W5-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 _Pe(e){try{let t=gPe(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 J5(e){return e===`OpenKnowledge`||e.startsWith(`OpenKnowledge `)}function vPe(e,t){let n={files:[],foreignIgnored:0,unparseable:0,droppedOverCap:0,windowDays:7},r;try{r=T(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=re(n).mtimeMs}catch{continue}if(r<i)continue;let c=_Pe(n),l=c.kind===`named`&&c.timestampMs!==null?c.timestampMs:r;if(c.kind===`unreadable`){s+=1;continue}if(!J5(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 Y5=`state/os-termination-evidence.json`,X5=6048e5,Z5=`/Library/Logs/DiagnosticReports`,Q5=/openknowledge/i,yPe=at.map(e=>ot(it[e]));function bPe(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({...xPe(e),stdout:t,stderr:n})})}catch(e){let t=e.code;r({status:null,stdout:``,stderr:``,errorCode:typeof t==`string`?t:`spawn-failed`})}})}function xPe(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 $5(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 e7(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 t7(e,t){return{...e,outcome:`unavailable`,unavailableReason:t}}function n7(e){return{...e,outcome:e.events.length>0?`collected`:`none-in-window`}}function r7(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function i7(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function a7(e,t){let n=t.indexOf(`
|
|
1527
|
-
`);if(n===-1)return null;let r,i;try{r=i7(JSON.parse(t.slice(0,n))),i=i7(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=i7(e);t===null||typeof t.name!=`string`||!J5(t.name)||a.push({name:t.name,pid:r7(t.pid),killReason:typeof t.reason==`string`?t.reason:null,residentPages:r7(t.rpages),lifetimeMaxPages:r7(t.lifetimeMax)})}let o=q5(r.timestamp);return{kind:`jetsam`,at:o===null?null:new Date(o).toISOString(),file:e,pageSize:r7(i7(i.memoryStatus)?.pageSize),largestProcessOwned:typeof i.largestProcess==`string`?J5(i.largestProcess):null,ownedProcesses:a}}const o7=/^JetsamEvent-.*\.ips$/;function s7(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=u7.exec(i);if(e===null){r+=1;continue}let[,a=``,o=``,s=``]=e;if(!Q5.test(s)){n+=1;continue}let c=
|
|
1530
|
-
`)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=u7.exec(i);if(e===null){r+=1;continue}let[,a=``,,o=``]=e,s=SPe.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 OPe(e,t,n){let r=DPe(e);if(r.lines.length===0)return{...r,events:[],unattributed:null};let i=await wPe(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 d7(e){return e.status===0||e.status===1&&/^-- No entries --$/m.test(e.stdout)}async function kPe(e,t,n){let r=e7(`linux`,`linux-journal`,[`journalctl ${c7.join(` `)}`,`journalctl ${l7.join(` `)}`]),[i,a]=await Promise.all([e(`journalctl`,[...c7]),e(`journalctl`,[...l7])]),o=[];if(d7(i)){let e=EPe(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: ${$5(i)}`);if(d7(a)){let e=await OPe(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: ${$5(a)}`);return o.length===2?t7(r,o.join(`; `)):o.length===1?{...r,outcome:`partial`,unavailableReason:o.join(`; `)}:n7(r)}const APe={41:`Microsoft-Windows-Kernel-Power`,1074:`User32`,2004:`Microsoft-Windows-Resource-Exhaustion-Detector`,6008:`EventLog`},jPe={1e3:`Application Error`,1001:`Windows Error Reporting`,1002:`Application Hang`};function f7(e){return e===`System`?APe:jPe}function MPe(e){let t=`System[(${Object.keys(f7(e)).map(e=>`EventID=${e}`).join(` or `)}) and TimeCreated[timediff(@SystemTime) <= ${X5}]]`;return e===`System`?`*[${t}]`:`*[${t} and EventData[${gPe.map(e=>`Data='${e}'`).join(` or `)}]]`}function p7(e){return[`qe`,e,`/q:${MPe(e)}`,`/f:xml`,`/rd:true`,`/c:200`]}function NPe(e){return de.join(e??`C:\\Windows`,`System32`,`wevtutil.exe`)}function PPe(e){return e.replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/&/g,`&`)}function FPe(e){return/[\\/]/.test(e)||/^[a-z]:/i.test(e)}function m7(e,t){let n=RegExp(`<${t}(?:\\s[^>]*)?>([\\s\\S]*?)</${t}>`,`g`);return[...e.matchAll(n)].map(e=>PPe(e[1]??``).trim())}function IPe(e,t){let n=f7(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=m7(o,`Data`),u=m7(o,`Name`),d=[...l,...u].some(e=>Q5.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!==``&&!FPe(e)):[]})}return{events:r,foreignIgnored:i,unparseable:a}}async function LPe(e,t){let n=NPe(t),r=[`System`,`Application`],i=e7(`win32`,`windows-event-log`,r.map(e=>`${n} ${p7(e).join(` `)}`)),a=await Promise.all(r.map(async t=>({log:t,result:await e(n,p7(t))}))),o=[];for(let{log:e,result:t}of a){if(t.status!==0){o.push(`${e}: ${$5(t)}`);continue}let n=IPe(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?t7(i,o.join(`; `)):o.length>0?{...i,outcome:`partial`,unavailableReason:o.join(`; `)}:n7(i)}async function h7(e={}){let t=e.platform??process.platform,n=e.runCommand??_Pe(),r=(e.now??(()=>new Date))();switch(t){case`darwin`:return yPe(e.macosReportsDir??Z5,r);case`linux`:return kPe(n,r,e.desktopLogsDir??j(cJ(),`logs`));case`win32`:return LPe(n,e.systemRoot??process.env.SystemRoot);default:return{...e7(t,null,[]),outcome:`unsupported`}}}const RPe={schemaVersion:1,outcome:`not-collected`};function g7(e){return`${JSON.stringify(e??RPe,null,2)}\n`}const zPe=it.stable.appId;function _7(){return j(cJ(),`bug-reports`)}function BPe(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=_7(),r=`${t}-bugreport`,i=j(n,`${r}.zip`);for(let e=2;_(i);e+=1)i=j(n,`${r}-${e}.zip`);return i}function v7(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function y7(e,t){let n=j(e,`.ok`,`config.yml`);if(_(n))try{let e=C(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 _(j(e,`.ok`))?Ee(`sha256`).update(le(e)).digest(`hex`).slice(0,12):null}function VPe(){let e={timestamp:new Date().toISOString(),platform:be(),osType:we(),osRelease:xe(),hostname:`[redacted]`,uptime:Te(),freeMem:_e(),totalMem:Ce(),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`,I6({encoding:`utf8`})).trim()}catch{}try{let t=j(__dirname,`..`,`..`,`package.json`);_(t)&&(e.okVersion=JSON.parse(C(t,`utf8`)).version)}catch{}return e}const HPe=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function b7(e){let t=oe(e);return HPe.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function UPe(e,t){return C7(e,t).files}const WPe=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function x7(e,t=zPe){let n=j(e,`${t}.ShipIt`);if(!_(n))return[];let r;try{r=T(n)}catch{return[]}return WPe.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 S7(e){if(!_(e))return[];try{let t=new Map;for(let n of T(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 C7(e,t){if(!_(t))return{files:[],excludedByProjectSlug:0};let n=T(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(b7),i=[],a=r.filter(t=>{try{return C(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=>!b7(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function GPe(e){let t=j(e,`.ok`,`local`);return _(t)?{files:[`server.lock`,yd,_d].map(e=>j(t,e)).filter(e=>_(e))}:{files:[]}}function w7(e,t,n){let r=_J(e),i=[],a=[];for(let e of t){let t=j(r,e),o=j(n,e),s=_(t);s&&i.push(t),_(o)&&(s?a:i).push(o)}return{files:i,legacyFiles:a}}function KPe(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#${Ee(`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 T7(e){let t=e.revealDocNames?e.content:KPe(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=xP(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 E7(e){for(let t of e.files)try{let n=C(t,`utf8`);T7({zipfile:e.zipfile,name:`${e.prefix}/${oe(t)}`,content:t.endsWith(`.ips`)?K5(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 qPe(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??j(cJ(),`logs`),s=t.projectDir?y7(t.projectDir,i):null;y(k(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=VPe();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=C7(s,o),{files:d}=t.projectDir?GPe(t.projectDir):{files:[]},{files:f,legacyFiles:p}=t.projectDir?w7(t.projectDir,[gd.logsCurrent,gd.logsPrevious],j(t.projectDir,`.ok`,`local`,`logs`)):{files:[],legacyFiles:[]},{files:m,legacyFiles:h}=t.projectDir?w7(t.projectDir,[hd],j(t.projectDir,`.ok`,`local`)):{files:[],legacyFiles:[]},_=t.shipItLogFiles??[],v=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length+m.length+h.length,localSinkFileCount:f.length+p.length,shipItLogFileCount:_.length,diagnosticReportCount:v.length},`files collected`);let b=[],x=[],{ZipFile:S}=await Promise.resolve().then(()=>e(kQ(),1)),w=new S;E7({zipfile:w,files:[...l,..._],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:[...d,...m],prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:p,prefix:`legacy/local-logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:h,prefix:`legacy/lockdir`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:t.bugReportLedgerFiles??[],prefix:Yq,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:v,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i});for(let e of t.extraFiles??[])try{let t=C(e.sourcePath),n=`extra/${e.zipName??oe(e.sourcePath)}`;w.addBuffer(t,n),x.push(n);let r=v7(e,n);r!==null&&b.push(r)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&T7({zipfile:w,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:x,redactions:b});let T=new Set(v.map(e=>`diagnostic-reports/${oe(e)}`)),E=x.filter(e=>T.has(e)),D=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:G5(t.diagnosticReports,E.length);w.addBuffer(Buffer.from(`${D}\n`,`utf8`),`state/diagnostic-reports-status.txt`),x.push(`state/diagnostic-reports-status.txt`),T7({zipfile:w,name:Y5,content:g7(t.osTerminationEvidence),redact:n,revealDocNames:!0,bundleFiles:x,redactions:b});let ee=JSON.stringify(c,null,2);w.addBuffer(Buffer.from(ee,`utf8`),`sysinfo.json`),x.push(`sysinfo.json`);let te={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:x,redactions:b,sysinfo:c};w.addBuffer(Buffer.from(JSON.stringify(te,null,2),`utf8`),`MANIFEST.json`);let ne=b.reduce((e,t)=>e+t.lineCount,0),re=new Set(_.map(e=>`logs/${oe(e)}`)),ie=x.filter(e=>re.has(e)),O=new Set((t.bugReportLedgerFiles??[]).map(e=>`${Yq}/${oe(e)}`)),ae=x.filter(e=>O.has(e)),A=s?x.filter(e=>e.startsWith(`logs/`)&&!b7(e)&&!re.has(e)):[],se=E.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.`]:[],ce=se.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...se]:[`Redaction was disabled for this bundle; file contents are unmodified.`],M=[`# Bug Report Bundle`,``,`Generated: ${te.generatedAt}`,`Project: ${s??`(unscoped)`}`,...t.projectDir?[`Project diagnostic source: ${Td(`logs`,`projects`)} (current product only).`]:[],`Discipline version: ${te.disciplineVersion}`,``,`## Contents`,``,...x.map(e=>`- ${e}`),``,`## Privacy`,``,...A.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:`,...A.map(e=>`- ${e}`),``]:[],...ie.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:`,...ie.map(e=>`- ${e}`),``]:[],...E.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:`,...E.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:`,`- ${Y5}`,``]:[],...ae.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:`,...ae.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${bP.join(`, `)}`,ne>0?`${ne} line(s) were scrubbed across ${b.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...se,``,`This bundle is safe to attach to a GitHub issue.`]:ce].join(`
|
|
1531
|
-
`);w.addBuffer(Buffer.from(M,`utf8`),`README.md`),w.end();let N=g(r);return w.outputStream.pipe(N),await new Promise((e,t)=>{N.on(`close`,e),N.on(`error`,t)}),i?.info({bundlePath:r,fileCount:x.length,redactionCount:ne},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:x,redactions:b,redactedLineCount:ne,generatedAt:te.generatedAt}}}function JPe(e){if(!e||typeof e!=`object`)return String(e);let t=typeof e.readProcessStart;return`${RJ(e)} readProcessStart=${t}`}function D7(e,t={}){if(!Number.isSafeInteger(e)||e<=0||e>4294967295)return null;let n=t.arch??process.arch,r=(e,n,r)=>{BJ(n,r),t.onNativeFailure?.({kind:e,reason:zJ(n,r)})};try{let i=!1,a=VJ(t.nativeResolver,(e,t)=>{i=!0,r(`unavailable`,e,t)});if(!a||typeof a!=`object`||!(`readProcessStart`in a)||typeof a.readProcessStart!=`function`){let e;return e=a==null?i?`no usable binding was returned`:`the addon was not found`:JPe(a),r(`unavailable`,`the Windows native addon (native-config.win32-${n}-msvc.node) did not load or does not export readProcessStart`,e),null}let o=a.readProcessStart(e);return typeof o==`number`&&Number.isSafeInteger(o)&&o>=0?o:(r(`unavailable`,`readProcessStart returned an invalid value`,RJ(o)),null)}catch(e){return r(`query-failed`,`readProcessStart failed`,e),null}}function YPe(e,t={}){return D8(e,{platform:t.platform,readNative:e=>D7(e,{onNativeFailure:t.onNativeFailure})})}function XPe(e){let{platform:t,pid:n,nativeFailures:r,causeRecorded:i}=e,a=r.some(e=>{switch(e.kind){case`unavailable`:return!0;case`query-failed`:return!1;default:return e.kind}}),o=r.length===0?``:a?`Reinstall OpenKnowledge to restore the Windows component that verifies process identity. `:`The Windows component loaded but the operating system refused the query, so reinstalling will not help; retry from an account that can inspect that process. `;return(t===`linux`?`Linux reads the process start from /proc/${n}/stat and /proc/stat; restore read access to /proc and retry. `:t===`darwin`?`macOS reads the process start with ps, and that read failed, as it does inside some sandboxes; retry from a shell where ps can run. `:t===`win32`?o:``)+(r.length>0&&i?`The failure detail is recorded in the CLI log under ${Td(`logs`)}. `:``)}function ZPe(e){let t=new Set;return wMe(n=>{let r=[],i=D7(n,{onNativeFailure:e=>{r.push(e)}});for(let i of new Set(r.map(e=>e.kind)))t.has(i)||(t.add(i),(e??void 0)?.warn({event:`process-start-native-failure`,lockPid:n,kind:i,reasons:r.filter(e=>e.kind===i).map(e=>e.reason)},`the Windows process-start query failed, so lock holders cannot be verified; later failures of this kind are not recorded again`));return i})}function O7(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 k7(e){return Ee(`sha256`).update(e).digest(`hex`)}function A7(e){return j(cJ(le(e)),`pi-trust`)}function j7(e,t){return j(A7(e),k7(le(t)))}function M7(e,t,n){return j(j7(e,t),`${k7(n)}.json`)}var N7=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${O7(e)} ${O7(t)}; ${O7(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function P7(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 N7(e,`could not ${t}: ${i}`,a,n)}function F7(e){let t;try{t=v(e)}catch(t){if(t.code===`ENOENT`)return!1;throw P7(e,`be inspected`,t)}if(!t.isDirectory())throw new N7(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function I7(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function L7(e,t){if(!IJ(e)||!I7(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==le(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==le(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==le(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!IJ(e.previous))throw new N7(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&&I7(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&I7(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new N7(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 R7(e,t,n){let r;try{r=v(n)}catch(e){throw P7(n,`be inspected`,e)}if(!r.isFile())throw new N7(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=C(n,`utf8`)}catch(e){throw P7(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new N7(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=L7(a,n);if(o.cwd!==le(t)||n!==M7(e,t,o.canonicalTrustPath))throw new N7(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 z7(e,t){let{record:n,path:r}=t;for(let t of[A7(e),j7(e,n.cwd)])if(!F7(t))throw new N7(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=R7(e,n.cwd,r);if(!Fe(i.record,n))throw new N7(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function QPe(e,t,n,r,i){let a={version:1,cwd:le(t),configuredTrustPath:le(n),canonicalTrustPath:le(r),state:`pending`,previous:i},o=M7(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!Fe(L7(JSON.parse(s),o),a))throw new N7(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);F7(A7(e)),F7(k(o));try{y(k(o),{recursive:!0,mode:448})}catch(e){throw P7(k(o),`be created`,e)}let c;try{c=v(o,{throwIfNoEntry:!1})}catch(e){throw P7(o,`be inspected`,e)}if(c)throw new N7(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{dJ(o,s,{mode:384})}catch(e){throw P7(o,`be written`,e)}return{path:o,record:a}}function $Pe(e,t){let n=z7(e,t);if(n.record.state!==`pending`)throw new N7(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{dJ(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw P7(n.path,`be committed`,e)}return{path:n.path,record:r}}function B7(e,t){if(!F7(A7(e)))return[];let n=j7(e,t);if(!F7(n))return[];let r;try{r=T(n).sort()}catch(e){throw P7(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>R7(e,t,j(n,r)))}function V7(e,t){let n=z7(e,t);try{ie(n.path)}catch(e){throw P7(n.path,`be removed after reconciling its grant`,e)}for(let t of[k(n.path),A7(e)])try{ne(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw P7(t,`be removed after reconciling its grant`,e)}}var eFe=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`)}}})),tFe=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())}}})),nFe=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}})),H7=i(((e,n)=>{var r=t(`fs`),i=eFe(),a=tFe(),o=nFe(),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;ee(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;ee(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=ee;function ee(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))}}})),rFe=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}})),iFe=i((e=>{var t=rFe();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}}})),aFe=i(((e,t)=>{t.exports=iFe()})),oFe=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`)})),sFe=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=oFe(),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)}}})),cFe=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})),lFe=i(((e,n)=>{let r=t(`path`),i=H7(),a=aFe(),o=sFe(),s=cFe(),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})),uFe=i(((e,t)=>{let n=H7();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}})),U7=e(i(((e,t)=>{let n=lFe(),{toPromise:r,toSync:i,toSyncOptions:a}=uFe();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 W7=5e3;function G7(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 ${W7}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function K7(e,t){}function q7(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 dFe(e,t,n){await rxe(`${t}.ok.lock`,async()=>{let t=performance.now()+W7,r;for(;;)try{r=await U7.default.lock(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await Ue(G7(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}q7(i,e)},{onWarn:K7})}function fFe(e,t,n){pJ(`${t}.ok.lock`,()=>{let t=performance.now()+W7,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=U7.default.lockSync(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,G7(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}q7(a,e)},{onWarn:K7})}const pFe=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var J7=class extends Error{name=`PiResourceInspectionError`};function Y7(e){let t;try{t=v(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=re(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new J7(E5(`missing-symlink-target`),{cause:e}):e}return d(e,p.R_OK|(n.isDirectory()?p.X_OK:0)),!0}function mFe(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function hFe(e,t,n){let r=e;try{let i=D(e),a;r=t;try{a=D(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=le(t)}let o=j(a,`.agents`,`skills`),s=[];for(let e of pFe)r=j(i,`.pi`,e),Y7(r)&&s.push(r);if(r=j(i,`.pi`,`extensions`),Y7(r))for(let t of T(r).sort()){let i=j(r,t);le(n)!==j(le(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[j(i,`.pi`,`skills`),j(i,`.agents`,`skills`)])if(e!==o&&(r=e,Y7(e)))for(let t of T(e).sort())mFe(t)||s.push(j(e,t));let c=k(i);for(;c!==i;){r=j(c,`.agents`,`skills`),r!==o&&Y7(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 ${O7(r)}: ${e instanceof J7?e.message:E5(T5(e))}`}}}function X7(e){let t;try{t=v(e).isSymbolicLink()}catch(e){return e.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:T5(e)}}let n=m5(e);if(n.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!re(n.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(e){return{kind:`declined`,reason:t&&e.code===`ENOENT`?`missing-symlink-target`:T5(e)}}return{kind:`ready`,path:n.writePath,symlink:t}}function Z7(e,t,n){let r=le(e),i=wY({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:EY.pi.projectConfigPath(r),trustPath:j(i,`trust.json`)}}function Q7(e){try{let t=D(e);return re(t).isDirectory()?(d(t,p.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${O7(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${O7(e)} could not be resolved or accessed: ${O7(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function $7(e){let t=Q7(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${O7(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function e9(e,t,n){let r=H5(EY.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 aY(i)?{state:`own-current`,text:a}:n5(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function t9(e,t){let n;try{n=C(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:T5(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 IJ(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
|
|
1533
|
-
`)}:{state:`unreadable`,reason:`invalid-json`}}function
|
|
1534
|
-
`:``),f=O5(s.path);dJ(s.path,d,f===void 0?void 0:{mode:f}),o9(n,()
|
|
1527
|
+
`);if(n===-1)return null;let r,i;try{r=i7(JSON.parse(t.slice(0,n))),i=i7(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=i7(e);t===null||typeof t.name!=`string`||!J5(t.name)||a.push({name:t.name,pid:r7(t.pid),killReason:typeof t.reason==`string`?t.reason:null,residentPages:r7(t.rpages),lifetimeMaxPages:r7(t.lifetimeMax)})}let o=q5(r.timestamp);return{kind:`jetsam`,at:o===null?null:new Date(o).toISOString(),file:e,pageSize:r7(i7(i.memoryStatus)?.pageSize),largestProcessOwned:typeof i.largestProcess==`string`?J5(i.largestProcess):null,ownedProcesses:a}}const o7=/^JetsamEvent-.*\.ips$/;function s7(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 SPe(e,t){let n=e7(`darwin`,`macos-jetsam`,[j(e,`JetsamEvent-*.ips`)]),r;try{r=await Ae(e)}catch(e){return t7(n,e.code??`unknown`)}let i=s7(await Promise.all(r.filter(e=>o7.test(e)).map(async t=>{try{return{file:t,mtimeMs:(await Ne(j(e,t))).mtimeMs}}catch{return{file:t,mtimeMs:null}}})),t.getTime()-X5,50,`newest-first`);n.unparseable+=i.statFailed,n.droppedOverCap=i.droppedOverCap;for(let t of i.files){let r=null;try{r=a7(t,await ke(j(e,t),`utf8`))}catch{}r===null?n.unparseable+=1:r.ownedProcesses.length===0?n.foreignIgnored+=1:n.events.push(r)}return n7(n)}const CPe=new Set([`vm-pageshortage`,`vm-compressor-thrashing`,`vm-pageout-starvation`,`low-swap`,`sustained-memory-pressure`]);function wPe(e,t=Z5){let n;try{n=T(t)}catch(e){return{outcome:`unavailable`,unavailableReason:e.code??`unknown`}}let r=e.fromMs-1e3,i=null,a=n.filter(e=>o7.test(e)).map(e=>{try{return{file:e,mtimeMs:re(j(t,e)).mtimeMs}}catch(t){return i??=t.code??`unknown`,{file:e,mtimeMs:null}}}),o=s7(a,r,5,`oldest-first`),s=0,c=o.statFailed,l=0,u=null;for(let n of o.files){let i;try{i=C(j(t,n),`utf8`)}catch(e){c+=1,u??=e.code??`unknown`;continue}s+=1;let a=a7(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:CPe.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 c7=[`--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`],l7=[`--user`,`--no-pager`,`--output=short-iso-precise`,`--since=-7d`,`--grep=Fatal Wayland communication error|Wayland protocol error|X IO error|Missing X server`],u7=/^(\S+) \S+ ([^:\s[]+)(?:\[\d+\])?: (.*)$/,TPe=/\[(\d+)(?::\d+)?:\d{4}\/\d{6}\.\d+:[A-Z0-9]+:[^\]]*\]\s*(.*)$/,EPe=/^desktop\.\d{4}-\d{2}-\d{2}\.log$/;async function DPe(e,t){let n=new Set,r;try{r=await Ae(e)}catch{return{pids:n,unreadable:!0}}let i=!1;for(let a of r){if(!EPe.test(a))continue;let r=j(e,a);try{if(t.getTime()-(await Ne(r)).mtimeMs>X5)continue;for(let e of(await ke(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 OPe(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:Q5.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 kPe(e){let t=[],n=0,r=0;for(let i of e.split(`
|
|
1529
|
+
`)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=u7.exec(i);if(e===null){r+=1;continue}let[,a=``,o=``,s=``]=e;if(!Q5.test(s)){n+=1;continue}let c=OPe(o,s);if(c===null){r+=1;continue}t.push({kind:`journal`,at:a,...c})}return{events:t,foreignIgnored:n,unparseable:r}}function APe(e){let t=[],n=0,r=0;for(let i of e.split(`
|
|
1530
|
+
`)){if(i.trim()===``||i.startsWith(`-- `))continue;let e=u7.exec(i);if(e===null){r+=1;continue}let[,a=``,,o=``]=e,s=TPe.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 jPe(e,t,n){let r=APe(e);if(r.lines.length===0)return{...r,events:[],unattributed:null};let i=await DPe(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 d7(e){return e.status===0||e.status===1&&/^-- No entries --$/m.test(e.stdout)}async function MPe(e,t,n){let r=e7(`linux`,`linux-journal`,[`journalctl ${c7.join(` `)}`,`journalctl ${l7.join(` `)}`]),[i,a]=await Promise.all([e(`journalctl`,[...c7]),e(`journalctl`,[...l7])]),o=[];if(d7(i)){let e=kPe(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: ${$5(i)}`);if(d7(a)){let e=await jPe(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: ${$5(a)}`);return o.length===2?t7(r,o.join(`; `)):o.length===1?{...r,outcome:`partial`,unavailableReason:o.join(`; `)}:n7(r)}const NPe={41:`Microsoft-Windows-Kernel-Power`,1074:`User32`,2004:`Microsoft-Windows-Resource-Exhaustion-Detector`,6008:`EventLog`},PPe={1e3:`Application Error`,1001:`Windows Error Reporting`,1002:`Application Hang`};function f7(e){return e===`System`?NPe:PPe}function FPe(e){let t=`System[(${Object.keys(f7(e)).map(e=>`EventID=${e}`).join(` or `)}) and TimeCreated[timediff(@SystemTime) <= ${X5}]]`;return e===`System`?`*[${t}]`:`*[${t} and EventData[${yPe.map(e=>`Data='${e}'`).join(` or `)}]]`}function p7(e){return[`qe`,e,`/q:${FPe(e)}`,`/f:xml`,`/rd:true`,`/c:200`]}function IPe(e){return de.join(e??`C:\\Windows`,`System32`,`wevtutil.exe`)}function LPe(e){return e.replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/&/g,`&`)}function RPe(e){return/[\\/]/.test(e)||/^[a-z]:/i.test(e)}function m7(e,t){let n=RegExp(`<${t}(?:\\s[^>]*)?>([\\s\\S]*?)</${t}>`,`g`);return[...e.matchAll(n)].map(e=>LPe(e[1]??``).trim())}function zPe(e,t){let n=f7(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=m7(o,`Data`),u=m7(o,`Name`),d=[...l,...u].some(e=>Q5.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!==``&&!RPe(e)):[]})}return{events:r,foreignIgnored:i,unparseable:a}}async function BPe(e,t){let n=IPe(t),r=[`System`,`Application`],i=e7(`win32`,`windows-event-log`,r.map(e=>`${n} ${p7(e).join(` `)}`)),a=await Promise.all(r.map(async t=>({log:t,result:await e(n,p7(t))}))),o=[];for(let{log:e,result:t}of a){if(t.status!==0){o.push(`${e}: ${$5(t)}`);continue}let n=zPe(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?t7(i,o.join(`; `)):o.length>0?{...i,outcome:`partial`,unavailableReason:o.join(`; `)}:n7(i)}async function h7(e={}){let t=e.platform??process.platform,n=e.runCommand??bPe(),r=(e.now??(()=>new Date))();switch(t){case`darwin`:return SPe(e.macosReportsDir??Z5,r);case`linux`:return MPe(n,r,e.desktopLogsDir??j(cJ(),`logs`));case`win32`:return BPe(n,e.systemRoot??process.env.SystemRoot);default:return{...e7(t,null,[]),outcome:`unsupported`}}}const VPe={schemaVersion:1,outcome:`not-collected`};function g7(e){return`${JSON.stringify(e??VPe,null,2)}\n`}const HPe=it.stable.appId;function _7(){return j(cJ(),`bug-reports`)}function UPe(e=new Date){let t=e.toISOString().replace(/[:.]/g,`-`),n=_7(),r=`${t}-bugreport`,i=j(n,`${r}.zip`);for(let e=2;_(i);e+=1)i=j(n,`${r}-${e}.zip`);return i}function v7(e,t){let{scrubbed:n}=e;return n!==void 0&&n.patterns.length>0?{file:t,lineCount:n.lineCount,patterns:[...n.patterns]}:null}function y7(e,t){let n=j(e,`.ok`,`config.yml`);if(_(n))try{let e=C(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 _(j(e,`.ok`))?Ee(`sha256`).update(le(e)).digest(`hex`).slice(0,12):null}function WPe(){let e={timestamp:new Date().toISOString(),platform:be(),osType:we(),osRelease:xe(),hostname:`[redacted]`,uptime:Te(),freeMem:_e(),totalMem:Ce(),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`,I6({encoding:`utf8`})).trim()}catch{}try{let t=j(__dirname,`..`,`..`,`package.json`);_(t)&&(e.okVersion=JSON.parse(C(t,`utf8`)).version)}catch{}return e}const GPe=[{prefix:`cli`,projectTagged:!0},{prefix:`desktop`,projectTagged:!1},{prefix:`mcp`,projectTagged:!1}];function b7(e){let t=oe(e);return GPe.some(e=>e.projectTagged&&t.startsWith(`${e.prefix}.`))}function KPe(e,t){return C7(e,t).files}const qPe=[`ShipIt_stderr.log`,`ShipIt_stdout.log`];function x7(e,t=HPe){let n=j(e,`${t}.ShipIt`);if(!_(n))return[];let r;try{r=T(n)}catch{return[]}return qPe.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).map(e=>{let t=j(n,e.entry);return{path:t,suffix:e.suffix,mtimeMs:JPe(t)}}).sort((e,t)=>t.mtimeMs-e.mtimeMs||t.suffix-e.suffix).slice(0,4).map(e=>e.path))}function JPe(e){try{return re(e).mtimeMs}catch{return 0}}function S7(e){if(!_(e))return[];try{let t=new Map;for(let n of T(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 C7(e,t){if(!_(t))return{files:[],excludedByProjectSlug:0};let n=T(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(b7),i=[],a=r.filter(t=>{try{return C(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=>!b7(e)||o.has(e)),excludedByProjectSlug:r.length-o.size}}function YPe(e){let t=j(e,`.ok`,`local`);return _(t)?{files:[`server.lock`,yd,_d].map(e=>j(t,e)).filter(e=>_(e))}:{files:[]}}function w7(e,t,n){let r=_J(e),i=[],a=[];for(let e of t){let t=j(r,e),o=j(n,e),s=_(t);s&&i.push(t),_(o)&&(s?a:i).push(o)}return{files:i,legacyFiles:a}}function XPe(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#${Ee(`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 T7(e){let t=e.revealDocNames?e.content:XPe(e.content).text;if(e.redact){let{redacted:n,patterns:r,lineCount:i}=xP(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 E7(e){for(let t of e.files)try{let n=C(t,`utf8`);T7({zipfile:e.zipfile,name:`${e.prefix}/${oe(t)}`,content:t.endsWith(`.ips`)?K5(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 ZPe(t){let{redact:n,outputPath:r,logger:i}=t,a=t.revealDocNames??!1,o=t.userLogsDir??j(cJ(),`logs`),s=t.projectDir?y7(t.projectDir,i):null;y(k(r),{recursive:!0}),i?.info({projectSlug:s},`gathering diagnostic data`);let c=WPe();c.desktop=t.desktop??null,c.language=t.language??null;let{files:l,excludedByProjectSlug:u}=C7(s,o),{files:d}=t.projectDir?YPe(t.projectDir):{files:[]},{files:f,legacyFiles:p}=t.projectDir?w7(t.projectDir,[gd.logsCurrent,gd.logsPrevious],j(t.projectDir,`.ok`,`local`,`logs`)):{files:[],legacyFiles:[]},{files:m,legacyFiles:h}=t.projectDir?w7(t.projectDir,[hd],j(t.projectDir,`.ok`,`local`)):{files:[],legacyFiles:[]},_=t.shipItLogFiles??[],v=t.diagnosticReports?.files??[];i?.info({logFileCount:l.length,logFilesExcludedByProjectSlug:u,lockFileCount:d.length+m.length+h.length,localSinkFileCount:f.length+p.length,shipItLogFileCount:_.length,diagnosticReportCount:v.length},`files collected`);let b=[],x=[],{ZipFile:S}=await Promise.resolve().then(()=>e(kQ(),1)),w=new S;E7({zipfile:w,files:[...l,..._],prefix:`logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:[...d,...m],prefix:`lockdir`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:f,prefix:`local-logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:p,prefix:`legacy/local-logs`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:h,prefix:`legacy/lockdir`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:t.bugReportLedgerFiles??[],prefix:Yq,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i}),E7({zipfile:w,files:v,prefix:`diagnostic-reports`,redact:n,revealDocNames:a,bundleFiles:x,redactions:b,logger:i});for(let e of t.extraFiles??[])try{let t=C(e.sourcePath),n=`extra/${e.zipName??oe(e.sourcePath)}`;w.addBuffer(t,n),x.push(n);let r=v7(e,n);r!==null&&b.push(r)}catch(t){i?.warn({sourcePath:e.sourcePath,err:t},`extra file unreadable; omitted from bundle`)}t.note&&T7({zipfile:w,name:`note.txt`,content:t.note,redact:n,revealDocNames:a,bundleFiles:x,redactions:b});let T=new Set(v.map(e=>`diagnostic-reports/${oe(e)}`)),E=x.filter(e=>T.has(e)),D=t.diagnosticReports===void 0?`not-collected (no collection attempted)`:G5(t.diagnosticReports,E.length);w.addBuffer(Buffer.from(`${D}\n`,`utf8`),`state/diagnostic-reports-status.txt`),x.push(`state/diagnostic-reports-status.txt`),T7({zipfile:w,name:Y5,content:g7(t.osTerminationEvidence),redact:n,revealDocNames:!0,bundleFiles:x,redactions:b});let ee=JSON.stringify(c,null,2);w.addBuffer(Buffer.from(ee,`utf8`),`sysinfo.json`),x.push(`sysinfo.json`);let te={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:s,files:x,redactions:b,sysinfo:c};w.addBuffer(Buffer.from(JSON.stringify(te,null,2),`utf8`),`MANIFEST.json`);let ne=b.reduce((e,t)=>e+t.lineCount,0),re=new Set(_.map(e=>`logs/${oe(e)}`)),ie=x.filter(e=>re.has(e)),O=new Set((t.bugReportLedgerFiles??[]).map(e=>`${Yq}/${oe(e)}`)),ae=x.filter(e=>O.has(e)),A=s?x.filter(e=>e.startsWith(`logs/`)&&!b7(e)&&!re.has(e)):[],se=E.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.`]:[],ce=se.length>0?[`Redaction was disabled for this bundle; file contents are unmodified,`,`with one exception.`,...se]:[`Redaction was disabled for this bundle; file contents are unmodified.`],M=[`# Bug Report Bundle`,``,`Generated: ${te.generatedAt}`,`Project: ${s??`(unscoped)`}`,...t.projectDir?[`Project diagnostic source: ${Td(`logs`,`projects`)} (current product only).`]:[],`Discipline version: ${te.disciplineVersion}`,``,`## Contents`,``,...x.map(e=>`- ${e}`),``,`## Privacy`,``,...A.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:`,...A.map(e=>`- ${e}`),``]:[],...ie.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:`,...ie.map(e=>`- ${e}`),``]:[],...E.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:`,...E.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:`,`- ${Y5}`,``]:[],...ae.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:`,...ae.map(e=>`- ${e}`),``]:[],...n?[`This bundle was auto-redacted before packaging.`,`Patterns checked: ${bP.join(`, `)}`,ne>0?`${ne} line(s) were scrubbed across ${b.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,...se,``,`This bundle is safe to attach to a GitHub issue.`]:ce].join(`
|
|
1531
|
+
`);w.addBuffer(Buffer.from(M,`utf8`),`README.md`),w.end();let N=g(r);return w.outputStream.pipe(N),await new Promise((e,t)=>{N.on(`close`,e),N.on(`error`,t)}),i?.info({bundlePath:r,fileCount:x.length,redactionCount:ne},`bundle written`),{zipPath:r,summary:{projectSlug:s,files:x,redactions:b,redactedLineCount:ne,generatedAt:te.generatedAt}}}function QPe(e){if(!e||typeof e!=`object`)return String(e);let t=typeof e.readProcessStart;return`${RJ(e)} readProcessStart=${t}`}function D7(e,t={}){if(!Number.isSafeInteger(e)||e<=0||e>4294967295)return null;let n=t.arch??process.arch,r=(e,n,r)=>{BJ(n,r),t.onNativeFailure?.({kind:e,reason:zJ(n,r)})};try{let i=!1,a=VJ(t.nativeResolver,(e,t)=>{i=!0,r(`unavailable`,e,t)});if(!a||typeof a!=`object`||!(`readProcessStart`in a)||typeof a.readProcessStart!=`function`){let e;return e=a==null?i?`no usable binding was returned`:`the addon was not found`:QPe(a),r(`unavailable`,`the Windows native addon (native-config.win32-${n}-msvc.node) did not load or does not export readProcessStart`,e),null}let o=a.readProcessStart(e);return typeof o==`number`&&Number.isSafeInteger(o)&&o>=0?o:(r(`unavailable`,`readProcessStart returned an invalid value`,RJ(o)),null)}catch(e){return r(`query-failed`,`readProcessStart failed`,e),null}}function $Pe(e,t={}){return D8(e,{platform:t.platform,readNative:e=>D7(e,{onNativeFailure:t.onNativeFailure})})}function eFe(e){let{platform:t,pid:n,nativeFailures:r,causeRecorded:i}=e,a=r.some(e=>{switch(e.kind){case`unavailable`:return!0;case`query-failed`:return!1;default:return e.kind}}),o=r.length===0?``:a?`Reinstall OpenKnowledge to restore the Windows component that verifies process identity. `:`The Windows component loaded but the operating system refused the query, so reinstalling will not help; retry from an account that can inspect that process. `;return(t===`linux`?`Linux reads the process start from /proc/${n}/stat and /proc/stat; restore read access to /proc and retry. `:t===`darwin`?`macOS reads the process start with ps, and that read failed, as it does inside some sandboxes; retry from a shell where ps can run. `:t===`win32`?o:``)+(r.length>0&&i?`The failure detail is recorded in the CLI log under ${Td(`logs`)}. `:``)}function tFe(e){let t=new Set;return wMe(n=>{let r=[],i=D7(n,{onNativeFailure:e=>{r.push(e)}});for(let i of new Set(r.map(e=>e.kind)))t.has(i)||(t.add(i),(e??void 0)?.warn({event:`process-start-native-failure`,lockPid:n,kind:i,reasons:r.filter(e=>e.kind===i).map(e=>e.reason)},`the Windows process-start query failed, so lock holders cannot be verified; later failures of this kind are not recorded again`));return i})}function O7(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 k7(e){return Ee(`sha256`).update(e).digest(`hex`)}function A7(e){return j(cJ(le(e)),`pi-trust`)}function j7(e,t){return j(A7(e),k7(le(t)))}function M7(e,t,n){return j(j7(e,t),`${k7(n)}.json`)}var N7=class extends Error{constructor(e,t,n,r){super(`Pi trust receipt at ${O7(e)} ${O7(t)}; ${O7(n)}`,{cause:r}),this.name=`PiTrustReceiptError`}};function P7(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 N7(e,`could not ${t}: ${i}`,a,n)}function F7(e){let t;try{t=v(e)}catch(t){if(t.code===`ENOENT`)return!1;throw P7(e,`be inspected`,t)}if(!t.isDirectory())throw new N7(e,`is not a regular directory`,`restore the intended receipt directory without a symlink, then retry`);return!0}function I7(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function L7(e,t){if(!IJ(e)||!I7(e,[`version`,`cwd`,`configuredTrustPath`,`canonicalTrustPath`,`state`,`previous`])||e.version!==1||typeof e.cwd!=`string`||e.cwd!==le(e.cwd)||typeof e.configuredTrustPath!=`string`||e.configuredTrustPath!==le(e.configuredTrustPath)||typeof e.canonicalTrustPath!=`string`||e.canonicalTrustPath!==le(e.canonicalTrustPath)||e.state!==`pending`&&e.state!==`committed`||!IJ(e.previous))throw new N7(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&&I7(e.previous,[`present`]))n={present:!1};else if(e.previous.present===!0&&I7(e.previous,[`present`,`value`]))n={present:!0,value:e.previous.value};else throw new N7(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 R7(e,t,n){let r;try{r=v(n)}catch(e){throw P7(n,`be inspected`,e)}if(!r.isFile())throw new N7(n,`is not a regular file`,`restore the intended receipt as a regular file without a symlink, then retry`);let i;try{i=C(n,`utf8`)}catch(e){throw P7(n,`be read`,e)}let a;try{a=JSON.parse(i)}catch(e){throw new N7(n,`is not valid JSON`,`repair its JSON syntax without changing the recorded decision, then retry`,e)}let o=L7(a,n);if(o.cwd!==le(t)||n!==M7(e,t,o.canonicalTrustPath))throw new N7(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 z7(e,t){let{record:n,path:r}=t;for(let t of[A7(e),j7(e,n.cwd)])if(!F7(t))throw new N7(t,`no longer exists`,`restore access to the expected receipt directory, then retry`);let i=R7(e,n.cwd,r);if(!Fe(i.record,n))throw new N7(r,`changed while its trust decision was being updated`,`retry to read its current ownership record`);return i}function nFe(e,t,n,r,i){let a={version:1,cwd:le(t),configuredTrustPath:le(n),canonicalTrustPath:le(r),state:`pending`,previous:i},o=M7(e,a.cwd,a.canonicalTrustPath),s=`${JSON.stringify(a,null,2)}\n`;if(!Fe(L7(JSON.parse(s),o),a))throw new N7(o,`cannot preserve the previous decision as JSON`,`provide the original decision as a JSON value before retrying`);F7(A7(e)),F7(k(o));try{y(k(o),{recursive:!0,mode:448})}catch(e){throw P7(k(o),`be created`,e)}let c;try{c=v(o,{throwIfNoEntry:!1})}catch(e){throw P7(o,`be inspected`,e)}if(c)throw new N7(o,`already exists`,`reconcile the existing ownership record before recording another grant`);try{dJ(o,s,{mode:384})}catch(e){throw P7(o,`be written`,e)}return{path:o,record:a}}function rFe(e,t){let n=z7(e,t);if(n.record.state!==`pending`)throw new N7(n.path,`is already committed`,`use the current ownership record without committing it again`);let r={...n.record,state:`committed`};try{dJ(n.path,`${JSON.stringify(r,null,2)}\n`,{mode:384})}catch(e){throw P7(n.path,`be committed`,e)}return{path:n.path,record:r}}function B7(e,t){if(!F7(A7(e)))return[];let n=j7(e,t);if(!F7(n))return[];let r;try{r=T(n).sort()}catch(e){throw P7(n,`be listed`,e)}return r.filter(e=>/^[a-f0-9]{64}\.json$/.test(e)).map(r=>R7(e,t,j(n,r)))}function V7(e,t){let n=z7(e,t);try{ie(n.path)}catch(e){throw P7(n.path,`be removed after reconciling its grant`,e)}for(let t of[k(n.path),A7(e)])try{ne(t)}catch(e){let n=e.code;if(n!==`ENOTEMPTY`&&n!==`EEXIST`&&n!==`ENOENT`)throw P7(t,`be removed after reconciling its grant`,e)}}var iFe=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`)}}})),aFe=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())}}})),oFe=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}})),H7=i(((e,n)=>{var r=t(`fs`),i=iFe(),a=aFe(),o=oFe(),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;ee(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;ee(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=ee;function ee(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))}}})),sFe=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}})),cFe=i((e=>{var t=sFe();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}}})),lFe=i(((e,t)=>{t.exports=cFe()})),uFe=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`)})),dFe=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=uFe(),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)}}})),fFe=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})),pFe=i(((e,n)=>{let r=t(`path`),i=H7(),a=lFe(),o=dFe(),s=fFe(),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})),mFe=i(((e,t)=>{let n=H7();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}})),U7=e(i(((e,t)=>{let n=pFe(),{toPromise:r,toSync:i,toSyncOptions:a}=mFe();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 W7=5e3;function G7(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 ${W7}ms`,{cause:e}),{code:`ELOCKED`});return Math.min(25,r)}function K7(e,t){}function q7(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 hFe(e,t,n){await rxe(`${t}.ok.lock`,async()=>{let t=performance.now()+W7,r;for(;;)try{r=await U7.default.lock(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){await Ue(G7(n,t,e))}let i=[];try{n()}catch(e){i.push(e)}finally{try{await r()}catch(e){i.push(e)}}q7(i,e)},{onWarn:K7})}function gFe(e,t,n){pJ(`${t}.ok.lock`,()=>{let t=performance.now()+W7,r=new Int32Array(new SharedArrayBuffer(4)),i;for(;;)try{i=U7.default.lockSync(k(e),{realpath:!1,lockfilePath:`${e}.lock`});break}catch(n){Atomics.wait(r,0,0,G7(n,t,e))}let a=[];try{n()}catch(e){a.push(e)}finally{try{i()}catch(e){a.push(e)}}q7(a,e)},{onWarn:K7})}const _Fe=[`settings.json`,`prompts`,`themes`,`SYSTEM.md`,`APPEND_SYSTEM.md`];var J7=class extends Error{name=`PiResourceInspectionError`};function Y7(e){let t;try{t=v(e)}catch(e){if(e.code===`ENOENT`)return!1;throw e}let n;try{n=re(e)}catch(e){throw t.isSymbolicLink()&&e.code===`ENOENT`?new J7(E5(`missing-symlink-target`),{cause:e}):e}return d(e,p.R_OK|(n.isDirectory()?p.X_OK:0)),!0}function vFe(e){return e===`open-knowledge`||e.startsWith(`open-knowledge-`)}function yFe(e,t,n){let r=e;try{let i=D(e),a;r=t;try{a=D(t)}catch(e){if(e.code!==`ENOENT`)throw e;a=le(t)}let o=j(a,`.agents`,`skills`),s=[];for(let e of _Fe)r=j(i,`.pi`,e),Y7(r)&&s.push(r);if(r=j(i,`.pi`,`extensions`),Y7(r))for(let t of T(r).sort()){let i=j(r,t);le(n)!==j(le(e),`.pi`,`extensions`,t)&&s.push(i)}for(let e of[j(i,`.pi`,`skills`),j(i,`.agents`,`skills`)])if(e!==o&&(r=e,Y7(e)))for(let t of T(e).sort())vFe(t)||s.push(j(e,t));let c=k(i);for(;c!==i;){r=j(c,`.agents`,`skills`),r!==o&&Y7(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 ${O7(r)}: ${e instanceof J7?e.message:E5(T5(e))}`}}}function X7(e){let t;try{t=v(e).isSymbolicLink()}catch(e){return e.code===`ENOENT`?{kind:`not-present`}:{kind:`declined`,reason:T5(e)}}let n=m5(e);if(n.readPath===null)return{kind:`declined`,reason:`unresolved-symlink`};try{if(!re(n.readPath).isFile())return{kind:`declined`,reason:`not-a-file`}}catch(e){return{kind:`declined`,reason:t&&e.code===`ENOENT`?`missing-symlink-target`:T5(e)}}return{kind:`ready`,path:n.writePath,symlink:t}}function Z7(e,t,n){let r=le(e),i=wY({home:t,env:n??(t===void 0?process.env:{})});return{cwd:r,bridgePath:EY.pi.projectConfigPath(r),trustPath:j(i,`trust.json`)}}function Q7(e){try{let t=D(e);return re(t).isDirectory()?(d(t,p.X_OK),{kind:`ready`,project:{path:e,canonical:t}}):{kind:`refused`,error:`Pi project path ${O7(e)} is not a directory; restore the intended project directory, then retry`}}catch(t){return{kind:`refused`,error:`Pi project directory ${O7(e)} could not be resolved or accessed: ${O7(t instanceof Error?t.message:String(t))}; restore the directory or symlink and check its permissions, then retry`}}}function $7(e){let t=Q7(e.path);if(t.kind===`refused`)return t.error;if(t.project.canonical!==e.canonical)return`Pi project path ${O7(e.path)} changed while waiting for its trust lock; restore the intended project location, then retry`}function e9(e,t,n){let r=H5(EY.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 aY(i)?{state:`own-current`,text:a}:n5(i)?{state:`own-stale`,text:a}:{state:`foreign`,text:a}}function t9(e,t){let n;try{n=C(e.path,`utf-8`)}catch(t){let n=t.code;return e.kind===`missing`&&n===`ENOENT`?{state:`untrusted`,entries:{},trailingNewline:!1}:{state:`unreadable`,reason:T5(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 IJ(r)?{state:r[t]===!0?`trusted`:`untrusted`,entries:r,trailingNewline:n.endsWith(`
|
|
1533
|
+
`)}:{state:`unreadable`,reason:`invalid-json`}}function bFe(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 E5(e)}}function n9(e,t){return{kind:`refused`,error:`trust store ${O7(e)}: ${bFe(t)}`}}function r9(e){let t=X7(e);try{switch(t.kind){case`declined`:return n9(e,t.reason);case`ready`:return{kind:`ready`,path:D(t.path)};case`not-present`:break;default:throw Error(`unhandled trust file resolution: ${t}`)}let n=k(e),r=[oe(e)],i=v(n,{throwIfNoEntry:!1});for(;!i;){let t=k(n);if(t===n)return n9(e,`unavailable-root`);r.unshift(oe(n)),n=t,i=v(n,{throwIfNoEntry:!1})}try{return{kind:`missing`,path:j(D(n),...r)}}catch(t){return n9(e,i.isSymbolicLink()&&t.code===`ENOENT`?`missing-symlink-target`:T5(t))}}catch(t){return n9(e,T5(t))}}function i9(e,t){let n=r9(e);return n.kind===`refused`?n:n.path!==t.path||t.kind===`ready`&&n.kind===`missing`?n9(e,`path-changed`):n}function xFe(e,t,n){let r=Z7(e,t,n),i=Q7(r.cwd);if(i.kind===`refused`)return{...r,project:`unavailable`,error:i.error};let a=e9(r.cwd,r.bridgePath,t).state,o=r9(r.trustPath),s=o.kind===`refused`?`unreadable`:o.kind===`missing`?`untrusted`:t9(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:SFe(r.bridgePath).displayNames}}function SFe(e){let t=k(e),n=oe(e);try{return{displayNames:T(t).filter(e=>e!==n&&e.endsWith(`.ts`)).sort().map(e=>O7(JSON.stringify(e)))}}catch{return{displayNames:[]}}}async function CFe(e,t={mode:`published`},n,r,i){let a=Z7(e,n,r),o=Q7(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 ${O7(i)} no longer matches the current directory ${O7(o.project.canonical)}. Reopen the intended project and approve the Pi integration again; no bridge or trust settings were changed.`};let s=e9(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=r5(t)}catch{e=void 0}c=e!==void 0&&s.text===e?`unchanged`:`refreshed`}if(c!==`unchanged`){let e=z5(EY.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}`:O7(e.error)}}let l=await wFe(a.trustPath,o.project,n??ve());return{...a,ok:l.action===`already-trusted`||l.action===`added`,bridge:c,trust:l.action,...l.error===void 0?{}:{error:l.error}}}async function wFe(e,t,n){let r=t.canonical,i=r9(e);if(i.kind===`refused`)return{action:`refused-unreadable`,error:i.error};try{y(k(i.path),{recursive:!0})}catch(e){return{action:`failed`,error:O7(e instanceof Error?e.message:String(e))}}let a={action:`added`};try{await hFe(e,i.path,()=>{let o=$7(t);if(o){a.action=`refused-unreadable`,a.error=o;return}let s=i9(e,i);if(s.kind===`refused`){a.action=`refused-unreadable`,a.error=s.error;return}let c=t9(s,r);if(c.state===`trusted`){a.action=`already-trusted`;return}if(c.state===`unreadable`){a.action=`refused-unreadable`,a.error=n9(e,c.reason).error;return}let l=o9(n,()=>{let t=B7(n,r).find(e=>e.record.canonicalTrustPath===s.path);return t&&V7(n,t),nFe(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=O5(s.path);dJ(s.path,d,f===void 0?void 0:{mode:f}),o9(n,()=>rFe(n,l)),a.action=`added`})}catch(e){return{action:`failed`,error:O7(e instanceof Error?e.message:String(e))}}return a}function TFe(e){let t=[],n=e;try{for(;;){if(v(n,{throwIfNoEntry:!1})){if(t.length===0)return;let e=D(n);return re(e).isDirectory()?(d(e,p.X_OK),j(e,...t)):void 0}let e=k(n);if(e===n)return;t.unshift(oe(n)),n=e}}catch{return}}function a9(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=O5(r);dJ(r,f,p===void 0?void 0:{mode:p}),i.entries=d,o9(t,()=>V7(t,l)),s.result={action:`removed`}}function
|
|
1536
|
+
`)}}function EFe(e,t,n,r={}){let i=Z7(e,t,n),a=t??ve(),o=Q7(i.cwd),s=o.kind===`refused`&&r.recordedOnly?TFe(i.cwd):void 0,c=o.kind===`ready`?o.project.canonical:s,l;try{l=o9(a,()=>{let e=B7(a,i.cwd);return c===void 0||c===i.cwd?e:[...B7(a,c),...e]})}catch(e){return{action:`failed`,error:O7(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 ${O7(JSON.stringify(t.cwd))}; configured store ${O7(JSON.stringify(t.configuredTrustPath))}; recorded destination ${O7(JSON.stringify(t.canonicalTrustPath))}; ownership record ${O7(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=yFe(o.project.canonical,a,EY.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=r9(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 ${O7(e)} no longer points to its recorded destination ${O7(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(DFe(e,a,d,o.project))}return a9(f)}function o9(e,t){try{return t()}catch(t){throw t instanceof N7?t:Error(`Could not access OpenKnowledge's Pi trust ownership records at ${O7(j(cJ(e),`pi-trust`))}: ${O7(t instanceof Error?t.message:String(t))}. Check the records and their permissions, then retry.`,{cause:t})}}function DFe(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{v(k(a.path))}catch(e){return{action:`failed`,error:`The recorded Pi trust directory ${O7(k(a.path))} is unavailable: ${O7(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{gFe(i,a.path,()=>{let e=$7(r);if(e){c.result={action:`kept-unverified`,error:e};return}let l=i9(i,a);if(l.kind===`refused`){c.result={action:`refused-unreadable`,error:l.error};return}let u=t9(l,r.canonical);if(u.state===`unreadable`){c.result={action:`refused-unreadable`,error:n9(i,u.reason).error};return}let d=o.map(e=>({cwd:e.cwd,mode:e.mode,expectedConfiguredPath:e.receipt?.record.configuredTrustPath,receipt:o9(t,()=>B7(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{OFe(e,t,i,l.path,u,n,r,c)}catch(t){let n=O7(t instanceof Error?t.message:String(t)),r=t instanceof N7?``:`; retry to check its current state.`;s.push({action:`failed`,error:`Pi trust entry ${O7(JSON.stringify(e.cwd))} in ${O7(i)} could not be reconciled: ${n}${r}`})}s.push(c.result),c.result={action:`not-present`}}})}catch(e){s.push({action:`failed`,error:O7(e instanceof Error?e.message:String(e))})}return a9([...s,c.result])}function OFe(e,t,n,r,i,a,o,s){let{cwd:c,receipt:l}=e;if(i.entries[c]!==!0){l&&e.mode===`recorded`&&o9(t,()=>V7(t,l)),s.result={action:`not-present`};return}let u=`To remove this grant manually, close Pi and remove only the ${O7(JSON.stringify(c))} entry from ${O7(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=>O7(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`&&o9(t,()=>V7(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 ${O7(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=O5(r);dJ(r,f,p===void 0?void 0:{mode:p}),i.entries=d,o9(t,()=>V7(t,l)),s.result={action:`removed`}}function kFe(e){return aY(e)||cY(e)||n5(e)}const s9=10485760;function c9(e,t,n,r=!1){let i=EFe(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 l9(e,t,n,r){if(e.id!==`pi`)return{kind:`not-present`};let i=c9(t,n,r,!0);return i.trust===`not-present`?{kind:`not-present`}:{kind:`removed`,...i}}function AFe(e,t,n,r,i){let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=X7(a);if(o.kind===`not-present`)return l9(e,t,n,i);if(o.kind===`declined`)return o;let s=H5(e,t,n,o.path);if(s.kind===`absent`||s.kind===`no-entry`)return l9(e,t,n,i);if(s.kind===`decline`)return{kind:`declined`,reason:s.reason};if(!kFe(s.entry))return{kind:`left-foreign`};let c=e.serverName(t);if(e.format===`file`){let e=c9(t,n,i);try{te(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`?NFe(o.path,c):e.format===`yaml`?MFe(o.path,e.topLevelKey,c):jFe(o.path,e.topLevelKey,e.serverMapSubKey,c)}function jFe(e,t,n,r){let i;try{i=C(e,`utf-8`)}catch(e){return{kind:`declined`,reason:T5(e)}}if(Buffer.byteLength(i,`utf-8`)>s9)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=qNe(i,P5(t,n,r));return o?(dJ(e,a,{mode:O5(e)}),{kind:`removed`}):{kind:`not-present`}}function MFe(e,t,n){let r;try{r=C(e,`utf-8`)}catch(e){return{kind:`declined`,reason:T5(e)}}if(Buffer.byteLength(r,`utf-8`)>s9)return{kind:`declined`,reason:`oversize`};let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=(0,Ts.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=D5(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&&dJ(e,u,{mode:O5(e)}),{kind:`removed`}}function
|
|
1542
|
+
`));let u=`${i?``:``}${c}`;return u!==r&&dJ(e,u,{mode:O5(e)}),{kind:`removed`}}function NFe(e,t){let n=WJ();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=C(e,`utf-8`)}catch(e){return{kind:`declined`,reason:T5(e)}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=D5(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&&dJ(e,u,{mode:O5(e)}),{kind:`removed`}}function AFe(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}function jFe(e){let{priorCommand:t,priorArgs:n}=u9(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function u9(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 d9(e,t,n={}){let r=WMe(e,t),i;try{i=C(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,text:i}}let o=a&&typeof a==`object`?a:{},s=k8(o),c=s&&!A8(o,n);if(!a||typeof a!=`object`||!vMe(a.pid))return{status:`corrupt`,lockPath:r,text:i,...c?{foreignHost:!0}:{}};let l=GMe(a),{pid:u}=l;if(c)return{status:`foreign-host`,lockPath:r,lock:l};let d=P8(l,{isAlive:n.isAlive,readProcessStart:n.readProcessStart,sameMachine:s});switch(d.verdict){case`gone`:return{status:`dead-pid`,lockPath:r,lock:l,text:i};case`replaced`:return{status:`reused-pid`,lockPath:r,lock:l,text:i};case`unverified`:return d.cause===`unverified-owner`?{status:`unverified-owner`,lockPath:r,pid:u}:{status:`alive`,lockPath:r,lock:l};case`writer`:return{status:`alive`,lockPath:r,lock:l};default:return d}}function MFe(e){return`does not record its owning machine, and its recorded process ${e} is still running on this machine`}function f9(e){return typeof e.machineId==`string`?`records a machine ID different from the one in ${g8()}`:`records only the host ${O7(e.hostname)}, not this machine's ${ye()}`}function NFe(e){return e===`win32`?`USERPROFILE`:`HOME`}function PFe(e){return e.processStart===void 0?` This lock records no process start; a server started by this release records one, which lets \`${ht()} stop\` confirm it from any home folder.`:``}function FFe(e,t){let n=`\`${ht()} stop\``;return`If the server was started on this machine from another account, run ${n} as that account. If it was started from this account with a different home folder, run ${n} with \`${NFe(t)}\` set to that folder. Otherwise stop it from the machine that owns the lock.${PFe(e)}`}async function IFe(e,t=void 0){let n=d9(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=qMe(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 LFe(e,t={}){return UFe(e,t.isAlive??m8)?{targets:[{name:`server`,pid:e.lock.pid,port:e.lock.port}],lock:e.lock}:{targets:[]}}function RFe(e){try{return ft()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function zFe(e){let t=e.inspect??(()=>d9(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??IFe,o=e.logger??void 0,s=e.platform??process.platform,c=t(),l=LFe(c,{isAlive:e.isAlive}),{lock:u}=l,d=[],f=[],p=(t,n)=>{o?.warn({lockDir:e.lockDir,lockPath:n.lockPath,lockPid:n.pid,platform:s,cause:n.cause,...`nativeFailures`in n&&n.nativeFailures.length>0?{nativeFailures:n.nativeFailures}:{}},`stop declined: lock holder identity unverified`),f.push({target:t,error:VFe(n,o!==void 0),unverified:n})},m=()=>{if(d.length>0){let e=d.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);r(`Stopped: ${e}`)}if(o?.info({lockDir:e.lockDir,signalled:d.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:f.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),f.length>0){let e=f.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `);i(`Failed to stop: ${e}`)}return{stopped:d,failed:f,hadTargets:!0}};if(c.status===`unverified-owner`){let{pid:e,lockPath:t}=c;return p({name:`server`,pid:e},{cause:`unverified-owner`,pid:e,lockPath:t}),m()}if(u===void 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 h=c.status===`alive`||c.status===`foreign-host`?c.lock.channel:void 0;if(e.force!==!0&&typeof h==`string`&&h.length>0){let t=e.selfChannel??RFe(o);if(t!==void 0&&h!==t)return i(`Not stopping: the server at ${e.lockDir} belongs to ${eee(h)}. `+(h===`dev`?`Stop it from that dev build, or run \`${gt} 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:h,selfChannel:t,pids:l.targets.map(e=>e.pid)},`stop declined: server belongs to another channel`),{stopped:[],failed:[],hadTargets:!0,declined:{otherChannel:h}}}if(e.force!==!0){let t=await a(e.lockDir,o);if(t!==null&&t>0)return i(`Not stopping: ${t} collaboration client${t===1?``:`s`} (editor window${t===1?``:`s`} or agents) still connected to the server at ${e.lockDir}. Close them, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,clients:t,pids:l.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}for(let t of l.targets){let a=[],o=(e.readProcessStart??YPe)(t.pid,{platform:s,onNativeFailure:e=>{a.push(e)}}),l=P8(u,{isAlive:e.isAlive??m8,readProcessStart:()=>o,refuseHolderStartedAfterLock:e.refuseHolderStartedAfterLock});switch(l.verdict){case`writer`:try{n(t.pid,`SIGTERM`),d.push(t)}catch(e){f.push({target:t,error:e instanceof Error?e.message:String(e)})}break;case`gone`:r(`${t.name} (pid=${t.pid}) had already exited`);break;case`replaced`:i(`Process ${t.pid} is no longer the server that wrote ${c.lockPath}; it was not signalled. Run \`${ht()} clean\` to remove the stale lock.`);break;case`unverified`:p(t,BFe(l.cause,{pid:t.pid,lockPath:c.lockPath,lock:u,platform:s,nativeFailures:a}));break;default:return l}}return m()}function BFe(e,t){let{pid:n,lockPath:r}=t;switch(e){case`foreign-host`:return{cause:e,pid:n,lockPath:r,lock:t.lock,platform:t.platform};case`unverified-owner`:return{cause:e,pid:n,lockPath:r};default:return{cause:e,pid:n,lockPath:r,platform:t.platform,nativeFailures:t.nativeFailures}}}const p9=`it was not signalled, and --force does not override this check.`;function VFe(e,t){let{pid:n,lockPath:r}=e;switch(e.cause){case`foreign-host`:{let{lock:t}=e;return typeof t.machineId==`string`?`The server lock at ${r} ${f9(t)}, so process ${n}, which is running on this machine, cannot be confirmed as the server that wrote it; ${p9} ${FFe(t,e.platform)}`:`The server lock at ${r} ${f9(t)}, and the start of process ${n}, which is running on this machine, does not confirm it as the server that wrote the lock; ${p9} If ${O7(t.hostname)} is another machine, stop the server there. If it is an earlier name of this machine, confirm that process ${n} is an OpenKnowledge server before ending it yourself, and once no OpenKnowledge server is running for this project, remove ${r}.`}case`unverified-owner`:return`The server lock at ${r} ${MFe(n)}, so it cannot be confirmed as the server that wrote the lock; ${p9} Check whether process ${n} is an OpenKnowledge server, and if it is, stop it yourself. Do not remove the lock file while that process is running.`;default:{let n=HFe(e,p9,`Once you have confirmed no OpenKnowledge server is running for this project, remove ${r}.`,t);return e.cause===`writer-identity-unrecorded`?`${n} A server you start again with this release records its machine ID, so \`${ht()} stop\` can confirm it.`:n}}}function HFe(e,t,n,r){let{pid:i,lockPath:a,platform:o,nativeFailures:s}=e,c=`Before ending process ${i} yourself, confirm that it is an OpenKnowledge server.`;switch(e.cause){case`process-start-unreadable`:return`Could not read when process ${i} started, so it cannot be confirmed as the server that wrote ${a}; ${t} `+XPe({platform:o,pid:i,nativeFailures:s,causeRecorded:r})+`${c} ${n}`;case`process-start-incomparable`:return`The start of process ${i} cannot be compared with the start recorded in ${a}, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`process-start-mismatch`:return`Process ${i} started before the start recorded in ${a}, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`process-started-after-lock`:return`Process ${i} started after the server lock at ${a} was written, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`recorded-start-in-future`:return`The server lock at ${a} records a start later than the current time on this machine, so process ${i} cannot be confirmed as the server that wrote it; ${t} ${c} ${n}`;case`writer-identity-unrecorded`:return`The server lock at ${a} records neither a machine ID nor a process start, as locks written by version 0.25.0 and earlier do, so process ${i} cannot be confirmed as the server that wrote it; ${t} ${c} ${n}`;default:return e.cause}}function UFe(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}function m9(e){if(!_(e))return{value:null,path:e,source:null,doc:null};let t;try{t=C(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,Ts.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 IJ(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function WFe(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=sd({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function GFe(e){let t=e??process.cwd(),n=[],r=[],i=[],a=[],o=hJ(`user`,t),s=sJ({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=m9(e);if(i.diagnostic!==void 0&&r.push(i.diagnostic),i.value===null)return{};let o=fd({value:i.value,file:i.path,source:i.source,doc:i.doc});r.push(...o),n.push(e);let s=o.length>0?md(i.value):i.value;return t&&a.push(...Nbe({value:s,file:i.path,source:i.source,doc:i.doc})),s},l=le(t,`.ok`,`config.yml`),u=c(l,!0),d=c(hJ(`project-local`,t)),f=fae(s.value,u,d),p=aNe.safeParse(f);if(!p.success){let e=m9(l),t={code:`SCHEMA_INVALID`,issues:WFe(p.error.issues,e)};throw Error(dae(t))}return{config:p.data,sources:n,diagnostics:r,sidelined:i,ignoredCommittedKeys:a}}function h9(e){return e.replace(/:\d+$/,``)}function g9(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:h9(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:h9(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:h9(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 _9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=Pc(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 v9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=Pc(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 KFe(e){let t=_9(e);if(t)return{kind:`doc`,...t};let n=v9(e);return n?{kind:`folder`,...n}:null}async function qFe(e,t){let n,r;try{n=await je(le(e)),r=await je(le(k(e)))}catch{return{kind:`not-git`}}if(!y9(n,r))return{kind:`symlink-escape`};let i=j(n,`.git`),a;try{a=re(i)}catch{return{kind:`not-git`}}if(a.isDirectory()){let e;try{e=await je(i)}catch{return{kind:`not-git`}}if(!y9(e,n))return{kind:`symlink-escape`}}else if(!a.isFile())return{kind:`not-git`};let o=QSe(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=g9(c);if(l===null)return{kind:`non-github`};let u=Pc(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 y9(e,t){if(e===t)return!0;let n=N(t,e);return n.length>0&&!n.startsWith(`..`)&&!se(n)}const JFe=`# >>> open-knowledge cli >>>`,YFe=`# <<< open-knowledge cli <<<`,XFe=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function ZFe(e){return Fbe(ft(),e)}function b9(e,t,n=[]){let r=_(j(e,k6[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function QFe(e,t){let n=GJ.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=bt.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:gS}));return[...n,...r]}function x9(e,t,n,r){let i=xke(e,QFe(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 $Fe(e,t){let n=(t??ve()).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 eIe(e,t){let n=EY[e];return R5(n,``,t)&&!L5(n,``,t)}function S9(e,t,n,r,i){let a=EY[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?$Fe(o,r):void 0,c=H5(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&eIe(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];aY(r)&&i.push(`reclaim-permissive`),cY(r)&&i.push(`pre-approval-exact`),U5(e)(r)&&i.push(`injection-functional`);let o=_Y(a,n);return i.length>0&&(o!==null&&Xxe(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}:Gxe(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function tIe(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let r=ka(e.pathId);if(r===null)return null;if(r.kind===`central-skill-store`)return n===void 0?null:b9(j(n,gS),`discovery`,x9(n,yt,e.agent,`global`));let i=r.editor;switch(r.kind){case`editor-user-skill-root`:{let e=yt[i];return e===null||n===void 0?null:z8(n).some(e=>e.editorId===i)?b9(j(n,e),`discovery`,x9(n,yt,i,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=vt[i];return e===null?null:b9(j(t,e),`project`,x9(t,vt,i,`project`))}case`editor-user-config`:return S9(i,e.strictness,t,n);case`editor-project-config`:{let r=EY[i].projectConfigPath?.(t);return r===void 0?null:S9(i,e.strictness,t,n,r)}}}}[...A6.map(e=>k6[e])];function nIe(e){if(!se(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=le(e);if(t===ue||k(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function C9(e){let t=nIe(e),n=[];for(let e of A6){let r=k6[e];n.push({path:j(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of Ct)n.push({path:j(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function rIe(e,t){let n=[];for(let r of C9(e))if(r.bundleId===t)try{te(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 iIe=[{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=z5(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=f5(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 aIe(e,t,n={},r=iIe){let i=[];for(let a of t){let t=EY[a];for(let a of r)i.push(a.write(t,e,n))}let a=kNe(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 oIe(e,t,n={}){return{integrations:aIe(e,t,n)}}function w9(e,t){let n=yt[e];return n===null?null:j(t,...n.split(`/`),k6.discovery,`SKILL.md`)}function sIe(e,t){let n=w9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!z8(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=N6(`discovery`,{checkDesktop:!0});return l5(k(n),t),{editorId:e,label:e,action:i5(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function cIe(e){return _(j(e,...`.agents/skills`.split(`/`),k6.discovery))?!0:_t.some(t=>{let n=w9(t,e);return n!==null&&_(k(n))})}function lIe(e,t){let n=w9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=k(n);try{return _(n)?(l5(r,t),te(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 uIe(e){return sJ({absPath:hJ(`user`,e,e),sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function T9({home:e=ve(),env:t=process.env}={}){let n=uIe(e),{override:r,preferenceList:i}=cxe(t),{locale:a,source:o}=hP({override:r,storedPreference:n,supportedLocales:ul,preferenceList:i,autoDetectableLocales:fl});return{preference:n,locale:a,source:o,systemLanguages:i}}function E9(e){let t=new Set([e]);try{t.add(D.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 D9(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function dIe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function O9(e,t){if(typeof e==`string`)return D9(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>O9(e,t));if(!dIe(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=O9(i,t);return n}function k9(e,t){let n=C(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
|
|
1546
|
+
`));let u=`${i?``:``}${l}`;return u!==r&&dJ(e,u,{mode:O5(e)}),{kind:`removed`}}function PFe(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}function FFe(e){let{priorCommand:t,priorArgs:n}=u9(e.priorEntry);return{event:`mcp-config-migrate`,scope:e.scope,surface:e.surface,editorId:e.editorId,configPath:e.configPath,priorCommand:t,priorArgs:n}}function u9(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 d9(e,t,n={}){let r=qMe(e,t),i;try{i=C(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,text:i}}let o=a&&typeof a==`object`?a:{},s=k8(o),c=s&&!A8(o,n);if(!a||typeof a!=`object`||!vMe(a.pid))return{status:`corrupt`,lockPath:r,text:i,...c?{foreignHost:!0}:{}};let l=JMe(a),{pid:u}=l;if(c)return{status:`foreign-host`,lockPath:r,lock:l};let d=P8(l,{isAlive:n.isAlive,readProcessStart:n.readProcessStart,readBootInstant:n.readBootInstant,sameMachine:s});switch(d.verdict){case`gone`:return{status:`dead-pid`,lockPath:r,lock:l,text:i};case`replaced`:return{status:`reused-pid`,lockPath:r,lock:l,text:i};case`unverified`:return d.cause===`unverified-owner`?{status:`unverified-owner`,lockPath:r,pid:u}:{status:`alive`,lockPath:r,lock:l};case`writer`:return{status:`alive`,lockPath:r,lock:l};default:return d}}function IFe(e){return`does not record its owning machine, and its recorded process ${e} is still running on this machine`}function f9(e){return typeof e.machineId==`string`?`records a machine ID different from the one in ${g8()}`:`records only the host ${O7(e.hostname)}, not this machine's ${ye()}`}function LFe(e){return e===`win32`?`USERPROFILE`:`HOME`}function RFe(e){return e.processStart===void 0?` This lock records no process start; a server started by this release records one, which lets \`${ht()} stop\` confirm it from any home folder.`:``}function zFe(e,t){let n=`\`${ht()} stop\``;return`If the server was started on this machine from another account, run ${n} as that account. If it was started from this account with a different home folder, run ${n} with \`${LFe(t)}\` set to that folder. Otherwise stop it from the machine that owns the lock.${RFe(e)}`}async function BFe(e,t=void 0){let n=d9(e,`server`);if(n.status!==`alive`&&n.status!==`foreign-host`)return null;let r=XMe(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 VFe(e,t={}){return qFe(e,t.isAlive??m8)?{targets:[{name:`server`,pid:e.lock.pid,port:e.lock.port}],lock:e.lock}:{targets:[]}}function HFe(e){try{return ft()}catch(t){e?.warn({err:t},`stop channel check skipped: ${t instanceof Error?t.message:String(t)}`);return}}async function UFe(e){let t=e.inspect??(()=>d9(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??BFe,o=e.logger??void 0,s=e.platform??process.platform,c=t(),l=VFe(c,{isAlive:e.isAlive}),{lock:u}=l,d=[],f=[],p=(t,n)=>{o?.warn({lockDir:e.lockDir,lockPath:n.lockPath,lockPid:n.pid,platform:s,cause:n.cause,...`nativeFailures`in n&&n.nativeFailures.length>0?{nativeFailures:n.nativeFailures}:{}},`stop declined: lock holder identity unverified`),f.push({target:t,error:GFe(n,o!==void 0),unverified:n})},m=()=>{if(d.length>0){let e=d.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);r(`Stopped: ${e}`)}if(o?.info({lockDir:e.lockDir,signalled:d.map(e=>({name:e.name,pid:e.pid,port:e.port})),failed:f.map(({target:e,error:t})=>({pid:e.pid,error:t})),forced:e.force===!0},`stop signalled processes`),f.length>0){let e=f.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `);i(`Failed to stop: ${e}`)}return{stopped:d,failed:f,hadTargets:!0}};if(c.status===`unverified-owner`){let{pid:e,lockPath:t}=c;return p({name:`server`,pid:e},{cause:`unverified-owner`,pid:e,lockPath:t}),m()}if(u===void 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 h=c.status===`alive`||c.status===`foreign-host`?c.lock.channel:void 0;if(e.force!==!0&&typeof h==`string`&&h.length>0){let t=e.selfChannel??HFe(o);if(t!==void 0&&h!==t)return i(`Not stopping: the server at ${e.lockDir} belongs to ${eee(h)}. `+(h===`dev`?`Stop it from that dev build, or run \`${gt} 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:h,selfChannel:t,pids:l.targets.map(e=>e.pid)},`stop declined: server belongs to another channel`),{stopped:[],failed:[],hadTargets:!0,declined:{otherChannel:h}}}if(e.force!==!0){let t=await a(e.lockDir,o);if(t!==null&&t>0)return i(`Not stopping: ${t} collaboration client${t===1?``:`s`} (editor window${t===1?``:`s`} or agents) still connected to the server at ${e.lockDir}. Close them, or re-run with --force to terminate anyway.`),o?.warn({lockDir:e.lockDir,clients:t,pids:l.targets.map(e=>e.pid)},`stop declined: live collaboration clients`),{stopped:[],failed:[],hadTargets:!0,declined:{clients:t}}}for(let t of l.targets){let a=[],o=(e.readProcessStart??$Pe)(t.pid,{platform:s,onNativeFailure:e=>{a.push(e)}}),l=P8(u,{isAlive:e.isAlive??m8,readProcessStart:()=>o,refuseHolderStartedAfterLock:e.refuseHolderStartedAfterLock,platform:s,readBootInstant:e.readBootInstant});switch(l.verdict){case`writer`:try{n(t.pid,`SIGTERM`),d.push(t)}catch(e){f.push({target:t,error:e instanceof Error?e.message:String(e)})}break;case`gone`:r(`${t.name} (pid=${t.pid}) had already exited`);break;case`replaced`:i(`Process ${t.pid} is no longer the server that wrote ${c.lockPath}; it was not signalled. Run \`${ht()} clean\` to remove the stale lock.`);break;case`unverified`:p(t,WFe(l.cause,{pid:t.pid,lockPath:c.lockPath,lock:u,platform:s,nativeFailures:a}));break;default:return l}}return m()}function WFe(e,t){let{pid:n,lockPath:r}=t;switch(e){case`foreign-host`:return{cause:e,pid:n,lockPath:r,lock:t.lock,platform:t.platform};case`unverified-owner`:return{cause:e,pid:n,lockPath:r};default:return{cause:e,pid:n,lockPath:r,platform:t.platform,nativeFailures:t.nativeFailures}}}const p9=`it was not signalled, and --force does not override this check.`;function GFe(e,t){let{pid:n,lockPath:r}=e;switch(e.cause){case`foreign-host`:{let{lock:t}=e;return typeof t.machineId==`string`?`The server lock at ${r} ${f9(t)}, so process ${n}, which is running on this machine, cannot be confirmed as the server that wrote it; ${p9} ${zFe(t,e.platform)}`:`The server lock at ${r} ${f9(t)}, and the start of process ${n}, which is running on this machine, does not confirm it as the server that wrote the lock; ${p9} If ${O7(t.hostname)} is another machine, stop the server there. If it is an earlier name of this machine, confirm that process ${n} is an OpenKnowledge server before ending it yourself, and once no OpenKnowledge server is running for this project, remove ${r}.`}case`unverified-owner`:return`The server lock at ${r} ${IFe(n)}, so it cannot be confirmed as the server that wrote the lock; ${p9} Check whether process ${n} is an OpenKnowledge server, and if it is, stop it yourself. Do not remove the lock file while that process is running.`;default:{let n=KFe(e,p9,`Once you have confirmed no OpenKnowledge server is running for this project, remove ${r}.`,t);return e.cause===`writer-identity-unrecorded`?`${n} A server you start again with this release records its machine ID, so \`${ht()} stop\` can confirm it.`:n}}}function KFe(e,t,n,r){let{pid:i,lockPath:a,platform:o,nativeFailures:s}=e,c=`Before ending process ${i} yourself, confirm that it is an OpenKnowledge server.`;switch(e.cause){case`process-start-unreadable`:return`Could not read when process ${i} started, so it cannot be confirmed as the server that wrote ${a}; ${t} `+eFe({platform:o,pid:i,nativeFailures:s,causeRecorded:r})+`${c} ${n}`;case`process-start-incomparable`:return`The start of process ${i} cannot be compared with the start recorded in ${a}, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`process-start-mismatch`:return`Process ${i} started before the start recorded in ${a}, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`process-started-after-lock`:return`Process ${i} started after the server lock at ${a} was written, so it cannot be confirmed as the server that wrote the lock; ${t} ${c} ${n}`;case`recorded-start-in-future`:return`The server lock at ${a} records a start later than the current time on this machine, so process ${i} cannot be confirmed as the server that wrote it; ${t} ${c} ${n}`;case`writer-identity-unrecorded`:return`The server lock at ${a} records neither a machine ID nor a process start, as locks written by version 0.25.0 and earlier do, so process ${i} cannot be confirmed as the server that wrote it; ${t} ${c} ${n}`;default:return e.cause}}function qFe(e,t){return e.status===`alive`||e.status===`foreign-host`&&t(e.lock.pid)}function m9(e){if(!_(e))return{value:null,path:e,source:null,doc:null};let t;try{t=C(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,Ts.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 IJ(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function JFe(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=sd({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function YFe(e){let t=e??process.cwd(),n=[],r=[],i=[],a=[],o=hJ(`user`,t),s=sJ({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=m9(e);if(i.diagnostic!==void 0&&r.push(i.diagnostic),i.value===null)return{};let o=fd({value:i.value,file:i.path,source:i.source,doc:i.doc});r.push(...o),n.push(e);let s=o.length>0?md(i.value):i.value;return t&&a.push(...Nbe({value:s,file:i.path,source:i.source,doc:i.doc})),s},l=le(t,`.ok`,`config.yml`),u=c(l,!0),d=c(hJ(`project-local`,t)),f=fae(s.value,u,d),p=cNe.safeParse(f);if(!p.success){let e=m9(l),t={code:`SCHEMA_INVALID`,issues:JFe(p.error.issues,e)};throw Error(dae(t))}return{config:p.data,sources:n,diagnostics:r,sidelined:i,ignoredCommittedKeys:a}}function h9(e){return e.replace(/:\d+$/,``)}function g9(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:h9(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[^/?#]*@)?([^@/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:h9(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:h9(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 _9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=Pc(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 v9(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`https:`)return null;let n=Pc(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 XFe(e){let t=_9(e);if(t)return{kind:`doc`,...t};let n=v9(e);return n?{kind:`folder`,...n}:null}async function ZFe(e,t){let n,r;try{n=await je(le(e)),r=await je(le(k(e)))}catch{return{kind:`not-git`}}if(!y9(n,r))return{kind:`symlink-escape`};let i=j(n,`.git`),a;try{a=re(i)}catch{return{kind:`not-git`}}if(a.isDirectory()){let e;try{e=await je(i)}catch{return{kind:`not-git`}}if(!y9(e,n))return{kind:`symlink-escape`}}else if(!a.isFile())return{kind:`not-git`};let o=QSe(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=g9(c);if(l===null)return{kind:`non-github`};let u=Pc(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 y9(e,t){if(e===t)return!0;let n=N(t,e);return n.length>0&&!n.startsWith(`..`)&&!se(n)}const QFe=`# >>> open-knowledge cli >>>`,$Fe=`# <<< open-knowledge cli <<<`,eIe=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function tIe(e){return Fbe(ft(),e)}function b9(e,t,n=[]){let r=_(j(e,k6[t]))?`satisfied`:`absent`;return{...r===`satisfied`?{state:r,strictness:[`reclaim-permissive`]}:{state:r},...n.length===0?{}:{sharedWith:n}}}function nIe(e,t){let n=GJ.flatMap(t=>{let n=e[t];return n===null?[]:[{editor:t,root:n}]}),r=bt.filter(e=>e.scope===t).map(e=>({editor:e.editorId,root:gS}));return[...n,...r]}function x9(e,t,n,r){let i=xke(e,nIe(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 rIe(e,t){let n=(t??ve()).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 iIe(e,t){let n=EY[e];return R5(n,``,t)&&!L5(n,``,t)}function S9(e,t,n,r,i){let a=EY[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?rIe(o,r):void 0,c=H5(a,n,r,i);switch(c.kind){case`absent`:case`no-entry`:return i===void 0&&iIe(e,r)?{state:`structural-na`}:{state:`absent`,path:s};case`decline`:return{state:`unprobed`};case`present`:{let{entry:r}=c,i=[];aY(r)&&i.push(`reclaim-permissive`),cY(r)&&i.push(`pre-approval-exact`),U5(e)(r)&&i.push(`injection-functional`);let o=_Y(a,n);return i.length>0&&(o!==null&&Xxe(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}:Gxe(a)?{state:`foreign-replaceable`,path:s}:{state:`foreign`,path:s}}}}function aIe(e){let{cwd:t,home:n}=e;return e=>{if(e.pathId===null)return null;let r=ka(e.pathId);if(r===null)return null;if(r.kind===`central-skill-store`)return n===void 0?null:b9(j(n,gS),`discovery`,x9(n,yt,e.agent,`global`));let i=r.editor;switch(r.kind){case`editor-user-skill-root`:{let e=yt[i];return e===null||n===void 0?null:z8(n).some(e=>e.editorId===i)?b9(j(n,e),`discovery`,x9(n,yt,i,`global`)):{state:`structural-na`}}case`editor-project-skill-root`:{let e=vt[i];return e===null?null:b9(j(t,e),`project`,x9(t,vt,i,`project`))}case`editor-user-config`:return S9(i,e.strictness,t,n);case`editor-project-config`:{let r=EY[i].projectConfigPath?.(t);return r===void 0?null:S9(i,e.strictness,t,n,r)}}}}[...A6.map(e=>k6[e])];function oIe(e){if(!se(e))throw Error(`skill cleanup requires an absolute home directory; got ${JSON.stringify(e)}`);let t=le(e);if(t===ue||k(t)===t)throw Error(`skill cleanup refuses to operate on the filesystem root (${t})`);return t}function C9(e){let t=oIe(e),n=[];for(let e of A6){let r=k6[e];n.push({path:j(t,`.agents`,`skills`,r),bundleId:e,scope:`central`});for(let i of Ct)n.push({path:j(t,i.skillsRoot,r),bundleId:e,scope:`host`,hostDir:i.hostDir})}return n}function sIe(e,t){let n=[];for(let r of C9(e))if(r.bundleId===t)try{te(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 cIe=[{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=z5(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=f5(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 lIe(e,t,n={},r=cIe){let i=[];for(let a of t){let t=EY[a];for(let a of r)i.push(a.write(t,e,n))}let a=MNe(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 uIe(e,t,n={}){return{integrations:lIe(e,t,n)}}function w9(e,t){let n=yt[e];return n===null?null:j(t,...n.split(`/`),k6.discovery,`SKILL.md`)}function dIe(e,t){let n=w9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};if(!z8(t).some(t=>t.editorId===e))return{editorId:e,label:e,action:`skipped-unsupported`,path:n};try{let r=N6(`discovery`,{checkDesktop:!0});return l5(k(n),t),{editorId:e,label:e,action:i5(r,n),path:n}}catch(t){return{editorId:e,label:e,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function fIe(e){return _(j(e,...`.agents/skills`.split(`/`),k6.discovery))?!0:_t.some(t=>{let n=w9(t,e);return n!==null&&_(k(n))})}function pIe(e,t){let n=w9(e,t);if(n===null)return{editorId:e,label:e,action:`skipped-unsupported`,path:``};let r=k(n);try{return _(n)?(l5(r,t),te(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 mIe(e){return sJ({absPath:hJ(`user`,e,e),sideline:!1,warn:()=>{}}).value.appearance?.language??`system`}function T9({home:e=ve(),env:t=process.env}={}){let n=mIe(e),{override:r,preferenceList:i}=cxe(t),{locale:a,source:o}=hP({override:r,storedPreference:n,supportedLocales:ul,preferenceList:i,autoDetectableLocales:fl});return{preference:n,locale:a,source:o,systemLanguages:i}}function E9(e){let t=new Set([e]);try{t.add(D.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 D9(e,t){let n=e;for(let e of t)n.includes(e)&&(n=n.split(e).join(`<CONTENT_DIR>`));return n}function hIe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function O9(e,t){if(typeof e==`string`)return D9(e,t.contentDirSpellings);if(Array.isArray(e))return e.map(e=>O9(e,t));if(!hIe(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=O9(i,t);return n}function k9(e,t){let n=C(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=O9(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
|
`);O(e,o)}function A9(e,t){let n=C(e,`utf-8`);if(n.trim().length!==0)try{let r=O9(JSON.parse(n),t),i=n.endsWith(`
|
|
1551
1551
|
`)?`
|
|
1552
|
-
`:``;O(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=D9(n,t.contentDirSpellings);r!==n&&O(e,r)}}function j9(e,t){let n=C(e,`utf-8`),r=D9(n,t.contentDirSpellings);r!==n&&O(e,r)}function M9(e){try{return T(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`;O(j(g,`state`,`server-status.txt`),k);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:G5(e.diagnosticReports,v);if(O(j(g,`state`,`diagnostic-reports-status.txt`),`${A}\n`),O(j(g,Y5),g7(e.osTerminationEvidence)),e.processDir&&_(e.processDir)){let t=j(g,`process`);y(t,{recursive:!0}),h(e.processDir,t,{recursive:!0})}let se=e.redact===!0;se&&(P9({stagingDir:g,contentDir:t}),P9({stagingDir:j(g,`legacy`),contentDir:t})),e.note&&O(j(g,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=
|
|
1552
|
+
`:``;O(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=D9(n,t.contentDirSpellings);r!==n&&O(e,r)}}function j9(e,t){let n=C(e,`utf-8`),r=D9(n,t.contentDirSpellings);r!==n&&O(e,r)}function M9(e){try{return T(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>j(e,t.name))}catch{return[]}}const gIe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function N9(e){return/\.log\.\d+$/.test(e)}function _Ie(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||N9(e)}const vIe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function P9(e){let t={contentDirSpellings:E9(e.contentDir)};for(let n of vIe)for(let r of M9(j(e.stagingDir,n)))_Ie(r)?k9(r,t):r.endsWith(`.json`)?A9(r,t):j9(r,t);for(let n of M9(j(e.stagingDir,`state`))){let e=oe(n);n.endsWith(`.jsonl`)?k9(n,t):gIe.has(e)?A9(n,t):j9(n,t)}}const F9=[`.ok`,`local`,`telemetry`],I9=[`.ok`,`local`,`logs`],L9=[`.ok`,`local`,`loss-capture`],R9=gd.spansCurrent,z9=gd.spansPrevious,B9=gd.logsCurrent,V9=gd.logsPrevious,H9=`loss-current.jsonl`,U9=`loss-prev.jsonl`;function yIe(e){return j(e,...L9,H9)}function bIe(e){return j(e,...L9,U9)}const W9=1e3;async function xIe(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 SIe(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 CIe(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 wIe(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 TIe(e){let t=j(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],I6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function EIe(e){let t=j(e,`.git`,`ok`);if(!_(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/`],I6({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 DIe(){return{nodeVersion:process.version,platform:be(),arch:he()}}function OIe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!_(e))return{};let t;try{t=(0,Ts.parse)(C(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 kIe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return kIe(e.maxBytes)}function AIe(e){let t=q9(hJ(`project`,e)),n=q9(hJ(`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 jIe(e){return Ee(`sha256`).update(e).digest(`hex`)}function MIe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const NIe=[`"doc.name"`,`"docName"`];function PIe(e){let t=C(e,`utf-8`),n=0;for(let e of NIe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function X9(e,t){if(!_(e))return!1;try{return y(k(t),{recursive:!0}),e.endsWith(`.ips`)?O(t,K5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Z9(e,t,n,r){let i=_(e);X9(e,j(n,r)),X9(t,i?j(n,`legacy`,r):j(n,r))}function Q9(e){let t=[],n=e=>{let r=T(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 FIe=new Set([`.jsonl`]);function IIe(e){let t=e.lastIndexOf(`.`);return t!==-1&&FIe.has(e.slice(t))}const LIe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function RIe(e){if(N9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&LIe.has(e.slice(t))}function zIe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!RIe(r))continue;let{redacted:i,patterns:a,lineCount:o}=xP(C(n,`utf-8`));a.length!==0&&(O(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 N(e,t).split(ue).join(`/`)}async function BIe(e){let t=le(e.contentDir),n=le(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??xIe,a=r.fetchAgentEffects??SIe,o=r.fetchWatcherRecent??CIe,s=r.readShadowHead??TIe,c=r.readCheckpointRefs??EIe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.88.3-beta.7`),d=r.readDesktopEnv??G9,f=r.readLanguage??T9,p=r.readRuntime??DIe,m=r.isOtlpPushEnabled??OIe,g=b(j(Se(),`ok-bundle-`));try{y(j(g,`telemetry`),{recursive:!0}),y(j(g,`logs`),{recursive:!0}),y(j(g,`state`),{recursive:!0}),Z9(KSe(n),j(n,...F9,R9),g,j(`telemetry`,R9)),Z9(qSe(n),j(n,...F9,z9),g,j(`telemetry`,z9)),Z9(bX(n),j(n,...I9,B9),g,j(`logs`,B9)),Z9(xX(n),j(n,...I9,V9),g,j(`logs`,V9));for(let t of e.userLogFiles??[])X9(t,j(g,`logs`,oe(t)));for(let t of e.userStateFiles??[])X9(t,j(g,Yq,oe(t)));let v=0;for(let t of e.diagnosticReports?.files??[])X9(t,j(g,`diagnostic-reports`,oe(t)))&&(v+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),S=`not-running`,w=`no server.lock`,T=null;if(_(x)){X9(x,j(g,`state`,`server.lock`));try{let e=C(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`:(O(j(g,`state`,`agent-presence.json`),e),S=`running`,w=``);let t=await a(T);t!==null&&O(j(g,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=wIe(n);e!==null&&O(j(g,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&O(j(g,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&O(j(g,`state`,`checkpoint-refs.txt`),D),X9(yIe(n),j(g,`state`,H9)),X9(bIe(n),j(g,`state`,U9)),Z9(uxe(n),j(b,hd),g,`state/last-spawn-error.log`),X9(j(b,vd),j(g,`state`,vd)),X9(j(b,yd),j(g,`state`,yd)),X9(j(b,_d),j(g,`state`,_d));let ee=p(),ne=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};O(j(g,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let k=S===`running`?`running
|
|
1554
|
+
`:`not-running (${w})\n`;O(j(g,`state`,`server-status.txt`),k);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:G5(e.diagnosticReports,v);if(O(j(g,`state`,`diagnostic-reports-status.txt`),`${A}\n`),O(j(g,Y5),g7(e.osTerminationEvidence)),e.processDir&&_(e.processDir)){let t=j(g,`process`);y(t,{recursive:!0}),h(e.processDir,t,{recursive:!0})}let se=e.redact===!0;se&&(P9({stagingDir:g,contentDir:t}),P9({stagingDir:j(g,`legacy`),contentDir:t})),e.note&&O(j(g,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=zIe(g));for(let t of e.extraFiles??[]){let e=t.zipName??oe(t.sourcePath);if(!X9(t.sourcePath,j(g,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=v7(t,`extra/${e}`);n!==null&&(ce??={redactions:[],redactedLineCount:0},ce.redactions.push(n),ce.redactedLineCount+=n.lineCount)}let M=AIe(n),N=Q9(g),le=[],ue=0,de=0;for(let e of N){let t=$9(g,e),n=re(e).size,r=IIe(t)?MIe(e):0;le.push({path:t,bytes:n,lines:r}),ue+=n;let i=t.startsWith(`legacy/`)?t.slice(7):t;(i.startsWith(`telemetry/`)||i.startsWith(`logs/`))&&(de+=PIe(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:jIe(t),absolutePath:se?`<CONTENT_DIR>`:t},telemetry:{localSink:{...M,directory:Td(`logs`,`projects`)},otlpPushEnabled:m()},redaction:fe,serverStatus:S,files:le};O(j(g,`manifest.json`),`${JSON.stringify(P,null,2)}\n`);let pe=E9(t),me=N.some(e=>{try{let t=C(e,`utf-8`);return pe.some(e=>t.includes(e))}catch{return!1}}),he={stagedDiagnosticReports:v,totalBytes:ue,fileCount:le.length,docNameCount:de,contentDirVisible:me,redacted:se},ge=!1;return{stagingDir:g,manifest:P,summary:he,cleanup:()=>{ge||(ge=!0,te(g,{recursive:!0,force:!0}))}}}catch(e){throw te(g,{recursive:!0,force:!0}),e}}async function VIe(e){let{collected:t,outputPath:n}=e,r=k(n);if(!_(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new WTe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=g(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 HIe(e,t){let n=j(e,`.ok`,`config.yml`);if(_(n))try{let t=(0,Ts.parse)(C(n,`utf-8`)),r=IJ(t)?t.content:void 0,i=IJ(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return le(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 le(e)}async function UIe(e,t,n,r,i,a){let o=y7(t,e.logger),s=await BIe({contentDir:HIe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...KPe(o,e.userLogsDir??j(cJ(),`logs`)),...x7(e.cachesDir??j(ve(),`Library`,`Caches`))],userStateFiles:S7(e.bugReportsDir??_7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{y(k(e.outputPath),{recursive:!0}),await VIe({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 WIe(e){let{projectDir:t}=e,n=e.readDesktopEnv??G9,r=e.readLanguage??T9,i=()=>vPe(e.diagnosticReportsDir??j(ve(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return UIe(e,t,n,r,i(),await h7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await ZPe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:x7(e.cachesDir??j(ve(),`Library`,`Caches`)),bugReportLedgerFiles:S7(e.bugReportsDir??_7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await h7(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{GJ as ALL_EDITOR_IDS,KJ as EDITOR_LABELS,EY as EDITOR_TARGETS,Vxe as HOSTS_WITH_USER_SKILL_DIR,oPe as LAUNCH_CONFIG_NAME,QFe as PATH_SHIM_BEGIN,eIe as PATH_SHIM_BLOCK_RE,$Fe as PATH_SHIM_END,o5 as ProjectPathSafetyError,LNe as addOkPathsToGitExclude,s5 as assertProjectPathSafe,sY as buildManagedServerEntry,PFe as buildMcpConfigDeclineEvent,FFe as buildMcpConfigMigrateEvent,_Y as canonicalEntryFor,H5 as classifyExistingMcpEntry,WIe as collectReportBundle,aIe as createCliProbeResolver,SJ as createTokenStore,UPe as defaultBugReportZipPath,qe as detectGh,Xe as detectGhAccounts,uPe as detectInstalledEditors,gY as droppedManagedKeys,cSe as editorConfigPathDisplay,sSe as editorEntryLocator,CFe as ensurePiBridge,wPe as findJetsamKillSync,b5 as formatTrackedRemediation,BNe as getExcludedOkPaths,v5 as getInstalledSkillProjectionPaths,Bxe as getNativeTomlMcpEditor,_5 as getOkArtifactPaths,aY as isEntryUpToDate,cY as isOwnManagedEntry,YFe as loadConfig,mxe as makeLazyProbeTokenStore,_7 as okBugReportsDir,_9 as parseGitHubBlobUrl,XFe as parseGitHubShareUrl,v9 as parseGitHubTreeUrl,g9 as parseGitUrl,tIe as pathInstallMarkerPath,SNe as previewContent,dPe as probeOwnManagedEditorMcpEntry,xFe as probePiBridgeState,y5 as probeTrackedOkPaths,B5 as readExistingMcpEntry,zNe as readSharingMode,xP as redactContent,tFe as registerWindowsProcessStartReader,RNe as removeOkPathsFromGitExclude,AFe as removeOwnMcpEntry,NNe as removeProjectSkill,sIe as removeUserGlobalSkillBundle,pIe as removeUserSkill,DNe as resolveProjectRoot,UFe as runStop,u9 as truncatePriorEntry,C9 as userGlobalSkillBundleTargets,fIe as userSkillPresentAnywhere,ZFe as validateLocalFolderForShare,z5 as writeEditorMcpConfig,uIe as writeProjectAiIntegrations,f5 as writeProjectSkill,lPe as writeUserMcpConfigs,dIe as writeUserSkill};
|
|
1555
1555
|
//# sourceMappingURL=index.mjs.map
|