@inkeep/open-knowledge 0.86.19-beta.2 → 0.86.19-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +6 -6
- package/dist/constants-D__Dkzs1.mjs +1 -0
- package/dist/{dist-DyVcFCkj.mjs → dist-CJb4z7Cx.mjs} +1 -1
- package/dist/{dist-DRgSOIS6.mjs → dist-CP1cIPST.mjs} +1 -1
- package/dist/index.mjs +2 -2
- package/dist/init-BJEVSZ5Z.mjs +1 -0
- package/dist/{init-Bfl6NStv.mjs → init-XYCfFXC2.mjs} +2 -2
- package/dist/{launch-json-removal-Dod4a_-P.mjs → launch-json-removal-BeUprPXt.mjs} +1 -1
- package/dist/loader-Bxzbqy9N.mjs +1 -0
- package/dist/{loader-1QamI-_M.mjs → loader-C3aJ7pno.mjs} +1 -1
- package/dist/native/native-config.win32-arm64-msvc.node +0 -0
- package/dist/native/native-config.win32-x64-msvc.node +0 -0
- package/dist/{open-browser-CFW5reH2.mjs → open-browser-D2QoIpKk.mjs} +1 -1
- package/dist/preview-DOE3RMB2.mjs +1 -0
- package/dist/{preview-CijEeyG0.mjs → preview-rfRPPmZw.mjs} +1 -1
- package/dist/public/assets/{AccountSection-3KFh0j-o.js → AccountSection-DojYWsvF.js} +1 -1
- package/dist/public/assets/{ActivityModeContent-BAMgVTks.js → ActivityModeContent-5eDMFCds.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-CcTOufGc.js → AddPropertiesButton-2uz1_eQ0.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-DRt588ak.js → AgentDiffPane-CyTVCF2i.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-BWoZqrFj.js → AttachmentsSection-kXSdmpS8.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-CnMfk0hq.js → CodeMirrorPropInput-D_sfUFdL.js} +1 -1
- package/dist/public/assets/{ContentRulesSection-BC2ldoBA.js → ContentRulesSection-DOJqWd7Z.js} +1 -1
- package/dist/public/assets/{DocumentContext-cZBCdTD5.js → DocumentContext-C7mE6mu6.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-I3lAEnBr.js → EditorModeToggle-4mNDd2Qr.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-BoI26knA.js → ExcalidrawDocEditor-Bpb19a7u.js} +1 -1
- package/dist/public/assets/FeedbackForm-CrGH6Sjh.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-Bhwizrdv.js → ImportSkillDialog-DDmDFsFX.js} +1 -1
- package/dist/public/assets/{LinkPreviewsSection-C4IdUXLV.js → LinkPreviewsSection-DC-XUEKY.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-CgcVT_jk.js → LintConfigEditor-D0EaXTzh.js} +1 -1
- package/dist/public/assets/{LintingSection-BBxbWZ_Q.js → LintingSection-8rk1N2xf.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-BCSB1r7p.js +1 -0
- package/dist/public/assets/{ManagedArtifactProperties-BO0zNDF5.js → ManagedArtifactProperties-BIuX58nK.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-S1zzPuZ3.js → MermaidDocEditor-Mzy0bDbh.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-D0394uvL.js → NetworkAccessSection-CbNihszz.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-BMCB8N4a.js → PropertyDisplayRow-CIGM7uEu.js} +1 -1
- package/dist/public/assets/{PublishToGitHubDialog-BJBrU1gT.js → PublishToGitHubDialog-Cyyc-7WZ.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-CzR5Lg4c.js → SchemaConfigEditor-DIMVYCnO.js} +1 -1
- package/dist/public/assets/{SearchSection-C4AjULre.js → SearchSection-OsK3-bM9.js} +1 -1
- package/dist/public/assets/{SessionsHost-9FQITgE2.js → SessionsHost-ddZzbbYD.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-3vIEV3s1.js → SettingsDialogBody-DahMDMVc.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-Dxusazw-.js → ShareReceiveMissDialog-BVXdjnFS.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-DZn91aUb.js → SkillToolbarControls-CWy86npn.js} +1 -1
- package/dist/public/assets/{SourceEditor-BdnYTYOr.js → SourceEditor-bEulpItb.js} +1 -1
- package/dist/public/assets/{SyncSection-ClflUgEs.js → SyncSection-DW6x2wXm.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-BMv_As0q.js → SyncStatusBadge-CodPHi7k.js} +1 -1
- package/dist/public/assets/{TerminalSection-ByKXggtz.js → TerminalSection-W882kbVI.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-BNA3YnxV.js → TerminalWindowApp-DQ04VIwE.js} +1 -1
- package/dist/public/assets/{TextDocEditor-Dc5nvs6R.js → TextDocEditor-CzNAofgq.js} +1 -1
- package/dist/public/assets/{ThreadView-CCTmdJ6C.js → ThreadView-ZvtUjW7G.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-BYwWnMOf.js → TimelineDiffPane-QwIzI-70.js} +1 -1
- package/dist/public/assets/{client-version-DqA-WRwO.js → client-version-DaqPNZrZ.js} +1 -1
- package/dist/public/assets/{comment-chips-Bw7GlIbv.js → comment-chips-CJoaS3Cr.js} +1 -1
- package/dist/public/assets/{config-provider-BhKxQXzB.js → config-provider-BZrRPx0L.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-CEaENJEP.js → doc-undo-manager-CYWGW9IX.js} +1 -1
- package/dist/public/assets/index-BSW8Oe5H.js +2209 -0
- package/dist/public/assets/{lint-plugins-BPdC7Ccd.js → lint-plugins-YpFY23BP.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-CLuU0Nf4.js → pending-receive-nav-store-BAkqfwcI.js} +1 -1
- package/dist/public/assets/{preferred-session-events-C7R1dtVr.js → preferred-session-events-Ixz9XkPb.js} +1 -1
- package/dist/public/assets/{progress-DU1CB6eE.js → progress-DZa81aer.js} +1 -1
- package/dist/public/assets/{selection-context-BzI58oKn.js → selection-context-Dl0HvyD2.js} +1 -1
- package/dist/public/assets/{src-CSkeVnyf.js → src-DVnJ3yRP.js} +1 -1
- package/dist/public/assets/{telemetry-impl-CkdG1Ih8.js → telemetry-impl-8tI6j9Yf.js} +1 -1
- package/dist/public/assets/{telemetry-startup-Dx5_pcAU.js → telemetry-startup-DYXC3ZEO.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-BK3ePa1_.js → typing-burst-detector-NANAUeWK.js} +2 -2
- package/dist/public/assets/{use-activity-panel-LWbmeKGf.js → use-activity-panel-D7UDHbaB.js} +1 -1
- package/dist/public/assets/{use-open-skill-DCRAgl4B.js → use-open-skill-CHcEq4yM.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-ChBm9j7q.js → use-terminal-enabled-CJC0W91S.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-C3J_ZzDZ.js → use-timeline-entry-diff-39zbjqC8.js} +1 -1
- package/dist/public/index.html +19 -19
- package/dist/{registry-probes-BizEx7Io.mjs → registry-probes-BePFTC2o.mjs} +1 -1
- package/dist/{removal-file-path-GRJ8XNYy.mjs → removal-file-path-adczU7M3.mjs} +1 -1
- package/dist/{repair-launch-json-C9kxB7_O.mjs → repair-launch-json-BKBgRjgC.mjs} +1 -1
- package/dist/{repair-mcp-configs-eUw0D6f1.mjs → repair-mcp-configs-DLgaoj3b.mjs} +1 -1
- package/dist/src-BICtdUdy.mjs +1 -0
- package/dist/{src-Dm3AegFc.mjs → src-CaqFOBSF.mjs} +1 -1
- package/dist/start-DrVKuTk8.mjs +1 -0
- package/dist/{start-CllFiQRt.mjs → start-smef5zYS.mjs} +3 -3
- package/package.json +4 -4
- package/dist/constants-yBl2PJiO.mjs +0 -1
- package/dist/init-D4-zC4aD.mjs +0 -1
- package/dist/loader-DyylMkNo.mjs +0 -1
- package/dist/preview-C9hE3xLw.mjs +0 -1
- package/dist/public/assets/FeedbackForm-DH-e8ey4.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-Co9aRIgQ.js +0 -1
- package/dist/public/assets/index-C5VIr_NL.js +0 -2209
- package/dist/src-BDX8WyNE.mjs +0 -1
- package/dist/start-CO72b_37.mjs +0 -1
|
@@ -1032,7 +1032,7 @@ ${rXe.join(`
|
|
|
1032
1032
|
`).length)}),before:o,after:s,properties:Lr(i,a)}}function c4e(e){let t=e.meta.get(`time`);return typeof t==`number`?t:Date.now()}function l4e(e,t){let n=t.doc,r=new Set,i=new Set;n&&n.transact(t=>{a4e(t,e.insertions,r),a4e(t,e.deletions,i)});let a=0,o=0;for(let e of lZ(t)){if(!(e.content instanceof pD))continue;let t=e.content.str.length;!e.deleted&&r.has(e)&&(a+=t),i.has(e)&&(o+=t)}return{additions:a,deletions:o}}function u4e(e,t){let n=[],r=null,i=!1;for(let a of e.sessionsForConnection(t)){if(i=!0,!r){let e=a.origin.context,n=typeof e?.agent_type==`string`?e.agent_type:void 0,i=typeof e?.color_seed==`string`?e.color_seed:t,o=Yn(n),s=eo[o]??ze(i);r={displayName:e?.display_name||(typeof e?.agent_type==`string`?e.agent_type:void 0)||t,color:s,icon:o,connectionId:t}}let e=a.docName,o=a.um,s=a.dc.document.getText(`source`),c=[];for(let e=0;e<o.undoStack.length;e++){let t=o.undoStack[e],n=c4e(t),{additions:r,deletions:i}=l4e(t,s);c.push({stackIndex:e,ts:n,additions:r,deletions:i})}if(c.length===0)continue;c.sort((e,t)=>t.stackIndex-e.stackIndex);let l=c.reduce((e,t)=>e+t.additions,0),u=c.reduce((e,t)=>e+t.deletions,0),d=Math.max(...c.map(e=>e.ts));n.push({docName:e,additionsTotal:l,deletionsTotal:u,lastTs:d,bursts:c})}return i?(n.sort((e,t)=>t.lastTs-e.lastTs),{sessionAlive:!0,agent:r,files:n}):{sessionAlive:!1,agent:null,files:[]}}function d4e(e,t,n){if(e===null)return{preDrain:!1,reason:`checkpoint-null-splice`};if(t===null)return{preDrain:!1,reason:`checkpoint-no-target`};if(t.start===t.end){let n=t.start;return e.start<n&&n<e.end?{preDrain:!1,reason:`checkpoint-substantive-overlap`}:{preDrain:!0,reason:`pre-drain-disjoint`}}let r=Math.max(e.start,t.start),i=Math.min(e.end,t.end);return r>=i?{preDrain:!0,reason:`pre-drain-disjoint`}:n.slice(r,i).trim()===``?{preDrain:!0,reason:`pre-drain-whitespace-graze`}:{preDrain:!1,reason:`checkpoint-substantive-overlap`}}function f4e(e,t,n,r){let i=r.clients.get(e);if(i===void 0)return!1;let a=t+n;for(let e of i)if(t<e.clock+e.len&&e.clock<a)return!0;return!1}function*p4e(e,t,n,r,i){let a=i.clients.get(e);if(a===void 0)return;let o=t+n;for(let e of a){let n=Math.max(t,e.clock),i=Math.min(o,e.clock+e.len);n<i&&(yield[r+(n-t),r+(i-t)])}}function m4e(e,t,n){let r=0,i=1/0,a=-1/0;for(let n of lZ(e)){if(!(n.content instanceof pD))continue;let{client:e,clock:o}=n.id,s=n.content.str.length;if(n.deleted)f4e(e,o,s,t.deletions)&&(i=Math.min(i,r),a=Math.max(a,r));else{for(let[n,c]of p4e(e,o,s,r,t.insertions))i=Math.min(i,n),a=Math.max(a,c);r+=s}}return i===1/0?null:{start:Math.max(0,i-n),end:Math.max(0,a-n)}}const h4e=new Set([`replace`,`patch`]);function g4e(e,t){return t===`append`?{start:e.replace(/\s+$/,``).length,end:e.length}:null}function _4e(e){let t=e=>({preDrain:!1,verdict:{preDrain:!1,reason:e},splice:null});if(!e.pendingDirty)return t(`skip-no-pending`);if(!e.witnessMatched)return t(`checkpoint-witness-mismatch`);if(e.op.kind===`agent-write`&&h4e.has(e.op.writeKind))return t(`checkpoint-full-overwrite`);let n=e.op.kind===`agent-undo`?m4e(e.op.ytext,e.op.stackItem,e.fmPrefixLen):g4e(e.body,e.op.writeKind);if(n===null)return t(`checkpoint-no-target`);let r=X2e(e.body,e.fragmentPmJson,e.mdManager,{lineEnding:e.lineEnding});if(r===null)return t(`checkpoint-null-splice`);if(r.newSlice===e.body.slice(r.spliceStart,r.spliceEnd))return t(`skip-already-converged`);let i=d4e({start:r.spliceStart,end:r.spliceEnd},n,e.body);return i.preDrain?{preDrain:!0,verdict:i,splice:r}:{preDrain:!1,verdict:i,splice:null}}const uZ=new Set,dZ=new Set,fZ=new Set,pZ=new Set,mZ=new Set;let hZ=null,gZ=null,_Z=null,vZ=null,yZ=null,bZ=null;nG(()=>{hZ=null,gZ=null,_Z=null,vZ=null,yZ=null,bZ=null});function v4e(e){return uZ.add(e),()=>{uZ.delete(e)}}function y4e(e){return dZ.add(e),()=>{dZ.delete(e)}}function b4e(e){return fZ.add(e),()=>{fZ.delete(e)}}function x4e(e){return pZ.add(e),()=>{pZ.delete(e)}}function S4e(e){return mZ.add(e),()=>{mZ.delete(e)}}function C4e(){if(!(hZ&&gZ&&_Z&&vZ&&yZ&&bZ)){if(!hZ){let e=aG().createObservableGauge(`ok.server.docs.loaded`,{description:`Server-side Y.Docs currently resident in memory (includes synthetic system/config docs).`,unit:`{documents}`});e.addCallback(e=>{let t=0;for(let e of uZ)try{t+=e()}catch{}e.observe(t)}),hZ=e}if(!gZ){let e=aG().createObservableGauge(`ok.persistence.queue.depth`,{description:`Pending persistence stores by queue. Bounded labels: queue ∈ {branch_deferred, quiescence_deferred}.`,unit:`{documents}`});e.addCallback(e=>{let t=0,n=0;for(let e of dZ)try{let r=e();t+=r.branchDeferred,n+=r.quiescenceDeferred}catch{}e.observe(t,{queue:`branch_deferred`}),e.observe(n,{queue:`quiescence_deferred`})}),gZ=e}if(!_Z){let e=aG().createObservableGauge(`ok.bridge.drain_backlog`,{description:`Docs whose bridge observers hold an un-settled dirty flag at sample time (settlement is synchronous per drain, so a sustained non-zero value indicates a stuck drain).`,unit:`{documents}`});e.addCallback(e=>{let t=0;for(let e of fZ)try{e()&&t++}catch{}e.observe(t)}),_Z=e}if(!vZ){let e=aG().createObservableGauge(`ok.ws.connections.active`,{description:`Live collab connections. Bounded labels: kind ∈ {websocket, direct}. websocket = deduplicated client sockets; direct = in-process DirectConnections (agent sessions + server-held system/config docs).`,unit:`{connections}`});e.addCallback(e=>{let t=0,n=0;for(let e of pZ)try{let r=e();t+=r.websocket,n+=r.direct}catch{}e.observe(t,{kind:`websocket`}),e.observe(n,{kind:`direct`})}),vZ=e}if(!yZ||!bZ){let e=aG().createObservableGauge(`ok.sessions.active`,{description:`Live (docName, agentId) agent sessions. Pinned at ok.sessions.limit means new sessions are being refused with 503s.`,unit:`{sessions}`}),t=aG().createObservableGauge(`ok.sessions.limit`,{description:`Hard cap on live agent sessions (summed across server instances in this process).`,unit:`{sessions}`});e.addCallback(e=>{let t=0;for(let e of mZ)try{t+=e().active}catch{}e.observe(t)}),t.addCallback(e=>{let t=0;for(let e of mZ)try{t+=e().limit}catch{}e.observe(t)}),yZ=e,bZ=t}}}const xZ=q(`server-observers`),SZ=q(`server-observers`),CZ={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},wZ=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0,w4e=e=>typeof e==`object`&&!!e&&e.source===`connection`;function T4e(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}var E4e=class extends Error{info;constructor(e){super(`Observer-A producer guard: serialize output failed structural legality (${e.reason}: ${e.detail})`),this.name=`ProducerGuardViolationError`,this.info=e}};const D4e=new Set([`jsxComponent`,`table`,`tableCell`,`tableHeader`]),TZ=`merge-boundary`;function O4e(e){if(e.type&&D4e.has(e.type))return!0;if(e.content){for(let t of e.content)if(O4e(t))return!0}return!1}function k4e(e){let t=new Set,n=e=>{if(e.type&&D4e.has(e.type)&&t.add(e.type),e.content)for(let t of e.content)n(t)};return n(e),[...t].sort().join(`,`)}let A4e=!1;function j4e(e,t){A4e||(A4e=!0,xZ.warn({docName:e??`unknown`,err:t instanceof Error?t:Error(String(t))},`[Server Observer A] Map-driven splice parse/serialize threw (doc: ${e??`unknown`}); drains fall back to the incremental diff (warned once; further failures count in mapDrivenSpliceFallback only)`))}let M4e=!1;function N4e(e,t){M4e||(M4e=!0,xZ.warn({docName:e??`unknown`,err:t instanceof Error?t:Error(String(t))},`[Server Observer A] Spliced-body memo composition threw (doc: ${e??`unknown`}); the splice is unaffected and the next drain re-parses (warned once; further failures count in mapDrivenSpliceMemoSkips only)`))}function P4e(e){let{currentText:t,lastSyncedXmlMd:n,mdManager:r,docName:i,mdastMemo:a,serializedNewPm:o,onResidualFallback:s}=e,c=s===void 0,l=e=>{s?s(e):WJe(e)},u=o.json;if(t!==n)return l(`text-mismatch`),null;if(i!==void 0&&(KK(i)||qK(i)))return l(`synthetic-doc`),null;let{body:d}=Ba(t),f=t.length-d.length,p=X2e(d,u,r,{onFallback:(e,t)=>{l(e),e===`parse-error`&&j4e(i,t)},onMemoHit:()=>{c&&GJe()},onMemoSkip:(e,t)=>{c&&KJe(e),e===`compose-failed`&&N4e(i,t)},memo:a,serializedNewPm:o,lineEnding:Xn(t)});return p?{spliceStart:f+p.spliceStart,spliceEnd:f+p.spliceEnd,newSlice:p.newSlice}:null}function F4e(e,t){let n=t.spliceEnd-t.spliceStart;n>0&&e.delete(t.spliceStart,n),t.newSlice.length>0&&e.insert(t.spliceStart,t.newSlice)}const EZ=new WeakMap;function I4e(e){return EZ.get(e)}const DZ=new WeakMap;function L4e(e){return DZ.get(e)?.()}const OZ=new WeakMap;function R4e(e){return OZ.get(e)?.()}function z4e(e,t,n,r){return e!==t&&(r??jt(e))!==(n??jt(t))}function B4e(e){return e instanceof nD?e.nodeName:e instanceof rD?`#text`:`#hook`}function V4e(e){return e._item?.id?.client}const H4e=e=>e.replace(/\s+/g,` `).trim(),U4e=e=>e.replace(/[*_~`]+/g,``);function W4e(e){return H4e(U4e(e.replace(/<[^>]*>/g,``).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/&/g,`&`)))}function G4e(e){return H4e(U4e(e.replace(/!?\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\\([\\`*_{}[\]()#+\-.!><])/g,`$1`)))}function K4e(e,t,n){if(n.length===0)return!1;let r=e.toArray(),i=r.map(e=>W4e(e.toString()));for(let e of n){let n=G4e(e);if(n.length<8)continue;let a=new Set,o=new Set;for(let e=0;e<r.length;e++){let s=r[e];if(s===void 0||!i[e]?.includes(n))continue;let c=V4e(s);c!==void 0&&(c===t?a.add(B4e(s)):o.add(B4e(s)))}for(let e of a)for(let t of o)if(e!==t)return!0}return!1}function q4e(e){let{doc:t,xmlFragment:n,ytext:r,mdManager:i,schema:a}=e,o=(t,n)=>{let r=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:r}),docName:e.docName??null,timestamp:new Date().toISOString()})),t.info.which===`growth`?wJe():CJe();let i=t.info.which,a=t.info.lostSubstrings.reduce((e,t)=>e+t.length,0),o=e.shadow?.();if(!o||!e.docName){e.lossRing?.record({event:pG,docName:e.docName??``,writerId:null,direction:`a`,site:TZ,lostLen:a,which:i});return}let s=e.getBranch?.()??`main`,c=e.contentRoot??``;queueMicrotask(()=>{kK(o,c,{kind:`bridge-merge-loss`,docName:e.docName,contents:n,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:s,metadata:{lostSubstrings:t.info.lostSubstrings,which:t.info.which}}).then(t=>{OJe(),e.lossRing?.record({event:pG,docName:e.docName,writerId:null,direction:`a`,site:TZ,lostLen:a,which:i,checkpointSha:t}),console.warn(JSON.stringify({event:`bridge-merge-checkpoint-created`,docName:e.docName,sha:t,kind:`bridge-merge-loss`,timestamp:new Date().toISOString()}))}).catch(t=>{let n=t instanceof Error?t:Error(String(t));xZ.warn({err:n},`[Server Observer A] Silent checkpoint write failed`),SZ.warn({err:n,"doc.name":e.docName??null,branch:s,kind:`bridge-merge-loss`},`checkpoint write failed`),e.lossRing?.record({event:pG,docName:e.docName,writerId:null,direction:`a`,site:TZ,lostLen:a,which:i})})})},s=t=>{j=!0,E=!0;try{H2e(t,e.docName)&&(yYe(),console.warn(JSON.stringify({event:`bridge-split-brain-rederive`,"doc.name":e.docName??null,site:t})))}catch(e){xZ.warn({err:e},`[Server Observer A] Split-brain telemetry failed`)}},c=t=>{e.lossRing?.record({event:`guard-defer`,docName:e.docName??``,writerId:null,direction:`b`,lostLen:t.reduce((e,t)=>e+t.length,0)})},l=(t,n)=>{let r=e.shadow?.();if(!r||!e.docName)return;let i=e.getBranch?.()??`main`,a=e.contentRoot??``,o=e.docName;queueMicrotask(()=>{kK(r,a,{kind:`observer-a-duplication`,docName:o,contents:t,label:`Before duplication re-derive @ ${new Date().toISOString()}`,branch:i,metadata:{duplicatedLineCount:n}}).then(e=>{QJe(),console.warn(JSON.stringify({event:`observer-a-duplication-checkpoint-created`,docName:o,sha:e,kind:`observer-a-duplication`,timestamp:new Date().toISOString()}))}).catch(e=>{let t=e instanceof Error?e:Error(String(e));xZ.warn({docName:o,err:t},`[Server Observer A] Duplication checkpoint write failed`),SZ.warn({err:t,"doc.name":o,branch:i,kind:`observer-a-duplication`},`checkpoint write failed`)})})},u=(t,n,r,i)=>{if(e.lossDetectorEnabled===!1)return;let a=NXe(t,n,r,i);if(a.length===0)return;$Je();let o=a.reduce((e,t)=>e+t.length,0),s=tn(a.join(`
|
|
1033
1033
|
`)),c=e.shadow?.();if(!c||!e.docName){e.lossRing?.record({event:pG,docName:e.docName??``,writerId:null,direction:`a`,site:`observer-a-apply`,lostLen:o,digest:s});return}let l=e.getBranch?.()??`main`,u=e.contentRoot??``,d=e.docName;queueMicrotask(()=>{kK(c,u,{kind:`observer-a-apply-loss`,docName:d,contents:t,label:`Before Observer-A apply content-loss @ ${new Date().toISOString()}`,branch:l,metadata:{lostSubstrings:a}}).then(t=>{eYe(),e.lossRing?.record({event:pG,docName:d,writerId:null,direction:`a`,site:`observer-a-apply`,lostLen:o,digest:s,checkpointSha:t}),console.warn(JSON.stringify({event:`observer-a-apply-loss-checkpoint-created`,docName:d,sha:t,kind:`observer-a-apply-loss`,timestamp:new Date().toISOString()}))}).catch(t=>{let n=t instanceof Error?t:Error(String(t));xZ.warn({docName:d,err:n},`[Server Observer A] Apply-loss checkpoint write failed`),SZ.warn({err:n,"doc.name":d,branch:l,kind:`observer-a-apply-loss`},`checkpoint write failed`),e.lossRing?.record({event:pG,docName:d,writerId:null,direction:`a`,site:`observer-a-apply`,lostLen:o,digest:s})})})},d=(t,n,r)=>{tYe();let i=r.reduce((e,t)=>e+t.length,0),a=e.shadow?.(),o=e.docName;if(!a||!o){e.lossRing?.record({event:hG,docName:o??``,writerId:null,direction:`b`,site:`derive-timing-exhaustion`,lostLen:i});return}let s=e.getBranch?.()??`main`,c=e.contentRoot??``;queueMicrotask(()=>{kK(a,c,{kind:`defer-exhaustion-loss`,docName:o,contents:t,label:`Before derive-defer force-resolve @ ${new Date().toISOString()}`,branch:s,metadata:{deferCount:n}}).then(t=>{e.lossRing?.record({event:hG,docName:o,writerId:null,direction:`b`,site:`derive-timing-exhaustion`,lostLen:i,checkpointSha:t}),console.warn(JSON.stringify({event:`derive-defer-exhaustion-checkpoint-created`,docName:o,sha:t,kind:`defer-exhaustion-loss`,timestamp:new Date().toISOString()}))}).catch(t=>{let n=t instanceof Error?t:Error(String(t));xZ.warn({docName:o,err:n},`[Server Observer B] Derive-defer exhaustion checkpoint write failed`),SZ.warn({err:n,"doc.name":o,branch:s,kind:`defer-exhaustion-loss`},`checkpoint write failed`),e.lossRing?.record({event:hG,docName:o,writerId:null,direction:`b`,site:`derive-timing-exhaustion`,lostLen:i})})})},f=t=>{A=!0,vYe(),e.onReDeriveBackstop?.(t);let n=r.toString(),i=e.shadow?.(),a=e.docName;if(!i||!a){e.lossRing?.record({event:mG,docName:a??``,writerId:null,direction:`b`,site:`rederive-backstop`});return}let o=e.getBranch?.()??`main`,s=e.contentRoot??``;queueMicrotask(()=>{kK(i,s,{kind:`bridge-backstop-trip`,docName:a,contents:n,label:`Before re-derive backstop freeze @ ${new Date().toISOString()}`,branch:o,metadata:{rounds:t}}).then(t=>{e.lossRing?.record({event:mG,docName:a,writerId:null,direction:`b`,site:`rederive-backstop`,checkpointSha:t}),console.warn(JSON.stringify({event:`bridge-rederive-backstop-checkpoint-created`,docName:a,sha:t,kind:`bridge-backstop-trip`,timestamp:new Date().toISOString()}))}).catch(t=>{let n=t instanceof Error?t:Error(String(t));xZ.warn({docName:a,err:n},`[Server Observer B] Re-derive backstop checkpoint write failed`),SZ.warn({err:n,"doc.name":a,branch:o,kind:`bridge-backstop-trip`},`checkpoint write failed`),e.lossRing?.record({event:mG,docName:a,writerId:null,direction:`b`,site:`rederive-backstop`})})})},p=``,m=``,h=J2e(),g=!1,_=!1,v=!1,y=0,b=0,x=e.deferGuardEnabled!==!1,S=``,C=!1,w=0,T=!1,E=!1,D=e.fixedPointBackstopEnabled!==!1,O=e.preDrainEnabled!==!1,k=[],ee=0,A=!1,j=!1,M=!1,N=!1,te=()=>{m=r.toString(),g=!1},ne=e=>{p=e,te(),g=e!==``,D&&e!==``&&m===e&&(M=!0)},P=e=>{p=e,m=e,g=!1},re=e=>{p=e,g=!1},ie=e=>{p=e,m=r.toString(),g=!0},ae=()=>Ba(r.toString()).frontmatter,oe=(e,t)=>{let{slot:n}=bt(e,Ba(r.toString()).body);return Fr(e,n+t)},se=(e,t)=>e.frontmatter+ai(e.body,Xn(t)),ce=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,le=W2e(i,{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,docName:e.docName}),ue=``,de=``,fe=!1,pe=(e,t)=>{if(fe&&e===ue&&t===de)return!0;let n=Ln(e,t,le);return n&&(ue=e,de=t,fe=!0),n},me=(e,t,n,r)=>z4e(e,t,n,r)&&!pe(e,t);try{let e=VD(n,a).toJSON(),t=i.serialize(e),o=oe(ae(),t).md;pe(r.toString(),o)?ne(o):P(o),S=o}catch(e){tK(`a`),xZ.warn({err:e instanceof Error?e:Error(String(e))},`[Server Observer A] Baseline init failed — starting from empty snapshot`),ne(``)}let he,ge=new Map,_e=new Map,ve=(t,n)=>{let i=e.docName??`__nodoc__`,a=Date.now(),o=ge.get(i);if(o!==void 0&&a-o.lastMs<5e3)o.suppressed+=1,jJe();else{let r=o?.suppressed??0;ge.set(i,{lastMs:a,suppressed:0}),AJe(),console.warn(JSON.stringify({event:`producer-guard-violation`,docName:e.docName??null,reason:t.reason,construct:n,appliedDegrades:t.appliedDegrades,suppressedSincePrevious:r,timestamp:new Date().toISOString()}))}let s=e.shadow?.();if(!s||!e.docName)return;let c=r.toString();if(_e.get(i)===c)return;_e.set(i,c);let l=e.getBranch?.()??`main`,u=e.contentRoot??``,d=e.docName;queueMicrotask(()=>{kK(s,u,{kind:`producer-guard-loss`,docName:d,contents:c,label:`Before producer-guard content-loss @ ${new Date().toISOString()}`,branch:l,metadata:{construct:n}}).then(e=>{kJe(),console.warn(JSON.stringify({event:`producer-guard-checkpoint-created`,docName:d,sha:e,kind:`producer-guard-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{_e.get(i)===c&&_e.delete(i);let t=e instanceof Error?e:Error(String(e));xZ.warn({err:t},`[Server Observer A] Producer-guard checkpoint write failed`),SZ.warn({err:t,"doc.name":d,branch:l,kind:`producer-guard-loss`},`checkpoint write failed`)})})},ye=(t,n)=>{if(n===he||(he=n,!O4e(t)))return;let r=i.parseWithFallback(n,ce),a=ct(t,r,{rawSourceSide:`expected`});if(!(a.equivalent||a.reason!==`content-loss`)){if(T4e())throw new E4e({docName:e.docName,reason:a.reason,detail:a.detail});ve(a,k4e(t))}},be=()=>{try{let c=VD(n,a).toJSON(),d=r.toString()===m,f=Date.now()-y>=2e3,_=d&&f,b=K2e(i,c,{skipFreshnessDerive:!_}),x=b.body;_&&ye(c,x);let E=ae(),D=oe(E,x),O=D.md,k=r.toString(),ee=pn(O,k,8);if(ee.length>0&&K4e(n,t.clientID,ee)){P(O),v=!0,T=!0,s(`duplication-guard`),ZJe(),l(O,ee.length),cG({"observer.a.path":`gated-duplication-rederive`});return}if(_&&(S=O,C=!1,w=0),g&&p===O){me(r.toString(),O)?(P(O),v=!0,s(`identity-gate`),cG({"observer.a.path":`gated-fragment-unchanged-rederive`})):cG({"observer.a.path":`gated-fragment-unchanged`});return}let A=jt(k),j=jt(O);if(A===j&&!fo(k,O)&&!De(k,O)){cG({"observer.a.path":`gated-in-sync`,"observer.a.gate_reason":k===O?`bytes-identical`:`tolerance-equivalent`}),ne(O);return}let M=m,N=k===m,te=N&&g&&m!==p&&A!==jt(p);cG({"observer.a.path":N?te?`residual-merge`:`path-a`:`path-b`});let re={mergedText:null},ie=t=>D.adjusted===`none`?De(k,O)?(t?.(`doc-edge-runs`),null):P4e({currentText:k,lastSyncedXmlMd:m,mdManager:i,docName:e.docName,mdastMemo:h,serializedNewPm:b,onResidualFallback:t}):(t?.(`composition-adjusted`),null),ce=e=>{if(!te||!me(e,O,j))return e;let t=`not-settled`,n=ie(e=>{t=e});if(n!==null){let t=k.slice(0,n.spliceStart)+n.newSlice+k.slice(n.spliceEnd);if(!me(t,O,j))return pne(p,k,{start:n.spliceStart,end:n.spliceEnd},n.newSlice).length>0?(YJe(),cG({"observer.a.residual_merge_fallback":`splice-blocked-lossy`}),e):(JJe(),cG({"observer.a.residual_merge_fallback":`map-driven-splice`}),t)}return XJe(t),cG({"observer.a.residual_merge_fallback":`splice-unavailable`,"observer.a.residual_merge_fallback_reason":t}),e},le=performance.now(),ue=te?null:ie();ue&&cG({"observer.a.path":`map-driven-splice`,"observer.a.splice.compute_ms":Math.round(performance.now()-le)}),t.transact(()=>{if(ue)F4e(r,ue);else if(N&&!te)Cie(r,k,se(D,k));else{let t=N?p:M,n=pie(x),i=e=>n.unproject(e,k),a=e.mergeThreeWay??Ze;try{let e=ce(i(a(n.project(t),n.project(O),n.project(k))));Pi(r,k,e),re.mergedText=e}catch(e){if(!(e instanceof xi)||(o(e,M),T4e()))throw e;let t=i(e.info.result);Pi(r,k,t),re.mergedText=t}}e.__testApplyLossInjector?.(r)},CZ),ue&&UJe();let de=r.toString(),fe=jt(de);(ue||N&&!te)&&u(O,j,de,fe),re.mergedText!==null&&!N&&B2e(e.docName)&&(VJe(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!N,mergeBytesChanged:Math.abs(re.mergedText.length-k.length)}))),re.mergedText!==null&&N&&qJe(),eK(`a`),ne(O),me(de,O,j,fe)&&(de===M&&P(O),v=!0,s(`post-merge`))}catch(t){if(t instanceof xi||t instanceof E4e)throw t;tK(`a`),xZ.error({err:t},`[Server Observer A] Failed to sync tree→text`);try{let e=VD(n,a).toJSON(),t=i.serialize(e),o=oe(ae(),t).md;me(r.toString(),o)?(ie(o),v=!0,s(`error-recovery`)):ne(o)}catch(n){xZ.warn({docName:e.docName??null,originalError:t instanceof Error?t.message:String(t),recoveryError:n instanceof Error?n.message:String(n)},`[Server Observer A] Baseline recovery also failed`),p=``,m=``,g=!1}}},xe=()=>{sG(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},be)},Se=(e,t)=>{if(t.origin!==CZ){if(wZ(t.origin)){try{let e=ae();te(),S=m,C=!1,w=0,Ce=e}catch(e){tK(`a`),xZ.warn({err:e instanceof Error?e:Error(String(e))},`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement`),_=!0}return}w4e(t.origin)&&(b=Date.now()),_=!0,C=!0}};if(n.length>0&&r.length===0)try{let e=VD(n,a).toJSON(),o=i.serialize(e),s=oe(ae(),o).md;t.transact(()=>{r.insert(0,s)},CZ),ne(s)}catch(e){tK(`a`),xZ.error({err:e},`[Server Observer A] Failed initial sync`),ne(``)}let Ce=ae(),we=()=>{try{let o=r.toString(),{frontmatter:s,body:l}=Ba(o),{slot:u,body:f}=bt(s,l);if(!E&&jt(m)===jt(o)&&!De(m,o)){Ce!==s&&(FX(`source-mode`),Ce=s),D&&g&&p===o&&(M=!0);return}if(A){cG({"observer.b.path":`backstop-frozen`});return}if(T)T=!1;else if(x&&C){let t=i.serialize(VD(n,a).toJSON()),r=oe(s,t).md;if(En(r,o,S)){if(w>=8)d(r,w,Er(r,o,S)),w=0,cG({"observer.b.path":`derive-timing-force-resolve`});else{w+=1,_=!0,v=!0,c(Er(r,o,S)),e.onDeriveTimingDefer?.({canonicalWitness:p,rawWitness:m}),N=!0,cG({"observer.b.path":`derive-timing-defer`});return}}}let h=i.parseWithFallback(f,ce),y=e.schema.nodeFromJSON(h);t.transact(()=>{zD(t,n,y,{mapping:new Map,isOMark:new Map})},CZ),E=!1,D&&(j=!0),Ce!==s&&(FX(`source-mode`),Ce=s),eK(`b`);try{let t=i.serialize(h),n=Gi(s,u+t);G2e(r.toString(),n,{site:`observer-b`,docName:e.docName,canonicalizeBody:e=>e===l?u+t:le(e)}),ne(n),S=n,C=!1,w=0}catch(e){if(e instanceof ta)throw e;xZ.warn({err:e},`[Server Observer B] Post-sync re-serialization failed — using input body as baseline`),ne(Gi(s,l))}}catch(e){if(e instanceof ta)throw e;tK(`b`),xZ.error({err:e},`[Server Observer B] Failed to sync text→tree`);try{let e=VD(n,a).toJSON(),t=i.serialize(e),r=ae();re(oe(r,t).md)}catch(e){if(e instanceof ta)throw e;xZ.warn({err:e},`[Server Observer B] Baseline recovery also failed`)}}},Te=()=>{sG(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},we)},Ee=(e,t)=>{if(t.origin!==CZ){if(wZ(t.origin)){try{let e=ae();te(),Ce=e}catch(e){tK(`b`),xZ.warn({err:e instanceof Error?e:Error(String(e))},`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement`),v=!0}return}w4e(t.origin)&&(b=Date.now()),y=Date.now(),v=!0}},Oe=(t,n)=>{sG(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!_&&!v){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(n.every(e=>e.origin===CZ)){_=!1,v=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}j=!1,M=!1,N=!1;let i=_;_&&(_=!1,e.onDispatch?.(`a`),xe());let a=v;if(v&&(v=!1,e.onDispatch?.(`b`),Te()),D&&!N){if(M)ee=0,k.length=0,A=!1;else if(j){let e=tn(r.toString());k.includes(e)?(ee+=1,ee>=8&&!A&&f(ee)):ee=0,k.push(e),k.length>8&&k.shift()}}t.setAttribute(`observer.dispatch`,i&&a?`a-then-b`:i?`a`:a?`b`:`none`)})};n.observeDeep(Se),r.observe(Ee),t.on(`afterAllTransactions`,Oe);let ke=b4e(()=>_||v),Ae=j2e(t);return EZ.set(t,{preDrain(o){if(!O)return{preDrain:!1,reason:`skip-disabled`};if(!C)return{preDrain:!1,reason:`skip-no-pending`};try{let e=VD(n,a).toJSON(),s=r.toString(),{body:c}=Ba(s),l=s.length-c.length,{preDrain:u,verdict:d,splice:f}=_4e({pendingDirty:!0,body:c,fragmentPmJson:e,witnessMatched:s===m,fmPrefixLen:l,lineEnding:Xn(s),op:o.kind===`agent-undo`?{kind:`agent-undo`,ytext:r,stackItem:o.stackItem}:{kind:`agent-write`,writeKind:o.writeKind},mdManager:i});if(!u)return d;let p=oe(ae(),i.serialize(e));if(p.adjusted!==`none`)return{preDrain:!1,reason:`checkpoint-fm-ambiguous`};let h=s.length-c.length;t.transact(()=>{F4e(r,{spliceStart:h+f.spliceStart,spliceEnd:h+f.spliceEnd,newSlice:f.newSlice})},CZ);let g=p.md;return ne(g),S=g,C=!1,w=0,d}catch(t){return tK(`a`),xZ.warn({err:t instanceof Error?t:Error(String(t)),docName:e.docName},`[Server pre-drain] Discrimination threw — routing to the checkpoint floor`),{preDrain:!1,reason:`checkpoint-witness-mismatch`}}}}),DZ.set(t,()=>S),OZ.set(t,()=>b>0?b:void 0),()=>{ke(),Ae(),EZ.delete(t),DZ.delete(t),OZ.delete(t),t.off(`afterAllTransactions`,Oe),n.unobserveDeep(Se),r.unobserve(Ee)}}const kZ=q(`agent-sessions`),J4e={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function AZ(e){return e.endsWith(`.md`)||e.endsWith(`.mdx`)?e:`${LK(e)}${VK(e)}`}async function jZ(e,t,n,r){if(AX(e))return;let i=IZ(e.getText(`source`).toString(),t,n);if(i!==void 0)return JX(i.newContent,r)}async function Y4e(e,t){let n=e.getText(`source`).toString(),{fenced:r,body:i}=Ut(n),a=Ma(r,t);if(!a.ok||a.nextFenced===r)return;let o=r===``&&i!==``&&!i.startsWith(`
|
|
1034
1034
|
`);return JX(a.nextFenced+(o?`
|
|
1035
|
-
`:``)+i)}const X4e=2e3,Z4e=new class{writes=new WeakMap;record(e,t,n){let r=this.writes.get(e)??new Map;for(let[e,t]of r)Q4e(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 Q4e(e,t){return e!==void 0&&Math.abs(t-e)<X4e}function $4e(e,t,n,r){if(t!==`replace`)return;let i=Z4e.hasRecentPeer(e,n,r),a=Q4e(R4e(e),r);if(!(!i&&!a))throw new MJ(AZ(e.name))}function MZ(e){return e.bridgeLossReporter?{reporter:e.bridgeLossReporter,writerId:e.agentId}:void 0}function NZ(e,t,n){let r=I4e(e);r&&IZ(e.getText(`source`).toString(),t,n)!==void 0&&r.preDrain({kind:`agent-write`,writeKind:n})}function PZ(e,t,n,r,i,a,o){if(AX(e))throw new BJ({file:AZ(e.name)});return sG(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":n,"agent.markdown.bytes":t.length}},()=>{let s=e3e(e,t,n,r,i,a,o);return s!==void 0&&cG({"agent.content_divergent":!0,"agent.intended_bytes":s.intendedBytes,"agent.actual_bytes":s.actualBytes,"agent.byte_delta":s.byteDelta,"agent.divergence_type":s.divergenceType}),s})}function FZ(e){return e.getXmlFragment(`default`).toArray().map(e=>e.toString())}function IZ(e,t,n){let{frontmatter:r,body:i}=Ba(e),{frontmatter:a,body:o}=n===`append`||n===`prepend`?XW(t):Ba(t);if((n===`append`||n===`prepend`)&&o===``)return;let s,c;switch(n){case`replace`:s=a||r,c=o;break;case`patch`:s=a||r,c=o;break;case`prepend`:s=r,c=i.length>0?`${o.replace(/\n+$/,``)}\n\n${i.replace(/^\n+/,``)}`:o;break;case`append`:s=r,c=i.length>0?`${i.replace(/\n+$/,``)}\n\n${o.replace(/^\n+/,``)}`:o}return{existingFm:r,finalFm:s,newContent:Gi(s,c)}}function e3e(e,t,n,r,i,a,o){try{let s=e.getText(`source`).toString(),c=IZ(s,t,n);if(c===void 0)return;let{existingFm:l,finalFm:u,newContent:d}=c,f=a&&NK(J4e.context.origin)?{report:t=>a.reporter(e.name,t,a.writerId,`agent-write-intake`),baselineFullMd:s}:void 0,p=!1;if(u!==l){let t=li(Ta(u));if(t.map===null)throw new NX({file:AZ(e.name),parseError:t.parseError??`unknown YAML parse error`});p=!0}else if(u===``&&Ba(d).frontmatter!==``)throw new NX({file:AZ(e.name),parseError:"the payload's leading `---` fence pair would land at byte 0, where the composed document re-reads it as the frontmatter region instead of body",refusalClass:`byte-0-promotion`,hint:"Start the payload with a blank line so the fence pair cannot open the document, or use `***` / `___` for the thematic break."});$4e(e,n,o,Date.now()),p&&FX(`mcp-write`),n===`replace`?fG(e,d,r,i,f):dG(e,d,`agent`,r,i,f);let m=e.getText(`source`).toString();o!==void 0&&m!==s&&Z4e.record(e,o,Date.now());let h=s2e(m,d,n);return kZ.debug({docName:e.name,position:n,markdownBytes:t.length,divergent:h!==void 0},`[agent-write] applied agent markdown write`),h}catch(r){throw!(r instanceof NX)&&!(r instanceof MJ)&&kZ.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function t3e(e,t,n,r){let i=e.dc.document;if(AX(i))throw new BJ({file:AZ(i.name)});return sG(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let i=n3e(e,t,n,r);return cG({"agent.undo_effective":i}),i})}function n3e(e,t,n,r){let{dc:i,um:a,undoOrigin:o}=e,s=i.document,c=t===`last`?1:t===`count`?Math.min(Math.max(0,r??0),a.undoStack.length):a.undoStack.length;c===1&&a.undoStack.length>0&&I4e(s)?.preDrain({kind:`agent-undo`,stackItem:a.undoStack[a.undoStack.length-1]});let l=!1,u=e.bridgeLossReporter,d=u&&NK(o.context.origin)?{report:t=>u(e.docName,t,e.agentId),baselineFullMd:s.getText(`source`).toString()}:void 0;return s.transact(()=>{for(let e=0;e<c&&a.undoStack.length>0;e++)a.undo(),l=!0;l&&Aqe(s,n,d)},o),kZ.debug({docName:e.docName,agentId:e.agentId,scope:t,framesToPop:c,undone:l},`[agent-session] applied agent undo`),l}function r3e(e,t,n,r,i){let a={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(a.agent_type=t),n!==void 0&&(a.principal=n),r!==void 0&&(a.display_name=r),i!==void 0&&(a.color_seed=i),Object.freeze(a);let o={source:`local`,skipStoreHooks:!1,context:a};return Object.freeze(o),o}function i3e(e,t){let n={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(n.agent_type=t),Object.freeze(n);let r={source:`local`,skipStoreHooks:!1,context:n};return Object.freeze(r),r}const a3e=256,o3e=5e3;var LZ=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}};let s3e=null;function c3e(){return s3e||=aG().createCounter(`ok.sessions.evictions_total`,{description:`Agent sessions evicted (LRU-idle) under capacity pressure to admit a new session. Sustained growth alongside ok.sessions.active pinned at ok.sessions.limit means the working set exceeds the cap.`,unit:`{sessions}`}),s3e}var l3e=class{sessions=new Map;pendingSessions=new Map;activeOperations=new Map;hocuspocus;maxSessions;minEvictableIdleMs;bridgeLossReporter;assertDocumentScope;awaitWriteAdmission;evictions=0;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256,this.minEvictableIdleMs=t.minEvictableIdleMs??5e3,this.bridgeLossReporter=t.bridgeLossReporter,this.assertDocumentScope=t.assertDocumentScope,this.awaitWriteAdmission=t.awaitWriteAdmission}attachBridgeLossReporter(e){this.bridgeLossReporter=e}get liveSessionCount(){return this.sessions.size}get sessionLimit(){return this.maxSessions}get evictionCount(){return this.evictions}touchSession(e,t){t.lastUsedAt=Date.now(),this.sessions.delete(e),this.sessions.set(e,t)}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,n]of this.sessions)e.endsWith(t)&&(yield n)}getLiveSession(e,t){this.assertDocumentScope?.(e);let n=this.sessionKey(e,t),r=this.sessions.get(n);return r&&this.touchSession(n,r),r}async withSessions(e){let t=[],n=async(e,n=JW,r)=>{let i=this.sessionKey(e,n),a=this.activeOperations.get(i)??{count:0};a.count+=1,this.activeOperations.set(i,a);let o=()=>{--a.count,a.count===0&&this.activeOperations.delete(i)};try{let i=await this.getSession(e,n,r);return t.push(o),i}catch(e){throw o(),e}};try{return await e(n)}finally{for(let e of t)e()}}async getSession(e,t=JW,n){if(KK(e)||qK(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);if(this.assertDocumentScope?.(e),this.awaitWriteAdmission){let t=Date.now();await this.awaitWriteAdmission()||kZ.warn({docName:e,waitedMs:Date.now()-t},`[agent-session] git batch still in progress after the admission wait; admitting the write`)}let r=this.sessionKey(e,t),i=this.sessions.get(r);if(i)return this.touchSession(r,i),i;let a=this.pendingSessions.get(r);if(a)return kZ.debug({docName:e,agentId:t},`[agent-session] joining in-flight session creation`),a;for(;this.sessions.size+this.pendingSessions.size>=this.maxSessions;)if(await this.evictLruIdleSession()===null)throw kZ.warn({docName:e,agentId:t,limit:this.maxSessions},`[agent-session] session capacity reached, refusing new session`),new LZ(this.maxSessions);let o=this._createSession(e,t,n);this.pendingSessions.set(r,o);try{let e=await o;return this.sessions.set(r,e),e}finally{this.pendingSessions.delete(r)}}async _createSession(e,t,n){let r=n?.clientName,i=t.startsWith(`agent-`)?t.slice(6):t,a=r3e(i,r,n?.principalId,n?.displayName,n?.colorSeed),o=i3e(i,r),s={session_id:i,...r===void 0?{}:{agent_type:r},...n?.clientName===void 0?{}:{client_name:n.clientName},...n?.principalId===void 0?{}:{principalId:n.principalId}},c=await this.hocuspocus.openDirectConnection(e,s);kZ.debug({docName:e,agentId:t,sessionId:i,agentType:r},`[agent-session] DirectConnection opened`);let l=new sTe([c.document.getText(`source`),c.document.getMap(`agent-flash`)],{trackedOrigins:new Set([a]),captureTimeout:500,captureTransaction:e=>e.origin!==o,ignoreRemoteMapChanges:!0}),u=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return l.on(`stack-item-added`,u),l.on(`stack-item-updated`,u),kZ.info({docName:e,agentId:t,sessionId:i},`[agent-session] Created session for: ${e} / ${t}`),{dc:c,origin:a,undoOrigin:o,um:l,agentId:t,docName:e,lastUsedAt:Date.now(),bridgeLossReporter:this.bridgeLossReporter}}async evictLruIdleSession(){for(let[e,t]of this.sessions){if(this.activeOperations.has(e))continue;let n=Date.now()-t.lastUsedAt;return n<this.minEvictableIdleMs?null:(this.sessions.delete(e),await this.cleanupSession(e,t,{docName:t.docName,agentId:t.agentId,evicted:!0}),this.evictions++,TJe(),c3e().add(1),kZ.info({docName:t.docName,agentId:t.agentId,idleMs:n},`[agent-session] Evicted LRU idle session under capacity pressure`),e)}return null}hasSession(e,t=JW){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,n){kZ.debug({docName:t.docName,agentId:t.agentId,...n},`[agent-session] closing session`);try{try{t.um.destroy()}catch(e){kZ.error({err:e,...n},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){kZ.error({err:e,...n},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=JW){let n=this.sessionKey(e,t),r=this.sessions.get(n);r&&(await this.cleanupSession(n,r,{docName:e,agentId:t}),kZ.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,n=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));n.length>0&&await Promise.allSettled(n.map(e=>this.pendingSessions.get(e)));let r=[...this.sessions.keys()].filter(e=>e.endsWith(t));kZ.debug({agentId:e,pendingSettled:n.length,closing:r.length},`[agent-session] closing all sessions for agent`);for(let t of r){let n=this.sessions.get(t);n&&await this.cleanupSession(t,n,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,n=[...this.sessions.keys()].filter(e=>e.startsWith(t));kZ.debug({docName:e,closing:n.length},`[agent-session] closing all sessions for doc`);for(let t of n){let n=this.sessions.get(t);n&&await this.cleanupSession(t,n,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];kZ.debug({closing:t.length},`[agent-session] closing all sessions`);for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RZ={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`},zZ=new Set(Object.values(RZ));function BZ(e){return zZ.has(e)}const VZ=Object.keys(RZ),HZ={discovery:`user`,project:`project`,"write-skill":`user`},UZ=VZ.filter(e=>HZ[e]===`user`),u3e=new Set(UZ.map(e=>RZ[e]));function d3e(e){return u3e.has(e)}const f3e=[`discovery`];function p3e(e){return`packages/server/assets/skills/${e}/SKILL.md`}const m3e=102400,h3e=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function g3e(e){return new URL(e).pathname.endsWith(`.ts`)}function _3e(e,t,n){let r=n.platform??process.platform,i=n.checkDesktop??!1,a=n.home??dc(),o=[],s=process.env.NODE_ENV===`test`;return i&&r===`darwin`&&(s||o.push(H(`/Applications`,h3e,e)),(!s||n.home!==void 0)&&o.push(H(a,`Applications`,h3e,e))),g3e(t)?(o.push(Bs(new URL(`../assets/skills/${e}`,t))),o):(o.push(Bs(new URL(`../dist/assets/skills/${e}`,t))),o.push(Bs(new URL(`../assets/skills/${e}`,t))),o.push(Bs(new URL(`./assets/skills/${e}`,t))),o)}function v3e(e,t,n){let r=g3e(t)?`Running from source, only the source assets are read, so the bundle name is unknown or its directory under packages/server/assets/skills is missing.`:"This usually means the package build did not copy packages/server/assets into dist/assets. Run `pnpm run build` in the package that ships the skills before publishing.";return`Bundled skill asset directory not found for bundle '${e}'. Tried: ${n.join(`, `)}. ${r}`}function WZ(e,t={}){let n=_3e(e,import.meta.url,t);for(let e of n)if(G(e))return e;throw Error(v3e(e,import.meta.url,n))}async function*y3e(e,t=e){let n=await yc(e,{withFileTypes:!0});for(let r of n){let n=H(e,r.name);r.isDirectory()?yield*y3e(n,t):r.isFile()&&(yield U(t,n))}}function b3e(e,t=js){return t(e)||`open-knowledge`}function x3e(e,t=Rs){return t===`/`?e:e.split(t).join(`/`)}async function S3e(e,t,n=b3e(e)){let r=new AMe.ZipFile;r.addEmptyDirectory(`${n}/`);let i=[];for await(let t of y3e(e))i.push(t);i.sort();for(let t of i){let i=H(e,t),a=`${n}/${x3e(t)}`;r.addFile(i,a)}r.end(),await new Promise((e,n)=>{let i=Js(t);r.outputStream.pipe(i),i.on(`close`,()=>e()),i.on(`error`,n),r.outputStream.on(`error`,n)})}async function C3e(e){return new Promise((t,n)=>{let r=Tc(`sha256`),i=qs(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>t(r.digest(`hex`))),i.on(`error`,n)})}async function w3e(e,t={}){let n=t.bundle??`project`,r=oc(e).size;if(r>m3e)throw Error(`Built ${e} is ${r} bytes, exceeds ${m3e}-byte ceiling`);let i=await C3e(e),a=t.sourceDir??WZ(n,{checkDesktop:!1}),o=await vc(H(a,`SKILL.md`),`utf-8`),s=RZ[n];if(!RegExp(`^name:\\s+${s}$`,`m`).test(o.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${s}'. Check packages/server/assets/skills/${n}/SKILL.md frontmatter.`);return{size:r,sha256:i}}async function T3e(e={}){let t=e.bundle??`project`,n=e.sourceDir??WZ(t,{checkDesktop:e.checkDesktop??!1}),r=e.outputPath??H(process.cwd(),`openknowledge.skill`);await S3e(n,r,RZ[t]);let{size:i,sha256:a}=await w3e(r,{bundle:t,sourceDir:n});return{outputPath:r,size:i,sha256:a}}const E3e=`x-ok-connection-id`,D3e=`x-ok-hosted-agent`;function O3e(e,t){let n=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return n?n.slice(0,128):t}function k3e(){try{let e=V(Bs(import.meta.url)),t=W(e,`..`,`package.json`),n=JSON.parse(K(t,`utf-8`));if(typeof n.version==`string`&&n.version.length>0)return n.version}catch{}return`0.0.0-unknown`}const GZ=k3e(),A3e=1;function KZ(e,t){let n=Fs(e)+Rs;return`${Fs(t)}${Rs}`.startsWith(n)}function qZ(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,`_`);return t===``||t===`.`||t===`..`?`_`:t}function j3e(e,t,n,r=12e4){let[i,a]=n?process.platform===`darwin`?[`ditto`,[`-x`,`-k`,e,t]]:process.platform===`win32`?[`tar`,[`-xf`,e,`-C`,t]]:[`unzip`,[`-q`,e,`-d`,t]]:[`tar`,[`-xf`,e,`-C`,t]];return new Promise((t,n)=>{let o=Os(i,a,{stdio:[`ignore`,`ignore`,`pipe`],shell:!1,windowsHide:!0}),s=setTimeout(()=>{o.kill(`SIGKILL`),n(Error(`${i} timed out after ${r}ms extracting ${e}`))},r);s.unref?.();let c=``;o.stderr?.on(`data`,e=>{c=(c+e.toString()).slice(-2e3)}),o.on(`error`,e=>{clearTimeout(s),n(e)}),o.on(`exit`,e=>{clearTimeout(s),e===0?t():n(Error(`${i} exited ${e}: ${c}`))})})}async function M3e(e,t,n={}){let r=await(n.fetchImpl??fetch)(e,{signal:n.signal});if(!r.ok||r.body===null)throw Error(`download failed: HTTP ${r.status} for ${e}`);let i=r.headers.get(`content-length`),a=i!==null&&i!==``?Number(i):null,o=Tc(`sha256`),s=0,c=Js(t),l=wc.fromWeb(r.body);return l.on(`data`,e=>{o.update(e),s+=e.length,n.onProgress?.({receivedBytes:s,totalBytes:Number.isFinite(a)?a:null})}),await new Promise((e,t)=>{l.pipe(c).on(`finish`,()=>e()).on(`error`,t),l.on(`error`,t)}),o.digest(`hex`)}async function N3e(e,t={}){let n=await(t.fetchImpl??fetch)(e,{signal:t.signal});if(!n.ok)throw Error(`fetch failed: HTTP ${n.status} for ${e}`);return n.text()}function P3e(e,t){for(let n of e.split(`
|
|
1035
|
+
`:``)+i)}const X4e=2e3,Z4e=new class{writes=new WeakMap;record(e,t,n){let r=this.writes.get(e)??new Map;for(let[e,t]of r)Q4e(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 Q4e(e,t){return e!==void 0&&Math.abs(t-e)<X4e}function $4e(e,t,n,r){if(t!==`replace`)return;let i=Z4e.hasRecentPeer(e,n,r),a=Q4e(R4e(e),r);if(!(!i&&!a))throw new MJ(AZ(e.name))}function MZ(e){return e.bridgeLossReporter?{reporter:e.bridgeLossReporter,writerId:e.agentId}:void 0}function NZ(e,t,n){let r=I4e(e);r&&IZ(e.getText(`source`).toString(),t,n)!==void 0&&r.preDrain({kind:`agent-write`,writeKind:n})}function PZ(e,t,n,r,i,a,o){if(AX(e))throw new BJ({file:AZ(e.name)});return sG(`agent.applyAgentMarkdownWrite`,{attributes:{"doc.name":e.name,"agent.write_position":n,"agent.markdown.bytes":t.length}},()=>{let s=e3e(e,t,n,r,i,a,o);return s!==void 0&&cG({"agent.content_divergent":!0,"agent.intended_bytes":s.intendedBytes,"agent.actual_bytes":s.actualBytes,"agent.byte_delta":s.byteDelta,"agent.divergence_type":s.divergenceType}),s})}function FZ(e){return e.getXmlFragment(`default`).toArray().map(e=>e.toString())}function IZ(e,t,n){let{frontmatter:r,body:i}=Ba(e),{frontmatter:a,body:o}=n===`append`||n===`prepend`?XW(t):Ba(t);if((n===`append`||n===`prepend`)&&o===``)return;let s,c;switch(n){case`replace`:s=a||r,c=o;break;case`patch`:s=a||r,c=o;break;case`prepend`:s=r,c=i.length>0?`${o.replace(/\n+$/,``)}\n\n${i.replace(/^\n+/,``)}`:o;break;case`append`:s=r,c=i.length>0?`${i.replace(/\n+$/,``)}\n\n${o.replace(/^\n+/,``)}`:o}return{existingFm:r,finalFm:s,newContent:Gi(s,c)}}function e3e(e,t,n,r,i,a,o){try{let s=e.getText(`source`).toString(),c=IZ(s,t,n);if(c===void 0)return;let{existingFm:l,finalFm:u,newContent:d}=c,f=a&&NK(J4e.context.origin)?{report:t=>a.reporter(e.name,t,a.writerId,`agent-write-intake`),baselineFullMd:s}:void 0,p=!1;if(u!==l){let t=li(Ta(u));if(t.map===null)throw new NX({file:AZ(e.name),parseError:t.parseError??`unknown YAML parse error`});p=!0}else if(u===``&&Ba(d).frontmatter!==``)throw new NX({file:AZ(e.name),parseError:"the payload's leading `---` fence pair would land at byte 0, where the composed document re-reads it as the frontmatter region instead of body",refusalClass:`byte-0-promotion`,hint:"Start the payload with a blank line so the fence pair cannot open the document, or use `***` / `___` for the thematic break."});$4e(e,n,o,Date.now()),p&&FX(`mcp-write`),n===`replace`?fG(e,d,r,i,f):dG(e,d,`agent`,r,i,f);let m=e.getText(`source`).toString();o!==void 0&&m!==s&&Z4e.record(e,o,Date.now());let h=s2e(m,d,n);return kZ.debug({docName:e.name,position:n,markdownBytes:t.length,divergent:h!==void 0},`[agent-write] applied agent markdown write`),h}catch(r){throw!(r instanceof NX)&&!(r instanceof MJ)&&kZ.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function t3e(e,t,n,r){let i=e.dc.document;if(AX(i))throw new BJ({file:AZ(i.name)});return sG(`agent.applyAgentUndo`,{attributes:{"doc.name":e.dc.document.name,"agent.undo_scope":t}},()=>{let i=n3e(e,t,n,r);return cG({"agent.undo_effective":i}),i})}function n3e(e,t,n,r){let{dc:i,um:a,undoOrigin:o}=e,s=i.document,c=t===`last`?1:t===`count`?Math.min(Math.max(0,r??0),a.undoStack.length):a.undoStack.length;c===1&&a.undoStack.length>0&&I4e(s)?.preDrain({kind:`agent-undo`,stackItem:a.undoStack[a.undoStack.length-1]});let l=!1,u=e.bridgeLossReporter,d=u&&NK(o.context.origin)?{report:t=>u(e.docName,t,e.agentId),baselineFullMd:s.getText(`source`).toString()}:void 0;return s.transact(()=>{for(let e=0;e<c&&a.undoStack.length>0;e++)a.undo(),l=!0;l&&Aqe(s,n,d)},o),kZ.debug({docName:e.docName,agentId:e.agentId,scope:t,framesToPop:c,undone:l},`[agent-session] applied agent undo`),l}function r3e(e,t,n,r,i){let a={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(a.agent_type=t),n!==void 0&&(a.principal=n),r!==void 0&&(a.display_name=r),i!==void 0&&(a.color_seed=i),Object.freeze(a);let o={source:`local`,skipStoreHooks:!1,context:a};return Object.freeze(o),o}function i3e(e,t){let n={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(n.agent_type=t),Object.freeze(n);let r={source:`local`,skipStoreHooks:!1,context:n};return Object.freeze(r),r}const a3e=256,o3e=5e3;var LZ=class extends Error{limit;constructor(e){super(`Maximum agent session count reached (${e})`),this.name=`AgentSessionCapacityError`,this.limit=e}};let s3e=null;function c3e(){return s3e||=aG().createCounter(`ok.sessions.evictions_total`,{description:`Agent sessions evicted (LRU-idle) under capacity pressure to admit a new session. Sustained growth alongside ok.sessions.active pinned at ok.sessions.limit means the working set exceeds the cap.`,unit:`{sessions}`}),s3e}var l3e=class{sessions=new Map;pendingSessions=new Map;activeOperations=new Map;hocuspocus;maxSessions;minEvictableIdleMs;bridgeLossReporter;assertDocumentScope;awaitWriteAdmission;evictions=0;constructor(e,t={}){this.hocuspocus=e,this.maxSessions=t.maxSessions??256,this.minEvictableIdleMs=t.minEvictableIdleMs??5e3,this.bridgeLossReporter=t.bridgeLossReporter,this.assertDocumentScope=t.assertDocumentScope,this.awaitWriteAdmission=t.awaitWriteAdmission}attachBridgeLossReporter(e){this.bridgeLossReporter=e}get liveSessionCount(){return this.sessions.size}get sessionLimit(){return this.maxSessions}get evictionCount(){return this.evictions}touchSession(e,t){t.lastUsedAt=Date.now(),this.sessions.delete(e),this.sessions.set(e,t)}sessionKey(e,t){return`${e}\0${t}`}*sessionsForConnection(e){let t=`\0${e}`;for(let[e,n]of this.sessions)e.endsWith(t)&&(yield n)}getLiveSession(e,t){this.assertDocumentScope?.(e);let n=this.sessionKey(e,t),r=this.sessions.get(n);return r&&this.touchSession(n,r),r}async withSessions(e){let t=[],n=async(e,n=JW,r)=>{let i=this.sessionKey(e,n),a=this.activeOperations.get(i)??{count:0};a.count+=1,this.activeOperations.set(i,a);let o=()=>{--a.count,a.count===0&&this.activeOperations.delete(i)};try{let i=await this.getSession(e,n,r);return t.push(o),i}catch(e){throw o(),e}};try{return await e(n)}finally{for(let e of t)e()}}async getSession(e,t=JW,n){if(KK(e)||qK(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);if(this.assertDocumentScope?.(e),this.awaitWriteAdmission){let t=Date.now();await this.awaitWriteAdmission()||kZ.warn({docName:e,waitedMs:Date.now()-t},`[agent-session] git batch still in progress after the admission wait; admitting the write`)}let r=this.sessionKey(e,t),i=this.sessions.get(r);if(i)return this.touchSession(r,i),i;let a=this.pendingSessions.get(r);if(a)return kZ.debug({docName:e,agentId:t},`[agent-session] joining in-flight session creation`),a;for(;this.sessions.size+this.pendingSessions.size>=this.maxSessions;)if(await this.evictLruIdleSession()===null)throw kZ.warn({docName:e,agentId:t,limit:this.maxSessions},`[agent-session] session capacity reached, refusing new session`),new LZ(this.maxSessions);let o=this._createSession(e,t,n);this.pendingSessions.set(r,o);try{let e=await o;return this.sessions.set(r,e),e}finally{this.pendingSessions.delete(r)}}async _createSession(e,t,n){let r=n?.clientName,i=t.startsWith(`agent-`)?t.slice(6):t,a=r3e(i,r,n?.principalId,n?.displayName,n?.colorSeed),o=i3e(i,r),s={session_id:i,...r===void 0?{}:{agent_type:r},...n?.clientName===void 0?{}:{client_name:n.clientName},...n?.principalId===void 0?{}:{principalId:n.principalId}},c=await this.hocuspocus.openDirectConnection(e,s);kZ.debug({docName:e,agentId:t,sessionId:i,agentType:r},`[agent-session] DirectConnection opened`);let l=new sTe([c.document.getText(`source`),c.document.getMap(`agent-flash`)],{trackedOrigins:new Set([a]),captureTimeout:500,captureTransaction:e=>e.origin!==o,ignoreRemoteMapChanges:!0}),u=({stackItem:e})=>{e.meta.set(`time`,Date.now())};return l.on(`stack-item-added`,u),l.on(`stack-item-updated`,u),kZ.info({docName:e,agentId:t,sessionId:i},`[agent-session] Created session for: ${e} / ${t}`),{dc:c,origin:a,undoOrigin:o,um:l,agentId:t,docName:e,lastUsedAt:Date.now(),bridgeLossReporter:this.bridgeLossReporter}}async evictLruIdleSession(){for(let[e,t]of this.sessions){if(this.activeOperations.has(e))continue;let n=Date.now()-t.lastUsedAt;return n<this.minEvictableIdleMs?null:(this.sessions.delete(e),await this.cleanupSession(e,t,{docName:t.docName,agentId:t.agentId,evicted:!0}),this.evictions++,TJe(),c3e().add(1),kZ.info({docName:t.docName,agentId:t.agentId,idleMs:n},`[agent-session] Evicted LRU idle session under capacity pressure`),e)}return null}hasSession(e,t=JW){return this.sessions.has(this.sessionKey(e,t))}async cleanupSession(e,t,n){kZ.debug({docName:t.docName,agentId:t.agentId,...n},`[agent-session] closing session`);try{try{t.um.destroy()}catch(e){kZ.error({err:e,...n},`[agent-session] um.destroy() failed`)}try{await t.dc.disconnect()}catch(e){kZ.error({err:e,...n},`[agent-session] dc.disconnect() failed`)}}finally{this.sessions.delete(e)}}async closeSession(e,t=JW){let n=this.sessionKey(e,t),r=this.sessions.get(n);r&&(await this.cleanupSession(n,r,{docName:e,agentId:t}),kZ.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,n=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));n.length>0&&await Promise.allSettled(n.map(e=>this.pendingSessions.get(e)));let r=[...this.sessions.keys()].filter(e=>e.endsWith(t));kZ.debug({agentId:e,pendingSettled:n.length,closing:r.length},`[agent-session] closing all sessions for agent`);for(let t of r){let n=this.sessions.get(t);n&&await this.cleanupSession(t,n,{agentId:e,key:t})}}async closeAllForDoc(e){let t=`${e}\0`,n=[...this.sessions.keys()].filter(e=>e.startsWith(t));kZ.debug({docName:e,closing:n.length},`[agent-session] closing all sessions for doc`);for(let t of n){let n=this.sessions.get(t);n&&await this.cleanupSession(t,n,{docName:e,key:t})}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];kZ.debug({closing:t.length},`[agent-session] closing all sessions`);for(let e of t){let t=this.sessions.get(e);t&&await this.cleanupSession(e,t,{key:e})}}};const RZ={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`},zZ=new Set(Object.values(RZ));function BZ(e){return zZ.has(e)}const VZ=Object.keys(RZ),HZ={discovery:`user`,project:`project`,"write-skill":`user`},UZ=VZ.filter(e=>HZ[e]===`user`),u3e=new Set(UZ.map(e=>RZ[e]));function d3e(e){return u3e.has(e)}const f3e=[`discovery`];function p3e(e){return`packages/server/assets/skills/${e}/SKILL.md`}const m3e=102400,h3e=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function g3e(e){return new URL(e).pathname.endsWith(`.ts`)}function _3e(e,t,n){let r=n.platform??process.platform,i=n.checkDesktop??!1,a=n.home??dc(),o=[],s=process.env.NODE_ENV===`test`;return i&&r===`darwin`&&(s||o.push(H(`/Applications`,h3e,e)),(!s||n.home!==void 0)&&o.push(H(a,`Applications`,h3e,e))),g3e(t)?(o.push(Bs(new URL(`../assets/skills/${e}`,t))),o):(o.push(Bs(new URL(`../dist/assets/skills/${e}`,t))),o.push(Bs(new URL(`../assets/skills/${e}`,t))),o.push(Bs(new URL(`./assets/skills/${e}`,t))),o)}function v3e(e,t,n){let r=g3e(t)?`Running from source, only the source assets are read, so the bundle name is unknown or its directory under packages/server/assets/skills is missing.`:"This usually means the package build did not copy packages/server/assets into dist/assets. Run `pnpm run build` in the package that ships the skills before publishing.";return`Bundled skill asset directory not found for bundle '${e}'. Tried: ${n.join(`, `)}. ${r}`}function WZ(e,t={}){let n=_3e(e,import.meta.url,t);for(let e of n)if(G(e))return e;throw Error(v3e(e,import.meta.url,n))}async function*y3e(e,t=e){let n=await yc(e,{withFileTypes:!0});for(let r of n){let n=H(e,r.name);r.isDirectory()?yield*y3e(n,t):r.isFile()&&(yield U(t,n))}}function b3e(e,t=js){return t(e)||`open-knowledge`}function x3e(e,t=Rs){return t===`/`?e:e.split(t).join(`/`)}async function S3e(e,t,n=b3e(e)){let r=new AMe.ZipFile;r.addEmptyDirectory(`${n}/`);let i=[];for await(let t of y3e(e))i.push(t);i.sort();for(let t of i){let i=H(e,t),a=`${n}/${x3e(t)}`;r.addFile(i,a)}r.end(),await new Promise((e,n)=>{let i=Js(t);r.outputStream.pipe(i),i.on(`close`,()=>e()),i.on(`error`,n),r.outputStream.on(`error`,n)})}async function C3e(e){return new Promise((t,n)=>{let r=Tc(`sha256`),i=qs(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>t(r.digest(`hex`))),i.on(`error`,n)})}async function w3e(e,t={}){let n=t.bundle??`project`,r=oc(e).size;if(r>m3e)throw Error(`Built ${e} is ${r} bytes, exceeds ${m3e}-byte ceiling`);let i=await C3e(e),a=t.sourceDir??WZ(n,{checkDesktop:!1}),o=await vc(H(a,`SKILL.md`),`utf-8`),s=RZ[n];if(!RegExp(`^name:\\s+${s}$`,`m`).test(o.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${s}'. Check packages/server/assets/skills/${n}/SKILL.md frontmatter.`);return{size:r,sha256:i}}async function T3e(e={}){let t=e.bundle??`project`,n=e.sourceDir??WZ(t,{checkDesktop:e.checkDesktop??!1}),r=e.outputPath??H(process.cwd(),`openknowledge.skill`);await S3e(n,r,RZ[t]);let{size:i,sha256:a}=await w3e(r,{bundle:t,sourceDir:n});return{outputPath:r,size:i,sha256:a}}const E3e=`x-ok-connection-id`,D3e=`x-ok-hosted-agent`;function O3e(e,t){let n=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return n?n.slice(0,128):t}function k3e(e=W(V(Bs(import.meta.url)),`..`,`package.json`)){try{let t=JSON.parse(K(e,`utf-8`));if(typeof t.version==`string`&&t.version.length>0)return t.version}catch{}return`0.0.0-unknown`}const GZ=k3e(),A3e=1;function KZ(e,t){let n=Fs(e)+Rs;return`${Fs(t)}${Rs}`.startsWith(n)}function qZ(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,`_`);return t===``||t===`.`||t===`..`?`_`:t}function j3e(e,t,n,r=12e4){let[i,a]=n?process.platform===`darwin`?[`ditto`,[`-x`,`-k`,e,t]]:process.platform===`win32`?[`tar`,[`-xf`,e,`-C`,t]]:[`unzip`,[`-q`,e,`-d`,t]]:[`tar`,[`-xf`,e,`-C`,t]];return new Promise((t,n)=>{let o=Os(i,a,{stdio:[`ignore`,`ignore`,`pipe`],shell:!1,windowsHide:!0}),s=setTimeout(()=>{o.kill(`SIGKILL`),n(Error(`${i} timed out after ${r}ms extracting ${e}`))},r);s.unref?.();let c=``;o.stderr?.on(`data`,e=>{c=(c+e.toString()).slice(-2e3)}),o.on(`error`,e=>{clearTimeout(s),n(e)}),o.on(`exit`,e=>{clearTimeout(s),e===0?t():n(Error(`${i} exited ${e}: ${c}`))})})}async function M3e(e,t,n={}){let r=await(n.fetchImpl??fetch)(e,{signal:n.signal});if(!r.ok||r.body===null)throw Error(`download failed: HTTP ${r.status} for ${e}`);let i=r.headers.get(`content-length`),a=i!==null&&i!==``?Number(i):null,o=Tc(`sha256`),s=0,c=Js(t),l=wc.fromWeb(r.body);return l.on(`data`,e=>{o.update(e),s+=e.length,n.onProgress?.({receivedBytes:s,totalBytes:Number.isFinite(a)?a:null})}),await new Promise((e,t)=>{l.pipe(c).on(`finish`,()=>e()).on(`error`,t),l.on(`error`,t)}),o.digest(`hex`)}async function N3e(e,t={}){let n=await(t.fetchImpl??fetch)(e,{signal:t.signal});if(!n.ok)throw Error(`fetch failed: HTTP ${n.status} for ${e}`);return n.text()}function P3e(e,t){for(let n of e.split(`
|
|
1036
1036
|
`)){let e=n.trim();if(e===``)continue;let r=/^([a-fA-F0-9]{64})\s+\*?(.+)$/.exec(e);if(r===null)continue;let[,i,a]=r;if(a.trim().split(/[\\/]/).pop()===t)return i.toLowerCase()}return null}function F3e(e){let t=e.lastIndexOf(`.`);return t<0?null:{md:`text/markdown`,mdx:`text/markdown`,txt:`text/plain`,log:`text/plain`,csv:`text/csv`,tsv:`text/tab-separated-values`,html:`text/html`,htm:`text/html`,xml:`application/xml`,json:`application/json`,yaml:`application/yaml`,yml:`application/yaml`,toml:`application/toml`,js:`application/javascript`,mjs:`application/javascript`,cjs:`application/javascript`,ts:`application/typescript`,tsx:`application/typescript`,py:`text/x-python`,rs:`text/x-rust`,go:`text/x-go`,java:`text/x-java`,rb:`text/x-ruby`,php:`text/x-php`,sh:`application/x-sh`,css:`text/css`,scss:`text/x-scss`,sql:`application/sql`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,pdf:`application/pdf`,zip:`application/zip`}[e.slice(t+1).toLowerCase()]??null}function I3e(e){return Vs(e).href}async function L3e(e,t,n,r={}){let i=r.readFile??vc,a=r.stat??Sc;if(e.kind===`image`)return t?.image===!0?{block:{type:`image`,data:e.data,mimeType:e.mimeType}}:{dropped:!0,reason:`agent does not accept images (${e.name})`};if(e.kind===`blob`)return e.textPayload?t?.embeddedContext===!0?{block:{type:`resource`,resource:{uri:`attachment:///${encodeURIComponent(e.name||`attachment`)}`,text:e.data,...e.mimeType===``?{}:{mimeType:e.mimeType}}}}:{block:{type:`text`,text:`\n\n--- Attachment: ${e.name} ---\n${e.data}\n--- End attachment ---`}}:{dropped:!0,reason:`binary files can't be sent with the message (${e.name})`};if(e.kind===`folder`){let t;try{({abs:t}=await n(e.path))}catch(t){return{dropped:!0,reason:z3e(e.path,t)}}return{block:{type:`resource_link`,uri:I3e(t),name:e.name||js(e.path)||e.path,mimeType:`inode/directory`}}}let o;try{({abs:o}=await n(e.path))}catch(t){return{dropped:!0,reason:z3e(e.path,t)}}let s=null;try{s=(await a(o)).size}catch(e){return{dropped:!0,reason:`file unavailable: ${JZ(e)}`}}let c=F3e(e.path),l=e.name||js(e.path)||e.path,u=I3e(o);if(!(t?.embeddedContext===!0&&s<=524288&&ACe(c)))return{block:{type:`resource_link`,uri:u,name:l,...c===null?{}:{mimeType:c},...s===null?{}:{size:s}}};let d;try{d=await i(o,`utf8`)}catch(e){return{dropped:!0,reason:`file read failed: ${JZ(e)}`}}return{block:{type:`resource`,resource:{uri:u,text:d,...c===null?{}:{mimeType:c}}}}}async function R3e(e,t,n,r,i={}){let a=[];for(let e of t??[])(e.kind===`file`||e.kind===`folder`)&&a.push(`[${e.name||e.path}](${e.path})`);let o=[{type:`text`,text:a.length>0?e===``?a.join(` `):`${a.join(` `)}\n\n${e}`:e}],s=[];for(let e of t??[]){let t=await L3e(e,n,r,i);`block`in t?o.push(t.block):s.push({part:e,reason:t.reason})}return{blocks:o,dropped:s}}function z3e(e,t){return`attachment path refused: ${e} (${JZ(t)})`}function JZ(e){return e instanceof Error?e.message:String(e)}function B3e(e,t,n){let[r,i,a,...o]=process.argv.slice(1);(r===void 0||i===void 0||a===void 0)&&(process.stderr.write(`ok-browser relay: missing the folder, files or command argument
|
|
1037
1037
|
`),process.exit(2));let s=new Set(n),c={roots:[{uri:t.pathToFileURL(i).href,name:`chat files`}]},l=e.spawn(a,o,{cwd:r,stdio:[`pipe`,`pipe`,`inherit`],windowsHide:!0}),u=l.stdin,d=l.stdout;(u===null||d===null)&&(process.stderr.write(`ok-browser relay: the browser server has no pipes
|
|
1038
1038
|
`),process.exit(1));let f=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:null,p=e=>{u.write(`${JSON.stringify(e)}\n`)},m=e=>{process.stdout.write(`${JSON.stringify(e)}\n`)},h=(e,t)=>{process.stderr.write(`ok-browser relay: dropped a ${e} line that ${t}\n`)},g=(e,t,n)=>{if(e.trim()===``)return null;let r;try{r=JSON.parse(e)}catch{return h(t,`is not JSON`),null}let i=f(r);if(i!==null)return i;if(Array.isArray(r))for(let e of r){let t=f(e);t?.method!==void 0&&t.id!==void 0&&n({jsonrpc:`2.0`,id:t.id,error:{code:-32600,message:`Batched messages are not supported`}})}return h(t,`is not a single JSON-RPC message`),null},_=e=>{let t=g(e,`client`,m);if(t===null||t.method===`notifications/roots/list_changed`)return null;let n=f(t.params),r=n?.name;return t.method===`tools/call`&&(typeof r!=`string`||!s.has(r))?(t.id!==void 0&&m({jsonrpc:`2.0`,id:t.id,error:{code:-32602,message:`Tool ${String(r)} is not available`}}),null):(t.method===`initialize`&&n!==null&&(n.capabilities={...f(n.capabilities),roots:{listChanged:!1}}),JSON.stringify(t))},v=e=>{let t=g(e,`server`,p);if(t===null)return null;if(t.method===`roots/list`)return t.id!==void 0&&p({jsonrpc:`2.0`,id:t.id,result:c}),null;let n=f(t.result),r=n?.tools;if(n===null||!Array.isArray(r))return e;let i=r.filter(e=>{let t=f(e)?.name;return typeof t==`string`&&s.has(t)});for(let e of i){let t=f(f(e)?.annotations);t!==null&&(t.readOnlyHint=!1)}return n.tools=i,JSON.stringify(t)},y=(e,t,n,r)=>{let i=``,a=e=>{let r=n(e);r!==null&&t.write(`${r}\n`)};e.setEncoding(`utf8`),e.on(`data`,e=>{i+=String(e);let t=i.indexOf(`
|
package/dist/index.mjs
CHANGED
|
@@ -1110,7 +1110,7 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
|
|
|
1110
1110
|
`);try{return[...e.rescanInPlaceSkillDirs(a)].sort().join(`
|
|
1111
1111
|
`)}catch{return[...a].sort().join(`
|
|
1112
1112
|
`)}},async rebuildIgnorePatterns(){let t=e=>(O=e().finally(()=>{O=null}),O),o=async()=>{if(c.reset(),e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs(a)}catch(e){l8.warn({err:e},`in-place skill re-scan failed — keeping previous allow-list`)}let t=d,o=f,s=p,l=m,u=h,g=_,S=v,C=Date.now();return mAe(`config.ignore.rebuild`,{attributes:{}},async e=>{try{let t=y();b.clear(),i===void 0&&await XAe(n,x,b);let a=Date.now()-C;if(e.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),l8.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:a},`content-filter rebuild succeeded`),r)try{r()}catch(e){l8.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){d=t,f=o,p=s,m=l,h=u,_=g,v=S,b.clear();try{T()}catch(e){l8.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 l8.warn({err:e instanceof Error?e:Error(n)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:n}}}})};return O===null?t(o):(ee===null&&(ee=O.catch(()=>null).then(()=>(ee=null,t(o)))),ee)}}}async function XAe(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=w(e,{withFileTypes:!0})}catch(t){l8.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(m8(i.name)||t(o)||t(`${o}/`))continue;r.push({dir:j(e,i.name),relPath:o})}else i.isFile()&&a8(i.name)&&!t(o)&&n.set(a,(n.get(a)??0)+1)}}}function k8(e,t,n,r){let i;try{i=w(e,{withFileTypes:!0})}catch(t){l8.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(m8(a.name)||n(i)||n(`${i}/`))continue;k8(j(e,a.name),i,n,r)}else a.isFile()&&a8(a.name)&&!n(i)&&r.set(t,(r.get(t)??0)+1)}}function A8(e){return e.split(`
|
|
1113
|
-
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function j8(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 M8(e,t,n,r,i){let a;try{a=w(e,{withFileTypes:!0})}catch(t){return l8.warn({dir:e,err:t},`Failed to read directory ${e}`),0}let o=0;for(let s of a){if(!s.isDirectory()||m8(s.name))continue;let a=j(e,s.name),c=o8(M(t,a));if(!c.startsWith(`..`)&&!(n.ignores(c)||n.ignores(`${c}/`))){for(let e of D8){let t=j(a,e);if(g(t))try{let a=S(t,`utf-8`);i.value+=a.length;let s=A8(a).map(e=>j8(e,c));n.add(s),e===`.okignore`&&r.add(s),o++}catch(n){l8.warn({path:t,err:n},`Failed to read nested ${e} at ${t}`)}}o+=M8(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 ZAe=/[\u200C-\u200F\u202A-\u202E\u206A-\u206F\uFEFF]/gu;function N8(e){return e.replace(ZAe,``).normalize(`NFC`).toUpperCase().toLowerCase().normalize(`NFC`)}function P8(e){let t=N8(e);for(let e=0;e<4;e++){let e=N8(t);if(e===t)break;t=e}return t.replace(/[. ]+$/u,(e,t)=>t===0?e:``)}const QAe=new Set([`.ok`,`.open-knowledge`,`.openknowledge`,...Object.values(rt).map(({userHomeDirName:e})=>e)].map(P8));new Set([...fd,...ld,...Kie].map(P8));function $Ae(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`)}$Ae(QAe);const F8=I().min(1).refine(e=>!e.includes(`\0`)&&A(e)&&se(e)===e);ea(`kind`,[V({kind:W(`file`),path:F8}),V({kind:W(`tree`),path:F8,excluded:B(F8)}).refine(({path:e,excluded:t})=>t.every(t=>M(e,t)!==``&&eje(e,t)))]),V({server_instance_id:I().min(1),owner_token:Hi(),pid:L().int().positive(),lease_protocol:I().min(1),project_dir:F8,scope_json:I(),started_at:ki()});function eje(e,t){let n=M(e,t);return n===``||n!==`..`&&!n.startsWith(`..${le}`)&&!A(n)}RegExp(`<(${AJ.map(e=>e.tagName).join(`|`)})\\b([^>]*)\\/>`,`y`);const tje=String.raw`\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]`,nje=String.raw`\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)`,I8=String.raw`([^\]\n]*)`,L8=String.raw`([^\]\n]*(?:\][^[\]\n]*)?)`,R8=e=>RegExp(`(!?)${tje}`,e),z8=(e,t)=>RegExp(`(!?)\\[${e}\\]${nje}`,t);R8(`y`),R8(`g`),z8(I8,`y`),z8(L8,`y`),z8(I8,`g`),z8(L8,`g`);const rje=String.raw`(!?)\[([^\]\n]*)\](?:\[([^\]\n]*)\])?`;new RegExp(rje,`y`),QX(`file-watcher`),QX(`conflict-authority`),QX(`parse-pool`),Math.max(1,Math.min(4,he()-1)),t8(()=>{}),QX(`bridge-watchdog`),t8(()=>{}),QX(`server-observers`),QX(`server-observers`),QX(`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)ije(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 ije(e,t){return e!==void 0&&Math.abs(t-e)<2e3}const B8={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`};new Set(Object.values(B8));const aje=Object.keys(B8),oje={discovery:`user`,project:`project`,"write-skill":`user`},V8=aje.filter(e=>oje[e]===`user`);new Set(V8.map(e=>B8[e]));const H8=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function U8(e){return new URL(e).pathname.endsWith(`.ts`)}function sje(e,t,n){let r=n.platform??process.platform,i=n.checkDesktop??!1,a=n.home??_e(),o=[],s=process.env.NODE_ENV===`test`;return i&&r===`darwin`&&(s||o.push(j(`/Applications`,H8,e)),(!s||n.home!==void 0)&&o.push(j(a,`Applications`,H8,e))),U8(t)?(o.push(fe(new URL(`../assets/skills/${e}`,t))),o):(o.push(fe(new URL(`../dist/assets/skills/${e}`,t))),o.push(fe(new URL(`../assets/skills/${e}`,t))),o.push(fe(new URL(`./assets/skills/${e}`,t))),o)}function cje(e,t,n){let r=U8(t)?`Running from source, only the source assets are read, so the bundle name is unknown or its directory under packages/server/assets/skills is missing.`:"This usually means the package build did not copy packages/server/assets into dist/assets. Run `pnpm run build` in the package that ships the skills before publishing.";return`Bundled skill asset directory not found for bundle '${e}'. Tried: ${n.join(`, `)}. ${r}`}function W8(e,t={}){let n=sje(e,import.meta.url,t);for(let e of n)if(g(e))return e;throw Error(cje(e,import.meta.url,n))}function lje(
|
|
1113
|
+
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function j8(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 M8(e,t,n,r,i){let a;try{a=w(e,{withFileTypes:!0})}catch(t){return l8.warn({dir:e,err:t},`Failed to read directory ${e}`),0}let o=0;for(let s of a){if(!s.isDirectory()||m8(s.name))continue;let a=j(e,s.name),c=o8(M(t,a));if(!c.startsWith(`..`)&&!(n.ignores(c)||n.ignores(`${c}/`))){for(let e of D8){let t=j(a,e);if(g(t))try{let a=S(t,`utf-8`);i.value+=a.length;let s=A8(a).map(e=>j8(e,c));n.add(s),e===`.okignore`&&r.add(s),o++}catch(n){l8.warn({path:t,err:n},`Failed to read nested ${e} at ${t}`)}}o+=M8(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 ZAe=/[\u200C-\u200F\u202A-\u202E\u206A-\u206F\uFEFF]/gu;function N8(e){return e.replace(ZAe,``).normalize(`NFC`).toUpperCase().toLowerCase().normalize(`NFC`)}function P8(e){let t=N8(e);for(let e=0;e<4;e++){let e=N8(t);if(e===t)break;t=e}return t.replace(/[. ]+$/u,(e,t)=>t===0?e:``)}const QAe=new Set([`.ok`,`.open-knowledge`,`.openknowledge`,...Object.values(rt).map(({userHomeDirName:e})=>e)].map(P8));new Set([...fd,...ld,...Kie].map(P8));function $Ae(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`)}$Ae(QAe);const F8=I().min(1).refine(e=>!e.includes(`\0`)&&A(e)&&se(e)===e);ea(`kind`,[V({kind:W(`file`),path:F8}),V({kind:W(`tree`),path:F8,excluded:B(F8)}).refine(({path:e,excluded:t})=>t.every(t=>M(e,t)!==``&&eje(e,t)))]),V({server_instance_id:I().min(1),owner_token:Hi(),pid:L().int().positive(),lease_protocol:I().min(1),project_dir:F8,scope_json:I(),started_at:ki()});function eje(e,t){let n=M(e,t);return n===``||n!==`..`&&!n.startsWith(`..${le}`)&&!A(n)}RegExp(`<(${AJ.map(e=>e.tagName).join(`|`)})\\b([^>]*)\\/>`,`y`);const tje=String.raw`\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]`,nje=String.raw`\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)`,I8=String.raw`([^\]\n]*)`,L8=String.raw`([^\]\n]*(?:\][^[\]\n]*)?)`,R8=e=>RegExp(`(!?)${tje}`,e),z8=(e,t)=>RegExp(`(!?)\\[${e}\\]${nje}`,t);R8(`y`),R8(`g`),z8(I8,`y`),z8(L8,`y`),z8(I8,`g`),z8(L8,`g`);const rje=String.raw`(!?)\[([^\]\n]*)\](?:\[([^\]\n]*)\])?`;new RegExp(rje,`y`),QX(`file-watcher`),QX(`conflict-authority`),QX(`parse-pool`),Math.max(1,Math.min(4,he()-1)),t8(()=>{}),QX(`bridge-watchdog`),t8(()=>{}),QX(`server-observers`),QX(`server-observers`),QX(`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)ije(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 ije(e,t){return e!==void 0&&Math.abs(t-e)<2e3}const B8={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`};new Set(Object.values(B8));const aje=Object.keys(B8),oje={discovery:`user`,project:`project`,"write-skill":`user`},V8=aje.filter(e=>oje[e]===`user`);new Set(V8.map(e=>B8[e]));const H8=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function U8(e){return new URL(e).pathname.endsWith(`.ts`)}function sje(e,t,n){let r=n.platform??process.platform,i=n.checkDesktop??!1,a=n.home??_e(),o=[],s=process.env.NODE_ENV===`test`;return i&&r===`darwin`&&(s||o.push(j(`/Applications`,H8,e)),(!s||n.home!==void 0)&&o.push(j(a,`Applications`,H8,e))),U8(t)?(o.push(fe(new URL(`../assets/skills/${e}`,t))),o):(o.push(fe(new URL(`../dist/assets/skills/${e}`,t))),o.push(fe(new URL(`../assets/skills/${e}`,t))),o.push(fe(new URL(`./assets/skills/${e}`,t))),o)}function cje(e,t,n){let r=U8(t)?`Running from source, only the source assets are read, so the bundle name is unknown or its directory under packages/server/assets/skills is missing.`:"This usually means the package build did not copy packages/server/assets into dist/assets. Run `pnpm run build` in the package that ships the skills before publishing.";return`Bundled skill asset directory not found for bundle '${e}'. Tried: ${n.join(`, `)}. ${r}`}function W8(e,t={}){let n=sje(e,import.meta.url,t);for(let e of n)if(g(e))return e;throw Error(cje(e,import.meta.url,n))}function lje(e=N(k(fe(import.meta.url)),`..`,`package.json`)){try{let t=JSON.parse(S(e,`utf-8`));if(typeof t.version==`string`&&t.version.length>0)return t.version}catch{}return`0.0.0-unknown`}lje();function uje(e,t,n){let[r,i,a,...o]=process.argv.slice(1);(r===void 0||i===void 0||a===void 0)&&(process.stderr.write(`ok-browser relay: missing the folder, files or command argument
|
|
1114
1114
|
`),process.exit(2));let s=new Set(n),c={roots:[{uri:t.pathToFileURL(i).href,name:`chat files`}]},l=e.spawn(a,o,{cwd:r,stdio:[`pipe`,`pipe`,`inherit`],windowsHide:!0}),u=l.stdin,d=l.stdout;(u===null||d===null)&&(process.stderr.write(`ok-browser relay: the browser server has no pipes
|
|
1115
1115
|
`),process.exit(1));let f=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:null,p=e=>{u.write(`${JSON.stringify(e)}\n`)},m=e=>{process.stdout.write(`${JSON.stringify(e)}\n`)},h=(e,t)=>{process.stderr.write(`ok-browser relay: dropped a ${e} line that ${t}\n`)},g=(e,t,n)=>{if(e.trim()===``)return null;let r;try{r=JSON.parse(e)}catch{return h(t,`is not JSON`),null}let i=f(r);if(i!==null)return i;if(Array.isArray(r))for(let e of r){let t=f(e);t?.method!==void 0&&t.id!==void 0&&n({jsonrpc:`2.0`,id:t.id,error:{code:-32600,message:`Batched messages are not supported`}})}return h(t,`is not a single JSON-RPC message`),null},_=e=>{let t=g(e,`client`,m);if(t===null||t.method===`notifications/roots/list_changed`)return null;let n=f(t.params),r=n?.name;return t.method===`tools/call`&&(typeof r!=`string`||!s.has(r))?(t.id!==void 0&&m({jsonrpc:`2.0`,id:t.id,error:{code:-32602,message:`Tool ${String(r)} is not available`}}),null):(t.method===`initialize`&&n!==null&&(n.capabilities={...f(n.capabilities),roots:{listChanged:!1}}),JSON.stringify(t))},v=e=>{let t=g(e,`server`,p);if(t===null)return null;if(t.method===`roots/list`)return t.id!==void 0&&p({jsonrpc:`2.0`,id:t.id,result:c}),null;let n=f(t.result),r=n?.tools;if(n===null||!Array.isArray(r))return e;let i=r.filter(e=>{let t=f(e)?.name;return typeof t==`string`&&s.has(t)});for(let e of i){let t=f(f(e)?.annotations);t!==null&&(t.readOnlyHint=!1)}return n.tools=i,JSON.stringify(t)},y=(e,t,n,r)=>{let i=``,a=e=>{let r=n(e);r!==null&&t.write(`${r}\n`)};e.setEncoding(`utf8`),e.on(`data`,e=>{i+=String(e);let t=i.indexOf(`
|
|
1116
1116
|
`);for(;t!==-1;)a(i.slice(0,t)),i=i.slice(t+1),t=i.indexOf(`
|
|
@@ -1550,6 +1550,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
|
|
|
1550
1550
|
`);re(e,o)}function j9(e,t){let n=S(e,`utf-8`);if(n.trim().length!==0)try{let r=k9(JSON.parse(n),t),i=n.endsWith(`
|
|
1551
1551
|
`)?`
|
|
1552
1552
|
`:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=O9(n,t.contentDirSpellings);r!==n&&re(e,r)}}function M9(e,t){let n=S(e,`utf-8`),r=O9(n,t.contentDirSpellings);r!==n&&re(e,r)}function N9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>j(e,t.name))}catch{return[]}}const OPe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function P9(e){return/\.log\.\d+$/.test(e)}function kPe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||P9(e)}const APe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function jPe(e){let t={contentDirSpellings:D9(e.contentDir)};for(let n of APe)for(let r of N9(j(e.stagingDir,n)))kPe(r)?A9(r,t):r.endsWith(`.json`)?j9(r,t):M9(r,t);for(let n of N9(j(e.stagingDir,`state`))){let e=ae(n);n.endsWith(`.jsonl`)?A9(n,t):OPe.has(e)?j9(n,t):M9(n,t)}}const F9=[`.ok`,`local`,`telemetry`],I9=[`.ok`,`local`,`logs`],L9=[`.ok`,`local`,`loss-capture`],R9=`spans-current.jsonl`,z9=`spans-prev.jsonl`,B9=`server-current.jsonl`,V9=`server-prev.jsonl`,H9=`loss-current.jsonl`,U9=`loss-prev.jsonl`;function MPe(e){return j(e,...F9,R9)}function NPe(e){return j(e,...F9,z9)}function PPe(e){return j(e,...I9,B9)}function FPe(e){return j(e,...I9,V9)}function IPe(e){return j(e,...L9,H9)}function LPe(e){return j(e,...L9,U9)}const W9=1e3;async function RPe(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 zPe(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 BPe(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 VPe(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 HPe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],c8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function UPe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],c8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function G9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function WPe(){return{nodeVersion:process.version,platform:ye(),arch:me()}}function GPe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!g(e))return{};let t;try{t=(0,xs.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function KPe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return KPe(e.maxBytes)}function qPe(e){let t=q9(GJ(`project`,e)),n=q9(GJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function JPe(e){return Te(`sha256`).update(e).digest(`hex`)}function X9(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const YPe=[`"doc.name"`,`"docName"`];function XPe(e){let t=S(e,`utf-8`),n=0;for(let e of YPe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(k(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,Z5(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const ZPe=new Set([`.jsonl`]);function QPe(e){let t=e.lastIndexOf(`.`);return t!==-1&&ZPe.has(e.slice(t))}const $Pe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function eFe(e){if(P9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&$Pe.has(e.slice(t))}function tFe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!eFe(r))continue;let{redacted:i,patterns:a,lineCount:o}=BP(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return M(e,t).split(le).join(`/`)}async function nFe(e){let t=N(e.contentDir),n=N(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??RPe,a=r.fetchAgentEffects??zPe,o=r.fetchWatcherRecent??BPe,s=r.readShadowHead??HPe,c=r.readCheckpointRefs??UPe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.86.19-beta.
|
|
1553
|
+
`)}\n`:null}catch{return null}}function HPe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],c8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function UPe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],c8({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function G9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function WPe(){return{nodeVersion:process.version,platform:ye(),arch:me()}}function GPe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!g(e))return{};let t;try{t=(0,xs.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function KPe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return KPe(e.maxBytes)}function qPe(e){let t=q9(GJ(`project`,e)),n=q9(GJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function JPe(e){return Te(`sha256`).update(e).digest(`hex`)}function X9(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const YPe=[`"doc.name"`,`"docName"`];function XPe(e){let t=S(e,`utf-8`),n=0;for(let e of YPe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(k(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,Z5(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const ZPe=new Set([`.jsonl`]);function QPe(e){let t=e.lastIndexOf(`.`);return t!==-1&&ZPe.has(e.slice(t))}const $Pe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function eFe(e){if(P9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&$Pe.has(e.slice(t))}function tFe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!eFe(r))continue;let{redacted:i,patterns:a,lineCount:o}=BP(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return M(e,t).split(le).join(`/`)}async function nFe(e){let t=N(e.contentDir),n=N(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??RPe,a=r.fetchAgentEffects??zPe,o=r.fetchWatcherRecent??BPe,s=r.readShadowHead??HPe,c=r.readCheckpointRefs??UPe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.86.19-beta.3`),d=r.readDesktopEnv??G9,f=r.readLanguage??E9,p=r.readRuntime??WPe,h=r.isOtlpPushEnabled??GPe,_=y(j(xe(),`ok-bundle-`));try{v(j(_,`telemetry`),{recursive:!0}),v(j(_,`logs`),{recursive:!0}),v(j(_,`state`),{recursive:!0}),Z9(MPe(n),j(_,`telemetry`,R9)),Z9(NPe(n),j(_,`telemetry`,z9)),Z9(PPe(n),j(_,`logs`,B9)),Z9(FPe(n),j(_,`logs`,V9));for(let t of e.userLogFiles??[])Z9(t,j(_,`logs`,ae(t)));for(let t of e.userStateFiles??[])Z9(t,j(_,TJ,ae(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,j(_,`diagnostic-reports`,ae(t)))&&(y+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,j(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(j(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(j(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=VPe(n);e!==null&&re(j(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(j(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(j(_,`state`,`checkpoint-refs.txt`),D),Z9(IPe(n),j(_,`state`,H9)),Z9(LPe(n),j(_,`state`,U9)),Z9(j(b,`last-spawn-error.log`),j(_,`state`,`last-spawn-error.log`)),Z9(j(b,od),j(_,`state`,od)),Z9(j(b,sd),j(_,`state`,sd)),Z9(j(b,ad),j(_,`state`,ad));let ee=p(),ne=d(),ie=f(),k={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(j(_,`state`,`runtime.json`),`${JSON.stringify(k,null,2)}\n`);let oe=C===`running`?`running
|
|
1554
1554
|
`:`not-running (${w})\n`;re(j(_,`state`,`server-status.txt`),oe);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:X5(e.diagnosticReports,y);if(re(j(_,`state`,`diagnostic-reports-status.txt`),`${A}\n`),re(j(_,e7),x7(e.osTerminationEvidence)),e.processDir&&g(e.processDir)){let t=j(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let se=e.redact===!0;se&&jPe({stagingDir:_,contentDir:t}),e.note&&re(j(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=tFe(_));for(let t of e.extraFiles??[]){let e=t.zipName??ae(t.sourcePath);if(!Z9(t.sourcePath,j(_,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=C7(t,`extra/${e}`);n!==null&&(ce??={redactions:[],redactedLineCount:0},ce.redactions.push(n),ce.redactedLineCount+=n.lineCount)}let M=qPe(n),N=Q9(_),le=[],ue=0,de=0;for(let e of N){let t=$9(_,e),n=te(e).size,r=QPe(t)?X9(e):0;le.push({path:t,bytes:n,lines:r}),ue+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=XPe(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:JPe(t),absolutePath:se?`<CONTENT_DIR>`:t},telemetry:{localSink:M,otlpPushEnabled:h()},redaction:fe,serverStatus:C,files:le};re(j(_,`manifest.json`),`${JSON.stringify(P,null,2)}\n`);let pe=D9(t),me=N.some(e=>{try{let t=S(e,`utf-8`);return pe.some(e=>t.includes(e))}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:ue,fileCount:le.length,docNameCount:de,contentDirVisible:me,redacted:se},ge=!1;return{stagingDir:_,manifest:P,summary:he,cleanup:()=>{ge||(ge=!0,O(_,{recursive:!0,force:!0}))}}}catch(e){throw O(_,{recursive:!0,force:!0}),e}}async function rFe(e){let{collected:t,outputPath:n}=e,r=k(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new DDe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function iFe(e,t){let n=j(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,xs.parse)(S(n,`utf-8`)),r=dY(t)?t.content:void 0,i=dY(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return N(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return N(e)}async function aFe(e,t,n,r,i,a){let o=w7(t,e.logger),s=await nFe({contentDir:iFe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...hNe(o,e.userLogsDir??j(RJ(),`logs`)),...E7(e.cachesDir??j(_e(),`Library`,`Caches`))],userStateFiles:D7(e.bugReportsDir??S7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(k(e.outputPath),{recursive:!0}),await rFe({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 oFe(e){let{projectDir:t}=e,n=e.readDesktopEnv??G9,r=e.readLanguage??E9,i=()=>VMe(e.diagnosticReportsDir??j(_e(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return aFe(e,t,n,r,i(),await b7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await bNe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:E7(e.cachesDir??j(_e(),`Library`,`Caches`)),bugReportLedgerFiles:D7(e.bugReportsDir??S7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await b7(e.osTerminationEvidenceDeps):void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{vY as ALL_EDITOR_IDS,yY as EDITOR_LABELS,$Y as EDITOR_TARGETS,Pbe as HOSTS_WITH_USER_SKILL_DIR,kMe as LAUNCH_CONFIG_NAME,uPe as PATH_SHIM_BEGIN,fPe as PATH_SHIM_BLOCK_RE,dPe as PATH_SHIM_END,u5 as ProjectPathSafetyError,oMe as addOkPathsToGitExclude,d5 as assertProjectPathSafe,PY as buildManagedServerEntry,$Ne as buildMcpConfigDeclineEvent,ePe as buildMcpConfigMigrateEvent,WY as canonicalEntryFor,q5 as classifyExistingMcpEntry,oFe as collectReportBundle,_Pe as createCliProbeResolver,ZJ as createTokenStore,fNe as defaultBugReportZipPath,Ke as detectGh,Ye as detectGhAccounts,NMe as detectInstalledEditors,UY as droppedManagedKeys,txe as editorConfigPathDisplay,exe as editorEntryLocator,HNe as ensurePiBridge,qMe as findJetsamKillSync,T5 as formatTrackedRemediation,lMe as getExcludedOkPaths,C5 as getInstalledSkillProjectionPaths,Nbe as getNativeTomlMcpEditor,S5 as getOkArtifactPaths,MY as isEntryUpToDate,FY as isOwnManagedEntry,sPe as loadConfig,abe as makeLazyProbeTokenStore,S7 as okBugReportsDir,v9 as parseGitHubBlobUrl,cPe as parseGitHubShareUrl,y9 as parseGitHubTreeUrl,_9 as parseGitUrl,pPe as pathInstallMarkerPath,Gje as previewContent,PMe as probeOwnManagedEditorMcpEntry,BNe as probePiBridgeState,w5 as probeTrackedOkPaths,G5 as readExistingMcpEntry,cMe as readSharingMode,BP as redactContent,sMe as removeOkPathsFromGitExclude,YNe as removeOwnMcpEntry,nMe as removeProjectSkill,yPe as removeUserGlobalSkillBundle,TPe as removeUserSkill,Xje as resolveProjectRoot,iPe as runStop,p9 as truncatePriorEntry,w9 as userGlobalSkillBundleTargets,wPe as userSkillPresentAnywhere,lPe as validateLocalFolderForShare,W5 as writeEditorMcpConfig,SPe as writeProjectAiIntegrations,_5 as writeProjectSkill,MMe as writeUserMcpConfigs,CPe as writeUserSkill};
|
|
1555
1555
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./dist-CP1cIPST.mjs";import{v as e}from"./init-XYCfFXC2.mjs";export{e as runInit};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{$u as r,Bf as i,Cf as a,Df as o,Ef as s,Ga as c,Jc as l,K as u,Mf as d,Nf as f,Pf as p,Sf as m,Tf as h,V as g,Wa as _,_ as v,_f as y,a as b,df as x,gd as S,jf as C,lf as ee,mf as te,pf as ne,tt as re,uf as ie,vc as ae,vf as oe,yd as se,z as ce,zf as le}from"./md-manager-BGnqyqi1-BzZ_8EQ9.mjs";import{Ao as ue,At as de,F as fe,Fo as pe,Fr as me,Hi as he,Jo as ge,Ko as w,No as _e,R as ve,U as ye,Vr as be,Xo as xe,Yo as Se,Yr as Ce,Zn as we,at as Te,ci as Ee,cs as De,di as Oe,dn as ke,ir as Ae,ja as je,m as Me,ma as Ne,ms as Pe,pa as Fe,qo as Ie,qr as Le,rt as Re,ts as T,va as ze,z as Be}from"./dist-
|
|
1
|
+
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{$u as r,Bf as i,Cf as a,Df as o,Ef as s,Ga as c,Jc as l,K as u,Mf as d,Nf as f,Pf as p,Sf as m,Tf as h,V as g,Wa as _,_ as v,_f as y,a as b,df as x,gd as S,jf as C,lf as ee,mf as te,pf as ne,tt as re,uf as ie,vc as ae,vf as oe,yd as se,z as ce,zf as le}from"./md-manager-BGnqyqi1-BzZ_8EQ9.mjs";import{Ao as ue,At as de,F as fe,Fo as pe,Fr as me,Hi as he,Jo as ge,Ko as w,No as _e,R as ve,U as ye,Vr as be,Xo as xe,Yo as Se,Yr as Ce,Zn as we,at as Te,ci as Ee,cs as De,di as Oe,dn as ke,ir as Ae,ja as je,m as Me,ma as Ne,ms as Pe,pa as Fe,qo as Ie,qr as Le,rt as Re,ts as T,va as ze,z as Be}from"./dist-CP1cIPST.mjs";import{i as Ve,n as E,o as D,r as He,s as O,t as k}from"./colors-r_owlCuY.mjs";import{t as A}from"./is-object-BGze3w87.mjs";import{t as Ue}from"./constants-D__Dkzs1.mjs";import{t as We}from"./preview-rfRPPmZw.mjs";import{createRequire as Ge}from"node:module";import{execFileSync as Ke}from"node:child_process";import qe,{basename as Je,dirname as j,isAbsolute as Ye,join as M,posix as Xe,relative as N,resolve as P,sep as F,win32 as Ze}from"node:path";import I from"node:process";import{fileURLToPath as Qe}from"node:url";import{cpSync as $e,existsSync as L,lstatSync as et,mkdirSync as tt,readFileSync as R,readdirSync as nt,readlinkSync as rt,realpathSync as it,rmSync as at,statSync as ot,writeFileSync as st}from"node:fs";import{homedir as z}from"node:os";import{inspect as ct,stripVTControlCharacters as lt,styleText as B}from"node:util";import*as ut from"node:readline";import{AsyncLocalStorage as dt,AsyncResource as ft}from"node:async_hooks";var pt=n((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})),mt=n((e=>{let{InvalidArgumentError:t}=pt();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})),ht=n((e=>{let{humanReadableArgName:t}=mt();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(`
|
|
2
2
|
`)}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,`
|
|
3
3
|
`+` `.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(`
|
|
4
4
|
`)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),gt=n((e=>{let{InvalidArgumentError:t}=pt();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}
|
|
@@ -689,5 +689,5 @@ export default function okBridge(pi: {
|
|
|
689
689
|
`));let g=`${s?``:``}${m}`;return g!==o&&T(e,g,{mode:Wa(e)}),a&&g===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const Lo=e=>e!==`project`,Ro=e=>e!==`user`;async function zo(){let e=await $a({message:`Where should the MCP server be configured?
|
|
690
690
|
`,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function Bo(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??zo)():`both`}async function Vo(e){return io({message:`How do you want to handle OpenKnowledge config files (.ok/, .mcp.json)?`,default:e,choices:[{name:`Share with my team (commit alongside content)`,value:`shared`,description:`OK config gets committed alongside your project content.`},{name:`Local only (keep out of git via .git/info/exclude)`,value:`local-only`,description:`OK config stays on this machine only; teammates do not see it. Safe escape hatch via \`${C()} config-sharing share\`.`}]})}async function Ho(e){if(e.sharing!==void 0)return e.sharing;let t=pa(e.projectRoot)===`local-only`||e.freshProject===!0?`local-only`:`shared`;return e.isTTY??process.stdout.isTTY?(e.promptFn??Vo)(t):t}var Uo=class extends Error{constructor(e){super(e),this.name=`ContentDirError`}},Wo=class extends Error{constructor(e){super(`A dev MCP entry is written to project config only, never to user-level editor config, so --scope ${e} is not supported with --dev-mcp or OK_CHANNEL=dev. Re-run with --scope project or without --scope.`),this.name=`DevMcpScopeError`}};const Go=`A dev build registers OpenKnowledge MCP in project config only, never in user-level editor config. Run \`${h} init --dev-mcp\` in the project, or set OK_CHANNEL=stable.`;function Ko(e){if(e===void 0||e===!0)return new Set(Re);if(e===!1)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(de.filter(e=>t.includes(e)))}function qo(e,t,n){let r=P(n,e),i;try{i=ot(r)}catch(e){let t=e.code;throw t===`ENOENT`?new Uo(`--content-dir path does not exist: ${r}`):new Uo(`--content-dir path is not accessible (${t??`unknown error`}): ${r}`)}if(!i.isDirectory())throw new Uo(`--content-dir must be a directory: ${r}`);let a=Jo(t),o=Jo(r),s=N(a,o);if(s.startsWith(`..`)||Ye(s))throw new Uo(`--content-dir must be inside the project root (${t}); got ${r}`);return s===``?`.`:s}function Jo(e){try{return it(e)}catch{return e}}const Yo=`open-knowledge-ui`;function Xo(e,t,n){try{let r=e.detectPath?.(t,n)??j(e.configPath(t,n));return L(r)}catch{return!1}}function Zo(e,t,n){try{let r=P(j(e.configPath(t,n))),i=P(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+F)}catch{return!1}}function Qo(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`||!L(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||Zo(e,t,r);if(!i&&c&&!Xo(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{Da(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 es(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||tt(j(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{De(`${o}.lock`,()=>{let t=_o(o).writePath;if(s||tt(j(t),{recursive:!0}),e.format===`toml`){let r=No(ai(),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=Io(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=Mo(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 $o={pi:co};function es(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=$o[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{tt(j(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{De(`${t}.lock`,()=>{let e=null;try{e=R(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}T(t,c,e===null?void 0:{mode:Wa(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}}function ts(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!L(n)))return{editorId:e.id,label:e.label,path:n}}async function ns(e){let t=oa(e.editors).filter(e=>e.scope===`global`);if(le())return t.map(t=>({editorId:t.id,label:t.label,action:`failed`,configPath:t.configPath(``,e.home),serverName:t.serverName(``),error:Go}));let n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>Qo(t,``,n,e.home))}function rs(e,t,n,r){let i=as(e,t,n,r);return i.kind===`present`?i.entry:null}function is(e,t,n,r){let i=jo(e,t,r);if(!A(i))return{kind:`no-entry`};let a=i[n];return A(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function as(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!L(i))return{kind:`absent`};try{if(ot(i).size>To)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:Ba(e)}}let a;try{a=R(i,`utf-8`)}catch(e){return{kind:`decline`,reason:Ba(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:so(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=ai().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return is(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,Kr.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:is(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=bo(a);return s?xo(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:is(Ie(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}async function os(e={}){let t=P(e.cwd??process.cwd()),n=fo(t,{homeDir:e.home}),r=n.projectRoot;if(Ce(r,e.home??z()))throw new ye(r);if(Le(r))throw new fe(r);let i=!L(M(r,`.ok`)),a=n.gitRootPromoted?N(r,t):void 0,o=e.contentDir===void 0?n.defaultContentDir:qo(e.contentDir,r,t);n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&o===`.`&&process.stderr.write(`${O(`[ok] Content scope promoted to the git repo root: ${r}`)}\n Ran in ${a}/, but .ok/ lives at the git root (one .ok/ per git repo),\n so the whole repo is now the content scope. To narrow it, re-run with\n \`${C()} init --content-dir .\`, or set content.dir: ${a} in .ok/config.yml.\n`);let s={mode:e.devMcp?`dev`:`published`},l=e.devMcp===!0||le();if(l&&e.mcp!==!1&&e.scope&&e.scope!==`project`)throw new Wo(e.scope);let u=await Ae(r),d;try{d=me(r,{contentDir:o})}catch(t){let i=$.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:u.didInit,rootGitignoreCreated:!1,gitRootPromoted:n.gitRootPromoted,promotedFromDir:a,contentDirRequested:e.contentDir,contentScaffoldFailed:!0,mcpAction:`failed`,mcpPath:i,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`,sharing:{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:!1}}}let f=d.created.includes(Ue),p=!1;if(u.didInit)try{p=pe(r)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${r}: ${e instanceof Error?e.message:String(e)}`)}try{Fe(r)===`removed`&&console.warn(`[ok] Removed the OpenKnowledge project-skill lines from .gitignore. The skill is ordinary project content now — commit it if your team wants it on clone.`)}catch(e){console.warn(`[ok] Skipping project-skill .gitignore cleanup at ${r}: ${e instanceof Error?e.message:String(e)}`)}let m=await Bo({scope:l?`project`:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),h=e.editors??fs(r,e.home),g=e.editors??h,_=oa(h),v=oa(g),y=e.mcp===!1||m===null,b=Array.from(new Map([..._,...y?[]:v].map(e=>[e.id,e])).values()),x=_.filter(t=>Xo(t,r,e.home)),S=[],ee=[],te=new Set;for(let t of b){if(y){let n=``;try{n=t.configPath(r,e.home)}catch{}S.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(Lo(m)&&_.includes(t)&&t.scope===`global`&&S.push(Qo(t,r,s,e.home)),Ro(m)&&v.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=Qo(t,r,s,e.home,n);S.push(i),(i.action===`written`||i.action===`overwritten`)&&te.add(n)}}let ne=new Set;for(let t of v){let n=t.projectSkillPath?.(r);!n||ne.has(n)||(ne.add(n),ee.push(Ra(t,r,{home:e.home})))}let re=La(r,v.map(e=>e.id));re&&ee.push(re);let ie=ee.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.editorId);if(ie.length>0){let t=e.home??z();Ne({source:c,skills:[Me.project],agents:ie,scope:r},{home:t,enabled:je(t).enabled})}let ae=!y&&m!==null&&Ro(m)?v.filter(e=>!e.projectConfigPath&&!e.projectSkillPath).map(e=>e.label):void 0,oe=y?[]:x.map(e=>ts(e,r)).filter(e=>e!==void 0).filter(e=>!te.has(e.path)),se=e.installUserSkill??be,ce=e.home??z(),ue=Ko(e.skills),ge=typeof e.skills!=`string`,w=!1,ve=!1,xe=!1,Se=!1,Te=!1,Ee=!1,De=!1,ke=[];for(let t of de){if(!ue.has(t))continue;if(w=!0,ge){let e=await he(ce,Me[t]).then(e=>({ok:!0,value:e}),()=>({ok:!1}));if(!e.ok){ke.push({bundleId:t,result:`decision-read-failed`}),De=!0;continue}if(e.value===!1){ke.push({bundleId:t,result:`opted-out`}),Ee=!0;continue}}await _e(ce,Me[t],!0).catch(()=>{});let n=await se({home:e.home,bundleId:t,force:!0});ke.push({bundleId:t,result:n}),n===`installed`?ve=!0:n===`failed`?xe=!0:n===`no-hosts`?Te=!0:Se=!0}let Pe=xe?`failed`:De?`decision-read-failed`:ve?`installed`:w&&Se?`skip-current`:w&&Te?`no-hosts`:Ee?`opted-out`:`declined`,Ie=ve?we(ce).map(e=>e.editorId):[],Re=je(ce).enabled&&!Oe(),T=y?`skipped-flag`:`skipped-missing`,ze=S.find(e=>e.editorId===`claude`)??S[0]??{action:T,configPath:$.claude.configPath(r,e.home)},Be=await ss({projectRoot:r,desiredMode:await Ho({sharing:e.sharing,projectRoot:r,isTTY:e.isTTY,freshProject:i,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:r,contentCreated:d.created,contentUpdated:d.updated,contentSkipped:d.skipped,editors:S,projectSkills:ee,legacyProjectConfigs:oe,skillInstall:Pe,skillBundles:ke,skillsRequested:e.skills,skillHosts:Ie,skillInstallsCounted:Re,didGitInit:u.didInit,rootGitignoreCreated:p,gitRootPromoted:n.gitRootPromoted,promotedFromDir:a,contentDir:f?o:void 0,contentDirRequested:e.contentDir,contentScaffoldFailed:!1,mcpAction:ze.action,mcpPath:ze.configPath,mcpError:`error`in ze?ze.error:void 0,projectScopeUnsupportedLabels:ae,sharing:Be}}async function ss(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=pa(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=la(t);if(n===`local-only`){let e=da(t,a);if(e.kind===`refused-tracked`){let t=e;return{kind:`refused-tracked`,tracked:t.tracked,remediation:t.remediation}}return e.kind===`no-exclude`?{kind:`no-exclude`,reason:e.reason,localOnlyRequested:r===`local-only`}:cs(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=fa(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:cs(t,o,`remove`)}function cs(e,t,n){let r=pa(e);return n===`add`?{kind:`applied`,mode:r,action:t.appended.length>0?`added`:t.removed.length>0?`cleaned`:`noop`,appended:t.appended,alreadyPresent:t.alreadyPresent,removed:t.removed}:{kind:`applied`,mode:r,action:`removed`,appended:[],alreadyPresent:[],removed:t.removed}}function ls(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions`;case`unresolved-symlink`:return`could not resolve the path or symlink; check permissions and symlink cycles`;case`not-a-file`:return`config path is not a regular file`;case`disappeared`:return`config disappeared while being read; retry to check its current state`;case`unreadable`:return`could not read the config file; check that the path is accessible`;case`unparseable`:return`config could not be parsed`;case`oversize`:return`config too large to edit safely`;case`duplicate-container`:return`duplicate server block`;case`no-native-writer`:return`no format-preserving writer available`;case void 0:return`config not readable`;default:throw Error(`unhandled MCP decline reason: ${e}`)}}function us(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`);e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let c=M(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(k(`Content scaffolded at ${c}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(k(`Content already present at ${c}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0){if(n.push(k(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`)}else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(k(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(k(`MCP server configuration:`));for(let r of e.editors){let e=r.configPath.startsWith(t)?N(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),i=r.serverName===f()?``:` (${r.serverName})`,a=r.configScope===`project`?` (project)`:``,o=`${r.label}${a}`,s=` `.repeat(Math.max(1,20-o.length)),c=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${o}${s}${e} ${D(`registered`)}${i}${c}`);break;case`overwritten`:n.push(` ${o}${s}${e} ${D(`updated`)}${i}${c}`);break;case`skipped-missing`:n.push(` ${o}${s}${e} config root missing; skipped`);break;case`failed`:n.push(` ${o}${s}${e} ${He(`FAILED`)}: ${r.error}`);break;case`declined`:n.push(` ${o}${s}${e} left unchanged (${ls(r.declineReason)})`);break;case`skipped-flag`:break;default:r.action}}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}let r=s.dev.mcpServerName;e.editors.some(e=>e.serverName===r&&(e.action===`written`||e.action===`overwritten`))&&n.push(` The ${r} entry runs this checkout on this machine only; keep it out of commits.`)}if(e.projectSkills.length>0){n.push(``),n.push(k(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?N(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${D(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${D(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`skipped-prerequisite`:n.push(` ${e}${i}OpenKnowledge MCP is not configured; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${He(`FAILED`)}: ${r.error}`)}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${N(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall===`declined`)n.push(``),n.push(k(`User-global skills:`)),typeof e.skillsRequested==`string`?(n.push(` ${E(`none installed — --skills "${e.skillsRequested}" names no known skill bundle (known: ${de.join(`, `)})`)}`),n.push(` ${E(`No user-global skill was installed or removed.`)}`)):(n.push(` ${E(`none installed — skipped for this run (--no-skills)`)}`),n.push(` ${E(`No user-global skill was installed or removed; any already on this`)}`),n.push(` ${E(`machine are untouched. Run init without the flag to install them:`)}`),n.push(` ${E(` ${C()} init`)}`),n.push(` ${E(`--no-skills covers user-global skills only, not project-local skills.`)}`));else if(e.skillInstall){n.push(``),n.push(k(`User-global skills:`));let t=e.skillBundles??[],r=Math.max(0,...t.map(e=>Me[e.bundleId].length));for(let i of t){let t=Me[i.bundleId].padEnd(r);switch(i.result){case`installed`:{let r=(e.skillHosts??[]).map(e=>X[e]??e),i=r.length>0?r.join(`, `):`the shared ~/.agents store`;n.push(` ${t} ${D(`installed for ${i}`)}`);break}case`skip-current`:n.push(` ${t} ${D(`already installed at current version`)}`);break;case`no-hosts`:n.push(` ${t} ${E(`skipped — no supported agent host detected in your home directory`)}`);break;case`failed`:n.push(` ${O(`${t} install failed`)}`);break;case`opted-out`:n.push(` ${t} ${E(`not installed — turned off on this machine; reinstall with ${C()} init --skills ${i.bundleId} or Settings → Skills Studio`)}`);break;case`decision-read-failed`:n.push(` ${O(`${t} not installed — could not read whether it is turned off on this machine; rerun ${C()} init once ${l(v)} is readable`)}`);break;default:i.result}}e.skillInstallsCounted&&t.some(e=>e.result===`installed`)&&(n.push(` ${E(`Counted on skills.sh (skill name + source repo, once per machine).`)}`),n.push(` ${E(`Opt out: DO_NOT_TRACK=1, or Settings → User → Preferences.`)}`)),t.some(e=>e.result===`failed`)&&n.push(` ${O(`Retry with: ${C()} repair-skills`)}`)}e.contentDirRequested!==void 0&&e.contentDir===void 0&&!e.contentScaffoldFailed?(n.push(``),n.push(O(`⚠ --content-dir ${e.contentDirRequested} ignored — .ok/config.yml already exists`)),n.push(` Edit .ok/config.yml → content.dir directly to change the content scope.`)):e.contentDir!==void 0&&e.contentDir!==`.`?(n.push(``),n.push(`Content scope set to ${e.contentDir}/ (content.dir in .ok/config.yml).`)):e.gitRootPromoted&&e.contentDir===`.`&&e.contentDirRequested===void 0&&(n.push(``),n.push(O(`⚠ Content scope promoted to the git repo root`)),n.push(` .ok/ was initialized at ${t} because it contains a .git folder (one .ok/ per git repo),`),n.push(` not the sub-folder you ran \`${C()} init\` in${e.promotedFromDir?` (${e.promotedFromDir})`:``}. The whole repo is now the content scope.`),e.promotedFromDir&&(n.push(` To scope to just that sub-folder, re-run \`${C()} init --content-dir .\` from there, or set`),n.push(` content.dir: ${e.promotedFromDir} in .ok/config.yml.`))),e.preview?(n.push(``),n.push(We(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(...hs(e.sharing,t));let u=e=>[`${e}- ${Ve(`${C()} seed --list-packs`)} — browse the starter packs`,`${e}- ${Ve(`${C()} seed`)} — scaffold an empty repo`];if(r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${D(`✓`)} ${k(`Next steps:`)}`),n.push(` 1. Open your editor (${Ve(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`);let i=3;e.contentScaffoldFailed||(n.push(` ${i++}. (Optional) scaffold the starter knowledge-base structure:`),n.push(...u(` `))),n.push(` ${i}. Ask your agent to capture a source, research a topic, or build a wiki —`),n.push(` the procedures ship as skills alongside the MCP tools.`)}else e.contentScaffoldFailed||(n.push(``),n.push(`${k(`Next steps:`)} (optional) scaffold the starter knowledge-base structure:`),n.push(...u(` `)));return n.join(`
|
|
691
691
|
`)}function ds(e,t){return{projectRoot:e.projectRoot,gitRootPromoted:e.gitRootPromoted,promotedFromDir:e.promotedFromDir??null,contentDir:t.contentDir,contentDirRequested:e.contentDirRequested??null,contentDirApplied:e.contentDir!==void 0,contentFileCount:t.contentFileCount,previewError:e.previewWarning??null,didGitInit:e.didGitInit,mcpAction:e.mcpAction,editors:e.editors.map(e=>({editorId:e.editorId,label:e.label,action:e.action,configPath:e.configPath,scope:e.configScope===`project`?`project`:`user`}))}}function fs(e,t){let n=[];for(let r of si)r!==`claude-desktop`&&Xo($[r],e,t)&&n.push(r);return n}function ps(){let e={log:console.log,info:console.info,debug:console.debug},t=(...e)=>{process.stderr.write(`${e.map(e=>typeof e==`string`?e:ct(e)).join(` `)}\n`)};return console.log=t,console.info=t,console.debug=t,()=>{console.log=e.log,console.info=e.info,console.debug=e.debug}}function ms(){return new Et(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry (node + packages/cli/dist/cli.mjs, debug logging) in project config only, as the dev channel unless OK_CHANNEL is set`).option(`--content-dir <dir>`,`Limit content to <dir> instead of the whole project. <dir> is interpreted relative to your current directory (e.g. "." = the folder you run the command in), then saved to .ok/config.yml as content.dir.`).option(`--json`,`Emit a structured JSON summary to stdout (diagnostics stay on stderr)`).option(`--skills <ids>`,`Install only the named user-global skill bundles (comma list: discovery,write-skill)`).option(`--no-skills`,`Do not install any user-global skill bundles`).addOption(new Ot(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new Ot(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new Ot(`--local-only`,`Keep OK config out of git via .git/info/exclude (per-clone, not committed)`).conflicts(`shared`)).action(async e=>{let t=process.cwd();e.devMcp&&p(process.env);let n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r=e.json?ps():null;try{let r;try{r=await os({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n,contentDir:e.contentDir,skills:e.skills})}catch(e){if(e instanceof Uo||e instanceof Wo||e instanceof ye||e instanceof fe){process.stderr.write(`${e.message}\n`),process.exitCode=64;return}if(e instanceof ve||e instanceof Be){process.stderr.write(`${e.message}\n`),process.exitCode=78;return}if(e instanceof Te){process.stderr.write(`open-knowledge could not initialize a git repo for this project. Re-run, or run 'git init' yourself in the project folder.
|
|
692
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-
|
|
692
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-Bxzbqy9N.mjs`),{resolveContentDir:s}=await import(`./dist-CJb4z7Cx.mjs`),c;try{c=o(r.projectRoot).config,i=c.content.dir}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}if(c)try{let{previewContent:e}=await import(`./preview-DOE3RMB2.mjs`),t=s(c,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:t}),a=r.preview.totalCount}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}e.json?process.stdout.write(`${JSON.stringify(ds(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${us(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function hs(e,t){let n=[];switch(e.kind){case`applied`:return n.push(k(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?(n.push(` ${D(`local-only`)} — appended ${e.appended.length} path(s) to ${k(`${t}/.git/info/exclude`)} (per-clone, not committed).`),e.removed.length>0&&n.push(` cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`)):e.action===`cleaned`?n.push(` ${D(`local-only`)} — already excluded; cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${D(`local-only`)} — already excluded; nothing to do.`):n.push(` ${D(`local-only`)}`):e.action===`removed`?n.push(` ${D(`shared`)} — removed OK paths from ${k(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${D(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(O(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
|
|
693
693
|
`))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${Ve(`${C()} config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(O(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${Ve(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${Ve(`${C()} config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(O(`Sharing mode unavailable: ${e.reason}.`));return n}}export{Z as $,Ua as A,Ra as B,_o as C,Rt as Ct,io as D,oo as E,Ot as Et,Aa as F,la as G,ya as H,Da as I,fa as J,ha as K,Oa as L,Va as M,Ba as N,$a as O,Ea as P,ci as Q,za as R,Zo as S,H as St,co as T,wt as Tt,ma as U,da as V,ua as W,X,si as Y,$ as Z,Ho as _,hr as _t,ss as a,Ti as at,Qo as b,fn as bt,fs as c,Wi as ct,ms as d,oi as dt,Bi as et,Xo as f,ai as ft,qo as g,Zr as gt,Bo as h,Jr as ht,$o as i,Si as it,Ga as j,Wa as k,us as l,ta as lt,Ko as m,Yr as mt,Wo as n,Vi as nt,ds as o,Ui as ot,rs as p,Y as pt,pa as q,Yo as r,Hi as rt,as as s,Q as st,Uo as t,zi as tt,hs as u,ki as ut,os as v,ir as vt,fo as w,Et as wt,ns as x,dn as xt,ko as y,hn as yt,ja as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Xo as e,qo as t,ts as n}from"./dist-
|
|
1
|
+
import{Xo as e,qo as t,ts as n}from"./dist-CP1cIPST.mjs";import{N as r,j as i,k as a}from"./init-XYCfFXC2.mjs";import{t as o}from"./is-object-BGze3w87.mjs";import{t as s}from"./removal-file-path-adczU7M3.mjs";import{join as c}from"node:path";import{readFileSync as l}from"node:fs";const u={allowTrailingComma:!0,disallowComments:!1};function d(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function f(o){let f=s(c(o,`.claude`,`launch.json`));if(f.kind!==`ready`)return f;let m=f.path,h;try{h=l(m,`utf-8`)}catch(e){return{kind:`declined`,reason:r(e)}}let g=[],_=e(h,g,u)??void 0;if(g.some(e=>!d(e,h))||_?.type!==`object`)return{kind:`declined`,reason:`unparseable`};let v=t(_).configurations;if(!Array.isArray(v))return{kind:`not-present`};let y=v.findIndex(p);if(y===-1)return{kind:`not-present`};let{text:b,changed:x}=i(h,[`configurations`,y]);return x?(n(m,b,{mode:a(m)}),{kind:`removed`}):{kind:`not-present`}}function p(e){if(!o(e))return!1;let t=e;if(t.name!==`open-knowledge-ui`||!Array.isArray(t.runtimeArgs))return!1;let n=t.runtimeArgs;return t.runtimeExecutable===`/bin/sh`?n.length===3&&n[0]===`-l`&&n[1]===`-c`&&typeof n[2]==`string`&&/^# ok-ui-v[1-9]\d*$/.test(n[2].split(/\r?\n/,1)[0]??``):t.runtimeExecutable===`npx`?m.some(e=>h(n,e)):t.runtimeExecutable===`powershell`&&n.length===4&&n[0]===`-NoProfile`&&n[1]===`-NonInteractive`&&n[2]===`-Command`&&typeof n[3]==`string`&&/^# ok-ui-win-v[1-9]\d*$/.test(n[3].split(/\r?\n/,1)[0]??``)}const m=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge@latest`,`ui`]];function h(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{f as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-C3aJ7pno.mjs";export{e as loadConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$u as e,Ic as t,Pc as n,cl as r,il as i,k as a,nl as o}from"./md-manager-BGnqyqi1-BzZ_8EQ9.mjs";import{is as s,os as c,x as l}from"./dist-
|
|
1
|
+
import{$u as e,Ic as t,Pc as n,cl as r,il as i,k as a,nl as o}from"./md-manager-BGnqyqi1-BzZ_8EQ9.mjs";import{is as s,os as c,x as l}from"./dist-CP1cIPST.mjs";import{t as u}from"./is-object-BGze3w87.mjs";import{t as d}from"./constants-D__Dkzs1.mjs";import{resolve as f}from"node:path";import{existsSync as p,readFileSync as m}from"node:fs";import{realpath as h}from"node:fs/promises";var g=e();async function _(e){let t=f(e);try{return await h(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}function v(e){if(!p(e))return{value:null,path:e,source:null,doc:null};let t;try{t=m(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,g.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 u(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function y(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=i({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function b(e){let i=e??process.cwd(),u=[],p=[],m=[],h=[],g=c(`user`,i),_=s({absPath:g});p.push(..._.diagnostics),!_.valid&&_.sidelinedTo!==void 0&&m.push({from:g,to:_.sidelinedTo}),_.valid&&_.source!==void 0&&u.push(g);let b=(e,t=!1)=>{let n=v(e);if(n.diagnostic!==void 0&&p.push(n.diagnostic),n.value===null)return{};let i=o({value:n.value,file:n.path,source:n.source,doc:n.doc});p.push(...i),u.push(e);let s=i.length>0?r(n.value):n.value;return t&&h.push(...a({value:s,file:n.path,source:n.source,doc:n.doc})),s},x=f(i,`.ok`,d),S=b(x,!0),C=b(c(`project-local`,i)),w=n(_.value,S,C),T=l.safeParse(w);if(!T.success){let e=v(x),n={code:`SCHEMA_INVALID`,issues:y(T.error.issues,e)};throw Error(t(n))}return{config:T.data,sources:u,diagnostics:p,sidelined:m,ignoredCommittedKeys:h}}function x(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=_(e.startupCwd);return async o=>{let s=await _(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,x as t};
|
|
Binary file
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ao as e}from"./dist-
|
|
1
|
+
import{Ao as e}from"./dist-CP1cIPST.mjs";import{execFile as t}from"node:child_process";const n=new Set([`http:`,`https:`]),r=/[\u0000-\u0020\u007F-\u009F"'`\\&|<>^()$;{}[\]*?!~]/;function i(e,t){console.warn(`Could not auto-open browser (${t}); visit ${e} manually`)}function a(a){let o;try{o=new URL(a)}catch{i(a,`invalid URL`);return}if(!n.has(o.protocol)){i(a,`unsupported scheme '${o.protocol}'`);return}if(r.test(a)){i(a,`URL contains unsafe characters`);return}let s=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,c=process.platform===`win32`?[`/c`,`start`,``,a]:[a];t(s,c,e({}),e=>{e&&console.warn(`Could not auto-open browser (${e.message}); visit ${a} manually`)})}export{a as openBrowser};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./preview-rfRPPmZw.mjs";export{t as formatPreviewBlock,e as previewContent};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Mf as e}from"./md-manager-BGnqyqi1-BzZ_8EQ9.mjs";import{Mn as t}from"./dist-
|
|
1
|
+
import{Mf as e}from"./md-manager-BGnqyqi1-BzZ_8EQ9.mjs";import{Mn as t}from"./dist-CP1cIPST.mjs";import"./constants-D__Dkzs1.mjs";import{join as n,relative as r}from"node:path";import{existsSync as i,lstatSync as a,readdirSync as o,realpathSync as s,statSync as c}from"node:fs";function l(e){let{projectDir:i,contentDir:l,sampleCap:u=5}=e,d=[],f=[];try{a(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=t({projectDir:i,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let t;try{t=o(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);d.push(`could not read directory ${r(l,e)||`.`}: ${n}`);return}for(let i of t){let t=n(e,i.name);if(i.isSymbolicLink()){let e;try{e=s(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?d.push(`broken or cyclic symlink: ${r(l,t)}`):d.push(`cannot resolve symlink ${r(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=c(e)}catch{continue}if(n.isDirectory()){let e=r(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(n.isFile()){let e=r(l,t);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=r(l,t);if(p.isDirExcluded(e))continue;m(t)}else if(i.isFile()){let e=r(l,t);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function u(t,a){let o=[],s=r(a,t.contentDir),c=s===``?`./`:`./${s}`;if(o.push(`Content:`),o.push(` Found ${t.totalCount} markdown files in ${c}`),t.sample.length>0){let e=t.sample.join(`, `),n=t.totalCount>t.sample.length?`, …`:``;o.push(` Sample: ${e}${n}`)}if(t.warnings.length>0)for(let e of t.warnings)o.push(` Warning: ${e}`);o.push(``);let l=n(a,`.ok`,`config.yml`);return i(l)?(o.push(` To adjust scope, add patterns to .okignore at the project root.`),o.push(` To change the content root, edit .ok/config.yml → content.dir.`)):o.push(` Run \`${e().cliCommandNames[1]} init\` to scaffold config + .okignore.`),o.push(``),o.push(` Re-check anytime: ${e().cliCommandNames[1]} preview`),o.join(`
|
|
2
2
|
`)}export{l as n,u as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e}from"./chunk-CYidjpOJ.js";import{t}from"./jsx-runtime-BUgB2tll.js";import{t as n}from"./react-f2sANaYj.js";import{n as r,r as i}from"./dist-Nvb76hAm.js";import{t as a}from"./compiler-runtime-BfE3aGVn.js";import{t as o}from"./label-CvMpFFbN.js";import{t as s}from"./button-DzgjsZzC.js";import{n as c}from"./config-errors-DDAH9fqy.js";import{n as l,r as u}from"./constants-github-B7yhDvQc.js";import{f as d,l as f}from"./SyncStatusBadge-BMv_As0q.js";import{t as p}from"./trash-2-CchZ0T47.js";import{t as m}from"./use-git-sync-status-PkMYmN4D.js";import{t as h}from"./input-BsFOyzfK.js";import{a as g,n as _,t as v}from"./AuthModal-DT32BOAJ.js";import{t as y}from"./channel-cli-copy-DOAEiMde.js";import{t as b}from"./skeleton-CrbF9ppq.js";import{n as x}from"./auth-state-cache-Bx6C01Jt.js";import{t as ee}from"./SettingsSectionHeader-DDNA1hrR.js";var S=e(n(),1),C=a(),w=`[a-z0-9](?:[a-z0-9-]*[a-z0-9])?`,T=RegExp(`^${w}(?:\\.${w})*$`),E=/^[a-z][a-z0-9+.-]*:\/\//i;function D(e){if(E.test(e))try{return new URL(e).host}catch{return null}let t=e.split(`/`)[0]??``;return t.slice(t.lastIndexOf(`@`)+1).replace(/:(?!\d+$).*$/,``)}function O(e,t){let n=e.trim();if(n===``)return{ok:!1,reason:`empty`};let r=D(n);if(r===null||r===``)return{ok:!1,reason:`invalid`};let i=u(r);return T.test(i)?i===`github.com`?{ok:!1,reason:`github-com`}:t.has(i)?{ok:!1,reason:`duplicate`}:{ok:!0,host:i}:{ok:!1,reason:`invalid`}}function k(e){let t=e.git?.hosts??{};return Object.entries(t).filter(([,e])=>e?.provider===`github`).map(([e])=>e).sort((e,t)=>e.localeCompare(t))}var A=t();function te(e){let t=(0,C.c)(59),{binding:n}=e,{_:a}=i(),o=(0,S.useId)(),l=(0,S.useId)(),u;t[0]===n?u=t[1]:(u=()=>k(n.current()),t[0]=n,t[1]=u);let[d,f]=(0,S.useState)(u),[m,g]=(0,S.useState)(``),[_,v]=(0,S.useState)(null),[y,b]=(0,S.useState)(!1),[x,ee]=(0,S.useState)(null),w;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(w=new Map,t[2]=w):w=t[2];let T=(0,S.useRef)(w),E=(0,S.useRef)(null),D,te;t[3]===x?(D=t[4],te=t[5]):(D=()=>{x!==null&&(((x.host===null?null:T.current.get(x.host))??E.current)?.focus(),ee(null))},te=[x],t[3]=x,t[4]=D,t[5]=te),(0,S.useEffect)(D,te);let M,N;t[6]===n?(M=t[7],N=t[8]):(M=()=>n.subscribe(e=>f(k(e))),N=[n],t[6]=n,t[7]=M,t[8]=N),(0,S.useEffect)(M,N);let P;t[9]===a?P=t[10]:(P=function(e){switch(e){case`empty`:return a({id:`cFONFy`});case`invalid`:return a({id:`QsnBxE`});case`github-com`:return a({id:`UK3GW4`});case`duplicate`:return a({id:`DEkRZA`})}},t[9]=a,t[10]=P);let F=P,I;t[11]!==n||t[12]!==m||t[13]!==d||t[14]!==F?(I=function(e){e.preventDefault();let t=O(m,new Set(d.map(j)));if(!t.ok){v(F(t.reason));return}let r=n.patch({git:{hosts:{[t.host]:{provider:`github`}}}});if(!r.ok){v(c(r.error));return}f(k(r.effective)),g(``),v(null),b(!0)},t[11]=n,t[12]=m,t[13]=d,t[14]=F,t[15]=I):I=t[15];let ne=I,L;t[16]!==n||t[17]!==d?(L=function(e){let t=d.indexOf(e),r=d[t+1]??d[t-1]??null,i=n.patch({git:{hosts:{[e]:null}}});if(!i.ok){v(c(i.error));return}f(k(i.effective)),ee({host:r}),v(null),b(!0)},t[16]=n,t[17]=d,t[18]=L):L=t[18];let R=L,z;t[19]===Symbol.for(`react.memo_cache_sentinel`)?(z=(0,A.jsx)(`h4`,{id:`settings-enterprise-hosts-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`J2-D_a`})}),t[19]=z):z=t[19];let B;t[20]===Symbol.for(`react.memo_cache_sentinel`)?(B=(0,A.jsx)(r,{id:`PgY2nN`}),t[20]=B):B=t[20];let V;t[21]===o?V=t[22]:(V=(0,A.jsxs)(`div`,{children:[z,(0,A.jsx)(`p`,{id:o,className:`text-1sm text-muted-foreground`,children:B})]}),t[21]=o,t[22]=V);let H;t[23]!==a||t[24]!==R||t[25]!==d?(H=d.length>0?(0,A.jsx)(`ul`,{className:`space-y-1`,"data-testid":`settings-enterprise-hosts-list`,children:d.map(e=>(0,A.jsxs)(`li`,{className:`flex items-center justify-between gap-3`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs`,children:e}),(0,A.jsx)(s,{variant:`ghost`,size:`icon`,className:`size-7`,"aria-label":a({id:`xVMoYb`,values:{host:e}}),ref:t=>{t?T.current.set(e,t):T.current.delete(e)},onClick:()=>R(e),children:(0,A.jsx)(p,{"aria-hidden":`true`})})]},e))}):(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,"data-testid":`settings-enterprise-hosts-empty`,children:(0,A.jsx)(r,{id:`HK2eIK`})}),t[23]=a,t[24]=R,t[25]=d,t[26]=H):H=t[26];let U;t[27]===a?U=t[28]:(U=a({id:`Qbf7Q4`}),t[27]=a,t[28]=U);let W=_!==null,G=_===null?o:`${o} ${l}`,K;t[29]===_?K=t[30]:(K=e=>{g(e.target.value),_!==null&&v(null)},t[29]=_,t[30]=K);let q;t[31]!==m||t[32]!==U||t[33]!==W||t[34]!==G||t[35]!==K?(q=(0,A.jsx)(h,{ref:E,value:m,"aria-label":U,placeholder:`github.example.com`,autoComplete:`off`,spellCheck:!1,inputMode:`url`,className:`h-7 flex-1 font-mono text-xs`,"aria-invalid":W,"aria-describedby":G,onChange:K}),t[31]=m,t[32]=U,t[33]=W,t[34]=G,t[35]=K,t[36]=q):q=t[36];let re;t[37]===m?re=t[38]:(re=m.trim(),t[37]=m,t[38]=re);let ie=re===``,J;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(J=(0,A.jsx)(r,{id:`ALFlyF`}),t[39]=J):J=t[39];let Y;t[40]===ie?Y=t[41]:(Y=(0,A.jsx)(s,{type:`submit`,size:`sm`,variant:`secondary`,disabled:ie,className:`h-7 px-2 font-normal text-xs`,children:J}),t[40]=ie,t[41]=Y);let X;t[42]!==ne||t[43]!==q||t[44]!==Y?(X=(0,A.jsxs)(`form`,{className:`flex items-center gap-2 pt-1`,onSubmit:ne,noValidate:!0,children:[q,Y]}),t[42]=ne,t[43]=q,t[44]=Y,t[45]=X):X=t[45];let Z;t[46]!==_||t[47]!==l?(Z=_===null?null:(0,A.jsx)(`p`,{id:l,role:`alert`,className:`text-1sm text-destructive`,children:_}),t[46]=_,t[47]=l,t[48]=Z):Z=t[48];let Q;t[49]===y?Q=t[50]:(Q=y?(0,A.jsx)(`p`,{role:`status`,className:`text-1sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`3LuFP-`})}):null,t[49]=y,t[50]=Q);let $;t[51]!==H||t[52]!==X||t[53]!==Z||t[54]!==Q?($=(0,A.jsxs)(`div`,{className:`space-y-2 rounded-lg border bg-card p-3`,children:[H,X,Z,Q]}),t[51]=H,t[52]=X,t[53]=Z,t[54]=Q,t[55]=$):$=t[55];let ae;return t[56]!==V||t[57]!==$?(ae=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-enterprise-hosts-title`,className:`space-y-4`,"data-field":`section:enterprise-hosts`,"data-testid":`settings-enterprise-hosts`,children:[V,$]}),t[56]=V,t[57]=$,t[58]=ae):ae=t[58],ae}function j(e){return u(e)}function M(e){let t=(0,C.c)(43),{authQueryTransport:n,authTransport:a,userBinding:o}=e,{_:s}=i(),c;t[0]===n?c=t[1]:(c=n??g(),t[0]=n,t[1]=c);let l=c,u=m()?.remote??null,d;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(d={phase:`loading`},t[2]=d):d=t[2];let[f,p]=(0,S.useState)(d),[h,_]=(0,S.useState)(!1),[y,b]=(0,S.useState)(!1),[w,T]=(0,S.useState)(null),E=(0,S.useRef)(!1),D;t[3]===l?D=t[4]:(D=async function(){p({phase:`loading`});try{let e=await l.status();p({phase:`loaded`,result:e}),x(e)}catch(e){console.warn(`[AccountSection] GitHub status check failed`,e),p({phase:`check-failed`})}},t[3]=l,t[4]=D);let O=D,k;t[5]===O?k=t[6]:(k=()=>{O()},t[5]=O,t[6]=k);let j;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(j=[],t[7]=j):j=t[7],(0,S.useEffect)(k,j);let M;t[8]!==s||t[9]!==O||t[10]!==l?(M=async function(){if(E.current)return;E.current=!0,_(!1),b(!0),T(null);let e=null;try{let t=l.signout?await l.signout():{ok:!1,error:s({id:`8cpOa8`})};t.ok||(e=t.error??s({id:`8cpOa8`}))}catch(t){console.warn(`[AccountSection] GitHub disconnect failed`,t),e=s({id:`8cpOa8`})}await O(),e&&T(e),b(!1),E.current=!1},t[8]=s,t[9]=O,t[10]=l,t[11]=M):M=t[11];let P=M,F;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(F=(0,A.jsx)(r,{id:`MpZRQy`}),t[12]=F):F=t[12];let I;t[13]===Symbol.for(`react.memo_cache_sentinel`)?(I=(0,A.jsx)(ee,{titleId:`settings-account-title`,title:F,scope:`user`,children:(0,A.jsx)(r,{id:`pd6t3G`})}),t[13]=I):I=t[13];let L;t[14]!==w||t[15]!==y||t[16]!==P||t[17]!==O||t[18]!==f?(L=f.phase===`loaded`&&f.result.unsupportedOrigin!==void 0?null:(0,A.jsxs)(`section`,{"aria-labelledby":`settings-github-account-title`,className:`space-y-4`,"data-field":`section:github-account`,children:[(0,A.jsx)(`h4`,{id:`settings-github-account-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`RkXlPZ`})}),(0,A.jsx)(N,{status:f,disconnecting:y,disconnectError:w,onRetry:()=>void O(),onConnect:()=>_(!0),onDisconnect:()=>void P()})]}),t[14]=w,t[15]=y,t[16]=P,t[17]=O,t[18]=f,t[19]=L):L=t[19];let R;t[20]===o?R=t[21]:(R=(0,A.jsx)(te,{binding:o}),t[20]=o,t[21]=R);let z;t[22]!==a||t[23]!==u?(z=(0,A.jsx)(ne,{authTransport:a,remote:u}),t[22]=a,t[23]=u,t[24]=z):z=t[24];let B;t[25]!==R||t[26]!==z||t[27]!==L?(B=(0,A.jsxs)(`div`,{className:`space-y-8`,children:[L,R,z]}),t[25]=R,t[26]=z,t[27]=L,t[28]=B):B=t[28];let V;t[29]===O?V=t[30]:(V=e=>{_(e),e||O()},t[29]=O,t[30]=V);let H=f.phase===`loaded`?f.result.host:void 0,U=f.phase===`loaded`?f.result.ghAvailable:void 0,W;t[31]===O?W=t[32]:(W=()=>{O()},t[31]=O,t[32]=W);let G;t[33]!==h||t[34]!==a||t[35]!==V||t[36]!==H||t[37]!==U||t[38]!==W?(G=(0,A.jsx)(v,{open:h,onOpenChange:V,transport:a,host:H,ghAvailable:U,onSuccess:W}),t[33]=h,t[34]=a,t[35]=V,t[36]=H,t[37]=U,t[38]=W,t[39]=G):G=t[39];let K;return t[40]!==B||t[41]!==G?(K=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-account-title`,className:`space-y-5`,"data-testid":`settings-account`,children:[I,B,G]}),t[40]=B,t[41]=G,t[42]=K):K=t[42],K}function N(e){let t=(0,C.c)(8),{status:n,disconnecting:i,disconnectError:a,onRetry:o,onConnect:c,onDisconnect:l}=e,u;return t[0]!==a||t[1]!==i||t[2]!==c||t[3]!==l||t[4]!==o||t[5]!==n.phase||t[6]!==n.result?(u=n.phase===`loading`?(0,A.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-busy":`true`,className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-loading`,children:[(0,A.jsx)(`span`,{className:`sr-only`,children:(0,A.jsx)(r,{id:`IWGfGF`})}),(0,A.jsx)(b,{className:`h-4 w-40`}),(0,A.jsx)(b,{className:`h-8 w-32`})]}):n.phase===`check-failed`?(0,A.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-check-failed`,children:[(0,A.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`T_wG4n`})}),(0,A.jsx)(s,{variant:`outline`,size:`sm`,onClick:o,children:(0,A.jsx)(r,{id:`KDw4GX`})})]}):n.result.authenticated?n.result.tier===`A`?(0,A.jsx)(R,{login:n.result.login,host:n.result.host}):(0,A.jsx)(L,{login:n.result.login,host:n.result.host,disconnecting:i,error:a,onDisconnect:l}):(0,A.jsx)(z,{onConnect:c}),t[0]=a,t[1]=i,t[2]=c,t[3]=l,t[4]=o,t[5]=n.phase,t[6]=n.result,t[7]=u):u=t[7],u}function P(e){let t=e.split(`/`)[0]??``;return l(t)?t:``}function F(e){let t=(0,C.c)(7),{login:n,host:i}=e,a;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=y(),t[0]=a):a=t[0];let o=a,s;t[1]!==i||t[2]!==n?(s={login:n,host:i,cliCommand:o},t[1]=i,t[2]=n,t[3]=s):s=t[3];let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c={0:(0,A.jsx)(`code`,{translate:`no`})},t[4]=c):c=t[4];let l;return t[5]===s?l=t[6]:(l=(0,A.jsx)(`p`,{role:`status`,className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-success`,children:(0,A.jsx)(r,{id:`o8OY2K`,values:s,components:c})}),t[5]=s,t[6]=l),l}var I={"data-1p-ignore":!0,"data-lpignore":`true`,"data-bwignore":!0,"data-form-type":`other`};function ne(e){let t=(0,C.c)(89),{authTransport:n,remote:a}=e,{_:c}=i(),u;t[0]===n?u=t[1]:(u=n??_(),t[0]=n,t[1]=u);let p=u,m=a?.label??null,g;t[2]===a?g=t[3]:(g=a?f(a):!1,t[2]=a,t[3]=g);let v=g,y;t[4]===a?y=t[5]:(y=d(a),t[4]=a,t[5]=y);let b=y,x=(0,S.useId)(),ee=(0,S.useId)(),w=(0,S.useId)(),T=(0,S.useId)(),E=(0,S.useId)(),[D,O]=(0,S.useState)(``),[k,te]=(0,S.useState)(``),[j,M]=(0,S.useState)(``),[N,ne]=(0,S.useState)(!1),[L,R]=(0,S.useState)(null),[z,B]=(0,S.useState)(!1),[V,H]=(0,S.useState)(null),U=(0,S.useRef)(!1),W=(0,S.useRef)(!1),G,K;t[6]!==v||t[7]!==m||t[8]!==b?(G=()=>{if(W.current||m===null||v||!b)return;let e=P(m);e&&(W.current=!0,O(e))},K=[m,v,b],t[6]=v,t[7]=m,t[8]=b,t[9]=G,t[10]=K):(G=t[9],K=t[10]),(0,S.useEffect)(G,K);let q;t[11]!==c||t[12]!==D||t[13]!==p||t[14]!==j||t[15]!==k?(q=async function(){if(U.current)return;let e=D.trim(),t=k.trim(),n=j.trim();if(!e||!t||!n)return;if(!l(e)){H(null),B(!0),R(c({id:`rZFxkH`}));return}if(B(!1),!p.hostToken){R(c({id:`iMYFJM`}));return}U.current=!0,ne(!0),R(null),H(null);let r=await p.hostToken(e,t,n).catch(e=>(console.warn(`[AccountSection] storing a host token failed`,e),{ok:!1,login:void 0,error:c({id:`Q5fqMz`})}));ne(!1),U.current=!1,r.ok?(M(``),H({login:r.login||t,host:e})):R(r.error??c({id:`sNeKjP`}))},t[11]=c,t[12]=D,t[13]=p,t[14]=j,t[15]=k,t[16]=q):q=t[16];let re=q,ie;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(ie=(0,A.jsx)(`h4`,{id:`settings-host-tokens-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`jbhCDS`})}),t[17]=ie):ie=t[17];let J;t[18]===Symbol.for(`react.memo_cache_sentinel`)?(J=(0,A.jsxs)(`div`,{children:[ie,(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`-nA68n`})})]}),t[18]=J):J=t[18];let Y;t[19]===re?Y=t[20]:(Y=e=>{e.preventDefault(),re()},t[19]=re,t[20]=Y);let X;t[21]!==v||t[22]!==m||t[23]!==b?(X=m!==null&&!v&&!b?(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-not-https`,children:(0,A.jsx)(r,{id:`OWs-8P`})}):null,t[21]=v,t[22]=m,t[23]=b,t[24]=X):X=t[24];let Z;t[25]===Symbol.for(`react.memo_cache_sentinel`)?(Z=(0,A.jsx)(r,{id:`Ai2U7L`}),t[25]=Z):Z=t[25];let Q;t[26]===x?Q=t[27]:(Q=(0,A.jsx)(o,{htmlFor:x,children:Z}),t[26]=x,t[27]=Q);let $=z||void 0,ae=z&&L?ee:void 0,oe;t[28]===z?oe=t[29]:(oe=e=>{W.current=!0,O(e.target.value),z&&(B(!1),R(null))},t[28]=z,t[29]=oe);let se;t[30]!==D||t[31]!==x||t[32]!==$||t[33]!==ae||t[34]!==oe?(se=(0,A.jsx)(h,{id:x,type:`text`,placeholder:`git.example.com`,autoComplete:`off`,...I,"aria-invalid":$,"aria-describedby":ae,value:D,onChange:oe}),t[30]=D,t[31]=x,t[32]=$,t[33]=ae,t[34]=oe,t[35]=se):se=t[35];let ce;t[36]!==Q||t[37]!==se?(ce=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[Q,se]}),t[36]=Q,t[37]=se,t[38]=ce):ce=t[38];let le;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(le=(0,A.jsx)(r,{id:`7sNhEz`}),t[39]=le):le=t[39];let ue;t[40]===w?ue=t[41]:(ue=(0,A.jsx)(o,{htmlFor:w,children:le}),t[40]=w,t[41]=ue);let de;t[42]===Symbol.for(`react.memo_cache_sentinel`)?(de=e=>te(e.target.value),t[42]=de):de=t[42];let fe;t[43]!==k||t[44]!==T||t[45]!==w?(fe=(0,A.jsx)(h,{id:w,type:`text`,autoComplete:`off`,...I,"aria-describedby":T,value:k,onChange:de}),t[43]=k,t[44]=T,t[45]=w,t[46]=fe):fe=t[46];let pe;t[47]===Symbol.for(`react.memo_cache_sentinel`)?(pe=(0,A.jsx)(r,{id:`azrR7I`,components:{0:(0,A.jsx)(`code`,{translate:`no`}),1:(0,A.jsx)(`code`,{translate:`no`}),2:(0,A.jsx)(`code`,{translate:`no`})}}),t[47]=pe):pe=t[47];let me;t[48]===T?me=t[49]:(me=(0,A.jsx)(`p`,{id:T,className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-username-hint`,children:pe}),t[48]=T,t[49]=me);let he;t[50]!==ue||t[51]!==fe||t[52]!==me?(he=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[ue,fe,me]}),t[50]=ue,t[51]=fe,t[52]=me,t[53]=he):he=t[53];let ge;t[54]===Symbol.for(`react.memo_cache_sentinel`)?(ge=(0,A.jsx)(r,{id:`SkUcEr`}),t[54]=ge):ge=t[54];let _e;t[55]===E?_e=t[56]:(_e=(0,A.jsx)(o,{htmlFor:E,children:ge}),t[55]=E,t[56]=_e);let ve;t[57]===Symbol.for(`react.memo_cache_sentinel`)?(ve=e=>M(e.target.value),t[57]=ve):ve=t[57];let ye;t[58]!==j||t[59]!==E?(ye=(0,A.jsx)(h,{id:E,type:`password`,autoComplete:`off`,...I,value:j,onChange:ve}),t[58]=j,t[59]=E,t[60]=ye):ye=t[60];let be;t[61]!==_e||t[62]!==ye?(be=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[_e,ye]}),t[61]=_e,t[62]=ye,t[63]=be):be=t[63];let xe;t[64]!==D||t[65]!==N||t[66]!==j||t[67]!==k?(xe=N||!D.trim()||!k.trim()||!j.trim(),t[64]=D,t[65]=N,t[66]=j,t[67]=k,t[68]=xe):xe=t[68];let Se;t[69]===N?Se=t[70]:(Se=N?(0,A.jsx)(r,{id:`1yHVE-`}):(0,A.jsx)(r,{id:`zXZJoN`}),t[69]=N,t[70]=Se);let Ce;t[71]!==xe||t[72]!==Se?(Ce=(0,A.jsx)(s,{type:`submit`,"data-testid":`settings-account-host-token-submit`,disabled:xe,children:Se}),t[71]=xe,t[72]=Se,t[73]=Ce):Ce=t[73];let we;t[74]===V?we=t[75]:(we=V?(0,A.jsx)(F,{login:V.login,host:V.host}):null,t[74]=V,t[75]=we);let Te;t[76]!==L||t[77]!==ee||t[78]!==z?(Te=L?(0,A.jsx)(`p`,{id:z?ee:void 0,role:`alert`,className:`text-sm text-destructive`,"data-testid":`settings-account-host-token-error`,children:L}):null,t[76]=L,t[77]=ee,t[78]=z,t[79]=Te):Te=t[79];let Ee;return t[80]!==X||t[81]!==ce||t[82]!==he||t[83]!==be||t[84]!==Ce||t[85]!==we||t[86]!==Te||t[87]!==Y?(Ee=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-host-tokens-title`,className:`space-y-4`,"data-field":`section:host-tokens`,children:[J,(0,A.jsxs)(`form`,{className:`space-y-3 rounded-lg border bg-card p-3`,"data-testid":`settings-account-host-token`,"aria-labelledby":`settings-host-tokens-title`,autoComplete:`off`,onSubmit:Y,children:[X,ce,he,be,Ce,we,Te]})]}),t[80]=X,t[81]=ce,t[82]=he,t[83]=be,t[84]=Ce,t[85]=we,t[86]=Te,t[87]=Y,t[88]=Ee):Ee=t[88],Ee}function L(e){let t=(0,C.c)(21),{login:n,host:i,disconnecting:a,error:o,onDisconnect:c}=e,l;t[0]!==i||t[1]!==n?(l=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`bc7aCh`,values:{host:i,login:n}})}),t[0]=i,t[1]=n,t[2]=l):l=t[2];let u;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(u=(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`nxlOpL`})}),t[3]=u):u=t[3];let d;t[4]===l?d=t[5]:(d=(0,A.jsxs)(`div`,{className:`min-w-0`,children:[l,u]}),t[4]=l,t[5]=d);let f;t[6]===a?f=t[7]:(f=a?(0,A.jsx)(r,{id:`rppgXF`}):(0,A.jsx)(r,{id:`-K0AvT`}),t[6]=a,t[7]=f);let p;t[8]!==a||t[9]!==c||t[10]!==f?(p=(0,A.jsx)(s,{variant:`outline`,onClick:c,disabled:a,"aria-describedby":`settings-account-disconnect-caveat`,"data-testid":`settings-account-disconnect`,children:f}),t[8]=a,t[9]=c,t[10]=f,t[11]=p):p=t[11];let m;t[12]!==d||t[13]!==p?(m=(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[d,p]}),t[12]=d,t[13]=p,t[14]=m):m=t[14];let h;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(h=(0,A.jsx)(`p`,{id:`settings-account-disconnect-caveat`,className:`text-muted-foreground text-1sm`,"data-testid":`settings-account-disconnect-caveat`,children:(0,A.jsx)(r,{id:`msOK6I`})}),t[15]=h):h=t[15];let g;t[16]===o?g=t[17]:(g=o?(0,A.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,"data-testid":`settings-account-disconnect-error`,children:o}):null,t[16]=o,t[17]=g);let _;return t[18]!==m||t[19]!==g?(_=(0,A.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-connected`,children:[m,h,g]}),t[18]=m,t[19]=g,t[20]=_):_=t[20],_}function R(e){let t=(0,C.c)(6),{login:n,host:i}=e,a;t[0]!==i||t[1]!==n?(a=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`bc7aCh`,values:{host:i,login:n}})}),t[0]=i,t[1]=n,t[2]=a):a=t[2];let o;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`UcTm1A`,components:{0:(0,A.jsx)(`code`,{translate:`no`}),1:(0,A.jsx)(`code`,{translate:`no`})}})}),t[3]=o):o=t[3];let s;return t[4]===a?s=t[5]:(s=(0,A.jsx)(`div`,{className:`rounded-md border p-3`,"data-testid":`settings-account-gh-cli`,children:(0,A.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[a,o]})}),t[4]=a,t[5]=s),s}function z(e){let t=(0,C.c)(5),{onConnect:n}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`S33tz3`})}),t[0]=i):i=t[0];let a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,A.jsxs)(`div`,{className:`min-w-0`,children:[i,(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`9djC8C`})})]}),t[1]=a):a=t[1];let o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,A.jsx)(r,{id:`5lWFkC`}),t[2]=o):o=t[2];let c;return t[3]===n?c=t[4]:(c=(0,A.jsx)(`div`,{className:`rounded-md border p-3`,"data-testid":`settings-account-disconnected`,children:(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[a,(0,A.jsx)(s,{onClick:n,"data-testid":`settings-account-connect`,children:o})]})}),t[3]=n,t[4]=c),c}export{M as AccountSection};
|
|
1
|
+
import{o as e}from"./chunk-CYidjpOJ.js";import{t}from"./jsx-runtime-BUgB2tll.js";import{t as n}from"./react-f2sANaYj.js";import{n as r,r as i}from"./dist-Nvb76hAm.js";import{t as a}from"./compiler-runtime-BfE3aGVn.js";import{t as o}from"./label-CvMpFFbN.js";import{t as s}from"./button-DzgjsZzC.js";import{n as c}from"./config-errors-DDAH9fqy.js";import{n as l,r as u}from"./constants-github-B7yhDvQc.js";import{f as d,l as f}from"./SyncStatusBadge-CodPHi7k.js";import{t as p}from"./trash-2-CchZ0T47.js";import{t as m}from"./use-git-sync-status-PkMYmN4D.js";import{t as h}from"./input-BsFOyzfK.js";import{a as g,n as _,t as v}from"./AuthModal-DT32BOAJ.js";import{t as y}from"./channel-cli-copy-DOAEiMde.js";import{t as b}from"./skeleton-CrbF9ppq.js";import{n as x}from"./auth-state-cache-Bx6C01Jt.js";import{t as ee}from"./SettingsSectionHeader-DDNA1hrR.js";var S=e(n(),1),C=a(),w=`[a-z0-9](?:[a-z0-9-]*[a-z0-9])?`,T=RegExp(`^${w}(?:\\.${w})*$`),E=/^[a-z][a-z0-9+.-]*:\/\//i;function D(e){if(E.test(e))try{return new URL(e).host}catch{return null}let t=e.split(`/`)[0]??``;return t.slice(t.lastIndexOf(`@`)+1).replace(/:(?!\d+$).*$/,``)}function O(e,t){let n=e.trim();if(n===``)return{ok:!1,reason:`empty`};let r=D(n);if(r===null||r===``)return{ok:!1,reason:`invalid`};let i=u(r);return T.test(i)?i===`github.com`?{ok:!1,reason:`github-com`}:t.has(i)?{ok:!1,reason:`duplicate`}:{ok:!0,host:i}:{ok:!1,reason:`invalid`}}function k(e){let t=e.git?.hosts??{};return Object.entries(t).filter(([,e])=>e?.provider===`github`).map(([e])=>e).sort((e,t)=>e.localeCompare(t))}var A=t();function te(e){let t=(0,C.c)(59),{binding:n}=e,{_:a}=i(),o=(0,S.useId)(),l=(0,S.useId)(),u;t[0]===n?u=t[1]:(u=()=>k(n.current()),t[0]=n,t[1]=u);let[d,f]=(0,S.useState)(u),[m,g]=(0,S.useState)(``),[_,v]=(0,S.useState)(null),[y,b]=(0,S.useState)(!1),[x,ee]=(0,S.useState)(null),w;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(w=new Map,t[2]=w):w=t[2];let T=(0,S.useRef)(w),E=(0,S.useRef)(null),D,te;t[3]===x?(D=t[4],te=t[5]):(D=()=>{x!==null&&(((x.host===null?null:T.current.get(x.host))??E.current)?.focus(),ee(null))},te=[x],t[3]=x,t[4]=D,t[5]=te),(0,S.useEffect)(D,te);let M,N;t[6]===n?(M=t[7],N=t[8]):(M=()=>n.subscribe(e=>f(k(e))),N=[n],t[6]=n,t[7]=M,t[8]=N),(0,S.useEffect)(M,N);let P;t[9]===a?P=t[10]:(P=function(e){switch(e){case`empty`:return a({id:`cFONFy`});case`invalid`:return a({id:`QsnBxE`});case`github-com`:return a({id:`UK3GW4`});case`duplicate`:return a({id:`DEkRZA`})}},t[9]=a,t[10]=P);let F=P,I;t[11]!==n||t[12]!==m||t[13]!==d||t[14]!==F?(I=function(e){e.preventDefault();let t=O(m,new Set(d.map(j)));if(!t.ok){v(F(t.reason));return}let r=n.patch({git:{hosts:{[t.host]:{provider:`github`}}}});if(!r.ok){v(c(r.error));return}f(k(r.effective)),g(``),v(null),b(!0)},t[11]=n,t[12]=m,t[13]=d,t[14]=F,t[15]=I):I=t[15];let ne=I,L;t[16]!==n||t[17]!==d?(L=function(e){let t=d.indexOf(e),r=d[t+1]??d[t-1]??null,i=n.patch({git:{hosts:{[e]:null}}});if(!i.ok){v(c(i.error));return}f(k(i.effective)),ee({host:r}),v(null),b(!0)},t[16]=n,t[17]=d,t[18]=L):L=t[18];let R=L,z;t[19]===Symbol.for(`react.memo_cache_sentinel`)?(z=(0,A.jsx)(`h4`,{id:`settings-enterprise-hosts-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`J2-D_a`})}),t[19]=z):z=t[19];let B;t[20]===Symbol.for(`react.memo_cache_sentinel`)?(B=(0,A.jsx)(r,{id:`PgY2nN`}),t[20]=B):B=t[20];let V;t[21]===o?V=t[22]:(V=(0,A.jsxs)(`div`,{children:[z,(0,A.jsx)(`p`,{id:o,className:`text-1sm text-muted-foreground`,children:B})]}),t[21]=o,t[22]=V);let H;t[23]!==a||t[24]!==R||t[25]!==d?(H=d.length>0?(0,A.jsx)(`ul`,{className:`space-y-1`,"data-testid":`settings-enterprise-hosts-list`,children:d.map(e=>(0,A.jsxs)(`li`,{className:`flex items-center justify-between gap-3`,children:[(0,A.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs`,children:e}),(0,A.jsx)(s,{variant:`ghost`,size:`icon`,className:`size-7`,"aria-label":a({id:`xVMoYb`,values:{host:e}}),ref:t=>{t?T.current.set(e,t):T.current.delete(e)},onClick:()=>R(e),children:(0,A.jsx)(p,{"aria-hidden":`true`})})]},e))}):(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,"data-testid":`settings-enterprise-hosts-empty`,children:(0,A.jsx)(r,{id:`HK2eIK`})}),t[23]=a,t[24]=R,t[25]=d,t[26]=H):H=t[26];let U;t[27]===a?U=t[28]:(U=a({id:`Qbf7Q4`}),t[27]=a,t[28]=U);let W=_!==null,G=_===null?o:`${o} ${l}`,K;t[29]===_?K=t[30]:(K=e=>{g(e.target.value),_!==null&&v(null)},t[29]=_,t[30]=K);let q;t[31]!==m||t[32]!==U||t[33]!==W||t[34]!==G||t[35]!==K?(q=(0,A.jsx)(h,{ref:E,value:m,"aria-label":U,placeholder:`github.example.com`,autoComplete:`off`,spellCheck:!1,inputMode:`url`,className:`h-7 flex-1 font-mono text-xs`,"aria-invalid":W,"aria-describedby":G,onChange:K}),t[31]=m,t[32]=U,t[33]=W,t[34]=G,t[35]=K,t[36]=q):q=t[36];let re;t[37]===m?re=t[38]:(re=m.trim(),t[37]=m,t[38]=re);let ie=re===``,J;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(J=(0,A.jsx)(r,{id:`ALFlyF`}),t[39]=J):J=t[39];let Y;t[40]===ie?Y=t[41]:(Y=(0,A.jsx)(s,{type:`submit`,size:`sm`,variant:`secondary`,disabled:ie,className:`h-7 px-2 font-normal text-xs`,children:J}),t[40]=ie,t[41]=Y);let X;t[42]!==ne||t[43]!==q||t[44]!==Y?(X=(0,A.jsxs)(`form`,{className:`flex items-center gap-2 pt-1`,onSubmit:ne,noValidate:!0,children:[q,Y]}),t[42]=ne,t[43]=q,t[44]=Y,t[45]=X):X=t[45];let Z;t[46]!==_||t[47]!==l?(Z=_===null?null:(0,A.jsx)(`p`,{id:l,role:`alert`,className:`text-1sm text-destructive`,children:_}),t[46]=_,t[47]=l,t[48]=Z):Z=t[48];let Q;t[49]===y?Q=t[50]:(Q=y?(0,A.jsx)(`p`,{role:`status`,className:`text-1sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`3LuFP-`})}):null,t[49]=y,t[50]=Q);let $;t[51]!==H||t[52]!==X||t[53]!==Z||t[54]!==Q?($=(0,A.jsxs)(`div`,{className:`space-y-2 rounded-lg border bg-card p-3`,children:[H,X,Z,Q]}),t[51]=H,t[52]=X,t[53]=Z,t[54]=Q,t[55]=$):$=t[55];let ae;return t[56]!==V||t[57]!==$?(ae=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-enterprise-hosts-title`,className:`space-y-4`,"data-field":`section:enterprise-hosts`,"data-testid":`settings-enterprise-hosts`,children:[V,$]}),t[56]=V,t[57]=$,t[58]=ae):ae=t[58],ae}function j(e){return u(e)}function M(e){let t=(0,C.c)(43),{authQueryTransport:n,authTransport:a,userBinding:o}=e,{_:s}=i(),c;t[0]===n?c=t[1]:(c=n??g(),t[0]=n,t[1]=c);let l=c,u=m()?.remote??null,d;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(d={phase:`loading`},t[2]=d):d=t[2];let[f,p]=(0,S.useState)(d),[h,_]=(0,S.useState)(!1),[y,b]=(0,S.useState)(!1),[w,T]=(0,S.useState)(null),E=(0,S.useRef)(!1),D;t[3]===l?D=t[4]:(D=async function(){p({phase:`loading`});try{let e=await l.status();p({phase:`loaded`,result:e}),x(e)}catch(e){console.warn(`[AccountSection] GitHub status check failed`,e),p({phase:`check-failed`})}},t[3]=l,t[4]=D);let O=D,k;t[5]===O?k=t[6]:(k=()=>{O()},t[5]=O,t[6]=k);let j;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(j=[],t[7]=j):j=t[7],(0,S.useEffect)(k,j);let M;t[8]!==s||t[9]!==O||t[10]!==l?(M=async function(){if(E.current)return;E.current=!0,_(!1),b(!0),T(null);let e=null;try{let t=l.signout?await l.signout():{ok:!1,error:s({id:`8cpOa8`})};t.ok||(e=t.error??s({id:`8cpOa8`}))}catch(t){console.warn(`[AccountSection] GitHub disconnect failed`,t),e=s({id:`8cpOa8`})}await O(),e&&T(e),b(!1),E.current=!1},t[8]=s,t[9]=O,t[10]=l,t[11]=M):M=t[11];let P=M,F;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(F=(0,A.jsx)(r,{id:`MpZRQy`}),t[12]=F):F=t[12];let I;t[13]===Symbol.for(`react.memo_cache_sentinel`)?(I=(0,A.jsx)(ee,{titleId:`settings-account-title`,title:F,scope:`user`,children:(0,A.jsx)(r,{id:`pd6t3G`})}),t[13]=I):I=t[13];let L;t[14]!==w||t[15]!==y||t[16]!==P||t[17]!==O||t[18]!==f?(L=f.phase===`loaded`&&f.result.unsupportedOrigin!==void 0?null:(0,A.jsxs)(`section`,{"aria-labelledby":`settings-github-account-title`,className:`space-y-4`,"data-field":`section:github-account`,children:[(0,A.jsx)(`h4`,{id:`settings-github-account-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`RkXlPZ`})}),(0,A.jsx)(N,{status:f,disconnecting:y,disconnectError:w,onRetry:()=>void O(),onConnect:()=>_(!0),onDisconnect:()=>void P()})]}),t[14]=w,t[15]=y,t[16]=P,t[17]=O,t[18]=f,t[19]=L):L=t[19];let R;t[20]===o?R=t[21]:(R=(0,A.jsx)(te,{binding:o}),t[20]=o,t[21]=R);let z;t[22]!==a||t[23]!==u?(z=(0,A.jsx)(ne,{authTransport:a,remote:u}),t[22]=a,t[23]=u,t[24]=z):z=t[24];let B;t[25]!==R||t[26]!==z||t[27]!==L?(B=(0,A.jsxs)(`div`,{className:`space-y-8`,children:[L,R,z]}),t[25]=R,t[26]=z,t[27]=L,t[28]=B):B=t[28];let V;t[29]===O?V=t[30]:(V=e=>{_(e),e||O()},t[29]=O,t[30]=V);let H=f.phase===`loaded`?f.result.host:void 0,U=f.phase===`loaded`?f.result.ghAvailable:void 0,W;t[31]===O?W=t[32]:(W=()=>{O()},t[31]=O,t[32]=W);let G;t[33]!==h||t[34]!==a||t[35]!==V||t[36]!==H||t[37]!==U||t[38]!==W?(G=(0,A.jsx)(v,{open:h,onOpenChange:V,transport:a,host:H,ghAvailable:U,onSuccess:W}),t[33]=h,t[34]=a,t[35]=V,t[36]=H,t[37]=U,t[38]=W,t[39]=G):G=t[39];let K;return t[40]!==B||t[41]!==G?(K=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-account-title`,className:`space-y-5`,"data-testid":`settings-account`,children:[I,B,G]}),t[40]=B,t[41]=G,t[42]=K):K=t[42],K}function N(e){let t=(0,C.c)(8),{status:n,disconnecting:i,disconnectError:a,onRetry:o,onConnect:c,onDisconnect:l}=e,u;return t[0]!==a||t[1]!==i||t[2]!==c||t[3]!==l||t[4]!==o||t[5]!==n.phase||t[6]!==n.result?(u=n.phase===`loading`?(0,A.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-busy":`true`,className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-loading`,children:[(0,A.jsx)(`span`,{className:`sr-only`,children:(0,A.jsx)(r,{id:`IWGfGF`})}),(0,A.jsx)(b,{className:`h-4 w-40`}),(0,A.jsx)(b,{className:`h-8 w-32`})]}):n.phase===`check-failed`?(0,A.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-check-failed`,children:[(0,A.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`T_wG4n`})}),(0,A.jsx)(s,{variant:`outline`,size:`sm`,onClick:o,children:(0,A.jsx)(r,{id:`KDw4GX`})})]}):n.result.authenticated?n.result.tier===`A`?(0,A.jsx)(R,{login:n.result.login,host:n.result.host}):(0,A.jsx)(L,{login:n.result.login,host:n.result.host,disconnecting:i,error:a,onDisconnect:l}):(0,A.jsx)(z,{onConnect:c}),t[0]=a,t[1]=i,t[2]=c,t[3]=l,t[4]=o,t[5]=n.phase,t[6]=n.result,t[7]=u):u=t[7],u}function P(e){let t=e.split(`/`)[0]??``;return l(t)?t:``}function F(e){let t=(0,C.c)(7),{login:n,host:i}=e,a;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=y(),t[0]=a):a=t[0];let o=a,s;t[1]!==i||t[2]!==n?(s={login:n,host:i,cliCommand:o},t[1]=i,t[2]=n,t[3]=s):s=t[3];let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c={0:(0,A.jsx)(`code`,{translate:`no`})},t[4]=c):c=t[4];let l;return t[5]===s?l=t[6]:(l=(0,A.jsx)(`p`,{role:`status`,className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-success`,children:(0,A.jsx)(r,{id:`o8OY2K`,values:s,components:c})}),t[5]=s,t[6]=l),l}var I={"data-1p-ignore":!0,"data-lpignore":`true`,"data-bwignore":!0,"data-form-type":`other`};function ne(e){let t=(0,C.c)(89),{authTransport:n,remote:a}=e,{_:c}=i(),u;t[0]===n?u=t[1]:(u=n??_(),t[0]=n,t[1]=u);let p=u,m=a?.label??null,g;t[2]===a?g=t[3]:(g=a?f(a):!1,t[2]=a,t[3]=g);let v=g,y;t[4]===a?y=t[5]:(y=d(a),t[4]=a,t[5]=y);let b=y,x=(0,S.useId)(),ee=(0,S.useId)(),w=(0,S.useId)(),T=(0,S.useId)(),E=(0,S.useId)(),[D,O]=(0,S.useState)(``),[k,te]=(0,S.useState)(``),[j,M]=(0,S.useState)(``),[N,ne]=(0,S.useState)(!1),[L,R]=(0,S.useState)(null),[z,B]=(0,S.useState)(!1),[V,H]=(0,S.useState)(null),U=(0,S.useRef)(!1),W=(0,S.useRef)(!1),G,K;t[6]!==v||t[7]!==m||t[8]!==b?(G=()=>{if(W.current||m===null||v||!b)return;let e=P(m);e&&(W.current=!0,O(e))},K=[m,v,b],t[6]=v,t[7]=m,t[8]=b,t[9]=G,t[10]=K):(G=t[9],K=t[10]),(0,S.useEffect)(G,K);let q;t[11]!==c||t[12]!==D||t[13]!==p||t[14]!==j||t[15]!==k?(q=async function(){if(U.current)return;let e=D.trim(),t=k.trim(),n=j.trim();if(!e||!t||!n)return;if(!l(e)){H(null),B(!0),R(c({id:`rZFxkH`}));return}if(B(!1),!p.hostToken){R(c({id:`iMYFJM`}));return}U.current=!0,ne(!0),R(null),H(null);let r=await p.hostToken(e,t,n).catch(e=>(console.warn(`[AccountSection] storing a host token failed`,e),{ok:!1,login:void 0,error:c({id:`Q5fqMz`})}));ne(!1),U.current=!1,r.ok?(M(``),H({login:r.login||t,host:e})):R(r.error??c({id:`sNeKjP`}))},t[11]=c,t[12]=D,t[13]=p,t[14]=j,t[15]=k,t[16]=q):q=t[16];let re=q,ie;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(ie=(0,A.jsx)(`h4`,{id:`settings-host-tokens-title`,className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`jbhCDS`})}),t[17]=ie):ie=t[17];let J;t[18]===Symbol.for(`react.memo_cache_sentinel`)?(J=(0,A.jsxs)(`div`,{children:[ie,(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,children:(0,A.jsx)(r,{id:`-nA68n`})})]}),t[18]=J):J=t[18];let Y;t[19]===re?Y=t[20]:(Y=e=>{e.preventDefault(),re()},t[19]=re,t[20]=Y);let X;t[21]!==v||t[22]!==m||t[23]!==b?(X=m!==null&&!v&&!b?(0,A.jsx)(`p`,{className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-not-https`,children:(0,A.jsx)(r,{id:`OWs-8P`})}):null,t[21]=v,t[22]=m,t[23]=b,t[24]=X):X=t[24];let Z;t[25]===Symbol.for(`react.memo_cache_sentinel`)?(Z=(0,A.jsx)(r,{id:`Ai2U7L`}),t[25]=Z):Z=t[25];let Q;t[26]===x?Q=t[27]:(Q=(0,A.jsx)(o,{htmlFor:x,children:Z}),t[26]=x,t[27]=Q);let $=z||void 0,ae=z&&L?ee:void 0,oe;t[28]===z?oe=t[29]:(oe=e=>{W.current=!0,O(e.target.value),z&&(B(!1),R(null))},t[28]=z,t[29]=oe);let se;t[30]!==D||t[31]!==x||t[32]!==$||t[33]!==ae||t[34]!==oe?(se=(0,A.jsx)(h,{id:x,type:`text`,placeholder:`git.example.com`,autoComplete:`off`,...I,"aria-invalid":$,"aria-describedby":ae,value:D,onChange:oe}),t[30]=D,t[31]=x,t[32]=$,t[33]=ae,t[34]=oe,t[35]=se):se=t[35];let ce;t[36]!==Q||t[37]!==se?(ce=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[Q,se]}),t[36]=Q,t[37]=se,t[38]=ce):ce=t[38];let le;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(le=(0,A.jsx)(r,{id:`7sNhEz`}),t[39]=le):le=t[39];let ue;t[40]===w?ue=t[41]:(ue=(0,A.jsx)(o,{htmlFor:w,children:le}),t[40]=w,t[41]=ue);let de;t[42]===Symbol.for(`react.memo_cache_sentinel`)?(de=e=>te(e.target.value),t[42]=de):de=t[42];let fe;t[43]!==k||t[44]!==T||t[45]!==w?(fe=(0,A.jsx)(h,{id:w,type:`text`,autoComplete:`off`,...I,"aria-describedby":T,value:k,onChange:de}),t[43]=k,t[44]=T,t[45]=w,t[46]=fe):fe=t[46];let pe;t[47]===Symbol.for(`react.memo_cache_sentinel`)?(pe=(0,A.jsx)(r,{id:`azrR7I`,components:{0:(0,A.jsx)(`code`,{translate:`no`}),1:(0,A.jsx)(`code`,{translate:`no`}),2:(0,A.jsx)(`code`,{translate:`no`})}}),t[47]=pe):pe=t[47];let me;t[48]===T?me=t[49]:(me=(0,A.jsx)(`p`,{id:T,className:`text-1sm text-muted-foreground`,"data-testid":`settings-account-host-token-username-hint`,children:pe}),t[48]=T,t[49]=me);let he;t[50]!==ue||t[51]!==fe||t[52]!==me?(he=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[ue,fe,me]}),t[50]=ue,t[51]=fe,t[52]=me,t[53]=he):he=t[53];let ge;t[54]===Symbol.for(`react.memo_cache_sentinel`)?(ge=(0,A.jsx)(r,{id:`SkUcEr`}),t[54]=ge):ge=t[54];let _e;t[55]===E?_e=t[56]:(_e=(0,A.jsx)(o,{htmlFor:E,children:ge}),t[55]=E,t[56]=_e);let ve;t[57]===Symbol.for(`react.memo_cache_sentinel`)?(ve=e=>M(e.target.value),t[57]=ve):ve=t[57];let ye;t[58]!==j||t[59]!==E?(ye=(0,A.jsx)(h,{id:E,type:`password`,autoComplete:`off`,...I,value:j,onChange:ve}),t[58]=j,t[59]=E,t[60]=ye):ye=t[60];let be;t[61]!==_e||t[62]!==ye?(be=(0,A.jsxs)(`div`,{className:`space-y-1`,children:[_e,ye]}),t[61]=_e,t[62]=ye,t[63]=be):be=t[63];let xe;t[64]!==D||t[65]!==N||t[66]!==j||t[67]!==k?(xe=N||!D.trim()||!k.trim()||!j.trim(),t[64]=D,t[65]=N,t[66]=j,t[67]=k,t[68]=xe):xe=t[68];let Se;t[69]===N?Se=t[70]:(Se=N?(0,A.jsx)(r,{id:`1yHVE-`}):(0,A.jsx)(r,{id:`zXZJoN`}),t[69]=N,t[70]=Se);let Ce;t[71]!==xe||t[72]!==Se?(Ce=(0,A.jsx)(s,{type:`submit`,"data-testid":`settings-account-host-token-submit`,disabled:xe,children:Se}),t[71]=xe,t[72]=Se,t[73]=Ce):Ce=t[73];let we;t[74]===V?we=t[75]:(we=V?(0,A.jsx)(F,{login:V.login,host:V.host}):null,t[74]=V,t[75]=we);let Te;t[76]!==L||t[77]!==ee||t[78]!==z?(Te=L?(0,A.jsx)(`p`,{id:z?ee:void 0,role:`alert`,className:`text-sm text-destructive`,"data-testid":`settings-account-host-token-error`,children:L}):null,t[76]=L,t[77]=ee,t[78]=z,t[79]=Te):Te=t[79];let Ee;return t[80]!==X||t[81]!==ce||t[82]!==he||t[83]!==be||t[84]!==Ce||t[85]!==we||t[86]!==Te||t[87]!==Y?(Ee=(0,A.jsxs)(`section`,{"aria-labelledby":`settings-host-tokens-title`,className:`space-y-4`,"data-field":`section:host-tokens`,children:[J,(0,A.jsxs)(`form`,{className:`space-y-3 rounded-lg border bg-card p-3`,"data-testid":`settings-account-host-token`,"aria-labelledby":`settings-host-tokens-title`,autoComplete:`off`,onSubmit:Y,children:[X,ce,he,be,Ce,we,Te]})]}),t[80]=X,t[81]=ce,t[82]=he,t[83]=be,t[84]=Ce,t[85]=we,t[86]=Te,t[87]=Y,t[88]=Ee):Ee=t[88],Ee}function L(e){let t=(0,C.c)(21),{login:n,host:i,disconnecting:a,error:o,onDisconnect:c}=e,l;t[0]!==i||t[1]!==n?(l=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`bc7aCh`,values:{host:i,login:n}})}),t[0]=i,t[1]=n,t[2]=l):l=t[2];let u;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(u=(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`nxlOpL`})}),t[3]=u):u=t[3];let d;t[4]===l?d=t[5]:(d=(0,A.jsxs)(`div`,{className:`min-w-0`,children:[l,u]}),t[4]=l,t[5]=d);let f;t[6]===a?f=t[7]:(f=a?(0,A.jsx)(r,{id:`rppgXF`}):(0,A.jsx)(r,{id:`-K0AvT`}),t[6]=a,t[7]=f);let p;t[8]!==a||t[9]!==c||t[10]!==f?(p=(0,A.jsx)(s,{variant:`outline`,onClick:c,disabled:a,"aria-describedby":`settings-account-disconnect-caveat`,"data-testid":`settings-account-disconnect`,children:f}),t[8]=a,t[9]=c,t[10]=f,t[11]=p):p=t[11];let m;t[12]!==d||t[13]!==p?(m=(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[d,p]}),t[12]=d,t[13]=p,t[14]=m):m=t[14];let h;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(h=(0,A.jsx)(`p`,{id:`settings-account-disconnect-caveat`,className:`text-muted-foreground text-1sm`,"data-testid":`settings-account-disconnect-caveat`,children:(0,A.jsx)(r,{id:`msOK6I`})}),t[15]=h):h=t[15];let g;t[16]===o?g=t[17]:(g=o?(0,A.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,"data-testid":`settings-account-disconnect-error`,children:o}):null,t[16]=o,t[17]=g);let _;return t[18]!==m||t[19]!==g?(_=(0,A.jsxs)(`div`,{className:`space-y-2 rounded-md border p-3`,"data-testid":`settings-account-connected`,children:[m,h,g]}),t[18]=m,t[19]=g,t[20]=_):_=t[20],_}function R(e){let t=(0,C.c)(6),{login:n,host:i}=e,a;t[0]!==i||t[1]!==n?(a=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`bc7aCh`,values:{host:i,login:n}})}),t[0]=i,t[1]=n,t[2]=a):a=t[2];let o;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`UcTm1A`,components:{0:(0,A.jsx)(`code`,{translate:`no`}),1:(0,A.jsx)(`code`,{translate:`no`})}})}),t[3]=o):o=t[3];let s;return t[4]===a?s=t[5]:(s=(0,A.jsx)(`div`,{className:`rounded-md border p-3`,"data-testid":`settings-account-gh-cli`,children:(0,A.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[a,o]})}),t[4]=a,t[5]=s),s}function z(e){let t=(0,C.c)(5),{onConnect:n}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,A.jsx)(`div`,{className:`text-sm font-medium`,children:(0,A.jsx)(r,{id:`S33tz3`})}),t[0]=i):i=t[0];let a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,A.jsxs)(`div`,{className:`min-w-0`,children:[i,(0,A.jsx)(`p`,{className:`text-muted-foreground text-1sm`,children:(0,A.jsx)(r,{id:`9djC8C`})})]}),t[1]=a):a=t[1];let o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,A.jsx)(r,{id:`5lWFkC`}),t[2]=o):o=t[2];let c;return t[3]===n?c=t[4]:(c=(0,A.jsx)(`div`,{className:`rounded-md border p-3`,"data-testid":`settings-account-disconnected`,children:(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[a,(0,A.jsx)(s,{onClick:n,"data-testid":`settings-account-connect`,children:o})]})}),t[3]=n,t[4]=c),c}export{M as AccountSection};
|