@inkeep/open-knowledge 0.89.10-beta.0 → 0.89.10-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{cli-DuTQpnfi.mjs → cli-C03YMRUU.mjs} +6 -6
- package/dist/cli.mjs +1 -1
- package/dist/constants-DNfL8lwk.mjs +1 -0
- package/dist/{dist-CLk9BDyE.mjs → dist-B-QQMMgD.mjs} +1 -1
- package/dist/{dist-BNdZzjgr.mjs → dist-D8yGS418.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{init-CXy1X9eP.mjs → init-BvIbEDs4.mjs} +2 -2
- package/dist/init-D4v4GLkU.mjs +1 -0
- package/dist/{launch-json-removal-B7vVCFBV.mjs → launch-json-removal-CiHdhK1s.mjs} +1 -1
- package/dist/{loader-BHK1kqxP.mjs → loader-7-Yt62LP.mjs} +1 -1
- package/dist/loader-kjUsg68e.mjs +1 -0
- package/dist/{open-browser-DzU6eS0X.mjs → open-browser-Dst9YzFG.mjs} +1 -1
- package/dist/{preview-DEG83Uxb.mjs → preview-5yFLE8l9.mjs} +1 -1
- package/dist/preview-CKtA1q7r.mjs +1 -0
- package/dist/public/assets/{AccountSection-BqL4s6YP.js → AccountSection-GhpA_vE7.js} +1 -1
- package/dist/public/assets/{ActivityModeContent-C42kiKB-.js → ActivityModeContent-CiqMEKKl.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-D4OE9whB.js → AddPropertiesButton-2HTeEJ0n.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-CDc5mtZ-.js → AgentDiffPane-CJKHGDSw.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-CRY017gc.js → AttachmentsSection-D9gkolej.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-B3ERDnwN.js → CodeMirrorPropInput-DBHubbES.js} +1 -1
- package/dist/public/assets/{ContentRulesSection-BZZ0uRpp.js → ContentRulesSection-r73qZOuv.js} +1 -1
- package/dist/public/assets/{DocumentContext-tjCBs5iM.js → DocumentContext-x8kJBlfU.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-DTSzp44_.js → EditorModeToggle-gXRKkWXq.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-CEo-k4K-.js → ExcalidrawDocEditor-Db9ulKie.js} +1 -1
- package/dist/public/assets/FeedbackForm-DVShKkg2.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-CyHoUxuA.js → ImportSkillDialog-C8AmQHA7.js} +1 -1
- package/dist/public/assets/{LinkPreviewsSection-CO7oBdpg.js → LinkPreviewsSection-B13jMLRF.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-BLMM0YXw.js → LintConfigEditor-BCzH0dq8.js} +1 -1
- package/dist/public/assets/{LintingSection-CHxHEOFS.js → LintingSection-CTa17foR.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-CB9-uy7m.js +1 -0
- package/dist/public/assets/{ManagedArtifactProperties-CAW43s3B.js → ManagedArtifactProperties-CTxkYZP6.js} +1 -1
- package/dist/public/assets/{Mermaid-BcowK1bP.js → Mermaid-DBaeo_-B.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-w4VlJz4i.js → MermaidDocEditor-BzxgQ4MO.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-sT8H1jm9.js → NetworkAccessSection-Dl6Qv49M.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-CR3oGERe.js → PropertyDisplayRow-BtTHsGAK.js} +1 -1
- package/dist/public/assets/{PublishToGitHubDialog-D5vpuxK-.js → PublishToGitHubDialog-Bb4ijH4p.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-Bq_G5vOn.js → SchemaConfigEditor-DXmO0CbK.js} +1 -1
- package/dist/public/assets/{SearchSection-DP2To-By.js → SearchSection-DXG3LSbk.js} +1 -1
- package/dist/public/assets/{SessionsHost-CiBXwe8A.js → SessionsHost-BDttGwT4.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-Wm7ffqsk.js → SettingsDialogBody-BAqJ12wn.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-Biq8DZrB.js → ShareReceiveMissDialog-D5NDn5r5.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-BUHQ4HKP.js → SkillToolbarControls-CmaCgQYO.js} +1 -1
- package/dist/public/assets/{SourceEditor-CYABPG6-.js → SourceEditor-CJ8-JXTZ.js} +1 -1
- package/dist/public/assets/{SyncSection-B55HJey_.js → SyncSection-C6IXtWzM.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-D92whmoD.js → SyncStatusBadge-C6xvIMos.js} +1 -1
- package/dist/public/assets/{TerminalSection-Cot3kZ1b.js → TerminalSection-XUg9zrYh.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-Bk3GZdT3.js → TerminalWindowApp-DjaOaIzB.js} +1 -1
- package/dist/public/assets/{TextDocEditor-Cmjge0ed.js → TextDocEditor-pSMZm_5Q.js} +1 -1
- package/dist/public/assets/{ThreadView-BdsRBXxP.js → ThreadView-myKHFoPr.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-Cmp2spQg.js → TimelineDiffPane-B1OKpBFc.js} +1 -1
- package/dist/public/assets/{client-version-A-GxukuD.js → client-version-CpekaFGz.js} +1 -1
- package/dist/public/assets/{comment-chips-CHaOUkXI.js → comment-chips-BDzvjQ4K.js} +1 -1
- package/dist/public/assets/{config-provider-VNO-8pnC.js → config-provider-Df28Kak3.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-BKTm511k.js → doc-undo-manager-BCMSQDX5.js} +1 -1
- package/dist/public/assets/{index-C1ZPNUde.js → index-DRgcv88i.js} +7 -7
- package/dist/public/assets/{lint-plugins-B2-SsSEw.js → lint-plugins-dBnVRuSg.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-dpOE8895.js → pending-receive-nav-store-CdyRiJN-.js} +1 -1
- package/dist/public/assets/{preferred-session-events-Hghttr98.js → preferred-session-events-DBfdnf0j.js} +1 -1
- package/dist/public/assets/{progress-CZuFzG86.js → progress-9gaUiKfZ.js} +1 -1
- package/dist/public/assets/{selection-context-x0Smfuvg.js → selection-context-DUSCI80-.js} +1 -1
- package/dist/public/assets/{src-DbOdApPx.js → src-BbEXTHkl.js} +1 -1
- package/dist/public/assets/{telemetry-impl-BvyaF4rq.js → telemetry-impl-z0X9sR1X.js} +1 -1
- package/dist/public/assets/{telemetry-startup-D9H-pijT.js → telemetry-startup-B1BH1LrL.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-OTRAtOce.js → typing-burst-detector-CzFzN6q0.js} +1 -1
- package/dist/public/assets/{use-activity-panel-D_1FtfiY.js → use-activity-panel-B3D1e4pV.js} +1 -1
- package/dist/public/assets/{use-open-skill-DJfSnwuI.js → use-open-skill-DoMflE0-.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-BjIU3d8F.js → use-terminal-enabled-DF6JNU1j.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-DvwEPALr.js → use-timeline-entry-diff-DzUebDea.js} +1 -1
- package/dist/public/index.html +20 -20
- package/dist/{registry-probes-zHczfZFZ.mjs → registry-probes-BYcJ_XTR.mjs} +1 -1
- package/dist/{removal-file-path-7-MdAEIS.mjs → removal-file-path-DDK0L6F5.mjs} +1 -1
- package/dist/{repair-launch-json-BOfweiWp.mjs → repair-launch-json-Bw89DSMn.mjs} +1 -1
- package/dist/{repair-mcp-configs-DIXgisAC.mjs → repair-mcp-configs-CI3XggBz.mjs} +1 -1
- package/dist/src-08vaMIJd.mjs +1 -0
- package/dist/{src-CrS-edQZ.mjs → src-DQJ0Rzwf.mjs} +1 -1
- package/dist/{start-CLJRdzjn.mjs → start-DrSKWujU.mjs} +3 -3
- package/dist/start-Gt6j5VXl.mjs +1 -0
- package/package.json +4 -4
- package/dist/constants-C3jlSnWU.mjs +0 -1
- package/dist/init-Bh7tibtK.mjs +0 -1
- package/dist/loader-CQOeIQS4.mjs +0 -1
- package/dist/preview-CBEyzv-I.mjs +0 -1
- package/dist/public/assets/FeedbackForm-JgP998Pr.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-CohT34HK.js +0 -1
- package/dist/src-k7CfDLlv.mjs +0 -1
- package/dist/start-CN8XT_VE.mjs +0 -1
|
@@ -2166,7 +2166,7 @@ tags: [lore, history]
|
|
|
2166
2166
|
`}}},q6=Object.keys(K6);function J6(e){return e&&K6[e]||K6[YSt]}function XSt(e){return typeof e==`string`&&q6.includes(e)}function Y6(e){return XSt(e)?e:void 0}function ZSt(e){let t=e.trim(),n=(/^([^.!?]+[.!?])/.exec(t)?.[1]??t).trim();return n.length<=140?n:`${n.slice(0,137)}…`}function QSt(){return q6.map(e=>{let t=K6[e];return{id:t.id,name:t.name,description:t.description,defaultSubfolder:t.defaultSubfolder,folders:t.folders.map(e=>({path:e.path,summary:e.uiSummary??ZSt(e.description)})),entryCounts:$St(t)}})}function $St(e){let t=e.folders.length,n=0;for(let t of e.folders)n+=1+(t.extraTemplates?.length??0);return n+=e.rootFiles?Object.keys(e.rootFiles).length:0,{files:n,folders:t}}const eCt=`frontmatter.yml`;function tCt(e){let t=[];t.push(`title: ${X6(e.title)}`),t.push(`description: ${X6(e.description)}`),t.push(`tags:`);for(let n of e.tags)t.push(` - ${X6(n)}`);return`${t.join(`
|
|
2167
2167
|
`)}\n`}function X6(e){return e===``?`""`:/[:#\n"'\\]|^\s|\s$/.test(e)?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e}function nCt(e,t){if(t.rootFiles?.[e]!==void 0)return t.rootFiles[e];let n=/^(.+)\/\.ok\/frontmatter\.yml$/.exec(e);if(n){let e=t.folders.find(e=>e.path===n[1]);return e?tCt(e):void 0}let r=/^(.+)\/\.ok\/templates\/([^/]+)\.md$/.exec(e);if(r){let e=r[2]??``;return t.templates[e]}}async function rCt(e,t={}){let n=Date.now(),r=K(t.projectDir??process.cwd()),i=J6(t.packId??`knowledge-base`),a=0,o=[],s=[];for(let t of e.created)try{let e=WSt(r,t.path);s.push({entry:t,absPath:e})}catch(e){o.push({path:typeof t.path==`string`?t.path:String(t.path),error:e instanceof G6||e instanceof Error?e.message:String(e)})}for(let{entry:e,absPath:t}of s.filter(e=>e.entry.kind===`folder`))try{Fs(t,{recursive:!0}),a+=1}catch(t){o.push({path:e.path,error:t instanceof Error?t.message:String(t)})}for(let{entry:e,absPath:t}of s.filter(e=>e.entry.kind===`file`)){let n=e.template??e.path,r=nCt(n,i);if(r===void 0){o.push({path:e.path,error:`No content template registered for template id "${n}" in pack "${i.id}"`});continue}if(!q(t))try{zV(t,r,{encoding:`utf-8`,flag:`wx`}),a+=1}catch(t){o.push({path:e.path,error:t instanceof Error?t.message:String(t)})}}let c=await HSt(r,i.id);if(!(`refusal`in U6(r))){let e=new Set(L1(r).map(e=>e.name));for(let{name:t}of H6(i.id)){let n=q(W(r,`.ok`,`skills`,t,`SKILL.md`));!e.has(t)&&!n&&o.push({path:t,error:`skill source could not be authored`})}}let l=[];try{l=JSt(r,i.requiredPlugins??[])}catch(e){o.push({path:`.ok/${Hq}`,error:`could not enable required plugin(s): ${e instanceof Error?e.message:String(e)}`})}return{applied:a,errors:o,durationMs:Date.now()-n,packSkillsInstalled:c.editors,packSkillConflicts:c.conflicts,pluginsEnabled:l}}function iCt(e){return`${e}/.ok/frontmatter.yml`}function aCt(e,t){return`${e}/.ok/templates/${t}.md`}function oCt(e,t){if(!e)return``;let n=e.trim();if(n===``||n===`.`||n===`./`)return``;if(n.startsWith(`/`))throw new G6(`rootDir must be relative to the project directory, got: ${e}`);let r=n.replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``);if(r.split(`/`).some(e=>e===`..`))throw new G6(`rootDir must not contain '..' segments, got: ${e}`);return WSt(t,r),r}function sCt(e,t){return e===``?t:`${e}/${t}`}async function cCt(e={}){let t=K(e.projectDir??process.cwd());if(!e.skipPrerequisite&&!ls(t))throw new W6(`No ${p} found at ${t}. Run \`${d()} init\` first to scaffold the tool config.`);let n=oCt(e.rootDir,t),r=J6(e.packId??`knowledge-base`),i=[],a=[],o=[];if(n!==``){let e=W(t,n);q(e)?a.push({path:n,reason:`already-exists`}):i.push({path:n,kind:`folder`})}for(let e of r.folders){let s=sCt(n,e.path),c=W(t,s);q(c)?a.push({path:s,reason:`already-exists`}):i.push({path:s,kind:`folder`});let l=`${s}/.ok`,u=W(t,l);q(u)?a.push({path:l,reason:`already-exists`}):i.push({path:l,kind:`folder`});let d=`${l}/${eCt}`,f=W(t,d);q(f)?a.push({path:d,reason:`already-exists`}):i.push({path:d,kind:`file`,template:iCt(e.path)});let p=`${l}/templates`,m=W(t,p);q(m)?a.push({path:p,reason:`already-exists`}):i.push({path:p,kind:`folder`});let h=[e.starterTemplate,...e.extraTemplates??[]];for(let n of h){let s=`${p}/${n}.md`,c=W(t,s);if(q(c)){a.push({path:s,reason:`already-exists`});continue}if(r.templates[n]===void 0){let t=n===e.starterTemplate;o.push(t?`No starter template body registered for "${n}" in pack "${r.id}". The folder will land without a pre-selected template.`:`No body registered for extra template "${n}" in pack "${r.id}". The folder will land without that optional variant.`);continue}i.push({path:s,kind:`file`,template:aCt(e.path,n)})}}if(r.rootFiles)for(let e of Object.keys(r.rootFiles)){let r=sCt(n,e),o=W(t,r);q(o)?a.push({path:r,reason:`already-exists`}):i.push({path:r,kind:`file`,template:e})}let s=H6(r.id),c=s.length>0?U6(t):null,l=c!==null&&`refusal`in c?c.refusal:void 0,u=s.length>0?L1(t):[],f=new Map(u.map(e=>[e.name,W(t,e.dir)])),m=s.length>0?y0(W(t,...lo)):null,h=s.map(({name:e})=>{let n=W(t,`.ok`,`skills`,e),i=zSt[e],a=i===void 0?null:f.get(i)??(q(W(t,`.ok`,`skills`,i,`SKILL.md`))?W(t,`.ok`,`skills`,i):null),o=f.get(e)??a??(q(W(n,`SKILL.md`))?n:null),s=f.has(e)||a===null?e:i,c=o!==null&&m!==null&&BSt(r.id,s,o,m)===`foreign`;return{name:e,pending:o===null&&l===void 0,...c?{conflict:!0}:{}}}),g=(r.requiredPlugins??[]).map(e=>({id:e,pending:!qSt(t,e)}));return{created:i,skipped:a,warnings:o,...h.length>0?{packSkills:h}:{},...g.length>0?{requiredPlugins:g}:{},...h.length>0&&l!==void 0?{packSkillHomeRefusal:l}:{}}}const lCt=[`These are patterns to adapt to your domain, not a layout to copy verbatim.`,"To build a variant: create your own folders (via `write` or your editor) and reuse only the ideas that fit.","To adopt this pack as-is: re-run without `--dry-run`."].join(`
|
|
2168
2168
|
`);function uCt(e){return[e.starterTemplate,...e.extraTemplates??[]].join(`, `)}function dCt(e){let t=[`Pack: ${e.name} — ${e.description}`,``,lCt,``];t.push(`Layout & rationale:`);for(let n of e.folders)t.push(` ${n.path}/ — ${n.title}`),t.push(` why: ${n.description}`),t.push(` templates: ${uCt(n)}`);let n=e.rootFiles?Object.keys(e.rootFiles):[];return n.length>0&&t.push(``,`Root files: ${n.join(`, `)}`),t.join(`
|
|
2169
|
-
`)}function fCt(e){let{contentDir:t,checkLocalOpSecurity:n}=e;async function r(e,r){if(!n(e,r,{handler:`seed-plan`}))return;if(e.method!==`GET`){Q(r,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let i=new URL(e.url??`/`,`http://localhost`),a=i.searchParams.get(`rootDir`)??void 0,o=i.searchParams.get(`packId`),s=Y6(o);if(o!==null&&o!==``&&s===void 0){Q(r,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${o}" is not registered.`});return}try{let e=await cCt({projectDir:t,rootDir:a,packId:s});$(r,200,vee,{plan:e},{handler:`seed-plan`})}catch(e){if(e instanceof W6){Q(r,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof G6){Q(r,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}Q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let i=XQ(Uie,async(e,n,r)=>{let i=r.plan;if(!i||typeof i!=`object`){Q(n,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let a=i,o=r.packId,s=Y6(o);if(typeof o==`string`&&o.length>0&&s===void 0){Q(n,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${o}" is not registered.`});return}try{let e=await rCt(a,{projectDir:t,packId:s});$(n,200,we,{result:e},{handler:`seed-apply`})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>n(e,t,{handler:`seed-apply`})}),a=XQ(lee,async(e,n,r)=>{let i=Y6(r.packId);if(i===void 0){Q(n,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-install-pack-skill`,detail:`Pack id "${r.packId}" is not registered.`});return}try{let e=await USt(t,i);$(n,200,Pt,e,{handler:`seed-install-pack-skill`})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Failed to install pack skill.`,{handler:`seed-install-pack-skill`,cause:e})}},{handler:`seed-install-pack-skill`,method:`POST`,preBodyGate:(e,t)=>n(e,t,{handler:`seed-install-pack-skill`})});async function o(e,t){if(n(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}$(t,200,_i,{packs:QSt()},{handler:`seed-packs`})}}return VQ({"/api/seed/plan":r,"/api/seed/apply":i,"/api/seed/install-pack-skill":a,"/api/seed/packs":o},{mutating:[`/api/seed/apply`,`/api/seed/install-pack-skill`]})}const Z6=`share-construct-url`;function pCt(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function mCt(e,t,n,r,i){return`https://${e}/${t}/${n}/blob/${encodeURIComponent(r)}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function hCt(e,t,n,r,i){let a=`https://${e}/${t}/${n}/tree/${encodeURIComponent(r)}`;return i===``?a:`${a}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function Q6(e,t){let n=t?.branchExists,r=t?.kind,i=t?.freshness;Y(`share`).info({action:`construct-url`,result:e,...n===void 0?{}:{branchExists:n},...r===void 0?{}:{kind:r},...i===void 0?{}:{freshness:i}},`share action`)}async function gCt(e,t,n,r){try{let{git:i}=LG(e,{timeoutMs:5e3,credentialConfig:[]}),a=`refs/remotes/origin/${t}`;await i.raw([`rev-parse`,`--verify`,a]);let o=on([n===``?`.`:n]),[s,c,l]=await Promise.all([i.raw([`cat-file`,`-e`,`${a}:${n}`]).then(()=>!0).catch(()=>!1),i.raw([`diff`,`--name-only`,a,...o]),i.raw([...Fq,...o])]);return s?c.trim()!==``||l.trim()!==``?`stale`:`current`:r===`folder`&&c.trim()===``&&l.trim()===``?`empty`:`absent`}catch(e){let t=B3(e);Y(`share`).warn({action:`freshness-probe-failed`,kind:r,error:t},`[share] freshness probe failed; omitting freshness`);return}}const $6=`share-target-status`;function _Ct(e,t){for(let n of e)if(n.from===t){if(n.status.startsWith(`R`))return{verdict:`renamed`,renamedTo:n.to};if(n.status===`D`)return{verdict:`deleted`}}return{verdict:`deleted`}}function vCt(e,t){let n=t.endsWith(`/`)?t:`${t}/`,r=new Set;for(let t of e){if(!t.from.startsWith(n)||!t.status.startsWith(`R`))continue;let e=t.from.slice(n.length);t.to.endsWith(`/${e}`)?r.add(t.to.slice(0,t.to.length-e.length-1)):r.add(`\0ambiguous`)}let i=r.size===1?[...r][0]:void 0;return i!==void 0&&i!==`\0ambiguous`?{verdict:`renamed`,renamedTo:i}:{verdict:`deleted`}}async function yCt(e,t,n,r,i){let a=Y(`share`),o=e=>(a.info({action:`target-status`,verdict:e.verdict,kind:r},`target-status verdict`),e),{git:s}=LG(e,i.skipFetch?{credentialConfig:[]}:{timeoutMs:i.fetchTimeoutMs??15e3,credentialConfig:i.credentialConfig});if(!i.skipFetch)try{await s.raw([`fetch`,`origin`,t])}catch(e){return a.warn({action:`target-status`,kind:r,error:B3(e)},`target-status fetch failed`),o({verdict:`unknown`})}let c=`origin/${t}`;try{if(await s.raw([`cat-file`,`-e`,`${c}:${n}`]).then(()=>!0).catch(()=>!1)){let t=await s.raw([`cat-file`,`-e`,`HEAD:${n}`]).then(()=>!0).catch(()=>!1),r=q(W(e,n));return o(t&&!r?{verdict:`changed-locally`}:{verdict:`on-origin`})}let t=(await s.raw([`log`,`-1`,`--format=%H`,c,...on([n===``?`.`:n])])).trim();if(t===``)return o({verdict:`never-on-branch`});let i=await zq(s,[`diff-tree`,`-M`,`-r`,`--no-commit-id`,`--name-status`,`${t}^1`,t]),a=r===`folder`?vCt(i,n):_Ct(i,n);return a.verdict===`renamed`&&!await s.raw([`cat-file`,`-e`,`${c}:${a.renamedTo}`]).then(()=>!0).catch(()=>!1)?o({verdict:`deleted`}):o(a)}catch(e){return a.warn({action:`target-status`,kind:r,error:B3(e)},`target-status detection failed`),o({verdict:`unknown`})}}function bCt(e){let{projectDir:t,contentDir:n,log:r,checkLocalOpSecurity:i,localOpCliArgs:a,localOpGuard:o,getSyncEngine:s,resolveCredentialConfig:c,toGitRelativePath:l}=e,u=e.declaredGitHubHosts??C6(),d=f.resolve({host:a===void 0?void 0:{cliArgs:a}}),p=XQ(hn,async(e,r,i)=>{try{if(!t){Q6(`no-remote`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`no-remote`},{handler:Z6});return}let e=i.kind===`doc`?i.docPath:i.folderPath;if(!pCt(e,i.kind)){Q6(`invalid-path`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`invalid-path`},{handler:Z6});return}let a=xxt(t);if(a===null){if(T6(t,u).kind===`no-remote`){Q6(`no-remote`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`no-remote`},{handler:Z6});return}Q6(`detached-head`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`detached-head`},{handler:Z6});return}let o=T6(t,u);if(o.kind===`no-remote`){Q6(`no-remote`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`no-remote`},{handler:Z6});return}if(o.kind===`non-github`){Q6(`non-github-remote`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`non-github-remote`},{handler:Z6});return}if(!Bxt(t,a)){Q6(`branch-not-on-origin`,{branchExists:!1,kind:i.kind}),$(r,200,Oa,{ok:!1,error:`branch-not-on-origin`,branch:a},{handler:Z6});return}let s=l(t,n);if(s===null)throw Error(`content dir is not contained within the project dir`);let c=s===``?e:e===``?s:`${s}/${e}`,d;d=i.kind===`doc`?mCt(o.host,o.owner,o.repo,a,c):hCt(o.host,o.owner,o.repo,a,c);let f;try{let e=s===``?0:zr(hCt(o.host,o.owner,o.repo,a,s)).targetSegments.length;f=`https://openknowledge.ai/d/${Dn(d,e)}`}catch(e){if(!(e instanceof Gt))throw e;Q6(`unsupported-share-url`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`unsupported-share-url`},{handler:Z6});return}let p=await gCt(t,a,c,i.kind);Q6(`ok`,{branchExists:!0,kind:i.kind,freshness:p}),$(r,200,Oa,{ok:!0,shareUrl:f,sharedUrl:d,branch:a,freshness:p},{handler:Z6})}catch(e){Q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Z6,cause:e})}},{handler:Z6,method:`POST`,preBodyGate:(e,t)=>i(e,t,{handler:Z6})});function m(e,t,n){let r=e.split(`/`),i=t.split(`/`);if(n>=r.length||n>=i.length)return{verdict:`unknown`};for(let e=0;e<n;e+=1)if(r[e]!==i[e])return{verdict:`unknown`};return{verdict:`renamed`,renamedTo:i.slice(n).join(`/`)}}let h=XQ(I,async(e,n,r)=>{try{if(!t){Q(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:$6});return}if(!nyt(r.path,r.kind)){Q(n,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:$6});return}let e=await yCt(t,r.branch,r.path,r.kind,{credentialConfig:await c()}),i=e.verdict!==`renamed`||r.contentRootDepth===void 0?e:m(r.path,e.renamedTo,r.contentRootDepth);$(n,200,Ote,i,{handler:$6})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:$6,cause:e})}},{handler:$6,method:`POST`,preBodyGate:(e,t)=>i(e,t,{handler:$6})});async function g(e){let t=d.spawn(e,process.env);if(`refused`in t)throw Error(t.refused);return await new Promise((e,n)=>{let i=Cc(t.command,t.args,eH({...$V,env:t.env})),a=!1,o=setTimeout(()=>{if(!a){a=!0;try{i.kill(`SIGKILL`)}catch{}i.stdout.destroy(),i.stderr.destroy(),n(Error(`share subprocess timed out after ${Vxt}ms`))}},Vxt);o.unref?.();let s=[],c=[];i.stdout.on(`data`,e=>s.push(e)),i.stderr.on(`data`,e=>c.push(e)),i.on(`close`,t=>{if(a)return;a=!0,clearTimeout(o);let n=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=j6(Buffer.concat(c).toString(`utf-8`)).slice(0,500);r.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:n,code:t})}),i.on(`error`,e=>{a||(a=!0,clearTimeout(o),n(e))})})}return VQ({"/api/share/construct-url":p,"/api/share/target-status":h,"/api/share/publish/owners":XQ(L,async(e,t)=>{if(!o.tryAcquire(`/api/share/publish/owners`)){Q(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:E6,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await g([`share`,`owners`,`--json`]),n=Wxt(k6(e));A6(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),$(t,200,Cee,n,{handler:E6})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E6,cause:e})}finally{o.release(`/api/share/publish/owners`)}},{handler:E6,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>i(e,t,{handler:E6})}),"/api/share/publish/name-check":XQ(L,async(e,t)=>{let n=ZU(e),r=n.get(`owner`)??``,i=n.get(`name`)??``;if(!Uxt(r)||!Hxt(i)){Q(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:D6});return}if(!o.tryAcquire(`/api/share/publish/name-check`)){Q(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:D6,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await g([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Kxt(k6(e));A6(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),$(t,200,Aee,n,{handler:D6})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:D6,cause:e})}finally{o.release(`/api/share/publish/name-check`)}},{handler:D6,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>i(e,t,{handler:D6})}),"/api/share/publish":XQ(Iee,async(e,n,i)=>{if(!t){A6(`publish-create`,`no-project`),$(n,200,Or,{ok:!1,error:`no-project`},{handler:O6});return}if(!Uxt(i.owner)||!Hxt(i.name)){Q(n,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:O6});return}if(!o.tryAcquire(`/api/share/publish`)){Q(n,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:O6,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,i.owner,`--name`,i.name,`--visibility`,i.visibility,`--project-dir`,t,`--json`];i.description!==void 0&&i.description.length>0&&e.push(`--description`,i.description);let{stdout:a}=await g(e),o=Yxt(k6(a));A6(`publish-create`,o.ok?`ok`:o.error),o.ok&&s?.()?.refreshRemote().catch(e=>{r.warn({err:e},`[share] post-publish refreshRemote failed`)}),$(n,200,Or,o,{handler:O6})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:O6,cause:e})}finally{o.release(`/api/share/publish`)}},{handler:O6,method:`POST`,preBodyGate:(e,t)=>i(e,t,{handler:O6})})})}function xCt(e){let{contentDir:t,projectDir:n,homeDirOverride:r,skillsHome:i,isSafeDocName:a,commentService:o,enumerateInstalledSkillsCached:s,checkLocalOpSecurity:c}=e,l=XQ(L,async(e,a)=>{try{let e=My(n??t),o=K(n??t),c=await z1(i),l=s({projectDir:e,...r===void 0?{}:{home:r}}),u=new Set(L1(t).map(e=>e.name)),d=new Set(c.map(e=>e.name)),f={...l,skills:l.skills.filter(t=>Kc(t.provenance,e)&&!(t.provenance.scope===`project`?u.has(t.name):d.has(t.name))).map(e=>Sse(e.provenance,e.home,o)?{...e,outsideProject:!0}:e)};$(a,200,_r,f,{handler:`skills-installed`})}catch(e){Q(a,500,`urn:ok:error:internal-server-error`,`Failed to enumerate installed skills.`,{handler:`skills-installed`,cause:e})}},{handler:`skills-installed`,method:`GET`,skipBodyParse:!0}),u={"/api/comment-counts":XQ(L,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`prefix`),i=n.searchParams.get(`docNames`);if(r===null&&i===null){Q(t,400,`urn:ok:error:invalid-request`,`Missing docNames or prefix parameter.`,{handler:`comment-counts`});return}let s={};if(r!==null){let e=r.trim();if(e!==``&&!a(e)){Q(t,400,`urn:ok:error:invalid-request`,`Invalid prefix parameter.`,{handler:`comment-counts`});return}s=Object.fromEntries(await o.countThreads({prefix:e}))}else{let e=(i??``).split(`,`).map(e=>e.trim()).filter(e=>e!==``&&a(e));s=Object.fromEntries(await o.countThreads({docNames:e}))}$(t,200,gte,{counts:s},{handler:`comment-counts`})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Failed to read comment counts.`,{handler:`comment-counts`,cause:e})}},{handler:`comment-counts`,method:`GET`,skipBodyParse:!0}),"/api/skills/installed":l,"/api/templates":XQ(L,UQ(async(e,n)=>{let r=await c_t(K(t)),i=r.templates.map(e=>{let{scope:t,...n}=e;return n});$(n,200,Zt,{templates:i,truncated:r.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),"/api/skill/install-state":XQ(L,UQ(async(e,t)=>{let n=await Fot(Ys());$(t,200,lre,{...n},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>c(e,t,{handler:`skill-install-state`})})};return{paths:Object.keys(u),table:{resolve(e){let t=u[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1}}}const e8=new Map;function SCt(e){return e.kind===`git`?`git\n${e.url}\n${e.subpath??``}`:e.kind===`well-known`?`wk\n${e.origin}\n${e.skill}`:`local\n${e.path}`}function CCt(e){for(let[t,n]of e8)n.expiresAt>e||(e8.delete(t),n.fetched.then(e=>e.cleanup()).catch(()=>{}))}async function wCt(e){return e.kind===`local`?PE(e):ECt(SCt(e),()=>PE(e))}async function TCt(e){return e.kind!==`git`||e.subpath?wCt(e):ECt(`listing\n${SCt(e)}`,()=>FE(e))}async function ECt(e,t){let n=Date.now();CCt(n);let r=e8.get(e);if(!r){let i=t();r={fetched:i,expiresAt:n+3e4},e8.set(e,r);let a=r;i.catch(()=>{e8.get(e)===a&&e8.delete(e)})}let i=await r.fetched;return{dir:i.dir,ref:i.ref,cleanup:()=>{}}}const DCt=Y(`skills-leaderboard`),OCt=6e5;let t8=null;async function kCt(e=24,t={}){let n=t.now??Date.now(),r=t.fetchImpl??fetch;if(t8&&n-t8.at<OCt)return t8.data.slice(0,e);try{let t=await r(`https://www.skills.sh/`,{headers:{"user-agent":`open-knowledge (+skills discovery)`,RSC:`1`},signal:AbortSignal.timeout(8e3),redirect:`manual`});if(!t.ok)throw Error(`HTTP ${t.status} ${t.statusText}`);let i=vPe(await t.text());if(i.length===0)throw Error(`parsed 0 skills (payload format may have changed)`);return t8={at:n,data:i},i.slice(0,e)}catch(t){return DCt.warn({err:t},`skills.sh leaderboard fetch failed — Discover falls back to topics`),t8?.data.slice(0,e)??[]}}const ACt=new Map;async function jCt(e,t={}){let n=t.now??Date.now(),r=t.fetchImpl??fetch,i=ACt.get(e);if(i&&n-i.at<OCt)return i.data;try{let t=await r(`https://www.skills.sh/${e}`,{headers:{"user-agent":`open-knowledge (+skills discovery)`},signal:AbortSignal.timeout(8e3),redirect:`manual`});if(!t.ok)throw Error(`HTTP ${t.status} ${t.statusText}`);let i=bPe(await t.text(),e);if(i.length===0)throw Error(`parsed 0 skills (page format may have changed)`);return ACt.set(e,{at:n,data:i}),i}catch(t){return DCt.warn({err:t,source:e},`skills.sh publisher page fetch failed — install counts unavailable`),i?.data??[]}}function MCt(e){let{log:t,skillsHome:n,projectDir:r,contentDir:i,resolveSkillDirForRead:a}=e;return{handleSkillsSearch:XQ(L,async(e,n)=>{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`q`)?.trim()??``;if(r.length<2){Q(n,400,`urn:ok:error:invalid-request`,`Search query must be at least 2 characters.`,{handler:`skills-search`});return}try{let e=await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(r)}&limit=30`,{signal:AbortSignal.timeout(8e3)});if(e.ok){let t=nD(await e.json());$(n,200,mt,{results:t,backend:`skills.sh`,degraded:!1},{handler:`skills-search`});return}t.warn({status:e.status},`skills.sh search unavailable — falling back to GitHub topic search`)}catch(e){t.warn({err:e},`skills.sh search failed — falling back to GitHub topic search`)}try{let e=encodeURIComponent(`${r} topic:agent-skills`),i=await fetch(`https://api.github.com/search/repositories?q=${e}&per_page=30`,{signal:AbortSignal.timeout(8e3),headers:{Accept:`application/vnd.github+json`}});if(!i.ok){t.warn({status:i.status},`GitHub skill search fallback returned non-ok`),Q(n,502,`urn:ok:error:internal-server-error`,`Skill discovery is temporarily unavailable.`,{handler:`skills-search`,detail:`GitHub fallback returned ${i.status}.`});return}let a=ONe(await i.json());$(n,200,mt,{results:a,backend:`github-fallback`,degraded:!0},{handler:`skills-search`})}catch(e){Q(n,502,`urn:ok:error:internal-server-error`,`Skill discovery is temporarily unavailable.`,{handler:`skills-search`,cause:e})}},{handler:`skills-search`,method:`GET`,skipBodyParse:!0}),handleSkillsPopular:XQ(L,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=Number(n.searchParams.get(`limit`)),i=Number.isFinite(r)&&r>0?Math.min(Math.floor(r),60):24;try{let e=await kCt(i);$(t,200,mt,{results:e,backend:`skills.sh`,degraded:e.length===0},{handler:`skills-popular`})}catch(e){Q(t,502,`urn:ok:error:internal-server-error`,`Popular skills are temporarily unavailable.`,{handler:`skills-popular`,cause:e})}},{handler:`skills-popular`,method:`GET`,skipBodyParse:!0}),handleSkillsPublisher:XQ(L,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`source`)?.trim()??``;if(!/^[\w.-]+\/[\w.-]+$/.test(n)||n.includes(`..`)){Q(t,400,`urn:ok:error:invalid-request`,`source must be owner/repo.`,{handler:`skills-publisher`});return}try{let e=await jCt(n);$(t,200,mt,{results:e,backend:`skills.sh`,degraded:e.length===0},{handler:`skills-publisher`})}catch(e){Q(t,502,`urn:ok:error:internal-server-error`,`Publisher skills are temporarily unavailable.`,{handler:`skills-publisher`,cause:e})}},{handler:`skills-publisher`,method:`GET`,skipBodyParse:!0}),handleSkillsDetail:XQ(L,async(e,n)=>{let r=new URL(e.url??``,`http://localhost`),i=r.searchParams.get(`source`)?.trim()??``,a=r.searchParams.get(`name`)?.trim()??``;if(!i||!a){Q(n,400,`urn:ok:error:invalid-request`,`source and name are required.`,{handler:`skills-detail`});return}let o=Tse(i,a);if(!o){Q(n,400,`urn:ok:error:invalid-request`,`Unrecognized skill source.`,{handler:`skills-detail`});return}let{skillsUrl:s,sourceKind:c,sourceUrl:l}=o,u={},d=!1;try{let e=await fetch(s,{signal:AbortSignal.timeout(8e3)});e.ok&&(d=!0,u=DNe(await e.text()))}catch(e){t.warn({err:e,skillsUrl:s},`skills.sh detail fetch failed — degrading to repo link`)}$(n,200,pe,{title:u.title??a,description:u.description??``,image:u.image??null,skillsUrl:d?s:null,sourceKind:c,sourceUrl:l},{handler:`skills-detail`})},{handler:`skills-detail`,method:`GET`,skipBodyParse:!0}),handleSkillsPreview:XQ(L,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`source`)?.trim()??``,i=n.searchParams.get(`name`)?.trim()??``;if(!r){Q(t,400,`urn:ok:error:invalid-request`,`source is required.`,{handler:`skills-preview`});return}let a=null;try{a=await aD(r,i||void 0)}catch(e){if(e instanceof vE){Q(t,400,`urn:ok:error:invalid-request`,`Could not resolve source.`,{handler:`skills-preview`,cause:e});return}throw e}let o=a?.spec??ME(r);if(!o){Q(t,400,`urn:ok:error:invalid-request`,`Unrecognized preview source.`,{handler:`skills-preview`,detail:`Expected owner/repo, a git URL, a website source, or a local path.`});return}if(!w0(t,o,`skills-preview`))try{let e=await wCt(o),n=tD(e.dir);if(n.length===0){Q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-preview`});return}let a=n[0];if(i){let e=n.find(e=>e.name===i)??n.find(e=>XE(e.dir)?.name===i);if(!e){Q(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skills-preview`,detail:`"${i}" not among: ${n.map(e=>e.name).join(`, `)}.`});return}a=e}let s=ZE(a.dir);if(s){Q(t,400,`urn:ok:error:invalid-request`,`Skill bundle is too large.`,{handler:`skills-preview`,detail:s});return}let c=QE(a.dir);if(!c){Q(t,404,`urn:ok:error:not-found`,`SKILL.md unreadable in source.`,{handler:`skills-preview`});return}let l=OD(r),u=ePe(e.dir);$(t,200,Rn,{name:c.name,description:c.description,skillMd:c.skillMd,files:c.files.map(e=>({relPath:e.relPath,content:e.content})),plugin:l??void 0,pluginBundle:u??void 0},{handler:`skills-preview`})}catch(e){if(e instanceof vE){Q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-preview`,cause:e});return}Q(t,502,`urn:ok:error:internal-server-error`,`Preview is unavailable.`,{handler:`skills-preview`,cause:e})}},{handler:`skills-preview`,method:`GET`,skipBodyParse:!0}),handleSkillsDiscover:XQ(L,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`source`)?.trim()??``;if(!n){Q(t,400,`urn:ok:error:invalid-request`,`source is required.`,{handler:`skills-discover`});return}let r=iD(n);if(r){try{let e=await pNe(`https://${r.hostname}`);$(t,200,xne,{skills:e},{handler:`skills-discover`})}catch(e){if(e instanceof vE){Q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-discover`,cause:e});return}throw e}return}let i=ME(n);if(!i){Q(t,400,`urn:ok:error:invalid-request`,`Unrecognized source.`,{handler:`skills-discover`,detail:`Expected owner/repo, a git URL, a website source, or a local path.`});return}if(!w0(t,i,`skills-discover`))try{let e=tD((await TCt(i)).dir).map(e=>{let t=XE(e.dir);return{name:t?.name??e.name,description:t?.description??null}});$(t,200,xne,{skills:e},{handler:`skills-discover`})}catch(e){if(e instanceof vE){Q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-discover`,cause:e});return}Q(t,502,`urn:ok:error:internal-server-error`,`Discovery is unavailable.`,{handler:`skills-discover`,cause:e})}},{handler:`skills-discover`,method:`GET`,skipBodyParse:!0}),handleSkillsResolveRef:XQ(L,async(e,o)=>{let s=new URL(e.url??``,`http://localhost`),c=s.searchParams.get(`ref`)?.trim()??``,l=s.searchParams.get(`from`)?.trim()??``,u=s.searchParams.get(`scope`)?.trim()===`global`?`global`:`project`;if(!c||!We.test(c)||c.length>64){Q(o,400,`urn:ok:error:invalid-request`,`A valid ref is required.`,{handler:`skills-resolve-ref`});return}try{let e=e=>$(o,200,Jn,e,{handler:`skills-resolve-ref`});for(let t of[u,u===`project`?`global`:`project`]){let r=a(t,c);if(r!==null){e({kind:`local`,scope:t,name:c,dir:G(t===`project`?i:n,r).split(Cs).join(`/`)});return}}let s=u===`project`?r:n,d=l&&s?y0(W(s,...lo)).skills[l]:void 0;if(d?.source){let n=(await aD(d.source,c))?.spec??ME(d.source),r=n&&!(n.kind===`git`&&!RQ(n.url));if(n&&r){let r;try{let t=await FE(n);if(r=t.cleanup,tD(t.dir).map(e=>XE(e.dir)?.name??e.name).includes(c)){e({kind:`import`,source:d.source,ref:c,via:`source`});return}}catch(e){t.debug({err:e,ref:c,from:l,source:d.source},`resolve-ref: source rung unreachable, falling through to publisher`)}finally{r?.()}}}if(d?.publisher)try{let t=await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(c)}&limit=30`,{signal:AbortSignal.timeout(8e3)});if(t.ok){let n=nD(await t.json()).filter(e=>e.name===c&&e.publisher===d.publisher);if(n.length===1){let t=n[0];if(t){e({kind:`import`,source:t.source,ref:c,via:`publisher`});return}}}}catch(e){t.debug({err:e,ref:c,publisher:d.publisher},`resolve-ref: skills.sh unavailable, no publisher resolution`)}e({kind:`none`})}catch(e){Q(o,500,`urn:ok:error:internal-server-error`,`Could not resolve the reference.`,{handler:`skills-resolve-ref`,cause:e instanceof Error?e:Error(String(e))})}},{handler:`skills-resolve-ref`,method:`GET`,skipBodyParse:!0})}}function NCt(e){let{handleSkillsSearch:t,handleSkillsPopular:n,handleSkillsPublisher:r,handleSkillsDetail:i,handleSkillsPreview:a,handleSkillsDiscover:o,handleSkillsResolveRef:s}=MCt(e);return VQ({"/api/skills/search":t,"/api/skills/popular":n,"/api/skills/publisher":r,"/api/skills/detail":i,"/api/skills/preview":a,"/api/skills/discover":o,"/api/skills/resolve-ref":s},{mutating:[`/api/skills/preview`,`/api/skills/discover`,`/api/skills/resolve-ref`]})}function PCt(e){let{projectDir:t,contentDir:n,getPrincipal:r,hocuspocus:i,log:a,checkLocalOpSecurity:o,getSyncEngine:s,conflicts:c,serializeDoc:l,setBatchInProgress:u}=e;function d(e){let t={file:e.file,detectedAt:e.detectedAt,conflict:e.kind,docName:c.docNameOf(e),conflictKind:e.kind===`reconcile`&&e.reason===`stale-external-write`?`stale-external-write`:`git`};switch(e.kind){case`merge-native`:return t;case`working-tree`:return{...t,theirsSha:e.theirsSha,...e.baseSha===void 0?{}:{baseSha:e.baseSha}};case`reconcile`:return{...t,reason:e.reason};default:return t}}async function f(e,t){if(o(e,t,{handler:`sync-status`})){if(e.method!==`GET`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=s?.();if(!e){$(t,200,Ma,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),$(t,200,Ma,e.getStatus(),{handler:`sync-status`})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let p=XQ(fte,async(e,t,n)=>{let r=s?.();if(!r){Q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;$(t,202,Ane,{op:i},{handler:`sync-trigger`}),r.trigger(i).catch(e=>{a.error({err:e,op:i},`[sync] fire-and-forget trigger failed`)})},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>o(e,t,{handler:`sync-trigger`})?s?.()?!0:(Q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1}),m=XQ(Nre,async(e,t,n)=>{let r=s?.();if(!r){Q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-blocking`});return}if(r.getBlockingPaths().length===0){Q(t,409,`urn:ok:error:no-blocking-changes`,`No local changes are blocking a merge.`,{handler:`sync-resolve-blocking`});return}try{let e=r.getBlockingPaths(),n=await r.commitBlockingPaths();$(t,200,one,{action:`commit`,paths:e,...n===null?{}:{commitSha:n}},{handler:`sync-resolve-blocking`}),r.trigger(`sync`).catch(e=>{a.error({err:e},`[sync] resolve-blocking follow-up sync failed`)})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-resolve-blocking`,cause:e})}},{handler:`sync-resolve-blocking`,method:`POST`,preBodyGate:(e,t)=>o(e,t,{handler:`sync-resolve-blocking`})});async function h(e,t){if(o(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{$(t,200,Jne,{conflicts:c.list().map(d)},{handler:`sync-conflicts`})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let g=XQ(Jee,async(e,i,a)=>{let{file:o,strategy:s,content:l}=a,d=EQ(a,r),f;t&&(d.kind===`agent`||d.kind===`principal`)&&(f=yX(K(t,o),n),Bst(f,{writerId:d.writerId,displayName:d.displayName,colorSeed:d.colorSeed},Date.now(),3e3)),u?.(!0);try{await c.resolve(o,s,l),$(i,200,ore,{},{handler:`sync-resolve-conflict`})}catch(e){if(f&&Hst(f),e instanceof lK){Q(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`sync-resolve-conflict`});return}if(e instanceof ntt){Q(i,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-resolve-conflict`,detail:`This file has no tracked conflict — it may have been resolved by another session, or the path may be stale. Refresh the conflict list in the OpenKnowledge app before retrying.`,extensions:{file:e.file}});return}if(e instanceof WJ){let t=c.findByFile(e.file),n=t===void 0?VJ:BJ(t.kind,t.kind===`reconcile`?t.reason:void 0),r=e.refusal===`strategy-not-offered`;Q(i,422,`urn:ok:error:unresolved-conflict-markers`,r?`Strategy not offered for this conflict.`:`Resolution still contains conflict markers.`,{handler:`sync-resolve-conflict`,detail:r?`Strategy "${s}" is not offered for this conflict. Pick one of the strategies listed in resolutionOptions.`:"The submitted content still contains a `<<<<<<< … >>>>>>>` block. Resolve every region, or take one side wholesale with a strategy listed in resolutionOptions.",extensions:{file:e.file,refusal:e.refusal,resolutionOptions:n}});return}Q(i,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0,extensions:{file:o,strategy:s}})}finally{u?.(!1)}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>o(e,t,{handler:`sync-resolve-conflict`})});async function _(e,n){if(!o(e,n,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){Q(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!t){Q(n,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=r.searchParams.get(`file`);if(!a){Q(n,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(a.includes(`..`)||a.startsWith(`/`)){Q(n,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let s=c.findByFile(a);if(s===void 0){Q(n,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:a}});return}let u=s.kind===`reconcile`?s.reason:void 0,d=[...BJ(s.kind,u)],f=c.docNameOf(s)??cB(a),p=i.documents.get(f),m=e=>{$(n,200,Jre,{file:a,...e,conflict:s.kind,conflictKind:u===`stale-external-write`?`stale-external-write`:`git`,...u===void 0?{}:{reason:u},resolutionOptions:d},{handler:`sync-conflict-content`})},h=r.searchParams.get(`source`);switch(s.kind){case`reconcile`:{let e=h===`ytext`&&l?l(f):null;m({base:s.stages.base,ours:knt(s,e),theirs:s.stages.theirs,kind:`both-modified`});return}case`working-tree`:{let e=xA({baseDir:t,timeout:{block:15e3}});try{let n=async t=>{if(!t)return``;try{return await e.raw([`cat-file`,`blob`,t])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:a,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},r=await n(s.theirsSha),i=await n(s.baseSha),o=``,c=!1;if(p){let e=l?l(f):null;e!==null&&(o=e,c=!0)}else{jY(W(t,a),t,{allowShareableOkArtifact:mG});try{o=J(W(t,a),`utf-8`),c=!0}catch(e){if(QU(e)!==`ENOENT`)throw console.warn(JSON.stringify({event:`conflict-content-ours-read-failed`,file:a,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e;c=!1}}m({base:i,ours:o,theirs:r,kind:c?r.length===0?`modify-delete`:`both-modified`:`delete-modify`})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}case`merge-native`:{let e=xA({baseDir:t,timeout:{block:15e3}}),r=async t=>{try{return{present:!0,content:await e.raw([`show`,`:${t}:${a}`])}}catch(e){let n=e instanceof Error?e.message:String(e);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:t,file:a,detail:n,handler:`sync-conflict-content`})),e;return{present:!1}}};try{let[e,t,n]=await Promise.all([r(1),r(2),r(3)]),i=e.present?e.content:``,a=n.present?n.content:``,o=t.present&&n.present?`both-modified`:!t.present&&n.present?`delete-modify`:t.present&&!n.present?`modify-delete`:`both-modified`,s=t.present?t.content:``;if(h===`ytext`&&p!==void 0&&o!==`delete-modify`){let e=l?l(f):null;e!==null&&!qJ(e)?s=e:e!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":f,handler:`sync-conflict-content`}))}m({base:i,ours:s,theirs:a,kind:o})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}default:Q(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:Error(`unknown conflict kind: ${JSON.stringify(s)}`)});return}}return VQ({"/api/sync/status":f,"/api/sync/trigger":p,"/api/sync/conflicts":h,"/api/sync/conflict-content":_,"/api/sync/resolve-conflict":g,"/api/sync/resolve-blocking":m},{mutating:[`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/sync/resolve-blocking`]})}function FCt(){return process.platform===`win32`?ws.join(process.env.SystemRoot??`C:\\Windows`,`System32`):`/`}function ICt(){return{detached:!0,stdio:`ignore`,shell:!1,cwd:FCt(),env:o(process.env)}}function LCt(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function n8(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,r(e))},o=setTimeout(()=>a({ok:!1,reason:`timeout`}),n);try{let n=Cc(e,[...t],eH(ICt()));n.once(`error`,e=>{clearTimeout(o),a(LCt(e))}),n.once(`spawn`,()=>{if(!i){try{n.unref()}catch{}clearTimeout(o),a({ok:!0})}})}catch(e){Y(`spawn-detached`).warn({err:e},`synchronous spawn throw`),clearTimeout(o),a(LCt(e))}})}const r8=`spawn-cursor`;function RCt(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function zCt(e,t,n){if(e.method!==`POST`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:r8,extraHeaders:{Allow:`POST`}});return}let r;try{r=await WQ(e,{maxBytes:4096,timeoutMs:5e3})}catch(e){if(e instanceof GQ){KQ(t,r8);return}if(e instanceof qQ){Q(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:r8,cause:e});return}if(e instanceof JQ){Q(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:r8,cause:e});return}Q(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:r8,cause:e});return}let i;try{i=JSON.parse(r.toString(`utf-8`))}catch(e){Q(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:r8,cause:e});return}let a=typeof i.path==`string`?i.path:``;if(!a){Q(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:r8});return}if(!o8(a,n.contentDir,n.platform)){Q(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:r8});return}let o=await(n.resolveCursorBinary??i8)(500);if(!o){Q(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:r8});return}let s=a8(o,a,n.platform),c=await(n.spawnDetached??n8)(s.exec,s.args,2e3);if(c.ok){$(t,200,dr,{},{handler:r8});return}switch(c.reason){case`not-installed`:Q(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:r8});return;case`timeout`:Q(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:r8});return;case`spawn-error`:Q(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:r8});return;case`invalid-path`:Q(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:r8});return;default:return RCt(c.reason)}}const BCt={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function i8(e){let t=BCt[process.platform];if(t&&t.length>0){let e=Ys();for(let n of t){let t=n(e);try{return await ec(t,tc.X_OK),t}catch(e){let n=e?.code;n!==`ENOENT`&&n!==`EACCES`&&n!==`EPERM`&&Y(`spawn-cursor`).warn({code:n,candidate:t},`unexpected fs.access error on bundle probe`)}}}return GCt(e)}const VCt=new WeakMap;function HCt(e,t){let n=VCt.get(e)??new Map;VCt.set(e,n);let r=n.get(t);if(r)return r;let i=e(t).finally(()=>n.delete(t));return n.set(t,i),i}async function UCt(e){try{return(await cc(e)).isFile()}catch{return!1}}async function WCt(e,t,n){let r=!1,i,a=new Promise(e=>{i=setTimeout(()=>{r=!0,e(null)},t)}),o=(async()=>{for(let t of e){if(r)return null;if(await HCt(n,t))return t}return null})();try{return await Promise.race([o,a])}finally{clearTimeout(i)}}async function GCt(e,t=process.platform,n=process.env,r=UCt){return t===`win32`?WCt(wU(`cursor`,n.PATH).filter(e=>ws.isAbsolute(e)),e,r):new Promise(t=>{xc(`which`,[`cursor`],eH({timeout:e,encoding:`utf-8`,env:n}),(e,n)=>{if(e){t(null);return}let r=n.split(/\r?\n/)[0]?.trim();t(r&&r.length>0?r:null)})})}function a8(e,t,n){return n===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:n===`win32`&&/\.(cmd|bat)$/i.test(e)?{exec:process.env.ComSpec||`cmd.exe`,args:[`/d`,`/c`,e,t]}:{exec:e,args:[t]}}function o8(e,t,n){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(n===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let r=n===`win32`?ws:Ss;try{let i=r.resolve(e),a=r.resolve(t);if(n===`win32`){let e=r.parse(i).root.toLowerCase(),t=r.parse(a).root.toLowerCase();if(!e||!t||e!==t)return!1}if(i===a)return!0;let o=r.relative(a,i);return o===``||o===`.`||!(o===`..`||o.startsWith(`..${r.sep}`)||n===`win32`&&(/^[a-zA-Z]:[\\/]/.test(o)||o.startsWith(`\\\\`))||n!==`win32`&&o.startsWith(`/`))}catch(e){return Y(`spawn-cursor`).warn({err:e},`unexpected path-resolution error`),!1}}const KCt=Y(`handoff-dispatch`),s8=`handoff`,c8=2e3,qCt={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},JCt=Object.keys(qCt),YCt=H({target:Li(JCt),url:V().min(1).max(4096),workspacePath:V().optional()}),XCt=H({}).loose();async function ZCt(e,t,n){if(e.method!==`POST`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:s8,extraHeaders:{Allow:`POST`}});return}let r;try{r=await WQ(e,{maxBytes:4096,timeoutMs:5e3})}catch(e){if(e instanceof GQ){KQ(t,s8);return}if(e instanceof qQ){Q(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s8,cause:e});return}if(e instanceof JQ){Q(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s8,cause:e});return}Q(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s8,cause:e});return}let i;try{i=JSON.parse(r.toString(`utf-8`))}catch(e){Q(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:s8,cause:e});return}let a=YCt.safeParse(i);if(!a.success){Q(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:s8});return}let{target:o,url:s,workspacePath:c}=a.data,l=qCt[o];if(!s.startsWith(l.urlScheme)){Q(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${l.urlScheme} for target ${o}.`,{handler:s8});return}let u=n.sleep??j,d=n.spawnDetached??n8,f=n.isSchemeRegistered??X$(n.platform);if(await Gz({site:`deep-link`,agentId:Lte(o)??o,mode:`external`,log:KCt,snapshot:n.hostSnapshot}),l.type===`app-bundle`){if(n.platform===`darwin`){l.quitFirst&&(await d(`/usr/bin/osascript`,[`-e`,`tell application "${l.appName}" to quit`],c8).catch(()=>void 0),await u(3e3));let e=await d(`/usr/bin/open`,[`-a`,l.appName],c8);if(!e.ok){l8(t,o,e.reason);return}await u(5e3)}else if(!await f(l.probeScheme)){Q(t,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:s8,extensions:{target:o}});return}let e=QCt(s,n.platform),r=await d(e.exec,e.args,c8);if(!r.ok){l8(t,o,r.reason);return}$(t,200,XCt,{},{handler:s8});return}if(!c){Q(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:s8});return}if(!o8(c,n.contentDir,n.platform)){Q(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:s8});return}let p=await(n.resolveCursorBinary??i8)(500);if(!p){Q(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:s8,extensions:{target:`cursor`}});return}let m=a8(p,c,n.platform),h=await d(m.exec,m.args,c8);if(!h.ok){l8(t,o,h.reason);return}await u(1500);let g=QCt(s,n.platform),_=await d(g.exec,g.args,c8);if(!_.ok){l8(t,o,_.reason);return}$(t,200,XCt,{},{handler:s8})}function QCt(e,t){return t===`darwin`?{exec:`/usr/bin/open`,args:[e]}:t===`win32`?{exec:`rundll32.exe`,args:[`url.dll,FileProtocolHandler`,e]}:{exec:`xdg-open`,args:[e]}}function l8(e,t,n){switch(n){case`not-installed`:Q(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:s8,extensions:{target:t}});return;case`timeout`:Q(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:s8,extensions:{target:t}});return;case`spawn-error`:Q(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:s8,extensions:{target:t}});return;default:$Ct(n)}}function $Ct(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}function ewt(e){let{contentDir:t,log:n,checkLocalOpSecurity:r,installedAgentsCache:i,agentIntegrations:a}=e;async function o(e,o){if(r(e,o,{handler:`handoff`}))try{await ZCt(e,o,{contentDir:t,platform:process.platform,isSchemeRegistered:i.probeWithCache,hostSnapshot:()=>wq({env:`local-web`,resolve:a?.probe})})}catch(t){o.headersSent||(n.error({err:t,requestId:VK(e)},`[handoff] route wrapper failed`),Q(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:t}))}}async function s(e,i){if(r(e,i,{handler:`spawn-cursor`}))try{await zCt(e,i,{contentDir:t,platform:process.platform})}catch(t){i.headersSent||(n.error({err:t,requestId:VK(e)},`[spawn-cursor] route wrapper failed`),Q(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:t}))}}return VQ({"/api/spawn-cursor":s,"/api/handoff":o,"/api/client-logs":XQ(ure,async(e,t,n)=>{try{let r=Y(`renderer`),i=ast(e)?.clientSurface,a=i===void 0?{}:{clientSurface:i};n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&r.warn({source:`renderer-console`,transport:`web`,...a,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let e of n.entries)try{r[e.level]({...e.fields,source:`renderer-console`,transport:`web`,...a,...e.sourceId?{sourceId:e.sourceId}:{},...e.lineNumber===void 0?{}:{lineNumber:e.lineNumber},...e.ts===void 0?{}:{clientTs:e.ts}},e.event??e.message)}catch{}$(t,200,Gre,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})})},{mutating:[`/api/client-logs`]})}const u8=Y(`github-permissions`);function twt(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function nwt(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function d8(e){return e.status===429||e.status===403&&(e.headers.get(`x-ratelimit-remaining`)===`0`||e.headers.get(`retry-after`)!==null)}function rwt(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let n=t.push;return typeof n==`boolean`?n:null}async function iwt(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return u8.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=rwt(t);return n===null?(u8.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:case 429:return d8(e)?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return u8.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function awt(e,t,n,r,i){let a=n(e,{login:t?.login});if(a.available&&a.token){if(t?.login!==void 0&&a.fallback===!0){let n=cwt(i,e);S6(n,t.login)||u8.warn({host:e,declaredLogin:t.login,declaredSource:t.source,resolvedLogin:n},`[permissions] declared GitHub account did not produce the gh token — probing as the active account`)}return{token:a.token,source:`gh`,resolvedLogin:a.resolvedLogin}}if(r)try{let t=await r.get(e);if(t?.token){let e=t.login===`unknown`?void 0:t.login;return{token:t.token,source:`token-store`,resolvedLogin:e}}}catch(t){u8.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}function owt(e,t){let n=t.resolvedLogin??(t.tokenSource===`gh`?cwt(t.detectGhAccounts,t.host):void 0);return{...e,...n===void 0?{}:{resolvedLogin:n},...swt(t.account,n)}}function swt(e,t){return e?.login===void 0||S6(e.login,t)?{}:{declaredLogin:e.login,declaredSource:e.source}}function cwt(e,t){if(e)try{return e(t)?.find(e=>e.active)?.login}catch(e){u8.warn({err:e,host:t},`[permissions] detectGhAccounts failed — denial stays unnamed`);return}}async function lwt(e){let{owner:t,repo:n,host:r=`github.com`,transport:i=`https`,account:a,detectGh:o=()=>({available:!1}),detectGhAccounts:s,tokenStore:c,_fetchFn:l=fetch,_timeoutMs:u=5e3}=e,{token:d,source:f,resolvedLogin:p}=await awt(r,a,o,c,s);if(f===`anonymous`)return i===`ssh`||i===`git`?(u8.info({host:r,transport:i},`[permissions] no credential resolved for ssh/git origin — abstaining (push auths with SSH keys, not tokens)`),{kind:`unknown`,error:`ssh-unverified`}):(u8.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`,...swt(a,void 0)});let m=`${twt(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;u8.info({host:r,tokenSource:f,tokenLen:d===void 0?0:d.length},`[permissions] probe starting`);let h=new AbortController,g=setTimeout(()=>h.abort(),u);try{let e=await l(m,{signal:h.signal,headers:nwt(d)}),t=await iwt(e,d!==void 0),n=t.kind===`denied`?owt(t,{account:a,tokenSource:f,resolvedLogin:p,detectGhAccounts:s,host:r}):t;return u8.info({host:r,tokenSource:f,httpStatus:e.status,kind:n.kind,reason:n.kind===`denied`?n.reason:void 0,error:n.kind===`unknown`?n.error:void 0},`[permissions] probe classified`),n}catch(e){return h.signal.aborted?(u8.warn({host:r,timeoutMs:u},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(u8.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(g)}}async function uwt(e){let t=performance.now(),n=await lwt(e);return gwt(n,performance.now()-t),n}function dwt(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let fwt=null;function pwt(){return fwt||=CV().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,ssh-unverified,none}.`}),fwt}let mwt=null;function hwt(){return mwt||=CV().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),mwt}function gwt(e,t){let n=dwt(e);pwt().add(1,n),hwt().record(t,{outcome:n.outcome})}const _wt=Y(`github-reference`);function vwt(e,t){let n=e.get(t);if(n===null||n.trim()===``)return null;let r=Number(n);return Number.isFinite(r)&&r>=0?r:null}function ywt(e,t){let n=vwt(e,`retry-after`);if(n!==null)return t+Math.max(n,1)*1e3;let r=vwt(e,`x-ratelimit-reset`);return e.get(`x-ratelimit-remaining`)===`0`&&r!==null&&r*1e3>t?r*1e3:t+6e4}function bwt(e){return e.status===200?!1:e.headers.get(`retry-after`)!==null||e.headers.get(`x-ratelimit-remaining`)!==`0`}const xwt=new Set([`RATE_LIMITED`,`RATE_LIMIT`]);function Swt(e){let t=p8(e)?.errors;return Array.isArray(t)&&t.some(e=>xwt.has(p8(e)?.type))}const Cwt={graphql:`[github-reference] GitHub rate-limited reference cards; no GraphQL requests to this host until the limit resets`,rest:`[github-reference] GitHub rate-limited reference cards; no REST requests to this host until the limit resets`,"graphql+rest":`[github-reference] GitHub rate-limited reference cards; no GraphQL or REST requests to this host until the limit resets`};var wwt=class{until=new Map;holding(e,t){let n=this.until.get(e);return n===void 0?!1:n>t||(this.until.delete(e),!1)}hold(e,t,n){let r=Math.max(this.until.get(e)??0,Math.min(n+36e5,ywt(t,n)));return this.until.set(e,r),r}};const Twt={ok:!1,reason:`not-found`},f8={ok:!1,reason:`unavailable`};function p8(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function m8(e){return typeof e==`string`?e:null}function h8(e){return m8(p8(e)?.login)}function Ewt(e){return`${e.host===`github.com`?`https://api.github.com`:`https://${e.host}/api/v3`}/repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function Dwt(e){return e===`github.com`?`https://api.github.com/graphql`:`https://${e}/api/graphql`}function Owt(e,t){let n={"User-Agent":`open-knowledge-server`,Accept:t};return e!==null&&(n.Authorization=`Bearer ${e}`),n}async function g8(e,t,n,r){let i=new AbortController,a=setTimeout(()=>i.abort(),r);try{let r=await n(e,{...t,signal:i.signal});return r.status===200?{status:200,headers:r.headers,body:await r.json()}:(await r.body?.cancel(),{status:r.status,headers:r.headers,body:null})}finally{clearTimeout(a)}}function kwt(e,t){if(e?.toUpperCase()===`OPEN`)return`open`;let n=t?.toUpperCase();return n===`NOT_PLANNED`||n===`DUPLICATE`?`not-planned`:`completed`}function _8(e){let t=Vt.safeParse(e);return t.success?t.data:null}function Awt(e,t){let n=p8(t);if(n===null)return null;let r={repo:`${e.owner}/${e.repo}`,number:e.number,title:n.title,author:h8(n.author),createdAt:n.createdAt};if(n.__typename===`Issue`)return _8({...r,kind:`issue`,lifecycle:kwt(m8(n.state),m8(n.stateReason))});if(n.__typename!==`PullRequest`)return null;let i=m8(n.state),a=i===`MERGED`?`merged`:i===`CLOSED`?`closed`:n.isDraft===!0?`draft`:`open`,o=p8(n.commits)?.nodes,s=Array.isArray(o)?p8(p8(o.at(-1))?.commit):null,c=p8(n.mergeQueueEntry);return _8({...r,kind:`pull`,lifecycle:a,additions:n.additions,deletions:n.deletions,...a===`open`?{status:{mergeQueue:c===null?null:{position:c.position,state:c.state},autoMerge:p8(n.autoMergeRequest)!==null,mergeState:n.mergeStateStatus,reviewDecision:n.reviewDecision,checks:p8(s?.statusCheckRollup)?.state??null}}:{}})}function jwt(e,t,n){let r={repo:`${e.owner}/${e.repo}`,number:e.number},i=p8(n);if(i!==null){let e=i.merged===!0||m8(i.merged_at)!==null?`merged`:i.state===`closed`?`closed`:i.draft===!0?`draft`:`open`,t=m8(i.mergeable_state)?.toUpperCase()??null;return _8({...r,kind:`pull`,title:i.title,author:h8(i.user),createdAt:i.created_at,lifecycle:e,additions:i.additions,deletions:i.deletions,...e===`open`?{status:{mergeQueue:null,autoMerge:p8(i.auto_merge)!==null,mergeState:t,reviewDecision:null,checks:null}}:{}})}let a=p8(t);return a===null?null:_8({...r,kind:`issue`,title:a.title,author:h8(a.user),createdAt:a.created_at,lifecycle:kwt(m8(a.state),m8(a.state_reason))})}async function Mwt(e,t,n,r,i){let a=await g8(Dwt(e.host),{method:`POST`,headers:{...Owt(t,`application/vnd.github.merge-info-preview+json`),"Content-Type":`application/json`},body:JSON.stringify({query:`query($owner: String!, $name: String!, $number: Int!) {
|
|
2169
|
+
`)}function fCt(e){let{contentDir:t,checkLocalOpSecurity:n}=e;async function r(e,r){if(!n(e,r,{handler:`seed-plan`}))return;if(e.method!==`GET`){Q(r,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let i=new URL(e.url??`/`,`http://localhost`),a=i.searchParams.get(`rootDir`)??void 0,o=i.searchParams.get(`packId`),s=Y6(o);if(o!==null&&o!==``&&s===void 0){Q(r,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${o}" is not registered.`});return}try{let e=await cCt({projectDir:t,rootDir:a,packId:s});$(r,200,vee,{plan:e},{handler:`seed-plan`})}catch(e){if(e instanceof W6){Q(r,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof G6){Q(r,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}Q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let i=XQ(Uie,async(e,n,r)=>{let i=r.plan;if(!i||typeof i!=`object`){Q(n,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let a=i,o=r.packId,s=Y6(o);if(typeof o==`string`&&o.length>0&&s===void 0){Q(n,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${o}" is not registered.`});return}try{let e=await rCt(a,{projectDir:t,packId:s});$(n,200,we,{result:e},{handler:`seed-apply`})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>n(e,t,{handler:`seed-apply`})}),a=XQ(lee,async(e,n,r)=>{let i=Y6(r.packId);if(i===void 0){Q(n,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-install-pack-skill`,detail:`Pack id "${r.packId}" is not registered.`});return}try{let e=await USt(t,i);$(n,200,Pt,e,{handler:`seed-install-pack-skill`})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Failed to install pack skill.`,{handler:`seed-install-pack-skill`,cause:e})}},{handler:`seed-install-pack-skill`,method:`POST`,preBodyGate:(e,t)=>n(e,t,{handler:`seed-install-pack-skill`})});async function o(e,t){if(n(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}$(t,200,_i,{packs:QSt()},{handler:`seed-packs`})}}return VQ({"/api/seed/plan":r,"/api/seed/apply":i,"/api/seed/install-pack-skill":a,"/api/seed/packs":o},{mutating:[`/api/seed/apply`,`/api/seed/install-pack-skill`]})}const Z6=`share-construct-url`;function pCt(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function mCt(e,t,n,r,i){return`https://${e}/${t}/${n}/blob/${encodeURIComponent(r)}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function hCt(e,t,n,r,i){let a=`https://${e}/${t}/${n}/tree/${encodeURIComponent(r)}`;return i===``?a:`${a}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function Q6(e,t){let n=t?.branchExists,r=t?.kind,i=t?.freshness;Y(`share`).info({action:`construct-url`,result:e,...n===void 0?{}:{branchExists:n},...r===void 0?{}:{kind:r},...i===void 0?{}:{freshness:i}},`share action`)}async function gCt(e,t,n,r){try{let{git:i}=LG(e,{timeoutMs:5e3,credentialConfig:[]}),a=`refs/remotes/origin/${t}`;await i.raw([`rev-parse`,`--verify`,a]);let o=on([n===``?`.`:n]),[s,c,l]=await Promise.all([i.raw([`cat-file`,`-e`,`${a}:${n}`]).then(()=>!0).catch(()=>!1),i.raw([`diff`,`--name-only`,a,...o]),i.raw([...Fq,...o])]);return s?c.trim()!==``||l.trim()!==``?`stale`:`current`:r===`folder`&&c.trim()===``&&l.trim()===``?`empty`:`absent`}catch(e){let t=B3(e);Y(`share`).warn({action:`freshness-probe-failed`,kind:r,error:t},`[share] freshness probe failed; omitting freshness`);return}}const $6=`share-target-status`;function _Ct(e,t){for(let n of e)if(n.from===t){if(n.status.startsWith(`R`))return{verdict:`renamed`,renamedTo:n.to};if(n.status===`D`)return{verdict:`deleted`}}return{verdict:`deleted`}}function vCt(e,t){let n=t.endsWith(`/`)?t:`${t}/`,r=new Set;for(let t of e){if(!t.from.startsWith(n)||!t.status.startsWith(`R`))continue;let e=t.from.slice(n.length);t.to.endsWith(`/${e}`)?r.add(t.to.slice(0,t.to.length-e.length-1)):r.add(`\0ambiguous`)}let i=r.size===1?[...r][0]:void 0;return i!==void 0&&i!==`\0ambiguous`?{verdict:`renamed`,renamedTo:i}:{verdict:`deleted`}}async function yCt(e,t,n,r,i){let a=Y(`share`),o=e=>(a.info({action:`target-status`,verdict:e.verdict,kind:r},`target-status verdict`),e),{git:s}=LG(e,i.skipFetch?{credentialConfig:[]}:{timeoutMs:i.fetchTimeoutMs??15e3,credentialConfig:i.credentialConfig});if(!i.skipFetch)try{await s.raw([`fetch`,`origin`,t])}catch(e){return a.warn({action:`target-status`,kind:r,error:B3(e)},`target-status fetch failed`),o({verdict:`unknown`})}let c=`origin/${t}`;try{if(await s.raw([`cat-file`,`-e`,`${c}:${n}`]).then(()=>!0).catch(()=>!1)){let t=await s.raw([`cat-file`,`-e`,`HEAD:${n}`]).then(()=>!0).catch(()=>!1),r=q(W(e,n));return o(t&&!r?{verdict:`changed-locally`}:{verdict:`on-origin`})}let t=(await s.raw([`log`,`-1`,`--format=%H`,c,...on([n===``?`.`:n])])).trim();if(t===``)return o({verdict:`never-on-branch`});let i=await zq(s,[`diff-tree`,`-M`,`-r`,`--no-commit-id`,`--name-status`,`${t}^1`,t]),a=r===`folder`?vCt(i,n):_Ct(i,n);return a.verdict===`renamed`&&!await s.raw([`cat-file`,`-e`,`${c}:${a.renamedTo}`]).then(()=>!0).catch(()=>!1)?o({verdict:`deleted`}):o(a)}catch(e){return a.warn({action:`target-status`,kind:r,error:B3(e)},`target-status detection failed`),o({verdict:`unknown`})}}function bCt(e){let{projectDir:t,contentDir:n,log:r,checkLocalOpSecurity:i,localOpCliArgs:a,localOpGuard:o,getSyncEngine:s,resolveCredentialConfig:c,toGitRelativePath:l}=e,u=e.declaredGitHubHosts??C6(),d=f.resolve({host:a===void 0?void 0:{cliArgs:a}}),p=XQ(hn,async(e,r,i)=>{try{if(!t){Q6(`no-remote`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`no-remote`},{handler:Z6});return}let e=i.kind===`doc`?i.docPath:i.folderPath;if(!pCt(e,i.kind)){Q6(`invalid-path`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`invalid-path`},{handler:Z6});return}let a=xxt(t);if(a===null){if(T6(t,u).kind===`no-remote`){Q6(`no-remote`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`no-remote`},{handler:Z6});return}Q6(`detached-head`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`detached-head`},{handler:Z6});return}let o=T6(t,u);if(o.kind===`no-remote`){Q6(`no-remote`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`no-remote`},{handler:Z6});return}if(o.kind===`non-github`){Q6(`non-github-remote`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`non-github-remote`},{handler:Z6});return}if(!Bxt(t,a)){Q6(`branch-not-on-origin`,{branchExists:!1,kind:i.kind}),$(r,200,Oa,{ok:!1,error:`branch-not-on-origin`,branch:a},{handler:Z6});return}let s=l(t,n);if(s===null)throw Error(`content dir is not contained within the project dir`);let c=s===``?e:e===``?s:`${s}/${e}`,d;d=i.kind===`doc`?mCt(o.host,o.owner,o.repo,a,c):hCt(o.host,o.owner,o.repo,a,c);let f;try{let e=s===``?0:zr(hCt(o.host,o.owner,o.repo,a,s)).targetSegments.length;f=`https://openknowledge.ai/d/${Dn(d,e)}`}catch(e){if(!(e instanceof Gt))throw e;Q6(`unsupported-share-url`,{kind:i.kind}),$(r,200,Oa,{ok:!1,error:`unsupported-share-url`},{handler:Z6});return}let p=await gCt(t,a,c,i.kind);Q6(`ok`,{branchExists:!0,kind:i.kind,freshness:p}),$(r,200,Oa,{ok:!0,shareUrl:f,sharedUrl:d,branch:a,freshness:p},{handler:Z6})}catch(e){Q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Z6,cause:e})}},{handler:Z6,method:`POST`,preBodyGate:(e,t)=>i(e,t,{handler:Z6})});function m(e,t,n){let r=e.split(`/`),i=t.split(`/`);if(n>=r.length||n>=i.length)return{verdict:`unknown`};for(let e=0;e<n;e+=1)if(r[e]!==i[e])return{verdict:`unknown`};return{verdict:`renamed`,renamedTo:i.slice(n).join(`/`)}}let h=XQ(I,async(e,n,r)=>{try{if(!t){Q(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:$6});return}if(!nyt(r.path,r.kind)){Q(n,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:$6});return}let e=await yCt(t,r.branch,r.path,r.kind,{credentialConfig:await c()}),i=e.verdict!==`renamed`||r.contentRootDepth===void 0?e:m(r.path,e.renamedTo,r.contentRootDepth);$(n,200,Ote,i,{handler:$6})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:$6,cause:e})}},{handler:$6,method:`POST`,preBodyGate:(e,t)=>i(e,t,{handler:$6})});async function g(e){let t=d.spawn(e,process.env);if(`refused`in t)throw Error(t.refused);return await new Promise((e,n)=>{let i=Cc(t.command,t.args,eH({...$V,env:t.env})),a=!1,o=setTimeout(()=>{if(!a){a=!0;try{i.kill(`SIGKILL`)}catch{}i.stdout.destroy(),i.stderr.destroy(),n(Error(`share subprocess timed out after ${Vxt}ms`))}},Vxt);o.unref?.();let s=[],c=[];i.stdout.on(`data`,e=>s.push(e)),i.stderr.on(`data`,e=>c.push(e)),i.on(`close`,t=>{if(a)return;a=!0,clearTimeout(o);let n=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=j6(Buffer.concat(c).toString(`utf-8`)).slice(0,500);r.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:n,code:t})}),i.on(`error`,e=>{a||(a=!0,clearTimeout(o),n(e))})})}return VQ({"/api/share/construct-url":p,"/api/share/target-status":h,"/api/share/publish/owners":XQ(L,async(e,t)=>{if(!o.tryAcquire(`/api/share/publish/owners`)){Q(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:E6,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await g([`share`,`owners`,`--json`]),n=Wxt(k6(e));A6(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),$(t,200,Cee,n,{handler:E6})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E6,cause:e})}finally{o.release(`/api/share/publish/owners`)}},{handler:E6,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>i(e,t,{handler:E6})}),"/api/share/publish/name-check":XQ(L,async(e,t)=>{let n=ZU(e),r=n.get(`owner`)??``,i=n.get(`name`)??``;if(!Uxt(r)||!Hxt(i)){Q(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:D6});return}if(!o.tryAcquire(`/api/share/publish/name-check`)){Q(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:D6,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await g([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Kxt(k6(e));A6(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),$(t,200,Aee,n,{handler:D6})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:D6,cause:e})}finally{o.release(`/api/share/publish/name-check`)}},{handler:D6,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>i(e,t,{handler:D6})}),"/api/share/publish":XQ(Iee,async(e,n,i)=>{if(!t){A6(`publish-create`,`no-project`),$(n,200,Or,{ok:!1,error:`no-project`},{handler:O6});return}if(!Uxt(i.owner)||!Hxt(i.name)){Q(n,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:O6});return}if(!o.tryAcquire(`/api/share/publish`)){Q(n,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:O6,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,i.owner,`--name`,i.name,`--visibility`,i.visibility,`--project-dir`,t,`--json`];i.description!==void 0&&i.description.length>0&&e.push(`--description`,i.description);let{stdout:a}=await g(e),o=Yxt(k6(a));A6(`publish-create`,o.ok?`ok`:o.error),o.ok&&s?.()?.refreshRemote().catch(e=>{r.warn({err:e},`[share] post-publish refreshRemote failed`)}),$(n,200,Or,o,{handler:O6})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:O6,cause:e})}finally{o.release(`/api/share/publish`)}},{handler:O6,method:`POST`,preBodyGate:(e,t)=>i(e,t,{handler:O6})})})}function xCt(e){let{contentDir:t,projectDir:n,homeDirOverride:r,skillsHome:i,isSafeDocName:a,commentService:o,enumerateInstalledSkillsCached:s,checkLocalOpSecurity:c}=e,l=XQ(L,async(e,a)=>{try{let e=My(n??t),o=K(n??t),c=await z1(i),l=s({projectDir:e,...r===void 0?{}:{home:r}}),u=new Set(L1(t).map(e=>e.name)),d=new Set(c.map(e=>e.name)),f={...l,skills:l.skills.filter(t=>Kc(t.provenance,e)&&!(t.provenance.scope===`project`?u.has(t.name):d.has(t.name))).map(e=>Sse(e.provenance,e.home,o)?{...e,outsideProject:!0}:e)};$(a,200,_r,f,{handler:`skills-installed`})}catch(e){Q(a,500,`urn:ok:error:internal-server-error`,`Failed to enumerate installed skills.`,{handler:`skills-installed`,cause:e})}},{handler:`skills-installed`,method:`GET`,skipBodyParse:!0}),u={"/api/comment-counts":XQ(L,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`prefix`),i=n.searchParams.get(`docNames`);if(r===null&&i===null){Q(t,400,`urn:ok:error:invalid-request`,`Missing docNames or prefix parameter.`,{handler:`comment-counts`});return}let s={};if(r!==null){let e=r.trim();if(e!==``&&!a(e)){Q(t,400,`urn:ok:error:invalid-request`,`Invalid prefix parameter.`,{handler:`comment-counts`});return}s=Object.fromEntries(await o.countThreads({prefix:e}))}else{let e=(i??``).split(`,`).map(e=>e.trim()).filter(e=>e!==``&&a(e));s=Object.fromEntries(await o.countThreads({docNames:e}))}$(t,200,gte,{counts:s},{handler:`comment-counts`})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Failed to read comment counts.`,{handler:`comment-counts`,cause:e})}},{handler:`comment-counts`,method:`GET`,skipBodyParse:!0}),"/api/skills/installed":l,"/api/templates":XQ(L,UQ(async(e,n)=>{let r=await c_t(K(t)),i=r.templates.map(e=>{let{scope:t,...n}=e;return n});$(n,200,Zt,{templates:i,truncated:r.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),"/api/skill/install-state":XQ(L,UQ(async(e,t)=>{let n=await Fot(Ys());$(t,200,lre,{...n},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>c(e,t,{handler:`skill-install-state`})})};return{paths:Object.keys(u),table:{resolve(e){let t=u[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1}}}const e8=new Map;function SCt(e){return e.kind===`git`?`git\n${e.url}\n${e.subpath??``}`:e.kind===`well-known`?`wk\n${e.origin}\n${e.skill}`:`local\n${e.path}`}function CCt(e){for(let[t,n]of e8)n.expiresAt>e||(e8.delete(t),n.fetched.then(e=>e.cleanup()).catch(()=>{}))}async function wCt(e){return e.kind===`local`?PE(e):ECt(SCt(e),()=>PE(e))}async function TCt(e){return e.kind!==`git`||e.subpath?wCt(e):ECt(`listing\n${SCt(e)}`,()=>FE(e))}async function ECt(e,t){let n=Date.now();CCt(n);let r=e8.get(e);if(!r){let i=t();r={fetched:i,expiresAt:n+3e4},e8.set(e,r);let a=r;i.catch(()=>{e8.get(e)===a&&e8.delete(e)})}let i=await r.fetched;return{dir:i.dir,ref:i.ref,cleanup:()=>{}}}const DCt=Y(`skills-leaderboard`),OCt=6e5;let t8=null;async function kCt(e=24,t={}){let n=t.now??Date.now(),r=t.fetchImpl??fetch;if(t8&&n-t8.at<OCt)return t8.data.slice(0,e);try{let t=await r(`https://www.skills.sh/`,{headers:{"user-agent":`open-knowledge (+skills discovery)`,RSC:`1`},signal:AbortSignal.timeout(8e3),redirect:`manual`});if(!t.ok)throw Error(`HTTP ${t.status} ${t.statusText}`);let i=vPe(await t.text());if(i.length===0)throw Error(`parsed 0 skills (payload format may have changed)`);return t8={at:n,data:i},i.slice(0,e)}catch(t){return DCt.warn({err:t},`skills.sh leaderboard fetch failed — Discover falls back to topics`),t8?.data.slice(0,e)??[]}}const ACt=new Map;async function jCt(e,t={}){let n=t.now??Date.now(),r=t.fetchImpl??fetch,i=ACt.get(e);if(i&&n-i.at<OCt)return i.data;try{let t=await r(`https://www.skills.sh/${e}`,{headers:{"user-agent":`open-knowledge (+skills discovery)`},signal:AbortSignal.timeout(8e3),redirect:`manual`});if(!t.ok)throw Error(`HTTP ${t.status} ${t.statusText}`);let i=bPe(await t.text(),e);if(i.length===0)throw Error(`parsed 0 skills (page format may have changed)`);return ACt.set(e,{at:n,data:i}),i}catch(t){return DCt.warn({err:t,source:e},`skills.sh publisher page fetch failed — install counts unavailable`),i?.data??[]}}function MCt(e){let{log:t,skillsHome:n,projectDir:r,contentDir:i,resolveSkillDirForRead:a}=e;return{handleSkillsSearch:XQ(L,async(e,n)=>{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`q`)?.trim()??``;if(r.length<2){Q(n,400,`urn:ok:error:invalid-request`,`Search query must be at least 2 characters.`,{handler:`skills-search`});return}try{let e=await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(r)}&limit=30`,{signal:AbortSignal.timeout(8e3)});if(e.ok){let t=nD(await e.json());$(n,200,mt,{results:t,backend:`skills.sh`,degraded:!1},{handler:`skills-search`});return}t.warn({status:e.status},`skills.sh search unavailable — falling back to GitHub topic search`)}catch(e){t.warn({err:e},`skills.sh search failed — falling back to GitHub topic search`)}try{let e=encodeURIComponent(`${r} topic:agent-skills`),i=await fetch(`https://api.github.com/search/repositories?q=${e}&per_page=30`,{signal:AbortSignal.timeout(8e3),headers:{Accept:`application/vnd.github+json`}});if(!i.ok){t.warn({status:i.status},`GitHub skill search fallback returned non-ok`),Q(n,502,`urn:ok:error:internal-server-error`,`Skill discovery is temporarily unavailable.`,{handler:`skills-search`,detail:`GitHub fallback returned ${i.status}.`});return}let a=ONe(await i.json());$(n,200,mt,{results:a,backend:`github-fallback`,degraded:!0},{handler:`skills-search`})}catch(e){Q(n,502,`urn:ok:error:internal-server-error`,`Skill discovery is temporarily unavailable.`,{handler:`skills-search`,cause:e})}},{handler:`skills-search`,method:`GET`,skipBodyParse:!0}),handleSkillsPopular:XQ(L,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=Number(n.searchParams.get(`limit`)),i=Number.isFinite(r)&&r>0?Math.min(Math.floor(r),60):24;try{let e=await kCt(i);$(t,200,mt,{results:e,backend:`skills.sh`,degraded:e.length===0},{handler:`skills-popular`})}catch(e){Q(t,502,`urn:ok:error:internal-server-error`,`Popular skills are temporarily unavailable.`,{handler:`skills-popular`,cause:e})}},{handler:`skills-popular`,method:`GET`,skipBodyParse:!0}),handleSkillsPublisher:XQ(L,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`source`)?.trim()??``;if(!/^[\w.-]+\/[\w.-]+$/.test(n)||n.includes(`..`)){Q(t,400,`urn:ok:error:invalid-request`,`source must be owner/repo.`,{handler:`skills-publisher`});return}try{let e=await jCt(n);$(t,200,mt,{results:e,backend:`skills.sh`,degraded:e.length===0},{handler:`skills-publisher`})}catch(e){Q(t,502,`urn:ok:error:internal-server-error`,`Publisher skills are temporarily unavailable.`,{handler:`skills-publisher`,cause:e})}},{handler:`skills-publisher`,method:`GET`,skipBodyParse:!0}),handleSkillsDetail:XQ(L,async(e,n)=>{let r=new URL(e.url??``,`http://localhost`),i=r.searchParams.get(`source`)?.trim()??``,a=r.searchParams.get(`name`)?.trim()??``;if(!i||!a){Q(n,400,`urn:ok:error:invalid-request`,`source and name are required.`,{handler:`skills-detail`});return}let o=Tse(i,a);if(!o){Q(n,400,`urn:ok:error:invalid-request`,`Unrecognized skill source.`,{handler:`skills-detail`});return}let{skillsUrl:s,sourceKind:c,sourceUrl:l}=o,u={},d=!1;try{let e=await fetch(s,{signal:AbortSignal.timeout(8e3)});e.ok&&(d=!0,u=DNe(await e.text()))}catch(e){t.warn({err:e,skillsUrl:s},`skills.sh detail fetch failed — degrading to repo link`)}$(n,200,pe,{title:u.title??a,description:u.description??``,image:u.image??null,skillsUrl:d?s:null,sourceKind:c,sourceUrl:l},{handler:`skills-detail`})},{handler:`skills-detail`,method:`GET`,skipBodyParse:!0}),handleSkillsPreview:XQ(L,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`source`)?.trim()??``,i=n.searchParams.get(`name`)?.trim()??``;if(!r){Q(t,400,`urn:ok:error:invalid-request`,`source is required.`,{handler:`skills-preview`});return}let a=null;try{a=await aD(r,i||void 0)}catch(e){if(e instanceof vE){Q(t,400,`urn:ok:error:invalid-request`,`Could not resolve source.`,{handler:`skills-preview`,cause:e});return}throw e}let o=a?.spec??ME(r);if(!o){Q(t,400,`urn:ok:error:invalid-request`,`Unrecognized preview source.`,{handler:`skills-preview`,detail:`Expected owner/repo, a git URL, a website source, or a local path.`});return}if(!w0(t,o,`skills-preview`))try{let e=await wCt(o),n=tD(e.dir);if(n.length===0){Q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-preview`});return}let a=n[0];if(i){let e=n.find(e=>e.name===i)??n.find(e=>XE(e.dir)?.name===i);if(!e){Q(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skills-preview`,detail:`"${i}" not among: ${n.map(e=>e.name).join(`, `)}.`});return}a=e}let s=ZE(a.dir);if(s){Q(t,400,`urn:ok:error:invalid-request`,`Skill bundle is too large.`,{handler:`skills-preview`,detail:s});return}let c=QE(a.dir);if(!c){Q(t,404,`urn:ok:error:not-found`,`SKILL.md unreadable in source.`,{handler:`skills-preview`});return}let l=OD(r),u=ePe(e.dir);$(t,200,Rn,{name:c.name,description:c.description,skillMd:c.skillMd,files:c.files.map(e=>({relPath:e.relPath,content:e.content})),plugin:l??void 0,pluginBundle:u??void 0},{handler:`skills-preview`})}catch(e){if(e instanceof vE){Q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-preview`,cause:e});return}Q(t,502,`urn:ok:error:internal-server-error`,`Preview is unavailable.`,{handler:`skills-preview`,cause:e})}},{handler:`skills-preview`,method:`GET`,skipBodyParse:!0}),handleSkillsDiscover:XQ(L,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`source`)?.trim()??``;if(!n){Q(t,400,`urn:ok:error:invalid-request`,`source is required.`,{handler:`skills-discover`});return}let r=iD(n);if(r){try{let e=await pNe(`https://${r.hostname}`);$(t,200,xne,{skills:e},{handler:`skills-discover`})}catch(e){if(e instanceof vE){Q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-discover`,cause:e});return}throw e}return}let i=ME(n);if(!i){Q(t,400,`urn:ok:error:invalid-request`,`Unrecognized source.`,{handler:`skills-discover`,detail:`Expected owner/repo, a git URL, a website source, or a local path.`});return}if(!w0(t,i,`skills-discover`))try{let e=tD((await TCt(i)).dir).map(e=>{let t=XE(e.dir);return{name:t?.name??e.name,description:t?.description??null}});$(t,200,xne,{skills:e},{handler:`skills-discover`})}catch(e){if(e instanceof vE){Q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-discover`,cause:e});return}Q(t,502,`urn:ok:error:internal-server-error`,`Discovery is unavailable.`,{handler:`skills-discover`,cause:e})}},{handler:`skills-discover`,method:`GET`,skipBodyParse:!0}),handleSkillsResolveRef:XQ(L,async(e,o)=>{let s=new URL(e.url??``,`http://localhost`),c=s.searchParams.get(`ref`)?.trim()??``,l=s.searchParams.get(`from`)?.trim()??``,u=s.searchParams.get(`scope`)?.trim()===`global`?`global`:`project`;if(!c||!We.test(c)||c.length>64){Q(o,400,`urn:ok:error:invalid-request`,`A valid ref is required.`,{handler:`skills-resolve-ref`});return}try{let e=e=>$(o,200,Jn,e,{handler:`skills-resolve-ref`});for(let t of[u,u===`project`?`global`:`project`]){let r=a(t,c);if(r!==null){e({kind:`local`,scope:t,name:c,dir:G(t===`project`?i:n,r).split(Cs).join(`/`)});return}}let s=u===`project`?r:n,d=l&&s?y0(W(s,...lo)).skills[l]:void 0;if(d?.source){let n=(await aD(d.source,c))?.spec??ME(d.source),r=n&&!(n.kind===`git`&&!RQ(n.url));if(n&&r){let r;try{let t=await FE(n);if(r=t.cleanup,tD(t.dir).map(e=>XE(e.dir)?.name??e.name).includes(c)){e({kind:`import`,source:d.source,ref:c,via:`source`});return}}catch(e){t.debug({err:e,ref:c,from:l,source:d.source},`resolve-ref: source rung unreachable, falling through to publisher`)}finally{r?.()}}}if(d?.publisher)try{let t=await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(c)}&limit=30`,{signal:AbortSignal.timeout(8e3)});if(t.ok){let n=nD(await t.json()).filter(e=>e.name===c&&e.publisher===d.publisher);if(n.length===1){let t=n[0];if(t){e({kind:`import`,source:t.source,ref:c,via:`publisher`});return}}}}catch(e){t.debug({err:e,ref:c,publisher:d.publisher},`resolve-ref: skills.sh unavailable, no publisher resolution`)}e({kind:`none`})}catch(e){Q(o,500,`urn:ok:error:internal-server-error`,`Could not resolve the reference.`,{handler:`skills-resolve-ref`,cause:e instanceof Error?e:Error(String(e))})}},{handler:`skills-resolve-ref`,method:`GET`,skipBodyParse:!0})}}function NCt(e){let{handleSkillsSearch:t,handleSkillsPopular:n,handleSkillsPublisher:r,handleSkillsDetail:i,handleSkillsPreview:a,handleSkillsDiscover:o,handleSkillsResolveRef:s}=MCt(e);return VQ({"/api/skills/search":t,"/api/skills/popular":n,"/api/skills/publisher":r,"/api/skills/detail":i,"/api/skills/preview":a,"/api/skills/discover":o,"/api/skills/resolve-ref":s},{mutating:[`/api/skills/preview`,`/api/skills/discover`,`/api/skills/resolve-ref`]})}function PCt(e){let{projectDir:t,contentDir:n,getPrincipal:r,hocuspocus:i,log:a,checkLocalOpSecurity:o,getSyncEngine:s,conflicts:c,serializeDoc:l,setBatchInProgress:u}=e;function d(e){let t={file:e.file,detectedAt:e.detectedAt,conflict:e.kind,docName:c.docNameOf(e),conflictKind:e.kind===`reconcile`&&e.reason===`stale-external-write`?`stale-external-write`:`git`};switch(e.kind){case`merge-native`:return t;case`working-tree`:return{...t,theirsSha:e.theirsSha,...e.baseSha===void 0?{}:{baseSha:e.baseSha}};case`reconcile`:return{...t,reason:e.reason};default:return t}}async function f(e,t){if(o(e,t,{handler:`sync-status`})){if(e.method!==`GET`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=s?.();if(!e){$(t,200,Ma,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),$(t,200,Ma,e.getStatus(),{handler:`sync-status`})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let p=XQ(fte,async(e,t,n)=>{let r=s?.();if(!r){Q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;$(t,202,Ane,{op:i},{handler:`sync-trigger`}),r.trigger(i).catch(e=>{a.error({err:e,op:i},`[sync] fire-and-forget trigger failed`)})},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>o(e,t,{handler:`sync-trigger`})?s?.()?!0:(Q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1}),m=XQ(Nre,async(e,t,n)=>{let r=s?.();if(!r){Q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-blocking`});return}if(r.getBlockingPaths().length===0){Q(t,409,`urn:ok:error:no-blocking-changes`,`No local changes are blocking a merge.`,{handler:`sync-resolve-blocking`});return}try{let e=r.getBlockingPaths(),n=await r.commitBlockingPaths();$(t,200,one,{action:`commit`,paths:e,...n===null?{}:{commitSha:n}},{handler:`sync-resolve-blocking`}),r.trigger(`sync`).catch(e=>{a.error({err:e},`[sync] resolve-blocking follow-up sync failed`)})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-resolve-blocking`,cause:e})}},{handler:`sync-resolve-blocking`,method:`POST`,preBodyGate:(e,t)=>o(e,t,{handler:`sync-resolve-blocking`})});async function h(e,t){if(o(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{$(t,200,Jne,{conflicts:c.list().map(d)},{handler:`sync-conflicts`})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let g=XQ(Jee,async(e,i,a)=>{let{file:o,strategy:s,content:l}=a,d=EQ(a,r),f;t&&(d.kind===`agent`||d.kind===`principal`)&&(f=yX(K(t,o),n),Bst(f,{writerId:d.writerId,displayName:d.displayName,colorSeed:d.colorSeed},Date.now(),3e3)),u?.(!0);try{await c.resolve(o,s,l),$(i,200,ore,{},{handler:`sync-resolve-conflict`})}catch(e){if(f&&Hst(f),e instanceof lK){Q(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`sync-resolve-conflict`});return}if(e instanceof ntt){Q(i,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-resolve-conflict`,detail:`This file has no tracked conflict — it may have been resolved by another session, or the path may be stale. Refresh the conflict list in the OpenKnowledge app before retrying.`,extensions:{file:e.file}});return}if(e instanceof WJ){let t=c.findByFile(e.file),n=t===void 0?VJ:BJ(t.kind,t.kind===`reconcile`?t.reason:void 0),r=e.refusal===`strategy-not-offered`;Q(i,422,`urn:ok:error:unresolved-conflict-markers`,r?`Strategy not offered for this conflict.`:`Resolution still contains conflict markers.`,{handler:`sync-resolve-conflict`,detail:r?`Strategy "${s}" is not offered for this conflict. Pick one of the strategies listed in resolutionOptions.`:"The submitted content still contains a `<<<<<<< … >>>>>>>` block. Resolve every region, or take one side wholesale with a strategy listed in resolutionOptions.",extensions:{file:e.file,refusal:e.refusal,resolutionOptions:n}});return}Q(i,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0,extensions:{file:o,strategy:s}})}finally{u?.(!1)}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>o(e,t,{handler:`sync-resolve-conflict`})});async function _(e,n){if(!o(e,n,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){Q(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!t){Q(n,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=r.searchParams.get(`file`);if(!a){Q(n,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(a.includes(`..`)||a.startsWith(`/`)){Q(n,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let s=c.findByFile(a);if(s===void 0){Q(n,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:a}});return}let u=s.kind===`reconcile`?s.reason:void 0,d=[...BJ(s.kind,u)],f=c.docNameOf(s)??cB(a),p=i.documents.get(f),m=e=>{$(n,200,Jre,{file:a,...e,conflict:s.kind,conflictKind:u===`stale-external-write`?`stale-external-write`:`git`,...u===void 0?{}:{reason:u},resolutionOptions:d},{handler:`sync-conflict-content`})},h=r.searchParams.get(`source`);switch(s.kind){case`reconcile`:{let e=h===`ytext`&&l?l(f):null;m({base:s.stages.base,ours:knt(s,e),theirs:s.stages.theirs,kind:`both-modified`});return}case`working-tree`:{let e=xA({baseDir:t,timeout:{block:15e3}});try{let n=async t=>{if(!t)return``;try{return await e.raw([`cat-file`,`blob`,t])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:a,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},r=await n(s.theirsSha),i=await n(s.baseSha),o=``,c=!1;if(p){let e=l?l(f):null;e!==null&&(o=e,c=!0)}else{jY(W(t,a),t,{allowShareableOkArtifact:mG});try{o=J(W(t,a),`utf-8`),c=!0}catch(e){if(QU(e)!==`ENOENT`)throw console.warn(JSON.stringify({event:`conflict-content-ours-read-failed`,file:a,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e;c=!1}}m({base:i,ours:o,theirs:r,kind:c?r.length===0?`modify-delete`:`both-modified`:`delete-modify`})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}case`merge-native`:{let e=xA({baseDir:t,timeout:{block:15e3}}),r=async t=>{try{return{present:!0,content:await e.raw([`show`,`:${t}:${a}`])}}catch(e){let n=e instanceof Error?e.message:String(e);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:t,file:a,detail:n,handler:`sync-conflict-content`})),e;return{present:!1}}};try{let[e,t,n]=await Promise.all([r(1),r(2),r(3)]),i=e.present?e.content:``,a=n.present?n.content:``,o=t.present&&n.present?`both-modified`:!t.present&&n.present?`delete-modify`:t.present&&!n.present?`modify-delete`:`both-modified`,s=t.present?t.content:``;if(h===`ytext`&&p!==void 0&&o!==`delete-modify`){let e=l?l(f):null;e!==null&&!qJ(e)?s=e:e!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":f,handler:`sync-conflict-content`}))}m({base:i,ours:s,theirs:a,kind:o})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}default:Q(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:Error(`unknown conflict kind: ${JSON.stringify(s)}`)});return}}return VQ({"/api/sync/status":f,"/api/sync/trigger":p,"/api/sync/conflicts":h,"/api/sync/conflict-content":_,"/api/sync/resolve-conflict":g,"/api/sync/resolve-blocking":m},{mutating:[`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/sync/resolve-blocking`]})}function FCt(){return process.platform===`win32`?ws.join(process.env.SystemRoot??`C:\\Windows`,`System32`):`/`}function ICt(){return{detached:!0,stdio:`ignore`,shell:!1,cwd:FCt(),env:o(process.env)}}function LCt(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function n8(e,t,n,r={}){return new Promise(i=>{let a=!1,o=e=>{a||(a=!0,i(e))},s=setTimeout(()=>o({ok:!1,reason:`timeout`}),n);try{let n=Cc(e,[...t],eH({...ICt(),...r}));n.once(`error`,e=>{clearTimeout(s),o(LCt(e))}),n.once(`spawn`,()=>{if(!a){try{n.unref()}catch{}clearTimeout(s),o({ok:!0})}})}catch(e){Y(`spawn-detached`).warn({err:e},`synchronous spawn throw`),clearTimeout(s),o(LCt(e))}})}const r8=`spawn-cursor`;function RCt(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function zCt(e,t,n){if(e.method!==`POST`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:r8,extraHeaders:{Allow:`POST`}});return}let r;try{r=await WQ(e,{maxBytes:4096,timeoutMs:5e3})}catch(e){if(e instanceof GQ){KQ(t,r8);return}if(e instanceof qQ){Q(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:r8,cause:e});return}if(e instanceof JQ){Q(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:r8,cause:e});return}Q(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:r8,cause:e});return}let i;try{i=JSON.parse(r.toString(`utf-8`))}catch(e){Q(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:r8,cause:e});return}let a=typeof i.path==`string`?i.path:``;if(!a){Q(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:r8});return}if(!o8(a,n.contentDir,n.platform)){Q(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:r8});return}let o=await(n.resolveCursorBinary??i8)(500);if(!o){Q(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:r8});return}let s=a8(o,a,n.platform),c=await(n.spawnDetached??n8)(s.exec,s.args,2e3,{windowsVerbatimArguments:s.windowsVerbatimArguments});if(c.ok){$(t,200,dr,{},{handler:r8});return}switch(c.reason){case`not-installed`:Q(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:r8});return;case`timeout`:Q(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:r8});return;case`spawn-error`:Q(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:r8});return;case`invalid-path`:Q(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:r8});return;default:return RCt(c.reason)}}const BCt={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function i8(e){let t=BCt[process.platform];if(t&&t.length>0){let e=Ys();for(let n of t){let t=n(e);try{return await ec(t,tc.X_OK),t}catch(e){let n=e?.code;n!==`ENOENT`&&n!==`EACCES`&&n!==`EPERM`&&Y(`spawn-cursor`).warn({code:n,candidate:t},`unexpected fs.access error on bundle probe`)}}}return GCt(e)}const VCt=new WeakMap;function HCt(e,t){let n=VCt.get(e)??new Map;VCt.set(e,n);let r=n.get(t);if(r)return r;let i=e(t).finally(()=>n.delete(t));return n.set(t,i),i}async function UCt(e){try{return(await cc(e)).isFile()}catch{return!1}}async function WCt(e,t,n){let r=!1,i,a=new Promise(e=>{i=setTimeout(()=>{r=!0,e(null)},t)}),o=(async()=>{for(let t of e){if(r)return null;if(await HCt(n,t))return t}return null})();try{return await Promise.race([o,a])}finally{clearTimeout(i)}}async function GCt(e,t=process.platform,n=process.env,r=UCt){return t===`win32`?WCt(wU(`cursor`,n.PATH).filter(e=>ws.isAbsolute(e)),e,r):new Promise(t=>{xc(`which`,[`cursor`],eH({timeout:e,encoding:`utf-8`,env:n}),(e,n)=>{if(e){t(null);return}let r=n.split(/\r?\n/)[0]?.trim();t(r&&r.length>0?r:null)})})}function a8(e,t,n){if(n===`darwin`&&/\.app\/?$/.test(e))return{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t],windowsVerbatimArguments:!1};if(n===`win32`&&/\.(cmd|bat)$/i.test(e)){let{cmd:n,args:r}=EU(e,[t]);return{exec:n,args:r,windowsVerbatimArguments:!0}}return{exec:e,args:[t],windowsVerbatimArguments:!1}}function o8(e,t,n){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(n===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let r=n===`win32`?ws:Ss;try{let i=r.resolve(e),a=r.resolve(t);if(n===`win32`){let e=r.parse(i).root.toLowerCase(),t=r.parse(a).root.toLowerCase();if(!e||!t||e!==t)return!1}if(i===a)return!0;let o=r.relative(a,i);return o===``||o===`.`||!(o===`..`||o.startsWith(`..${r.sep}`)||n===`win32`&&(/^[a-zA-Z]:[\\/]/.test(o)||o.startsWith(`\\\\`))||n!==`win32`&&o.startsWith(`/`))}catch(e){return Y(`spawn-cursor`).warn({err:e},`unexpected path-resolution error`),!1}}const KCt=Y(`handoff-dispatch`),s8=`handoff`,c8=2e3,qCt={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},JCt=Object.keys(qCt),YCt=H({target:Li(JCt),url:V().min(1).max(4096),workspacePath:V().optional()}),XCt=H({}).loose();async function ZCt(e,t,n){if(e.method!==`POST`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:s8,extraHeaders:{Allow:`POST`}});return}let r;try{r=await WQ(e,{maxBytes:4096,timeoutMs:5e3})}catch(e){if(e instanceof GQ){KQ(t,s8);return}if(e instanceof qQ){Q(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s8,cause:e});return}if(e instanceof JQ){Q(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s8,cause:e});return}Q(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s8,cause:e});return}let i;try{i=JSON.parse(r.toString(`utf-8`))}catch(e){Q(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:s8,cause:e});return}let a=YCt.safeParse(i);if(!a.success){Q(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:s8});return}let{target:o,url:s,workspacePath:c}=a.data,l=qCt[o];if(!s.startsWith(l.urlScheme)){Q(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${l.urlScheme} for target ${o}.`,{handler:s8});return}let u=n.sleep??j,d=n.spawnDetached??n8,f=n.isSchemeRegistered??X$(n.platform);if(await Gz({site:`deep-link`,agentId:Lte(o)??o,mode:`external`,log:KCt,snapshot:n.hostSnapshot}),l.type===`app-bundle`){if(n.platform===`darwin`){l.quitFirst&&(await d(`/usr/bin/osascript`,[`-e`,`tell application "${l.appName}" to quit`],c8).catch(()=>void 0),await u(3e3));let e=await d(`/usr/bin/open`,[`-a`,l.appName],c8);if(!e.ok){l8(t,o,e.reason);return}await u(5e3)}else if(!await f(l.probeScheme)){Q(t,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:s8,extensions:{target:o}});return}let e=QCt(s,n.platform),r=await d(e.exec,e.args,c8);if(!r.ok){l8(t,o,r.reason);return}$(t,200,XCt,{},{handler:s8});return}if(!c){Q(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:s8});return}if(!o8(c,n.contentDir,n.platform)){Q(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:s8});return}let p=await(n.resolveCursorBinary??i8)(500);if(!p){Q(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:s8,extensions:{target:`cursor`}});return}let m=a8(p,c,n.platform),h=await d(m.exec,m.args,c8,{windowsVerbatimArguments:m.windowsVerbatimArguments});if(!h.ok){l8(t,o,h.reason);return}await u(1500);let g=QCt(s,n.platform),_=await d(g.exec,g.args,c8);if(!_.ok){l8(t,o,_.reason);return}$(t,200,XCt,{},{handler:s8})}function QCt(e,t){return t===`darwin`?{exec:`/usr/bin/open`,args:[e]}:t===`win32`?{exec:`rundll32.exe`,args:[`url.dll,FileProtocolHandler`,e]}:{exec:`xdg-open`,args:[e]}}function l8(e,t,n){switch(n){case`not-installed`:Q(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:s8,extensions:{target:t}});return;case`timeout`:Q(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:s8,extensions:{target:t}});return;case`spawn-error`:Q(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:s8,extensions:{target:t}});return;default:$Ct(n)}}function $Ct(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}function ewt(e){let{contentDir:t,log:n,checkLocalOpSecurity:r,installedAgentsCache:i,agentIntegrations:a}=e;async function o(e,o){if(r(e,o,{handler:`handoff`}))try{await ZCt(e,o,{contentDir:t,platform:process.platform,isSchemeRegistered:i.probeWithCache,hostSnapshot:()=>wq({env:`local-web`,resolve:a?.probe})})}catch(t){o.headersSent||(n.error({err:t,requestId:VK(e)},`[handoff] route wrapper failed`),Q(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:t}))}}async function s(e,i){if(r(e,i,{handler:`spawn-cursor`}))try{await zCt(e,i,{contentDir:t,platform:process.platform})}catch(t){i.headersSent||(n.error({err:t,requestId:VK(e)},`[spawn-cursor] route wrapper failed`),Q(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:t}))}}return VQ({"/api/spawn-cursor":s,"/api/handoff":o,"/api/client-logs":XQ(ure,async(e,t,n)=>{try{let r=Y(`renderer`),i=ast(e)?.clientSurface,a=i===void 0?{}:{clientSurface:i};n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&r.warn({source:`renderer-console`,transport:`web`,...a,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let e of n.entries)try{r[e.level]({...e.fields,source:`renderer-console`,transport:`web`,...a,...e.sourceId?{sourceId:e.sourceId}:{},...e.lineNumber===void 0?{}:{lineNumber:e.lineNumber},...e.ts===void 0?{}:{clientTs:e.ts}},e.event??e.message)}catch{}$(t,200,Gre,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})})},{mutating:[`/api/client-logs`]})}const u8=Y(`github-permissions`);function twt(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function nwt(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function d8(e){return e.status===429||e.status===403&&(e.headers.get(`x-ratelimit-remaining`)===`0`||e.headers.get(`retry-after`)!==null)}function rwt(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let n=t.push;return typeof n==`boolean`?n:null}async function iwt(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return u8.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=rwt(t);return n===null?(u8.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:case 429:return d8(e)?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return u8.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function awt(e,t,n,r,i){let a=n(e,{login:t?.login});if(a.available&&a.token){if(t?.login!==void 0&&a.fallback===!0){let n=cwt(i,e);S6(n,t.login)||u8.warn({host:e,declaredLogin:t.login,declaredSource:t.source,resolvedLogin:n},`[permissions] declared GitHub account did not produce the gh token — probing as the active account`)}return{token:a.token,source:`gh`,resolvedLogin:a.resolvedLogin}}if(r)try{let t=await r.get(e);if(t?.token){let e=t.login===`unknown`?void 0:t.login;return{token:t.token,source:`token-store`,resolvedLogin:e}}}catch(t){u8.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}function owt(e,t){let n=t.resolvedLogin??(t.tokenSource===`gh`?cwt(t.detectGhAccounts,t.host):void 0);return{...e,...n===void 0?{}:{resolvedLogin:n},...swt(t.account,n)}}function swt(e,t){return e?.login===void 0||S6(e.login,t)?{}:{declaredLogin:e.login,declaredSource:e.source}}function cwt(e,t){if(e)try{return e(t)?.find(e=>e.active)?.login}catch(e){u8.warn({err:e,host:t},`[permissions] detectGhAccounts failed — denial stays unnamed`);return}}async function lwt(e){let{owner:t,repo:n,host:r=`github.com`,transport:i=`https`,account:a,detectGh:o=()=>({available:!1}),detectGhAccounts:s,tokenStore:c,_fetchFn:l=fetch,_timeoutMs:u=5e3}=e,{token:d,source:f,resolvedLogin:p}=await awt(r,a,o,c,s);if(f===`anonymous`)return i===`ssh`||i===`git`?(u8.info({host:r,transport:i},`[permissions] no credential resolved for ssh/git origin — abstaining (push auths with SSH keys, not tokens)`),{kind:`unknown`,error:`ssh-unverified`}):(u8.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`,...swt(a,void 0)});let m=`${twt(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;u8.info({host:r,tokenSource:f,tokenLen:d===void 0?0:d.length},`[permissions] probe starting`);let h=new AbortController,g=setTimeout(()=>h.abort(),u);try{let e=await l(m,{signal:h.signal,headers:nwt(d)}),t=await iwt(e,d!==void 0),n=t.kind===`denied`?owt(t,{account:a,tokenSource:f,resolvedLogin:p,detectGhAccounts:s,host:r}):t;return u8.info({host:r,tokenSource:f,httpStatus:e.status,kind:n.kind,reason:n.kind===`denied`?n.reason:void 0,error:n.kind===`unknown`?n.error:void 0},`[permissions] probe classified`),n}catch(e){return h.signal.aborted?(u8.warn({host:r,timeoutMs:u},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(u8.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(g)}}async function uwt(e){let t=performance.now(),n=await lwt(e);return gwt(n,performance.now()-t),n}function dwt(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let fwt=null;function pwt(){return fwt||=CV().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,ssh-unverified,none}.`}),fwt}let mwt=null;function hwt(){return mwt||=CV().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),mwt}function gwt(e,t){let n=dwt(e);pwt().add(1,n),hwt().record(t,{outcome:n.outcome})}const _wt=Y(`github-reference`);function vwt(e,t){let n=e.get(t);if(n===null||n.trim()===``)return null;let r=Number(n);return Number.isFinite(r)&&r>=0?r:null}function ywt(e,t){let n=vwt(e,`retry-after`);if(n!==null)return t+Math.max(n,1)*1e3;let r=vwt(e,`x-ratelimit-reset`);return e.get(`x-ratelimit-remaining`)===`0`&&r!==null&&r*1e3>t?r*1e3:t+6e4}function bwt(e){return e.status===200?!1:e.headers.get(`retry-after`)!==null||e.headers.get(`x-ratelimit-remaining`)!==`0`}const xwt=new Set([`RATE_LIMITED`,`RATE_LIMIT`]);function Swt(e){let t=p8(e)?.errors;return Array.isArray(t)&&t.some(e=>xwt.has(p8(e)?.type))}const Cwt={graphql:`[github-reference] GitHub rate-limited reference cards; no GraphQL requests to this host until the limit resets`,rest:`[github-reference] GitHub rate-limited reference cards; no REST requests to this host until the limit resets`,"graphql+rest":`[github-reference] GitHub rate-limited reference cards; no GraphQL or REST requests to this host until the limit resets`};var wwt=class{until=new Map;holding(e,t){let n=this.until.get(e);return n===void 0?!1:n>t||(this.until.delete(e),!1)}hold(e,t,n){let r=Math.max(this.until.get(e)??0,Math.min(n+36e5,ywt(t,n)));return this.until.set(e,r),r}};const Twt={ok:!1,reason:`not-found`},f8={ok:!1,reason:`unavailable`};function p8(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function m8(e){return typeof e==`string`?e:null}function h8(e){return m8(p8(e)?.login)}function Ewt(e){return`${e.host===`github.com`?`https://api.github.com`:`https://${e.host}/api/v3`}/repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function Dwt(e){return e===`github.com`?`https://api.github.com/graphql`:`https://${e}/api/graphql`}function Owt(e,t){let n={"User-Agent":`open-knowledge-server`,Accept:t};return e!==null&&(n.Authorization=`Bearer ${e}`),n}async function g8(e,t,n,r){let i=new AbortController,a=setTimeout(()=>i.abort(),r);try{let r=await n(e,{...t,signal:i.signal});return r.status===200?{status:200,headers:r.headers,body:await r.json()}:(await r.body?.cancel(),{status:r.status,headers:r.headers,body:null})}finally{clearTimeout(a)}}function kwt(e,t){if(e?.toUpperCase()===`OPEN`)return`open`;let n=t?.toUpperCase();return n===`NOT_PLANNED`||n===`DUPLICATE`?`not-planned`:`completed`}function _8(e){let t=Vt.safeParse(e);return t.success?t.data:null}function Awt(e,t){let n=p8(t);if(n===null)return null;let r={repo:`${e.owner}/${e.repo}`,number:e.number,title:n.title,author:h8(n.author),createdAt:n.createdAt};if(n.__typename===`Issue`)return _8({...r,kind:`issue`,lifecycle:kwt(m8(n.state),m8(n.stateReason))});if(n.__typename!==`PullRequest`)return null;let i=m8(n.state),a=i===`MERGED`?`merged`:i===`CLOSED`?`closed`:n.isDraft===!0?`draft`:`open`,o=p8(n.commits)?.nodes,s=Array.isArray(o)?p8(p8(o.at(-1))?.commit):null,c=p8(n.mergeQueueEntry);return _8({...r,kind:`pull`,lifecycle:a,additions:n.additions,deletions:n.deletions,...a===`open`?{status:{mergeQueue:c===null?null:{position:c.position,state:c.state},autoMerge:p8(n.autoMergeRequest)!==null,mergeState:n.mergeStateStatus,reviewDecision:n.reviewDecision,checks:p8(s?.statusCheckRollup)?.state??null}}:{}})}function jwt(e,t,n){let r={repo:`${e.owner}/${e.repo}`,number:e.number},i=p8(n);if(i!==null){let e=i.merged===!0||m8(i.merged_at)!==null?`merged`:i.state===`closed`?`closed`:i.draft===!0?`draft`:`open`,t=m8(i.mergeable_state)?.toUpperCase()??null;return _8({...r,kind:`pull`,title:i.title,author:h8(i.user),createdAt:i.created_at,lifecycle:e,additions:i.additions,deletions:i.deletions,...e===`open`?{status:{mergeQueue:null,autoMerge:p8(i.auto_merge)!==null,mergeState:t,reviewDecision:null,checks:null}}:{}})}let a=p8(t);return a===null?null:_8({...r,kind:`issue`,title:a.title,author:h8(a.user),createdAt:a.created_at,lifecycle:kwt(m8(a.state),m8(a.state_reason))})}async function Mwt(e,t,n,r,i){let a=await g8(Dwt(e.host),{method:`POST`,headers:{...Owt(t,`application/vnd.github.merge-info-preview+json`),"Content-Type":`application/json`},body:JSON.stringify({query:`query($owner: String!, $name: String!, $number: Int!) {
|
|
2170
2170
|
repository(owner: $owner, name: $name) {
|
|
2171
2171
|
issueOrPullRequest(number: $number) {
|
|
2172
2172
|
__typename
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Cc as e,Et as t,Ot as n,Pc as r,S as i,X as a,_c as o,no as s,v as c}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{$ as l,$a as u,$i as d,$n as f,$r as p,$t as m,A as h,Aa as g,Ai as _,An as v,Ao as y,Ar as b,At as x,B as S,Ba as C,Bi as w,Bn as T,Bo as E,Br as D,Bt as O,C as k,Ca as A,Ci as j,Cn as M,Co as N,Cr as P,Cs as F,Ct as I,D as L,Da as R,Di as z,Dn as B,Do as V,Dr as H,Dt as U,E as W,Ea as G,Ei as K,En as q,Eo as J,Er as Y,Et as X,F as Z,Fa as Q,Fi as $,Fn as ee,Fo as te,Fr as ne,Ft as re,G as ie,Ga as ae,Gi as oe,Gn as se,Go as ce,Gr as le,Gs as ue,Gt as de,H as fe,Ha as pe,Hi as me,Hn as he,Ho as ge,Hr as _e,Ht as ve,I as ye,Ia as be,Ii as xe,In as Se,Io as Ce,Ir as we,It as Te,J as Ee,Ja as De,Ji as Oe,Jn as ke,Jo as Ae,Jr as je,Jt as Me,K as Ne,Ka as Pe,Ki as Fe,Kn as Ie,Ko as Le,Kr as Re,Ks as ze,Kt as Be,L as Ve,La as He,Li as Ue,Ln as We,Lo as Ge,Lr as Ke,Lt as qe,M as Je,Ma as Ye,Mi as Xe,Mn as Ze,Mo as Qe,Mr as $e,Mt as et,N as tt,Na as nt,Ni as rt,Nn as it,No as at,Nr as ot,Nt as st,O as ct,Oa as lt,Oi as ut,On as dt,Oo as ft,Or as pt,Ot as mt,P as ht,Pa as gt,Pi as _t,Pn as vt,Po as yt,Pr as bt,Pt as xt,Q as St,Qa as Ct,Qi as wt,Qn as Tt,Qr as Et,Qt as Dt,R as Ot,Ra as kt,Ri as At,Rn as jt,Ro as Mt,Rr as Nt,Rt as Pt,S as Ft,Sa as It,Si as Lt,Sn as Rt,So as zt,Sr as Bt,Ss as Vt,St as Ht,T as Ut,Ta as Wt,Ti as Gt,Tn as Kt,To as qt,Tr as Jt,Ts as Yt,Tt as Xt,U as Zt,Ua as Qt,Ui as $t,Un as en,Uo as tn,Ur as nn,Ut as rn,V as an,Va as on,Vi as sn,Vn as cn,Vo as ln,Vr as un,Vt as dn,W as fn,Wa as pn,Wi as mn,Wn as hn,Wo as gn,Wr as _n,Ws as vn,Wt as yn,X as bn,Xa as xn,Xi as Sn,Xn as Cn,Xo as wn,Xr as Tn,Xt as En,Y as Dn,Ya as On,Yi as kn,Yn as An,Yo as jn,Yr as Mn,Yt as Nn,Z as Pn,Za as Fn,Zi as In,Zn as Ln,Zr as Rn,Zt as zn,_ as Bn,_a as Vn,_i as Hn,_n as Un,_o as Wn,_r as Gn,_s as Kn,_t as qn,a as Jn,aa as Yn,ai as Xn,an as Zn,ao as Qn,ar as $n,at as er,b as tr,ba as nr,bi as rr,bn as ir,bo as ar,br as or,bs as sr,bt as cr,c as lr,ca as ur,ci as dr,cn as fr,co as pr,cr as mr,ct as hr,d as gr,da as _r,di as vr,dn as yr,do as br,dr as xr,dt as Sr,ea as Cr,ei as wr,en as Tr,eo as Er,er as Dr,et as Or,f as kr,fa as Ar,fi as jr,fn as Mr,fo as Nr,fr as Pr,fs as Fr,ft as Ir,g as Lr,ga as Rr,gi as zr,gn as Br,go as Vr,gr as Hr,gt as Ur,h as Wr,ha as Gr,hi as Kr,hn as qr,ho as Jr,hr as Yr,ht as Xr,i as Zr,ia as Qr,ii as $r,in as ei,io as ti,ir as ni,it as ri,j as ii,ja as ai,ji as oi,jn as si,jo as ci,jr as li,jt as ui,k as di,ka as fi,ki as pi,kn as mi,ko as hi,kr as gi,kt as _i,l as vi,la as yi,li as bi,ln as xi,lo as Si,lr as Ci,lt as wi,m as Ti,ma as Ei,mi as Di,mn as Oi,mo as ki,mr as Ai,mt as ji,n as Mi,na as Ni,ni as Pi,nn as Fi,no as Ii,nr as Li,nt as Ri,o as zi,oa as Bi,oi as Vi,on as Hi,oo as Ui,or as Wi,ot as Gi,p as Ki,pa as qi,pi as Ji,pn as Yi,po as Xi,pr as Zi,ps as Qi,pt as $i,q as ea,qa as ta,qi as na,qn as ra,qo as ia,qr as aa,qs as oa,qt as sa,r as ca,ra as la,ri as ua,rn as da,ro as fa,rr as pa,rt as ma,s as ha,sa as ga,si as _a,sn as va,so as ya,sr as ba,st as xa,t as Sa,ta as Ca,ti as wa,tn as Ta,to as Ea,tr as Da,tt as Oa,u as ka,ua as Aa,ui as ja,un as Ma,uo as Na,ur as Pa,ut as Fa,v as Ia,va as La,vi as Ra,vn as za,vo as Ba,vr as Va,vs as Ha,vt as Ua,w as Wa,wa as Ga,wi as Ka,wn as qa,wo as Ja,wr as Ya,ws as Xa,wt as Za,x as Qa,xa as $a,xi as eo,xn as to,xo as no,xr as ro,xs as io,xt as ao,y as oo,ya as so,yi as co,yn as lo,yo as uo,yr as fo,ys as po,yt as mo,z as ho,za as go,zi as _o,zn as vo,zo as yo,zr as bo,zt as xo}from"./dist-CLk9BDyE.mjs";import{f as So,h as Co,m as wo,n as To,p as Eo,t as Do}from"./fs-find-project-root-pgJRBsWv.mjs";export{Sa as AGENT_ID_MAX_LEN,Mi as AGENT_ID_RE,ca as AGENT_WRITE_ORIGIN,s as AUDIT_EMPTY_SCOPE_WARNING,Zr as AcpPermissionStore,Jn as AcpRegistry,zi as AcpThreadManager,ha as AgentFocusBroadcaster,lr as AgentPresenceBroadcaster,vi as AgentSessionCapacityError,ka as AgentSessionManager,gr as AutoStartDisabledError,kr as BUNDLE_IDS,Ki as BUNDLE_SCOPE,Ti as BUNDLE_SKILL_NAME,Wr as BacklinkIndex,Lr as CC1Broadcaster,e as CC1_CONTRACT_VERSION,Bn as CONCURRENT_REPLACE_WINDOW_MS,Ia as CONFIG_FILENAME,oo as CONFLICT_MARKER_RE,tr as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Qa as ConfigSchema,Ft as ConflictAuthority,k as DEFAULT_CHECKPOINT_RETENTION,Wa as DEFAULT_EMBEDDINGS_DIMENSIONS,Ut as DEFAULT_PACK_ID,W as DocumentDurabilityState,L as DocumentDurabilityStateError,ct as EMBEDDINGS_API_KEY_ENV,di as EPHEMERAL_PROJECT_DIR_PREFIX,h as EmbeddingsSecretStoreError,ii as ExposureConsentError,Je as FEATURED_AGENT_IDS,tt as FILE_SYSTEM_WRITER,ht as FILE_WATCHER_ORIGIN,Z as FileEmbeddingsBackend,ye as FilesystemRootProjectError,Ve as GIT_PREFLIGHT_FAIL_SPAN_NAME,Ot as GIT_UPSTREAM_WRITER,Fr as GitDirAccessError,ho as GitNotAvailableError,S as GitProbeTimeoutError,an as GitTooOldError,fe as HOCUSPOCUS_AUTH_REJECTION_REASONS,Zt as HocuspocusAuthRejection,fn as HocuspocusAuthTokenSchema,ie as HomeProjectRootError,Ne as INSTALLED_AGENTS_SCHEMES,ea as JSON_SCHEMA_DIALECT_2020_12,ze as LINEAGE_EPOCH_KEY,Ee as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Dn as LOCK_FILE_ACCESS_REMEDY,bn as MANAGED_RENAME_ORIGIN,Pn as MAX_ACP_THREADS,St as MAX_AGENT_SESSIONS,l as MCP_CONNECTION_ID_HEADER,o as MCP_SERVER_NAME,Or as MIN_EVICTABLE_IDLE_MS,Oa as MIN_GIT_VERSION,Qi as MalformedGitPointerError,Ri as McpLogger,ma as MissingOkConfigError,ri as OBSERVER_SYNC_ORIGIN,er as OK_OKIGNORE_TEMPLATE,Gi as ONBOARDING_BUNDLE_IDS,vn as ORPHAN_MODES,oa as PROTOCOL_VERSION,Kn as PinoLogger,xa as ProcessLockCollisionError,hr as ProcessLockFileError,wi as ProjectGitInitError,Fa as ROLLBACK_ORIGIN,Sr as ROOT_GITIGNORE_TEMPLATE,Ir as RUNTIME_VERSION,$i as SERVICE_WRITER,ji as SKILL_INSTALL_EVENTS_FILENAME,c as SKILL_STATE_TARGETS,Xr as STARTER_FOLDER_FRONTMATTER_FILENAME,Ur as STARTER_PACKS,qn as STARTER_PACK_IDS,Ua as STATE_MANIFEST_FILENAME,mo as STATE_SCHEMA_VERSION,cr as SYMLINK_MERGE_MIN_GIT_LABEL,ao as SYMLINK_MERGE_MIN_GIT_VERSION,r as SYSTEM_DOC_NAME,Ht as SeedPrerequisiteError,I as SeedRootDirError,Za as ServerAuthorityCollisionError,Xt as ServerAuthorityRegistryError,X as ServerLockCollisionError,U as SingleFileNotAFileError,mt as SingleFileNotFoundError,_i as SingleFileNotMarkdownError,x as SingleFileProjectOverrideError,ui as StateManifestError,i as TEST_LOOP_CORE_MARKER,et as TEST_LOOP_SERVER_MARKER,st as TagIndex,xt as USER_GLOBAL_BUNDLE_IDS,re as UnsafeIncomingSymlinkError,Te as __getShowAllWalkStatsForTesting,qe as __resetShowAllWalkStatsForTesting,Pt as acpThreadStoreRoots,xo as acpThreadsDir,O as acquireProcessLock,dn as acquireServerLock,ve as applyAgentMarkdownWrite,rn as applyExternalChange,yn as applySeed,de as assertCheckoutSymlinksSafe,Be as assertCompatibleStateManifest,sa as assertGitAvailable,Me as assertIncomingSymlinksSafe,Nn as assertMergeNameResolvesTo,En as assertNeverDiskEvent,zn as assertRepoCheckoutSymlinksSafe,Dt as assertSafeProjectRoot,m as assessLockHolder,Tr as attachAcpThreadSocket,Ta as attachCollabClientCounter,Fi as attachIdleShutdown,da as auditScopeNotFoundTitle,ei as bindConflictAuthority,Zn as bootServer,Hi as buildAndOpenSkill,va as buildConfigYmlContent,fr as buildExecResult,xi as buildIngressPolicy,Ma as buildOkMcpStdioCommand,yr as buildSkillZip,Mr as buildStarterFolderFrontmatterYaml,Yi as buildWipTree,Oi as bundleSkillMdPath,qr as canonicalProjectKey,Br as canonicalizeForCompare,Un as classifyEvents,za as classifyFsPath,lo as classifyLockHolder,ir as clearAllEmbeddingsKeys,to as coercePackId,Rt as collectServerHostSnapshot,t as colorFromSeed,M as commitUpstreamImport,qa as commitWip,Kt as commitWipFromTree,q as compareSemver,B as composeEffectiveLinterConfig,dt as composeFrontmatterSchemasConfig,mi as containsConflictMarkers,v as contentHash,si as contributorCount,Ze as countShadowObjects,it as countStaleAgentWipRefs,vt as countWipRefs,ee as createApiExtension,Se as createAssetServeMiddleware,We as createCollaborationHost,jt as createContentFilter,vo as createContentFilterAsync,T as createEmbeddingsSecretStore,cn as createEphemeralProjectDir,he as createExternalChangeHandler,So as createFileLogger,en as createLiveDerivedIndexExtension,hn as createMcpHttpHandler,se as createOsProbe,Ie as createPersistenceExtension,ra as createProbeFailureReporter,ke as createServer,An as createServerObserverExtension,Cn as createServerProbeResolver,Ln as createStreamingErrorWriter,Ha as createTestLogger,Tt as describeStoredEmbeddingsKey,f as detectClaudeDesktopPresence,Dr as detectGit,Da as detectProjectShape,Li as detectUserSkillHosts,pa as discoverLockDirs,ni as discoverMarkdownlintConfig,$n as emitPreflightFailureSpan,Wi as encodeDocName,ba as encodeFolderRoute,mr as encodeSkillRoute,Ci as ensureProjectGit,Pa as errorResponse,xr as evictStaleTrackerEntries,Pr as extractHeadings,Zi as extractOkBinaryPath,Ai as extractWikiLinksFromMarkdown,Yr as fallbackPaths,Hr as findEnclosingGitRoot,Do as findEnclosingProjectRoot,Gn as findNativeMarkdownlintFile,Eo as flushFileLogger,Va as formatAuditBrokenLinkSuppressionLine,fo as formatAuthRejectionWire,or as formatContributorsFrom,ro as formatPackRationale,Bt as gcCheckpointRefs,P as getCurrentMcpLogger,Ya as getIngressContext,Jt as getLocalDir,wo as getLogFilePath,po as getLogger,Co as getLogsDir,Y as getMachineId,H as getMeter,pt as getMetrics,gi as getTracer,b as handleCollabSocketError,li as handleSpawnCursor,$e as hasForwardingHeaders,ot as hasGcLogLatch,n as iconFromClientName,bt as incrementCollabSocketFilteredError,ne as incrementServerObserverFire,we as initContent,Ke as initShadowRepo,Nt as initTelemetry,bo as initToleranceTelemetryWriter,D as installJsonSchemaDialect,un as installPrettyZodErrors,sr as installTestLoggers,_e as installUserSkill,nn as isAllowedApiOrigin,_n as isAllowedWorkspaceHostHeader,le as isConfigDoc,Re as isDefunctProcess,aa as isDocInConflict,je as isFilesystemRoot,Mn as isHocuspocusAuthRejectionReason,Tn as isHomeDir,Rn as isHostAdmitted,Et as isKnownPackId,p as isLinkIndexExcludedDoc,wr as isLockFromThisMachine,wa as isLockProcessRunning,Pi as isLoopbackAddress,ua as isManagedArtifactDoc,$r as isMintedThreadId,Xn as isOriginAdmitted,ue as isOrphanMode,Vi as isPairedWriteOrigin,_a as isPathWithinDir,dr as isPeerAdmitted,bi as isProcessAlive,To as isProjectRoot,ja as isReservedForUserTree,vr as isSelfWrite,jr as isSkillInstallReportEnvOptOut,Ji as isSystemDoc,Di as isToleranceTelemetryEnabled,Kr as isValidLockPid,zr as lastKnownHash,Hn as listRescueCheckpoints,Ra as listStarterPacks,co as loadCustomAgents,rr as loadPrincipal,eo as lockAdvertisesUi,Lt as lockBaseUrl,j as lockFilePath,io as loggerFactory,Ka as loginShapedUserinfoUser,Vt as logsCurrentPath,F as logsPreviousPath,Gt as machineIdFilePath,K as makeLazyEmbeddingsKeyStore,z as markServerLockDraining,ut as missingOkConfigMessage,pi as mountMcpAndApi,_ as normalizeFsPath,oi as observeReadiness,Xe as packageVersionMajorMinor,rt as parseAuthRejectionWire,_t as parseGitVersion,$ as parseHocuspocusAuthToken,xe as parseKeepaliveConnectionId,Ue as parseProcessStartToken,At as pathToDocName,_o as planSeed,w as prepareProjectLogsDir,sn as prepareSingleFileOpen,me as prepareSpawnProjectLogsDir,$t as processCommand,mn as processStartToken,oe as processUsage,Fe as readAgentBrowserTools,na as readAllTargets,Oe as readBootStartedAtMs,kn as readBundleDecision,Sn as readDeclaredGitHubHosts,In as readOriginCredentialHost,wt as readOriginGitHubRepo,d as readOwnNativeRules,Cr as readProcessLock,Ca as readProcessLockDetailed,Ni as readProcessStart,la as readProcessState,Qr as readProjectHeadState,Yn as readProjectLocalSemanticConfig,Bi as readServerLock,ga as readServerPackageVersion,ur as readSkillInstallStateSnapshot,yi as readStateManifest,Aa as readTargetRecordedAt,_r as readTargetVersion,Ar as reconcile,qi as recordContributor,Ei as recordSkillInstallEvent,Gr as recordsLockOwner,Rr as redactShareSubprocessStderr,Vn as registerAllTools,La as registerNativeProcessStartReader,so as registerWrite,nr as releaseProcessLock,$a as releaseServerLock,It as removeLastKnownHash,A as removeLockIfUnchanged,Ga as removeProjectSkillGitignoreBlock,Wt as reportSkillInstall,G as resetMetrics,R as resolveAuditScope,lt as resolveBuiltinSkillHosts,a as resolveBundleEnabled,fi as resolveBundledSkillDir,g as resolveContentDir,ai as resolveCursorBinaryDefault,Ye as resolveCursorSpawnInvocation,nt as resolveEffectiveLinterConfig,gt as resolveEmbeddingsCredential,Q as resolveGitHubAccountFromUrl,be as resolveGitHubAuthHost,He as resolveLockDir,kt as resolveNativeConfigForDoc,go as resolveNativeMarkdownlintConfig,C as resolvePack,on as resolvePackageVersion,pe as resolveSkillInstallReportSettings,Qt as resolveUiInfo,pn as restoreContributors,ae as rewriteMarkdownLinksForDocumentRename,Pe as rewriteWikiLinksForDocumentRename,ta as runAuthReposSubprocess,De as runAuthStatusSubprocess,On as runCloneSubprocess,xn as runDeviceFlowSubprocess,Fn as runWithMcpLogger,Ct as safeContentPath,u as safeSubdir,Er as safetyCheckpoint,Ea as sameGitHubLogin,Ii as sanitizeClientName,fa as saveInMemoryCheckpoint,ti as saveVersion,Qn as scanLockProcesses,Ui as seedBasenameIndex,ya as seedEphemeralProjectDir,pr as serializeError,Si as setActiveSpanAttributes,Na as setupServerObservers,br as shadowGit,Nr as shutdownTelemetry,Xa as spansCurrentPath,Yt as spansPreviousPath,Xi as spawnDetached,ki as splitMarkdownBlocks,Jr as startWatcher,Vr as strategiesFor,Wn as streamedChunkOf,Ba as streamingProblemEvent,uo as swapContributors,ar as teardownToleranceTelemetryWriter,no as toBroadcasterKey,zt as toProcessLockMetadata,N as tracedAppendFileSync,Ja as tracedLinkSync,qt as tracedMkdir,J as tracedMkdirSync,V as tracedRename,ft as tracedRenameSync,hi as tracedRmSync,y as tracedRmdirSync,ci as tracedUnlinkSync,Qe as tracedWriteFile,at as tracedWriteFileSync,yt as trustSystemCertificates,te as updateLastKnownHash,Ce as updateProcessLockPort,Ge as updateServerLockPort,Mt as validateAgentId,yo as validateCloneInputs,E as validateSkillZip,ln as waitForServerLockDrain,ge as withHiddenWindowsConsole,tn as withSpan,gn as withSpanSync,ce as writeBundleDecision,Le as writeMarkdownlintRule,ia as writeRootGitignoreForNewRepo,Ae as writeStateManifest,jn as writeTargetVersion,wn as writeTracker};
|
|
1
|
+
import{Cc as e,Et as t,Ot as n,Pc as r,S as i,X as a,_c as o,no as s,v as c}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{$ as l,$a as u,$i as d,$n as f,$r as p,$t as m,A as h,Aa as g,Ai as _,An as v,Ao as y,Ar as b,At as x,B as S,Ba as C,Bi as w,Bn as T,Bo as E,Br as D,Bt as O,C as k,Ca as A,Ci as j,Cn as M,Co as N,Cr as P,Cs as F,Ct as I,D as L,Da as R,Di as z,Dn as B,Do as V,Dr as H,Dt as U,E as W,Ea as G,Ei as K,En as q,Eo as J,Er as Y,Et as X,F as Z,Fa as Q,Fi as $,Fn as ee,Fo as te,Fr as ne,Ft as re,G as ie,Ga as ae,Gi as oe,Gn as se,Go as ce,Gr as le,Gs as ue,Gt as de,H as fe,Ha as pe,Hi as me,Hn as he,Ho as ge,Hr as _e,Ht as ve,I as ye,Ia as be,Ii as xe,In as Se,Io as Ce,Ir as we,It as Te,J as Ee,Ja as De,Ji as Oe,Jn as ke,Jo as Ae,Jr as je,Jt as Me,K as Ne,Ka as Pe,Ki as Fe,Kn as Ie,Ko as Le,Kr as Re,Ks as ze,Kt as Be,L as Ve,La as He,Li as Ue,Ln as We,Lo as Ge,Lr as Ke,Lt as qe,M as Je,Ma as Ye,Mi as Xe,Mn as Ze,Mo as Qe,Mr as $e,Mt as et,N as tt,Na as nt,Ni as rt,Nn as it,No as at,Nr as ot,Nt as st,O as ct,Oa as lt,Oi as ut,On as dt,Oo as ft,Or as pt,Ot as mt,P as ht,Pa as gt,Pi as _t,Pn as vt,Po as yt,Pr as bt,Pt as xt,Q as St,Qa as Ct,Qi as wt,Qn as Tt,Qr as Et,Qt as Dt,R as Ot,Ra as kt,Ri as At,Rn as jt,Ro as Mt,Rr as Nt,Rt as Pt,S as Ft,Sa as It,Si as Lt,Sn as Rt,So as zt,Sr as Bt,Ss as Vt,St as Ht,T as Ut,Ta as Wt,Ti as Gt,Tn as Kt,To as qt,Tr as Jt,Ts as Yt,Tt as Xt,U as Zt,Ua as Qt,Ui as $t,Un as en,Uo as tn,Ur as nn,Ut as rn,V as an,Va as on,Vi as sn,Vn as cn,Vo as ln,Vr as un,Vt as dn,W as fn,Wa as pn,Wi as mn,Wn as hn,Wo as gn,Wr as _n,Ws as vn,Wt as yn,X as bn,Xa as xn,Xi as Sn,Xn as Cn,Xo as wn,Xr as Tn,Xt as En,Y as Dn,Ya as On,Yi as kn,Yn as An,Yo as jn,Yr as Mn,Yt as Nn,Z as Pn,Za as Fn,Zi as In,Zn as Ln,Zr as Rn,Zt as zn,_ as Bn,_a as Vn,_i as Hn,_n as Un,_o as Wn,_r as Gn,_s as Kn,_t as qn,a as Jn,aa as Yn,ai as Xn,an as Zn,ao as Qn,ar as $n,at as er,b as tr,ba as nr,bi as rr,bn as ir,bo as ar,br as or,bs as sr,bt as cr,c as lr,ca as ur,ci as dr,cn as fr,co as pr,cr as mr,ct as hr,d as gr,da as _r,di as vr,dn as yr,do as br,dr as xr,dt as Sr,ea as Cr,ei as wr,en as Tr,eo as Er,er as Dr,et as Or,f as kr,fa as Ar,fi as jr,fn as Mr,fo as Nr,fr as Pr,fs as Fr,ft as Ir,g as Lr,ga as Rr,gi as zr,gn as Br,go as Vr,gr as Hr,gt as Ur,h as Wr,ha as Gr,hi as Kr,hn as qr,ho as Jr,hr as Yr,ht as Xr,i as Zr,ia as Qr,ii as $r,in as ei,io as ti,ir as ni,it as ri,j as ii,ja as ai,ji as oi,jn as si,jo as ci,jr as li,jt as ui,k as di,ka as fi,ki as pi,kn as mi,ko as hi,kr as gi,kt as _i,l as vi,la as yi,li as bi,ln as xi,lo as Si,lr as Ci,lt as wi,m as Ti,ma as Ei,mi as Di,mn as Oi,mo as ki,mr as Ai,mt as ji,n as Mi,na as Ni,ni as Pi,nn as Fi,no as Ii,nr as Li,nt as Ri,o as zi,oa as Bi,oi as Vi,on as Hi,oo as Ui,or as Wi,ot as Gi,p as Ki,pa as qi,pi as Ji,pn as Yi,po as Xi,pr as Zi,ps as Qi,pt as $i,q as ea,qa as ta,qi as na,qn as ra,qo as ia,qr as aa,qs as oa,qt as sa,r as ca,ra as la,ri as ua,rn as da,ro as fa,rr as pa,rt as ma,s as ha,sa as ga,si as _a,sn as va,so as ya,sr as ba,st as xa,t as Sa,ta as Ca,ti as wa,tn as Ta,to as Ea,tr as Da,tt as Oa,u as ka,ua as Aa,ui as ja,un as Ma,uo as Na,ur as Pa,ut as Fa,v as Ia,va as La,vi as Ra,vn as za,vo as Ba,vr as Va,vs as Ha,vt as Ua,w as Wa,wa as Ga,wi as Ka,wn as qa,wo as Ja,wr as Ya,ws as Xa,wt as Za,x as Qa,xa as $a,xi as eo,xn as to,xo as no,xr as ro,xs as io,xt as ao,y as oo,ya as so,yi as co,yn as lo,yo as uo,yr as fo,ys as po,yt as mo,z as ho,za as go,zi as _o,zn as vo,zo as yo,zr as bo,zt as xo}from"./dist-B-QQMMgD.mjs";import{f as So,h as Co,m as wo,n as To,p as Eo,t as Do}from"./fs-find-project-root-pgJRBsWv.mjs";export{Sa as AGENT_ID_MAX_LEN,Mi as AGENT_ID_RE,ca as AGENT_WRITE_ORIGIN,s as AUDIT_EMPTY_SCOPE_WARNING,Zr as AcpPermissionStore,Jn as AcpRegistry,zi as AcpThreadManager,ha as AgentFocusBroadcaster,lr as AgentPresenceBroadcaster,vi as AgentSessionCapacityError,ka as AgentSessionManager,gr as AutoStartDisabledError,kr as BUNDLE_IDS,Ki as BUNDLE_SCOPE,Ti as BUNDLE_SKILL_NAME,Wr as BacklinkIndex,Lr as CC1Broadcaster,e as CC1_CONTRACT_VERSION,Bn as CONCURRENT_REPLACE_WINDOW_MS,Ia as CONFIG_FILENAME,oo as CONFLICT_MARKER_RE,tr as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Qa as ConfigSchema,Ft as ConflictAuthority,k as DEFAULT_CHECKPOINT_RETENTION,Wa as DEFAULT_EMBEDDINGS_DIMENSIONS,Ut as DEFAULT_PACK_ID,W as DocumentDurabilityState,L as DocumentDurabilityStateError,ct as EMBEDDINGS_API_KEY_ENV,di as EPHEMERAL_PROJECT_DIR_PREFIX,h as EmbeddingsSecretStoreError,ii as ExposureConsentError,Je as FEATURED_AGENT_IDS,tt as FILE_SYSTEM_WRITER,ht as FILE_WATCHER_ORIGIN,Z as FileEmbeddingsBackend,ye as FilesystemRootProjectError,Ve as GIT_PREFLIGHT_FAIL_SPAN_NAME,Ot as GIT_UPSTREAM_WRITER,Fr as GitDirAccessError,ho as GitNotAvailableError,S as GitProbeTimeoutError,an as GitTooOldError,fe as HOCUSPOCUS_AUTH_REJECTION_REASONS,Zt as HocuspocusAuthRejection,fn as HocuspocusAuthTokenSchema,ie as HomeProjectRootError,Ne as INSTALLED_AGENTS_SCHEMES,ea as JSON_SCHEMA_DIALECT_2020_12,ze as LINEAGE_EPOCH_KEY,Ee as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Dn as LOCK_FILE_ACCESS_REMEDY,bn as MANAGED_RENAME_ORIGIN,Pn as MAX_ACP_THREADS,St as MAX_AGENT_SESSIONS,l as MCP_CONNECTION_ID_HEADER,o as MCP_SERVER_NAME,Or as MIN_EVICTABLE_IDLE_MS,Oa as MIN_GIT_VERSION,Qi as MalformedGitPointerError,Ri as McpLogger,ma as MissingOkConfigError,ri as OBSERVER_SYNC_ORIGIN,er as OK_OKIGNORE_TEMPLATE,Gi as ONBOARDING_BUNDLE_IDS,vn as ORPHAN_MODES,oa as PROTOCOL_VERSION,Kn as PinoLogger,xa as ProcessLockCollisionError,hr as ProcessLockFileError,wi as ProjectGitInitError,Fa as ROLLBACK_ORIGIN,Sr as ROOT_GITIGNORE_TEMPLATE,Ir as RUNTIME_VERSION,$i as SERVICE_WRITER,ji as SKILL_INSTALL_EVENTS_FILENAME,c as SKILL_STATE_TARGETS,Xr as STARTER_FOLDER_FRONTMATTER_FILENAME,Ur as STARTER_PACKS,qn as STARTER_PACK_IDS,Ua as STATE_MANIFEST_FILENAME,mo as STATE_SCHEMA_VERSION,cr as SYMLINK_MERGE_MIN_GIT_LABEL,ao as SYMLINK_MERGE_MIN_GIT_VERSION,r as SYSTEM_DOC_NAME,Ht as SeedPrerequisiteError,I as SeedRootDirError,Za as ServerAuthorityCollisionError,Xt as ServerAuthorityRegistryError,X as ServerLockCollisionError,U as SingleFileNotAFileError,mt as SingleFileNotFoundError,_i as SingleFileNotMarkdownError,x as SingleFileProjectOverrideError,ui as StateManifestError,i as TEST_LOOP_CORE_MARKER,et as TEST_LOOP_SERVER_MARKER,st as TagIndex,xt as USER_GLOBAL_BUNDLE_IDS,re as UnsafeIncomingSymlinkError,Te as __getShowAllWalkStatsForTesting,qe as __resetShowAllWalkStatsForTesting,Pt as acpThreadStoreRoots,xo as acpThreadsDir,O as acquireProcessLock,dn as acquireServerLock,ve as applyAgentMarkdownWrite,rn as applyExternalChange,yn as applySeed,de as assertCheckoutSymlinksSafe,Be as assertCompatibleStateManifest,sa as assertGitAvailable,Me as assertIncomingSymlinksSafe,Nn as assertMergeNameResolvesTo,En as assertNeverDiskEvent,zn as assertRepoCheckoutSymlinksSafe,Dt as assertSafeProjectRoot,m as assessLockHolder,Tr as attachAcpThreadSocket,Ta as attachCollabClientCounter,Fi as attachIdleShutdown,da as auditScopeNotFoundTitle,ei as bindConflictAuthority,Zn as bootServer,Hi as buildAndOpenSkill,va as buildConfigYmlContent,fr as buildExecResult,xi as buildIngressPolicy,Ma as buildOkMcpStdioCommand,yr as buildSkillZip,Mr as buildStarterFolderFrontmatterYaml,Yi as buildWipTree,Oi as bundleSkillMdPath,qr as canonicalProjectKey,Br as canonicalizeForCompare,Un as classifyEvents,za as classifyFsPath,lo as classifyLockHolder,ir as clearAllEmbeddingsKeys,to as coercePackId,Rt as collectServerHostSnapshot,t as colorFromSeed,M as commitUpstreamImport,qa as commitWip,Kt as commitWipFromTree,q as compareSemver,B as composeEffectiveLinterConfig,dt as composeFrontmatterSchemasConfig,mi as containsConflictMarkers,v as contentHash,si as contributorCount,Ze as countShadowObjects,it as countStaleAgentWipRefs,vt as countWipRefs,ee as createApiExtension,Se as createAssetServeMiddleware,We as createCollaborationHost,jt as createContentFilter,vo as createContentFilterAsync,T as createEmbeddingsSecretStore,cn as createEphemeralProjectDir,he as createExternalChangeHandler,So as createFileLogger,en as createLiveDerivedIndexExtension,hn as createMcpHttpHandler,se as createOsProbe,Ie as createPersistenceExtension,ra as createProbeFailureReporter,ke as createServer,An as createServerObserverExtension,Cn as createServerProbeResolver,Ln as createStreamingErrorWriter,Ha as createTestLogger,Tt as describeStoredEmbeddingsKey,f as detectClaudeDesktopPresence,Dr as detectGit,Da as detectProjectShape,Li as detectUserSkillHosts,pa as discoverLockDirs,ni as discoverMarkdownlintConfig,$n as emitPreflightFailureSpan,Wi as encodeDocName,ba as encodeFolderRoute,mr as encodeSkillRoute,Ci as ensureProjectGit,Pa as errorResponse,xr as evictStaleTrackerEntries,Pr as extractHeadings,Zi as extractOkBinaryPath,Ai as extractWikiLinksFromMarkdown,Yr as fallbackPaths,Hr as findEnclosingGitRoot,Do as findEnclosingProjectRoot,Gn as findNativeMarkdownlintFile,Eo as flushFileLogger,Va as formatAuditBrokenLinkSuppressionLine,fo as formatAuthRejectionWire,or as formatContributorsFrom,ro as formatPackRationale,Bt as gcCheckpointRefs,P as getCurrentMcpLogger,Ya as getIngressContext,Jt as getLocalDir,wo as getLogFilePath,po as getLogger,Co as getLogsDir,Y as getMachineId,H as getMeter,pt as getMetrics,gi as getTracer,b as handleCollabSocketError,li as handleSpawnCursor,$e as hasForwardingHeaders,ot as hasGcLogLatch,n as iconFromClientName,bt as incrementCollabSocketFilteredError,ne as incrementServerObserverFire,we as initContent,Ke as initShadowRepo,Nt as initTelemetry,bo as initToleranceTelemetryWriter,D as installJsonSchemaDialect,un as installPrettyZodErrors,sr as installTestLoggers,_e as installUserSkill,nn as isAllowedApiOrigin,_n as isAllowedWorkspaceHostHeader,le as isConfigDoc,Re as isDefunctProcess,aa as isDocInConflict,je as isFilesystemRoot,Mn as isHocuspocusAuthRejectionReason,Tn as isHomeDir,Rn as isHostAdmitted,Et as isKnownPackId,p as isLinkIndexExcludedDoc,wr as isLockFromThisMachine,wa as isLockProcessRunning,Pi as isLoopbackAddress,ua as isManagedArtifactDoc,$r as isMintedThreadId,Xn as isOriginAdmitted,ue as isOrphanMode,Vi as isPairedWriteOrigin,_a as isPathWithinDir,dr as isPeerAdmitted,bi as isProcessAlive,To as isProjectRoot,ja as isReservedForUserTree,vr as isSelfWrite,jr as isSkillInstallReportEnvOptOut,Ji as isSystemDoc,Di as isToleranceTelemetryEnabled,Kr as isValidLockPid,zr as lastKnownHash,Hn as listRescueCheckpoints,Ra as listStarterPacks,co as loadCustomAgents,rr as loadPrincipal,eo as lockAdvertisesUi,Lt as lockBaseUrl,j as lockFilePath,io as loggerFactory,Ka as loginShapedUserinfoUser,Vt as logsCurrentPath,F as logsPreviousPath,Gt as machineIdFilePath,K as makeLazyEmbeddingsKeyStore,z as markServerLockDraining,ut as missingOkConfigMessage,pi as mountMcpAndApi,_ as normalizeFsPath,oi as observeReadiness,Xe as packageVersionMajorMinor,rt as parseAuthRejectionWire,_t as parseGitVersion,$ as parseHocuspocusAuthToken,xe as parseKeepaliveConnectionId,Ue as parseProcessStartToken,At as pathToDocName,_o as planSeed,w as prepareProjectLogsDir,sn as prepareSingleFileOpen,me as prepareSpawnProjectLogsDir,$t as processCommand,mn as processStartToken,oe as processUsage,Fe as readAgentBrowserTools,na as readAllTargets,Oe as readBootStartedAtMs,kn as readBundleDecision,Sn as readDeclaredGitHubHosts,In as readOriginCredentialHost,wt as readOriginGitHubRepo,d as readOwnNativeRules,Cr as readProcessLock,Ca as readProcessLockDetailed,Ni as readProcessStart,la as readProcessState,Qr as readProjectHeadState,Yn as readProjectLocalSemanticConfig,Bi as readServerLock,ga as readServerPackageVersion,ur as readSkillInstallStateSnapshot,yi as readStateManifest,Aa as readTargetRecordedAt,_r as readTargetVersion,Ar as reconcile,qi as recordContributor,Ei as recordSkillInstallEvent,Gr as recordsLockOwner,Rr as redactShareSubprocessStderr,Vn as registerAllTools,La as registerNativeProcessStartReader,so as registerWrite,nr as releaseProcessLock,$a as releaseServerLock,It as removeLastKnownHash,A as removeLockIfUnchanged,Ga as removeProjectSkillGitignoreBlock,Wt as reportSkillInstall,G as resetMetrics,R as resolveAuditScope,lt as resolveBuiltinSkillHosts,a as resolveBundleEnabled,fi as resolveBundledSkillDir,g as resolveContentDir,ai as resolveCursorBinaryDefault,Ye as resolveCursorSpawnInvocation,nt as resolveEffectiveLinterConfig,gt as resolveEmbeddingsCredential,Q as resolveGitHubAccountFromUrl,be as resolveGitHubAuthHost,He as resolveLockDir,kt as resolveNativeConfigForDoc,go as resolveNativeMarkdownlintConfig,C as resolvePack,on as resolvePackageVersion,pe as resolveSkillInstallReportSettings,Qt as resolveUiInfo,pn as restoreContributors,ae as rewriteMarkdownLinksForDocumentRename,Pe as rewriteWikiLinksForDocumentRename,ta as runAuthReposSubprocess,De as runAuthStatusSubprocess,On as runCloneSubprocess,xn as runDeviceFlowSubprocess,Fn as runWithMcpLogger,Ct as safeContentPath,u as safeSubdir,Er as safetyCheckpoint,Ea as sameGitHubLogin,Ii as sanitizeClientName,fa as saveInMemoryCheckpoint,ti as saveVersion,Qn as scanLockProcesses,Ui as seedBasenameIndex,ya as seedEphemeralProjectDir,pr as serializeError,Si as setActiveSpanAttributes,Na as setupServerObservers,br as shadowGit,Nr as shutdownTelemetry,Xa as spansCurrentPath,Yt as spansPreviousPath,Xi as spawnDetached,ki as splitMarkdownBlocks,Jr as startWatcher,Vr as strategiesFor,Wn as streamedChunkOf,Ba as streamingProblemEvent,uo as swapContributors,ar as teardownToleranceTelemetryWriter,no as toBroadcasterKey,zt as toProcessLockMetadata,N as tracedAppendFileSync,Ja as tracedLinkSync,qt as tracedMkdir,J as tracedMkdirSync,V as tracedRename,ft as tracedRenameSync,hi as tracedRmSync,y as tracedRmdirSync,ci as tracedUnlinkSync,Qe as tracedWriteFile,at as tracedWriteFileSync,yt as trustSystemCertificates,te as updateLastKnownHash,Ce as updateProcessLockPort,Ge as updateServerLockPort,Mt as validateAgentId,yo as validateCloneInputs,E as validateSkillZip,ln as waitForServerLockDrain,ge as withHiddenWindowsConsole,tn as withSpan,gn as withSpanSync,ce as writeBundleDecision,Le as writeMarkdownlintRule,ia as writeRootGitignoreForNewRepo,Ae as writeStateManifest,jn as writeTargetVersion,wn as writeTracker};
|
package/dist/index.mjs
CHANGED
|
@@ -1637,6 +1637,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
|
|
|
1637
1637
|
`);j(e,o)}function A9(e,t){let n=C(e,`utf-8`);if(n.trim().length!==0)try{let r=O9(JSON.parse(n),t),i=n.endsWith(`
|
|
1638
1638
|
`)?`
|
|
1639
1639
|
`:``;j(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=D9(n,t.contentDirSpellings);r!==n&&j(e,r)}}function j9(e,t){let n=C(e,`utf-8`),r=D9(n,t.contentDirSpellings);r!==n&&j(e,r)}function M9(e){try{return T(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>F(e,t.name))}catch{return[]}}const SVe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function N9(e){return/\.log\.\d+$/.test(e)}function CVe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||N9(e)}const wVe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function P9(e){let t={contentDirSpellings:E9(e.contentDir)};for(let n of wVe)for(let r of M9(F(e.stagingDir,n)))CVe(r)?k9(r,t):r.endsWith(`.json`)?A9(r,t):j9(r,t);for(let n of M9(F(e.stagingDir,`state`))){let e=ne(n);n.endsWith(`.jsonl`)?k9(n,t):SVe.has(e)?A9(n,t):j9(n,t)}}const F9=[`.ok`,`local`,`telemetry`],I9=[`.ok`,`local`,`logs`],L9=[`.ok`,`local`,`loss-capture`],R9=Bf.spansCurrent,z9=Bf.spansPrevious,B9=Bf.logsCurrent,V9=Bf.logsPrevious,H9=`loss-current.jsonl`,U9=`loss-prev.jsonl`;function TVe(e){return F(e,...L9,H9)}function EVe(e){return F(e,...L9,U9)}const W9=1e3;async function DVe(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 OVe(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 kVe(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 AVe(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(`
|
|
1640
|
-
`)}\n`:null}catch{return null}}function jVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function MVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],N6({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 NVe(){return{nodeVersion:process.version,platform:pe(),arch:R()}}function PVe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!_(e))return{};let t;try{t=(0,On.parse)(C(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function FVe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return FVe(e.maxBytes)}function IVe(e){let t=q9(hJ(`project`,e)),n=q9(hJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function LVe(e){return ye(`sha256`).update(e).digest(`hex`)}function RVe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const zVe=[`"doc.name"`,`"docName"`];function BVe(e){let t=C(e,`utf-8`),n=0;for(let e of zVe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function X9(e,t){if(!_(e))return!1;try{return y(N(t),{recursive:!0}),e.endsWith(`.ips`)?j(t,K5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Z9(e,t,n,r){let i=_(e);X9(e,F(n,r)),X9(t,i?F(n,`legacy`,r):F(n,r))}function Q9(e){let t=[],n=e=>{let r=T(e,{withFileTypes:!0});for(let i of r){let r=F(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const VVe=new Set([`.jsonl`]);function HVe(e){let t=e.lastIndexOf(`.`);return t!==-1&&VVe.has(e.slice(t))}const UVe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function WVe(e){if(N9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&UVe.has(e.slice(t))}function GVe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!WVe(r))continue;let{redacted:i,patterns:a,lineCount:o}=eF(C(n,`utf-8`));a.length!==0&&(j(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 L(e,t).split(oe).join(`/`)}async function KVe(e){let t=ae(e.contentDir),n=ae(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??DVe,a=r.fetchAgentEffects??OVe,o=r.fetchWatcherRecent??kVe,s=r.readShadowHead??jVe,c=r.readCheckpointRefs??MVe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.89.10-beta.
|
|
1640
|
+
`)}\n`:null}catch{return null}}function jVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],N6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function MVe(e){let t=F(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],N6({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 NVe(){return{nodeVersion:process.version,platform:pe(),arch:R()}}function PVe(){return process.env.OTEL_SDK_DISABLED===`false`}function K9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q9(e){if(!_(e))return{};let t;try{t=(0,On.parse)(C(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!K9(t))return{};let n=t.telemetry;if(!K9(n))return{};let r=n.localSink;return K9(r)?r:{}}function J9(e){return typeof e==`boolean`?e:void 0}function FVe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Y9(e){if(K9(e))return FVe(e.maxBytes)}function IVe(e){let t=q9(hJ(`project`,e)),n=q9(hJ(`project-local`,e));return{enabled:J9(n.enabled)??J9(t.enabled)??!0,spansMaxBytes:Y9(n.spans)??Y9(t.spans)??52428800,logsMaxBytes:Y9(n.logs)??Y9(t.logs)??26214400}}function LVe(e){return ye(`sha256`).update(e).digest(`hex`)}function RVe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const zVe=[`"doc.name"`,`"docName"`];function BVe(e){let t=C(e,`utf-8`),n=0;for(let e of zVe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function X9(e,t){if(!_(e))return!1;try{return y(N(t),{recursive:!0}),e.endsWith(`.ips`)?j(t,K5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Z9(e,t,n,r){let i=_(e);X9(e,F(n,r)),X9(t,i?F(n,`legacy`,r):F(n,r))}function Q9(e){let t=[],n=e=>{let r=T(e,{withFileTypes:!0});for(let i of r){let r=F(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const VVe=new Set([`.jsonl`]);function HVe(e){let t=e.lastIndexOf(`.`);return t!==-1&&VVe.has(e.slice(t))}const UVe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function WVe(e){if(N9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&UVe.has(e.slice(t))}function GVe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!WVe(r))continue;let{redacted:i,patterns:a,lineCount:o}=eF(C(n,`utf-8`));a.length!==0&&(j(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 L(e,t).split(oe).join(`/`)}async function KVe(e){let t=ae(e.contentDir),n=ae(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??DVe,a=r.fetchAgentEffects??OVe,o=r.fetchWatcherRecent??kVe,s=r.readShadowHead??jVe,c=r.readCheckpointRefs??MVe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.89.10-beta.1`),d=r.readDesktopEnv??G9,f=r.readLanguage??T9,p=r.readRuntime??NVe,m=r.isOtlpPushEnabled??PVe,g=b(F(he(),`ok-bundle-`));try{y(F(g,`telemetry`),{recursive:!0}),y(F(g,`logs`),{recursive:!0}),y(F(g,`state`),{recursive:!0}),Z9(XEe(n),F(n,...F9,R9),g,F(`telemetry`,R9)),Z9(ZEe(n),F(n,...F9,z9),g,F(`telemetry`,z9)),Z9(dY(n),F(n,...I9,B9),g,F(`logs`,B9)),Z9(fY(n),F(n,...I9,V9),g,F(`logs`,V9));for(let t of e.userLogFiles??[])X9(t,F(g,`logs`,ne(t)));for(let t of e.userStateFiles??[])X9(t,F(g,JK,ne(t)));let v=0;for(let t of e.diagnosticReports?.files??[])X9(t,F(g,`diagnostic-reports`,ne(t)))&&(v+=1);let b=F(n,`.ok`,`local`),x=F(b,`server.lock`),S=`not-running`,w=`no server.lock`,T=null;if(_(x)){X9(x,F(g,`state`,`server.lock`));try{let e=C(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(j(F(g,`state`,`agent-presence.json`),e),S=`running`,w=``);let t=await a(T);t!==null&&j(F(g,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=AVe(n);e!==null&&j(F(g,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&j(F(g,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&j(F(g,`state`,`checkpoint-refs.txt`),D),X9(TVe(n),F(g,`state`,H9)),X9(EVe(n),F(g,`state`,U9)),Z9(pEe(n),F(b,zf),g,`state/last-spawn-error.log`),X9(F(b,Hf),F(g,`state`,Hf)),X9(F(b,Uf),F(g,`state`,Uf)),X9(F(b,Vf),F(g,`state`,Vf));let O=p(),A=d(),te=f(),M={ok:{version:u(),nodeVersion:O.nodeVersion,platform:O.platform,arch:O.arch},host:{desktop:A,language:te}};j(F(g,`state`,`runtime.json`),`${JSON.stringify(M,null,2)}\n`);let N=S===`running`?`running
|
|
1641
1641
|
`:`not-running (${w})\n`;j(F(g,`state`,`server-status.txt`),N);let P=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:G5(e.diagnosticReports,v);if(j(F(g,`state`,`diagnostic-reports-status.txt`),`${P}\n`),j(F(g,Y5),g7(e.osTerminationEvidence)),e.processDir&&_(e.processDir)){let t=F(g,`process`);y(t,{recursive:!0}),h(e.processDir,t,{recursive:!0})}let re=e.redact===!0;re&&(P9({stagingDir:g,contentDir:t}),P9({stagingDir:F(g,`legacy`),contentDir:t})),e.note&&j(F(g,`note.txt`),e.note);let ie=null;e.scrubSecrets===!0&&(ie=GVe(g));for(let t of e.extraFiles??[]){let e=t.zipName??ne(t.sourcePath);if(!X9(t.sourcePath,F(g,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=v7(t,`extra/${e}`);n!==null&&(ie??={redactions:[],redactedLineCount:0},ie.redactions.push(n),ie.redactedLineCount+=n.lineCount)}let I=IVe(n),L=Q9(g),ae=[],oe=0,se=0;for(let e of L){let t=$9(g,e),n=ee(e).size,r=HVe(t)?RVe(e):0;ae.push({path:t,bytes:n,lines:r}),oe+=n;let i=t.startsWith(`legacy/`)?t.slice(7):t;(i.startsWith(`telemetry/`)||i.startsWith(`logs/`))&&(se+=BVe(e))}let ce={applied:re};ie!==null&&(ce.secretScrub=ie);let R={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:O.nodeVersion,platform:O.platform,arch:O.arch},host:{desktop:A,language:te},contentDir:{pathSha256:LVe(t),absolutePath:re?`<CONTENT_DIR>`:t},telemetry:{localSink:{...I,directory:xt(`logs`,`projects`)},otlpPushEnabled:m()},redaction:ce,serverStatus:S,files:ae};j(F(g,`manifest.json`),`${JSON.stringify(R,null,2)}\n`);let le=E9(t),ue=L.some(e=>{try{let t=C(e,`utf-8`);return le.some(e=>t.includes(e))}catch{return!1}}),de={stagedDiagnosticReports:v,totalBytes:oe,fileCount:ae.length,docNameCount:se,contentDirVisible:ue,redacted:re},fe=!1;return{stagingDir:g,manifest:R,summary:de,cleanup:()=>{fe||(fe=!0,k(g,{recursive:!0,force:!0}))}}}catch(e){throw k(g,{recursive:!0,force:!0}),e}}async function qVe(e){let{collected:t,outputPath:n}=e,r=N(n);if(!_(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new zAe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=g(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function JVe(e,t){let n=F(e,`.ok`,`config.yml`);if(_(n))try{let t=(0,On.parse)(C(n,`utf-8`)),r=_q(t)?t.content:void 0,i=_q(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return ae(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 ae(e)}async function YVe(e,t,n,r,i,a){let o=y7(t,e.logger),s=await KVe({contentDir:JVe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...Qze(o,e.userLogsDir??F(St(),`logs`)),...x7(e.cachesDir??F(de(),`Library`,`Caches`))],userStateFiles:S7(e.bugReportsDir??_7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{y(N(e.outputPath),{recursive:!0}),await qVe({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 XVe(e){let{projectDir:t}=e,n=e.readDesktopEnv??G9,r=e.readLanguage??T9,i=()=>wze(e.diagnosticReportsDir??F(de(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return YVe(e,t,n,r,i(),await h7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await rBe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:x7(e.cachesDir??F(de(),`Library`,`Caches`)),bugReportLedgerFiles:S7(e.bugReportsDir??_7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await h7(e.osTerminationEvidenceDeps):void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{Eq as ALL_EDITOR_IDS,Dq as EDITOR_LABELS,sJ as EDITOR_TARGETS,OTe as HOSTS_WITH_USER_SKILL_DIR,fze as LAUNCH_CONFIG_NAME,iVe as PATH_SHIM_BEGIN,oVe as PATH_SHIM_BLOCK_RE,aVe as PATH_SHIM_END,o5 as ProjectPathSafetyError,URe as addOkPathsToGitExclude,s5 as assertProjectPathSafe,Hq as buildManagedServerEntry,BBe as buildMcpConfigDeclineEvent,VBe as buildMcpConfigMigrateEvent,Qq as canonicalEntryFor,H5 as classifyExistingMcpEntry,XVe as collectReportBundle,dVe as createCliProbeResolver,Pn as createTokenStore,Yze as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,gze as detectInstalledEditors,Zq as droppedManagedKeys,YTe as editorConfigPathDisplay,JTe as editorEntryLocator,kBe as ensurePiBridge,Aze as findJetsamKillSync,b5 as formatTrackedRemediation,KRe as getExcludedOkPaths,v5 as getInstalledSkillProjectionPaths,DTe as getNativeTomlMcpEditor,_5 as getOkArtifactPaths,Bq as isEntryUpToDate,Uq as isOwnManagedEntry,tVe as loadConfig,Dee as makeLazyProbeTokenStore,_7 as okBugReportsDir,_9 as parseGitHubBlobUrl,nVe as parseGitHubShareUrl,v9 as parseGitHubTreeUrl,g9 as parseGitUrl,sVe as pathInstallMarkerPath,ORe as previewContent,_ze as probeOwnManagedEditorMcpEntry,DBe as probePiBridgeState,y5 as probeTrackedOkPaths,B5 as readExistingMcpEntry,GRe as readSharingMode,eF as redactContent,sBe as registerWindowsProcessStartReader,WRe as removeOkPathsFromGitExclude,IBe as removeOwnMcpEntry,zRe as removeProjectSkill,pVe as removeUserGlobalSkillBundle,yVe as removeUserSkill,NRe as resolveProjectRoot,YBe as runStop,u9 as truncatePriorEntry,C9 as userGlobalSkillBundleTargets,vVe as userSkillPresentAnywhere,rVe as validateLocalFolderForShare,z5 as writeEditorMcpConfig,gVe as writeProjectAiIntegrations,f5 as writeProjectSkill,hze as writeUserMcpConfigs,_Ve as writeUserSkill};
|
|
1642
1642
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{A as r,C as i,I as a,L as o,O as s,S as c,d as l,j as u,k as d,w as f,x as p}from"./constants-ok-dir-BmRrWVQT.mjs";import{K as m,Qd as h,V as g,Xa as _,Xd as v,Ya as y,Zd as b,_ as x,a as S,af as ee,ef as C,if as te,kc as ne,lf as re,pd as ie,tf as ae,tt as oe,ud as se,uf as ce,z as w}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{B as le,G as ue,Go as de,Ha as fe,Ho as pe,Hr as me,I as he,Ir as ge,Jr as _e,Ps as ve,Pt as ye,Ta as be,V as xe,Xr as Se,Yi as Ce,as as we,cs as Te,fi as Ee,gn as De,gs as Oe,is as ke,ka as Ae,lr as je,lt as Me,m as Ne,nr as Pe,os as Fe,ot as Ie,qo as Le,ss as Re,wa as ze,z as Be}from"./dist-
|
|
1
|
+
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{A as r,C as i,I as a,L as o,O as s,S as c,d as l,j as u,k as d,w as f,x as p}from"./constants-ok-dir-BmRrWVQT.mjs";import{K as m,Qd as h,V as g,Xa as _,Xd as v,Ya as y,Zd as b,_ as x,a as S,af as ee,ef as C,if as te,kc as ne,lf as re,pd as ie,tf as ae,tt as oe,ud as se,uf as ce,z as w}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{B as le,G as ue,Go as de,Ha as fe,Ho as pe,Hr as me,I as he,Ir as ge,Jr as _e,Ps as ve,Pt as ye,Ta as be,V as xe,Xr as Se,Yi as Ce,as as we,cs as Te,fi as Ee,gn as De,gs as Oe,is as ke,ka as Ae,lr as je,lt as Me,m as Ne,nr as Pe,os as Fe,ot as Ie,qo as Le,ss as Re,wa as ze,z as Be}from"./dist-B-QQMMgD.mjs";import{n as Ve,s as T}from"./fs-find-project-root-pgJRBsWv.mjs";import{i as E,n as D,o as O,r as He,s as k,t as A}from"./colors-r_owlCuY.mjs";import{t as j}from"./is-object-BGze3w87.mjs";import{t as Ue}from"./constants-DNfL8lwk.mjs";import{t as We}from"./preview-5yFLE8l9.mjs";import{createRequire as Ge}from"node:module";import{fileURLToPath as Ke}from"node:url";import qe,{basename as Je,dirname as M,isAbsolute as Ye,join as N,posix as Xe,relative as P,resolve as F,sep as I,win32 as Ze}from"node:path";import L from"node:process";import{copyFileSync as Qe,existsSync as R,lstatSync as $e,mkdirSync as et,readFileSync as z,readdirSync as tt,readlinkSync as nt,realpathSync as rt,rmSync as it,statSync as at,writeFileSync as ot}from"node:fs";import{homedir as B}from"node:os";import{AsyncLocalStorage as st,AsyncResource as ct}from"node:async_hooks";import{execFileSync as lt}from"node:child_process";import{inspect as ut,stripVTControlCharacters as dt,styleText as V}from"node:util";import*as ft from"node:readline";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:Ka(e)}),a&&g===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const zo=e=>e!==`project`,Bo=e=>e!==`user`;async function Vo(){let e=await to({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 Ho(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??Vo)():`both`}async function Uo(e){return oo({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 \`${s()} config-sharing share\`.`}]})}async function Wo(e){if(e.sharing!==void 0)return e.sharing;let t=ma(e.projectRoot)===`local-only`||e.freshProject===!0?`local-only`:`shared`;return e.isTTY??process.stdout.isTTY?(e.promptFn??Uo)(t):t}var Go=class extends Error{constructor(e){super(e),this.name=`ContentDirError`}},Ko=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 qo=`A dev build registers OpenKnowledge MCP in project config only, never in user-level editor config. Run \`${c} init --dev-mcp\` in the project, or set OK_CHANNEL=stable.`;function Jo(e){if(e===void 0||e===!0)return new Set(Ie);if(e===!1)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(ye.filter(e=>t.includes(e)))}function Yo(e,t,n){let r=F(n,e),i;try{i=at(r)}catch(e){let t=e.code;throw t===`ENOENT`?new Go(`--content-dir path does not exist: ${r}`):new Go(`--content-dir path is not accessible (${t??`unknown error`}): ${r}`)}if(!i.isDirectory())throw new Go(`--content-dir must be a directory: ${r}`);let a=Xo(t),o=Xo(r),s=P(a,o);if(s.startsWith(`..`)||Ye(s))throw new Go(`--content-dir must be inside the project root (${t}); got ${r}`);return s===``?`.`:s}function Xo(e){try{return rt(e)}catch{return e}}const Zo=`open-knowledge-ui`;function Qo(e,t,n){try{let r=e.detectPath?.(t,n)??M(e.configPath(t,n));return R(r)}catch{return!1}}function $o(e,t,n){try{let r=F(M(e.configPath(t,n))),i=F(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+I)}catch{return!1}}function es(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`||!R(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||$o(e,t,r);if(!i&&c&&!Qo(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{Aa(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 ns(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||et(M(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{ve(`${o}.lock`,()=>{let t=yo(o).writePath;if(s||et(M(t),{recursive:!0}),e.format===`toml`){let r=Fo(oi(),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=Ro(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=Po(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 ts={pi:uo};function ns(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=ts[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{et(M(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{ve(`${t}.lock`,()=>{let e=null;try{e=z(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}T(t,c,e===null?void 0:{mode:Ka(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 rs(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!R(n)))return{editorId:e.id,label:e.label,path:n}}async function is(e){let t=sa(e.editors).filter(e=>e.scope===`global`);if(a())return t.map(t=>({editorId:t.id,label:t.label,action:`failed`,configPath:t.configPath(``,e.home),serverName:t.serverName(``),error:qo}));let n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>es(t,``,n,e.home))}function as(e,t,n,r){let i=ss(e,t,n,r);return i.kind===`present`?i.entry:null}function os(e,t,n,r){let i=No(e,t,r);if(!j(i))return{kind:`no-entry`};let a=i[n];return j(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function ss(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!R(i))return{kind:`absent`};try{if(at(i).size>Do)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:Ha(e)}}let a;try{a=z(i,`utf-8`)}catch(e){return{kind:`decline`,reason:Ha(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:lo(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=oi().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return os(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,qr.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:os(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=So(a);return s?Co(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:os(we(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}async function cs(e={}){let t=F(e.cwd??process.cwd()),n=e.projectRootMode===`cwd`?{projectRoot:t,defaultContentDir:`.`,ancestorPromoted:!1,gitRootPromoted:!1}:mo(t,{homeDir:e.home}),r=n.projectRoot;if(Se(r,e.home??B()))throw new ue(r);if(_e(r))throw new he(r);let i=!R(N(r,`.ok`)),o=n.gitRootPromoted?P(r,t):void 0,c=e.contentDir===void 0?n.defaultContentDir:Yo(e.contentDir,r,t);n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&c===`.`&&process.stderr.write(`${k(`[ok] Content scope promoted to the git repo root: ${r}`)}\n Ran in ${o}/, 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 \`${s()} init --content-dir .\`, or set content.dir: ${o} in .ok/config.yml.\n`);let l={mode:e.devMcp?`dev`:`published`},u=e.devMcp===!0||a();if(u&&e.mcp!==!1&&e.scope&&e.scope!==`project`)throw new Ko(e.scope);let d=await je(r),f;try{f=ge(r,{contentDir:c})}catch(t){let i=$.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:d.didInit,rootGitignoreCreated:!1,gitRootPromoted:n.gitRootPromoted,promotedFromDir:o,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 p=f.created.includes(Ue),m=!1;if(d.didInit)try{m=Le(r)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${r}: ${e instanceof Error?e.message:String(e)}`)}try{ze(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 h=await Ho({scope:u?`project`:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),g=e.editors??ms(r,e.home),v=e.editors??g,y=sa(g),b=sa(v),x=e.mcp===!1||h===null,S=Array.from(new Map([...y,...x?[]:b].map(e=>[e.id,e])).values()),ee=y.filter(t=>Qo(t,r,e.home)),C=[],te=[],ne=new Set;for(let t of S){if(x){let n=``;try{n=t.configPath(r,e.home)}catch{}C.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(zo(h)&&y.includes(t)&&t.scope===`global`&&C.push(es(t,r,l,e.home)),Bo(h)&&b.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=es(t,r,l,e.home,n);C.push(i),(i.action===`written`||i.action===`overwritten`)&&ne.add(n)}}let re=new Set;for(let t of b){let n=t.projectSkillPath?.(r);!n||re.has(n)||(re.add(n),te.push(Ba(t,r,{home:e.home})))}let ie=za(r,b.map(e=>e.id));ie&&te.push(ie);let ae=te.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.editorId);if(ae.length>0){let t=e.home??B();be({source:_,skills:[Ne.project],agents:ae,scope:r},{home:t,enabled:fe(t).enabled})}let oe=!x&&h!==null&&Bo(h)?b.filter(e=>!e.projectConfigPath&&!e.projectSkillPath).map(e=>e.label):void 0,se=x?[]:ee.map(e=>rs(e,r)).filter(e=>e!==void 0).filter(e=>!ne.has(e.path)),ce=e.installUserSkill??me,w=e.home??B(),le=Jo(e.skills),pe=typeof e.skills!=`string`,ve=!1,xe=!1,we=!1,Te=!1,De=!1,Oe=!1,ke=!1,Ae=[];for(let t of ye){if(!le.has(t))continue;if(ve=!0,pe){let e=await Ce(w,Ne[t]).then(e=>({ok:!0,value:e}),()=>({ok:!1}));if(!e.ok){Ae.push({bundleId:t,result:`decision-read-failed`}),ke=!0;continue}if(e.value===!1){Ae.push({bundleId:t,result:`opted-out`}),Oe=!0;continue}}await de(w,Ne[t],!0).catch(()=>{});let n=await ce({home:e.home,bundleId:t,force:!0});Ae.push({bundleId:t,result:n}),n===`installed`?xe=!0:n===`failed`?we=!0:n===`no-hosts`?De=!0:Te=!0}let Me=we?`failed`:ke?`decision-read-failed`:xe?`installed`:ve&&Te?`skip-current`:ve&&De?`no-hosts`:Oe?`opted-out`:`declined`,Fe=xe?Pe(w).map(e=>e.editorId):[],Ie=fe(w).enabled&&!Ee(),Re=x?`skipped-flag`:`skipped-missing`,Be=C.find(e=>e.editorId===`claude`)??C[0]??{action:Re,configPath:$.claude.configPath(r,e.home)},Ve=await ls({projectRoot:r,desiredMode:await Wo({sharing:e.sharing,projectRoot:r,isTTY:e.isTTY,freshProject:i,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:r,contentCreated:f.created,contentUpdated:f.updated,contentSkipped:f.skipped,editors:C,projectSkills:te,legacyProjectConfigs:se,skillInstall:Me,skillBundles:Ae,skillsRequested:e.skills,skillHosts:Fe,skillInstallsCounted:Ie,didGitInit:d.didInit,rootGitignoreCreated:m,gitRootPromoted:n.gitRootPromoted,promotedFromDir:o,contentDir:p?c:void 0,contentDirRequested:e.contentDir,contentScaffoldFailed:!1,mcpAction:Be.action,mcpPath:Be.configPath,mcpError:`error`in Be?Be.error:void 0,projectScopeUnsupportedLabels:oe,sharing:Ve}}async function ls(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=ma(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=ua(t);if(n===`local-only`){let e=fa(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`}:us(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=pa(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:us(t,o,`remove`)}function us(e,t,n){let r=ma(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 ds(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 fs(e,t){let n=[],a=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),o=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),c=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),u=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`);e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let d=N(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(A(`Content scaffolded at ${d}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(A(`Content already present at ${d}/`)),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(A(`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(c)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(u)n.push(A(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(A(`MCP server configuration:`));for(let i of e.editors){let e=i.configPath.startsWith(t)?P(t,i.configPath):i.configPath.replace(/^\/Users\/[^/]+/,`~`),a=i.serverName===r()?``:` (${i.serverName})`,o=i.configScope===`project`?` (project)`:``,s=`${i.label}${o}`,c=` `.repeat(Math.max(1,20-s.length)),l=i.editorId===`claude-desktop`&&(i.action===`written`||i.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(i.action){case`written`:n.push(` ${s}${c}${e} ${O(`registered`)}${a}${l}`);break;case`overwritten`:n.push(` ${s}${c}${e} ${O(`updated`)}${a}${l}`);break;case`skipped-missing`:n.push(` ${s}${c}${e} config root missing; skipped`);break;case`failed`:n.push(` ${s}${c}${e} ${He(`FAILED`)}: ${i.error}`);break;case`declined`:n.push(` ${s}${c}${e} left unchanged (${ds(i.declineReason)})`);break;case`skipped-flag`:break;default:i.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 a=i.dev.mcpServerName;e.editors.some(e=>e.serverName===a&&(e.action===`written`||e.action===`overwritten`))&&n.push(` The ${a} entry runs this checkout on this machine only; keep it out of commits.`)}if(e.projectSkills.length>0){n.push(``),n.push(A(`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?P(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${O(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${O(`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(o&&(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} ${P(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(A(`User-global skills:`)),typeof e.skillsRequested==`string`?(n.push(` ${D(`none installed — --skills "${e.skillsRequested}" names no known skill bundle (known: ${ye.join(`, `)})`)}`),n.push(` ${D(`No user-global skill was installed or removed.`)}`)):(n.push(` ${D(`none installed — skipped for this run (--no-skills)`)}`),n.push(` ${D(`No user-global skill was installed or removed; any already on this`)}`),n.push(` ${D(`machine are untouched. Run init without the flag to install them:`)}`),n.push(` ${D(` ${s()} init`)}`),n.push(` ${D(`--no-skills covers user-global skills only, not project-local skills.`)}`));else if(e.skillInstall){n.push(``),n.push(A(`User-global skills:`));let t=e.skillBundles??[],r=Math.max(0,...t.map(e=>Ne[e.bundleId].length));for(let i of t){let t=Ne[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} ${O(`installed for ${i}`)}`);break}case`skip-current`:n.push(` ${t} ${O(`already installed at current version`)}`);break;case`no-hosts`:n.push(` ${t} ${D(`skipped — no supported agent host detected in your home directory`)}`);break;case`failed`:n.push(` ${k(`${t} install failed`)}`);break;case`opted-out`:n.push(` ${t} ${D(`not installed — turned off on this machine; reinstall with ${s()} init --skills ${i.bundleId} or Settings → Skills Studio`)}`);break;case`decision-read-failed`:n.push(` ${k(`${t} not installed — could not read whether it is turned off on this machine; rerun ${s()} init once ${l(x)} is readable`)}`);break;default:i.result}}e.skillInstallsCounted&&t.some(e=>e.result===`installed`)&&(n.push(` ${D(`Counted on skills.sh (skill name + source repo, once per machine).`)}`),n.push(` ${D(`Opt out: DO_NOT_TRACK=1, or Settings → User → Preferences.`)}`)),t.some(e=>e.result===`failed`)&&n.push(` ${k(`Retry with: ${s()} repair-skills`)}`)}e.contentDirRequested!==void 0&&e.contentDir===void 0&&!e.contentScaffoldFailed?(n.push(``),n.push(k(`⚠ --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(k(`⚠ 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 \`${s()} 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 \`${s()} 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(..._s(e.sharing,t));let f=e=>[`${e}- ${E(`${s()} seed --list-packs`)} — browse the starter packs`,`${e}- ${E(`${s()} seed`)} — scaffold an empty repo`];if(a){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(`${O(`✓`)} ${A(`Next steps:`)}`),n.push(` 1. Open your editor (${E(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(...f(` `))),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(`${A(`Next steps:`)} (optional) scaffold the starter knowledge-base structure:`),n.push(...f(` `)));return n.join(`
|
|
691
691
|
`)}function ps(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 ms(e,t){let n=[];for(let r of ci)r!==`claude-desktop`&&Qo($[r],e,t)&&n.push(r);return n}function hs(){let e={log:console.log,info:console.info,debug:console.debug},t=(...e)=>{process.stderr.write(`${e.map(e=>typeof e==`string`?e:ut(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 gs(){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&&u(process.env);let n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r=e.json?hs():null;try{let r;try{r=await cs({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n,contentDir:e.contentDir,skills:e.skills})}catch(e){if(e instanceof Go||e instanceof Ko||e instanceof ue||e instanceof he){process.stderr.write(`${e.message}\n`),process.exitCode=64;return}if(e instanceof Be||e instanceof le||e instanceof xe){process.stderr.write(`${e.message}\n`),process.exitCode=78;return}if(e instanceof Me){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-kjUsg68e.mjs`),{resolveContentDir:s}=await import(`./dist-D8yGS418.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-CKtA1q7r.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(ps(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${fs(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function _s(e,t){let n=[];switch(e.kind){case`applied`:return n.push(A(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?(n.push(` ${O(`local-only`)} — appended ${e.appended.length} path(s) to ${A(`${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(` ${O(`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(` ${O(`local-only`)} — already excluded; nothing to do.`):n.push(` ${O(`local-only`)}`):e.action===`removed`?n.push(` ${O(`shared`)} — removed OK paths from ${A(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${O(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(k(`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 ${E(`${s()} config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(k(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${E(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${E(`${s()} config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(k(`Sharing mode unavailable: ${e.reason}.`));return n}}export{Z as $,Ga as A,Da as B,yo as C,Rt as Ct,oo as D,co as E,Ot as Et,Na as F,ua as G,ba as H,Aa as I,pa as J,ga as K,ja as L,Ua as M,Ha as N,to as O,ka as P,li as Q,Va as R,$o as S,U as St,uo as T,wt as Tt,ha as U,fa as V,da as W,X,ci as Y,$ as Z,Wo as _,gr as _t,ls as a,Ei as at,es as b,fn as bt,ms as c,Gi as ct,gs as d,si as dt,Vi as et,Qo as f,oi as ft,Yo as g,Qr as gt,Ho as h,Yr as ht,ts as i,Ci as it,qa as j,Ka as k,fs as l,na as lt,Jo as m,Xr as mt,Ko as n,Hi as nt,ps as o,Wi as ot,as as p,Y as pt,ma as q,Zo as r,Ui as rt,ss as s,Q as st,Go as t,Bi as tt,_s as u,Ai as ut,cs as v,ar as vt,mo as w,Et as wt,is as x,dn as xt,jo as y,hn as yt,Ba as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./dist-B-QQMMgD.mjs";import{v as e}from"./init-BvIbEDs4.mjs";export{e as runInit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{as as e,cs as t}from"./dist-
|
|
1
|
+
import{as as e,cs as t}from"./dist-B-QQMMgD.mjs";import{s as n}from"./fs-find-project-root-pgJRBsWv.mjs";import{N as r,j as i,k as a}from"./init-BvIbEDs4.mjs";import{t as o}from"./is-object-BGze3w87.mjs";import{t as s}from"./removal-file-path-DDK0L6F5.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=[],_=t(h,g,u)??void 0;if(g.some(e=>!d(e,h))||_?.type!==`object`)return{kind:`declined`,reason:`unparseable`};let v=e(_).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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{x as e}from"./constants-ok-dir-BmRrWVQT.mjs";import{Gc as t,Qc as n,Zc as r,el as i,k as a,qc as o}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{Ms as s,js as c,x as l}from"./dist-
|
|
1
|
+
import{x as e}from"./constants-ok-dir-BmRrWVQT.mjs";import{Gc as t,Qc as n,Zc as r,el as i,k as a,qc as o}from"./md-manager-BGnqyqi1-CmUAdK_J.mjs";import{Ms as s,js as c,x as l}from"./dist-B-QQMMgD.mjs";import{t as u}from"./is-object-BGze3w87.mjs";import{t as d}from"./constants-DNfL8lwk.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 r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=n({file:t.path,source:t.source,doc:t.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function b(e){let n=e??process.cwd(),u=[],p=[],m=[],h=[],g=s(`user`,n),_=c({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 o=r({value:n.value,file:n.path,source:n.source,doc:n.doc});p.push(...o),u.push(e);let s=o.length>0?i(n.value):n.value;return t&&h.push(...a({value:s,file:n.path,source:n.source,doc:n.doc})),s},x=f(n,`.ok`,d),S=b(x,!0),C=b(s(`project-local`,n)),w=t(_.value,S,C),T=l.safeParse(w);if(!T.success){let e=v(x),t={code:`SCHEMA_INVALID`,issues:y(T.error.issues,e)};throw Error(o(t))}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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-7-Yt62LP.mjs";export{e as loadConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ho as e}from"./dist-
|
|
1
|
+
import{Ho as e}from"./dist-B-QQMMgD.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};
|