@inkeep/open-knowledge 0.87.0-beta.2 → 0.87.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +6 -6
- package/dist/constants-D5N3ATV7.mjs +1 -0
- package/dist/{dist-0gI1oLbO.mjs → dist-Nf304EbD.mjs} +1 -1
- package/dist/{dist-_mI3Jjf-.mjs → dist-WUkQ-0NU.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{init-DIAKdBV0.mjs → init-D2HMy-rO.mjs} +2 -2
- package/dist/init-DOe_gwkN.mjs +1 -0
- package/dist/{launch-json-removal-DJC4Yapa.mjs → launch-json-removal-BV1cuUR3.mjs} +1 -1
- package/dist/loader-aSv2-dxV.mjs +1 -0
- package/dist/{loader-CnGe_Flu.mjs → loader-elHDFVY8.mjs} +1 -1
- package/dist/{open-browser-3bURxjbo.mjs → open-browser-DpCYxQUn.mjs} +1 -1
- package/dist/preview-CGs0H5zJ.mjs +1 -0
- package/dist/{preview-c3qAKdkh.mjs → preview-CdgarkKG.mjs} +1 -1
- package/dist/public/assets/{AccountSection-Bo4dPyFQ.js → AccountSection-Da9eATrG.js} +1 -1
- package/dist/public/assets/{ActivityModeContent-CfexCY5K.js → ActivityModeContent-BUaojt46.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-DhN1KHUi.js → AddPropertiesButton-Dv_aXLmb.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-B4ONrFEX.js → AgentDiffPane-CCqjs0BK.js} +1 -1
- package/dist/public/assets/{AttachmentsSection-CCkTnF8H.js → AttachmentsSection-BFWpP5m2.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-C14KgbUB.js → CodeMirrorPropInput-Du6DOr8I.js} +1 -1
- package/dist/public/assets/{ContentRulesSection-B9osiZ5e.js → ContentRulesSection-BZ3w3iWW.js} +1 -1
- package/dist/public/assets/{DocumentContext-B534Taw0.js → DocumentContext-BxX9aCXl.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-lBQIZux4.js → EditorModeToggle-DKB6AYHP.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-DiwiWo-5.js → ExcalidrawDocEditor-DIhUGVEU.js} +1 -1
- package/dist/public/assets/FeedbackForm-DnDW5ZvG.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-gWGVsUXL.js → ImportSkillDialog-B10-vVW-.js} +1 -1
- package/dist/public/assets/{LinkPreviewsSection-BCYSzx82.js → LinkPreviewsSection-edg0Suk2.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-d7iNbkFu.js → LintConfigEditor-DKzvWSti.js} +1 -1
- package/dist/public/assets/{LintingSection-BfQJhSqK.js → LintingSection-BtAmeAqv.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-CU_Aac_w.js +1 -0
- package/dist/public/assets/{ManagedArtifactProperties-CgYx_raS.js → ManagedArtifactProperties-slr2G0kW.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-hIN30U4A.js → MermaidDocEditor-BzEE2qez.js} +1 -1
- package/dist/public/assets/{NetworkAccessSection-Bc1mBEpU.js → NetworkAccessSection-BZ_Zx0UF.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-DYZRoIHn.js → PropertyDisplayRow-BAj6XpXT.js} +1 -1
- package/dist/public/assets/{PublishToGitHubDialog-CWgik3XO.js → PublishToGitHubDialog-Cuvbd1PX.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-kryiWiDK.js → SchemaConfigEditor-DxbIHZRY.js} +1 -1
- package/dist/public/assets/{SearchSection-Cj7FdFQQ.js → SearchSection-q7b2zzwT.js} +1 -1
- package/dist/public/assets/{SessionsHost-B9gM79-g.js → SessionsHost-BWDzIa8M.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-CdmGZmCh.js → SettingsDialogBody-CldIUNBc.js} +2 -2
- package/dist/public/assets/{ShareReceiveMissDialog-BydqiR7F.js → ShareReceiveMissDialog-D6VhxJ_Y.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-KYUxZQNe.js → SkillToolbarControls-CWAXROAl.js} +1 -1
- package/dist/public/assets/{SourceEditor-BIPGmkaK.js → SourceEditor-B4RY78dW.js} +1 -1
- package/dist/public/assets/{SyncSection-CPLGR0K4.js → SyncSection-docw4lTk.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-Co74i3q_.js → SyncStatusBadge-1UDFY6j9.js} +1 -1
- package/dist/public/assets/{TerminalSection-DEVYY41F.js → TerminalSection-CN0hq8qQ.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-XRrhf3K3.js → TerminalWindowApp-DFda7-xy.js} +1 -1
- package/dist/public/assets/{TextDocEditor-Eqrxtsiw.js → TextDocEditor--_7fvg_B.js} +1 -1
- package/dist/public/assets/{ThreadView-CDE0BRUz.js → ThreadView-BQ2Y4JH_.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-CLScmppv.js → TimelineDiffPane-BF6Iafy6.js} +1 -1
- package/dist/public/assets/{client-version-V5JX2_9H.js → client-version-C11DEAPt.js} +1 -1
- package/dist/public/assets/{comment-chips-B6PiUF0P.js → comment-chips-yh6f0zsl.js} +1 -1
- package/dist/public/assets/{config-provider-CY8rv6VT.js → config-provider-UObpGf2E.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-BgNKZ6KQ.js → doc-undo-manager-SN41xWWj.js} +1 -1
- package/dist/public/assets/globals-Bwyn_Aih.css +1 -0
- package/dist/public/assets/{index-zyBtEQ0N.js → index-BhuCGeYi.js} +8 -8
- package/dist/public/assets/{lint-plugins-D1JSXJl8.js → lint-plugins-Cxz_4JIJ.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-DDsjXMmg.js → pending-receive-nav-store-a1lp2fF8.js} +1 -1
- package/dist/public/assets/{preferred-session-events-YlTzEpA1.js → preferred-session-events-DzTVah4z.js} +1 -1
- package/dist/public/assets/{progress-fe7kZ4GR.js → progress-CcPmHzZx.js} +1 -1
- package/dist/public/assets/{selection-context-CJj4QU9m.js → selection-context-DGCAU79Q.js} +1 -1
- package/dist/public/assets/{src-DHA7yznt.js → src-Dj0cdtcD.js} +1 -1
- package/dist/public/assets/{telemetry-impl-BoQfVHFh.js → telemetry-impl-DsSo3nZ4.js} +1 -1
- package/dist/public/assets/{telemetry-startup-BePJfd1G.js → telemetry-startup-2MOj_oCR.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-DEB_IQXO.js → typing-burst-detector-fvuDVIJb.js} +1 -1
- package/dist/public/assets/{uninstall-DnITG12q.js → uninstall-DyYmGM9i.js} +1 -1
- package/dist/public/assets/{use-activity-panel-DmN2jwm1.js → use-activity-panel-yAZjRfm-.js} +1 -1
- package/dist/public/assets/{use-open-skill-D8ppWfzv.js → use-open-skill-CtacPC1u.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-CnYgBQu6.js → use-terminal-enabled-Bq2DLqc4.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-Bj9IKZ0j.js → use-timeline-entry-diff-D9RvUmWs.js} +1 -1
- package/dist/public/index.html +21 -21
- package/dist/public/uninstall.html +3 -3
- package/dist/{registry-probes-DjoTkaRp.mjs → registry-probes-bwpVPMUz.mjs} +1 -1
- package/dist/{removal-file-path-C3qKjXP1.mjs → removal-file-path-2sXE6n01.mjs} +1 -1
- package/dist/{repair-launch-json-BLLbBwuS.mjs → repair-launch-json-ClWuGwZf.mjs} +1 -1
- package/dist/{repair-mcp-configs-Du599MHw.mjs → repair-mcp-configs-C3RWrRWR.mjs} +1 -1
- package/dist/src-CSO0D5AA.mjs +1 -0
- package/dist/{src-CV7s8o8N.mjs → src-d571WNqx.mjs} +1 -1
- package/dist/{start-WZZeXyQg.mjs → start-C4mELfrM.mjs} +3 -3
- package/dist/start-gWQOJ8F1.mjs +1 -0
- package/package.json +4 -4
- package/dist/constants-BHRHFiiA.mjs +0 -1
- package/dist/init-D8PiEGEU.mjs +0 -1
- package/dist/loader-CjDr4LBh.mjs +0 -1
- package/dist/preview-Bb3fqNig.mjs +0 -1
- package/dist/public/assets/FeedbackForm-DN-7wKfh.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-D0kvL_kU.js +0 -1
- package/dist/public/assets/globals-kLKgmkBv.css +0 -1
- package/dist/src-C3wvr_Qn.mjs +0 -1
- package/dist/start-B6ETYSpw.mjs +0 -1
- /package/dist/public/assets/{globals-CcgTjZMO.js → globals-DcxxoWPt.js} +0 -0
|
@@ -1115,7 +1115,7 @@ ${oW(e).join(`
|
|
|
1115
1115
|
`).replaceAll(`\r`,`
|
|
1116
1116
|
`).split(`
|
|
1117
1117
|
`))n(i)||Olt(klt(i,r).replace(/`[^`]*`/g,``),t);return[...t.values()]}function jlt(e){let t=Slt(e.href);if(!t||xlt(t))return null;let n=Ka(t,e.fromDocName,{literal:e.literal});if(!n)return null;let r=us(n).slice(1).toLowerCase();if(!Yt.has(r))return null;let i=W(e.contentDir,n),a,o;try{if(a=fs(As(i)),!SG(a,e.contentDir))return null;o=Ps(a)}catch(t){let n=Dlt(t);return n!==`ENOENT`&&n!==`ENOTDIR`&&ylt.warn({href:e.href,err:t},`unexpected error resolving asset`),null}return o.isFile()?{absolutePath:a,relativePath:Mlt(e.contentDir,a),stat:o}:null}function Mlt(e,t){let n=fs(As(e));return fs(t).slice(n.length+ +!n.endsWith(ms)).split(ms).join(`/`)}function Nlt(e){let t;try{t=fs(As(e.contentDir))}catch(e){return ylt.warn({err:e},`could not resolve content directory`),[]}let n=new Map;for(let[r,i]of e.fileIndex){let a=e.readMarkdown(i.canonicalPath);if(a!==null)for(let i of Alt(a)){let a=jlt({contentDir:t,fromDocName:r,href:i.href,literal:i.literal});if(!a||e.isExcluded?.(a.relativePath))continue;let o=Elt(a.absolutePath),s=n.get(a.relativePath);if(s){s.referencedBy.includes(r)||s.referencedBy.push(r);continue}n.set(a.relativePath,{kind:`asset`,path:a.relativePath,assetExt:us(a.relativePath).toLowerCase(),mediaKind:o,size:a.stat.size,modified:a.stat.mtime.toISOString(),referencedBy:[r]})}}return[...n.values()].sort((e,t)=>e.path.localeCompare(t.path))}function Plt(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}function Flt(e){let{hocuspocus:t,conflicts:n,contentDir:r,isSafeDocName:i,resolveAlias:a,resolveContentEntryPath:o,resolveDocPath:s,extractHeadings:c,getFileIndex:l,getFileIndexGeneration:u,log:d,ready:f,contentFilter:p,safeSubdir:m,getShowAllMaxEntries:h,streamShowAllEntries:g,walkContentDirForShowAll:_,synthesizeShowAllAssetExt:v,getAllFilesIndex:y,getFolderIndex:b,getFolderAliasIndex:x,onReferencedAssetsCacheInvalidator:S}=e,C=new Map,w=null;function T(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
|
|
1118
|
-
`)}function E(){w=null}S?.(E);function D(e){let t=n.lifecycleOf(e,e.name);return t===null?null:t.status===`conflict`?{status:t.status,reason:t.reason}:{status:t.status,reason:``}}let O=Z(La,async(e,n)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!i(s)){X(n,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let c=GW(a(s));if(YW(c)||XW(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${c}' is a reserved document name.`,{handler:`document-read`});return}let l=o(r,`file`,c),u=t.documents.get(c);if(u){Q(n,200,hte,{docName:c,content:u.getText(`source`).toString(),lifecycle:D(u)},{handler:`document-read`});return}if(!G(l)){X(n,404,`urn:ok:error:doc-not-found`,`Document not found: ${c}.`,{handler:`document-read`});return}let d=await t.openDirectConnection(c);try{let e=d.document;if(!e){X(n,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}let t=e.getText(`source`).toString();Q(n,200,hte,{docName:c,content:t,lifecycle:D(e)},{handler:`document-read`})}finally{await d.disconnect()}}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),k=Z(La,async(e,t)=>{try{f&&await f.catch(e=>{d.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`dir`),a=n.searchParams.get(`showAll`)===`true`,o=n.searchParams.get(`showOk`)===`true`,s=n.searchParams.get(`depth`)===`1`?1:1/0;if(i)try{m(r,i)}catch{X(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(a&&p&&Plt(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`});let n=Lq(t,`document-list`),a=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let n=()=>{t.off(`drain`,n),t.off(`close`,n),e()};t.once(`drain`,n),t.once(`close`,n)})};try{let t=h(),n=g({contentDir:r,contentFilter:p,dirFilter:i,maxEntries:t,maxDepth:s,showOk:o,signal:e.signal}),c=0,l=await n.next();for(;!l.done;)await a(`${JSON.stringify(l.value)}\n`),c+=1,l=await n.next();let{truncated:u}=l.value;u&&d.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await a(`${JSON.stringify({type:`complete`,truncated:u,count:c})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):d.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(a&&p){let e=`showAll:${s===1?`d1:`:``}${o?`ok:`:``}${i??``}`,n=C.get(e);if(!n){let t=new AbortController,a=(async()=>{let e=[],n=h(),{truncated:a}=await _({contentDir:r,contentFilter:p,dirFilter:i,documents:e,maxEntries:n,maxDepth:s,showOk:o,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),a&&d.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:a}})();n={promise:a,controller:t,waiters:0};let c=n;C.set(e,c),a.finally(()=>{C.get(e)===c&&C.delete(e)})}let a=n;a.waiters+=1;let c=!1,l=()=>{t.writableEnded||c||(c=!0,--a.waiters,a.waiters<=0&&(a.controller.abort(),C.get(e)===a&&C.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await a.promise;if(c)return;Q(t,200,Uie,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)return;X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,l)}return}let c=l(),S=[...y()],E=b?.()??new Map,D=x?.()??new Map,O=[];for(let[e,t]of E)D.has(e)||i&&!e.startsWith(`${i}/`)&&e!==i||O.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let k=[];try{let e=T(c),t=u?.();(!w||w.signature!==e||w.generation!==t||w.assets.some(e=>p?.isPathIgnored(e.path)))&&(w={signature:e,generation:t,assets:Nlt({contentDir:r,fileIndex:c,readMarkdown:e=>{try{return K(e,`utf-8`)}catch{return null}},isExcluded:p?e=>p.isPathIgnored(e):void 0})}),k=w?.assets??[]}catch(e){w=null,d.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let ee=new Set;for(let e of k)i&&!e.path.startsWith(`${i}/`)&&e.path!==i||(ee.add(e.path),O.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of S){if(t.kind===`markdown`){let n=UW(e);(!i||e.startsWith(`${i}/`)||e===i)&&O.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});let a=new Set([e]);for(let o of wY(r,e,t).members){if(o.role!==`symlink`||a.has(o.path))continue;a.add(o.path);let r=o.path;i&&!r.startsWith(`${i}/`)&&r!==i||O.push({kind:`document`,docName:r,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:o.targetPath})}continue}let n=(n,r)=>{if(i&&n!==i&&!n.startsWith(`${i}/`)||ee.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:r!==null,canonicalDocName:r===null?null:e,targetPath:r})};for(let i of wY(r,e,t).members)n(i.path,i.role===`symlink`?i.targetPath:null)}if(D.size>0){let e=e=>!i||e===i||e.startsWith(`${i}/`),t=new Map;for(let[e,n]of D){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,i]of t){let t=E.get(n),a=t?TY(r,t.canonicalPath,n):n;for(let r of i)e(r)&&O.push({kind:`folder`,path:r,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:a})}let n=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of E)n(e,n=>{O.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:TY(r,t.canonicalPath,e)})});for(let[e,t]of S){let{resolved:i,members:a}=wY(r,e,t),o=i?a:[...new Map(a.map(e=>[e.path,e])).values()];for(let r of o)n(r.path,n=>{if(t.kind===`markdown`){O.push({kind:`document`,docName:n,docExt:UW(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath});return}if(i&&ee.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath})})}}O.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),Q(t,200,Uie,{documents:O},{handler:`document-list`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),ee=Z(La,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){X(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!i(n)){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=s(n);if(!r){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!G(r)){X(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}let a=K(r,`utf-8`),o=c(a);Q(t,200,Ote,{docName:n,headings:o},{handler:`page-headings`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),A={"/api/document":O,"/api/documents":k,"/api/pages":Z(La,async(e,t)=>{try{let e=l(),n=[];for(let[t,i]of e){let e=UW(t),a,o;if(i.title!==void 0)a=i.title,o=i.icon;else{a=t;try{let n=W(r,`${t}${e}`),i=K(n,`utf-8`);a=pY(i,t),o=hY(i)}catch(e){d.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:a,docExt:e,size:i.size,modified:i.modified,icon:o})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),Q(t,200,Vne,{pages:n},{handler:`pages`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),"/api/page-headings":ee};return{paths:Object.keys(A),table:{resolve(e){let t=A[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1},invalidateReferencedAssetsCache:E}}const Ilt=[`date`,`user`],Llt=/\{\{([^{}\n]+?)\}\}/g;function Rlt(e){let t=[];for(let n of e.matchAll(Llt)){let e=(n[1]??``).trim();Blt(e)||t.push({token:e,offset:n.index??0})}return t}function zlt(e,t){return e.replace(Llt,(e,n)=>{let r=n.trim();return Blt(r)?t[r]:e})}function Blt(e){return Ilt.includes(e)}function Vlt(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}function x3(e,t,n={}){let r=Wlt(t),i=r===``?[]:r.split(`/`),a=new Set,o=[],s=n.onRefused;C3(e,r,`local`,a,o,s);for(let t=i.length-1;t>=1;t--)C3(e,i.slice(0,t).join(`/`),`inherited`,a,o,s);return i.length>0&&C3(e,``,`inherited`,a,o,s),o}async function Hlt(e){let t=[],n=new Map,r=e=>{let t=n.get(e);return t||(t=new Set,n.set(e,t)),t},i=0,a=!1,o=[``];for(;o.length>0;){let n=o.shift()??``;if(i++>=S3){a=!0,q(`templates`).warn({projectDir:e,cap:S3,queueDepth:o.length},`project scan hit the ${S3}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${o.length}.`);break}C3(e,n,`local`,r(n),t);let s=n?H(e,n):e,c;try{c=await qs(s,{withFileTypes:!0})}catch(e){if(lG(e)!==`ENOENT`&&!w3.has(s)){w3.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`failed to read directory ${s} during project scan — skipped. Reason: ${t}`)}continue}c.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of c){if(Ult.has(e.name)||e.name.startsWith(`.`))continue;let t=e.isDirectory();if(!t&&e.isSymbolicLink()){let n=H(s,e.name);try{t=(await Xs(n)).isDirectory()}catch(e){if(lG(e)!==`ENOENT`&&!w3.has(n)){w3.add(n);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({link:n,reason:t},`failed to resolve symlink ${n} during project scan — skipped. Reason: ${t}`)}continue}}if(!t)continue;let r=n?ps.join(n,e.name):e.name;o.push(r)}}return{templates:t,truncated:a}}const S3=2e3,Ult=new Set([`node_modules`,`dist`,`build`]);function C3(e,t,n,r,i,a){let o=H(e,t,`.ok`),s=H(o,`templates`);if(rq(o).kind===`symlink`){a?.({kind:`symlink`,folder:t,component:`.ok`}),w3.has(o)||(w3.add(o),q(`templates`).warn({dir:o},`${o} is a symlink — its templates are not enumerated. Replace the symlink with a real directory.`));return}let c;try{c=ws(s)}catch(e){let n=lG(e);if(n===`ENOENT`)return;if(n!==`ENOTDIR`&&a?.({kind:`unverifiable`,folder:t,component:`.ok/templates`,code:n}),!w3.has(s)){w3.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`cannot stat templates directory ${s} — its templates are not enumerated. Reason: ${t}`)}return}if(!c.isDirectory()){c.isSymbolicLink()&&a?.({kind:`symlink`,folder:t,component:`.ok/templates`}),w3.has(s)||(w3.add(s),q(`templates`).warn({dir:s},`${s} is not a real directory (symlink or file) — its templates are not enumerated`));return}let l;try{l=ks(s)}catch{return}for(let a of l){if(!a.endsWith(`.md`))continue;let o=a.slice(0,-3);if(r.has(o))continue;let c=H(s,a),l;try{l=Ps(c)}catch{continue}if(!l.isFile())continue;try{nq(c,s),nq(c,e)}catch(e){if(e instanceof ZK){w3.has(c)||(w3.add(c),q(`templates`).warn({template:c,reason:e.message},`template ${c} escapes its containment boundary — excluded from the menu. Reason: ${e.message}`));continue}if(lG(e)!==`ENOENT`&&!w3.has(c)){w3.add(c);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({template:c,reason:t},`failed to canonicalize template ${c} — excluded from the menu. Reason: ${t}`)}continue}let u=Glt(c),d={name:o,path:t?ps.join(t,`.ok`,`templates`,a):ps.join(`.ok`,`templates`,a),source_folder:t,scope:n};u.title!==void 0&&(d.title=u.title),u.description!==void 0&&(d.description=u.description),r.add(o),i.push(d)}}function Wlt(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const w3=new Set;function Glt(e){let t;try{t=K(e,`utf-8`)}catch(t){if(lG(t)!==`ENOENT`&&!w3.has(e)){w3.add(e);let n=t instanceof Error?t.message:String(t);q(`templates`).warn({path:e,reason:n},`failed to read template at ${e} — metadata skipped. Reason: ${n}`)}return{}}let{identity:n}=lt(t);typeof n.title!=`string`&&!w3.has(e)&&(w3.add(e),q(`templates`).warn({path:e},`template at ${e} has no title — YAML may be malformed or the title is missing.`));let r={};return typeof n.title==`string`&&(r.title=n.title),typeof n.description==`string`&&(r.description=n.description),r}var T3=class extends Error{sourcePath;constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};const E3=q(`file-ops`);function Klt(e){let{contentDir:t}=e;function n(t,n){if(e.markRecentlyRemoved)for(let r of t)YW(r)||XW(r)||(e.markRecentlyRemoved(r),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:r,kind:`deleted`,source:n})))}function r(n){for(let r of n)e.mutateFileIndexDelete?.({path:W(t,e.docNameToRelativePath(r)),docName:r})}function i(t){for(let n of t){let t=e.conflictFileForDocName(n);if(t!==null)return t}return null}return{createPage(t){let{fullPath:n,docName:r,initialContent:i}=t;wH(V(n),{recursive:!0});try{SH(n,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(cq(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}return e.unmarkRecentlyRemoved?.(r),e.contentFilter?.incrementMdDir(V(r)),jY(n,xY(i)),e.mutateFileIndexCreate?.({path:n,docName:r,content:i}),{ok:!0}},createFolder(n){let r=e.resolveContentEntryPath(t,`folder`,n);return G(r)?{ok:!1,kind:`already-exists`}:(wH(r,{recursive:!0}),e.upsertFolderIndexPathSegments(n),e.signalFiles(),{ok:!0})},async deletePath(a,o){let s=a===`asset`?e.resolveContentEntryPath(t,`folder`,o):e.resolveContentEntryPath(t,a,o);if(!G(s))return{ok:!1,kind:`not-found`};let c=Ps(s);if((a===`file`||a===`asset`)&&!c.isFile()||a===`folder`&&!c.isDirectory())return{ok:!1,kind:`type-mismatch`};a===`folder`&&(bG(s,t),e.assertContentSubtree?.(s));let l=a===`asset`?[]:a===`file`?[e.docNameForPath(o)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,o)),u=i(l);return u===null?(await e.captureAndCloseDocuments(l,`deleted-upstream`),n(l,`handleDeletePath`),a===`file`||a===`asset`?DH(s):(jH(s,{recursive:!0,force:!1}),e.removeFolderIndexEntries(o)),e.invalidateReferencedAssetsCache(),r(l),e.deleteDerivedDocumentsBestEffort(l,`delete-path`),e.signalFiles(),{ok:!0,deletedDocNames:l}):{ok:!1,kind:`conflict`,file:u}},async trashCleanup(t,i,a,o){if(t===`asset`)return e.invalidateReferencedAssetsCache(),e.signalFiles(),{deletedDocNames:[]};let s=e.getFileIndex(),c=t===`file`?s.has(a)?[a]:[]:e.listAffectedDocNames(s,`folder`,i);return e.invalidateReferencedAssetsCache(),c.length===0?{deletedDocNames:[]}:(await e.captureAndCloseDocuments(c,`deleted-upstream`),n(c,o),r(c),t===`folder`&&e.removeFolderIndexEntries(i),e.deleteDerivedDocumentsBestEffort(c,`trash-cleanup`),e.signalFiles(),{deletedDocNames:c})},async duplicatePath(n,r,a){let o=e.resolveContentEntryPath(t,n,r);if(!G(o)){if(n===`file`){let n=e.resolveContentEntryPath(t,`folder`,r);if(G(n)&&Ps(n).isDirectory())return{ok:!1,kind:`type-mismatch`}}return{ok:!1,kind:`not-found`}}let s=Ps(o);if(n===`file`&&!s.isFile()||n===`folder`&&!s.isDirectory())return{ok:!1,kind:`type-mismatch`};n===`folder`&&(bG(o,t),e.assertContentSubtree?.(o));let c=i(n===`file`?[e.docNameForPath(r)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,r)));if(c!==null)return{ok:!1,kind:`conflict`,file:c};if(n===`file`){let t=us(o),{docName:n}=e.nextAvailableDuplicateDocName(a);if(YW(n)||XW(n)||e.contentFilter?.isExcluded(`${n}${t}`))return{ok:!1,kind:`destination-excluded`};let r=e.resolveDuplicateDocPath(n,t),i=K(o,`utf-8`),s=V(r),c=G(s);try{wH(s,{recursive:!0}),SH(r,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(cq(e))return{ok:!1,kind:`already-exists`,cause:e};if(!c)try{MH(s)}catch(e){let t=lG(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&E3.warn({destinationDir:s,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let l=!1;try{HW(n,t),e.unmarkRecentlyRemoved?.(n),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n)),l=!0),jY(r,xY(i)),e.mutateFileIndexCreate?.({path:r,docName:n,content:i})}catch(t){try{jH(r,{force:!0})}catch(e){E3.warn({destinationPath:r,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw JW(n),e.contentFilter&&l&&e.contentFilter.decrementMdDir(V(n)),e.mutateFileIndexDelete?.({path:r,docName:n}),t}return e.recordDerivedDocumentBestEffort(n,i,`duplicate-path-file`),{ok:!0,duplicatedPath:n,duplicatedDocNames:[n]}}let{folderPath:l}=e.nextAvailableDuplicateFolderPath(r);if(e.contentFilter?.isDirExcluded(l))return{ok:!1,kind:`destination-excluded`};let u=e.resolveContentEntryPath(t,`folder`,l),d=[];try{EH(o,u,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(cq(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}let f=[],p=[];try{for(let t of e.collectFolderPaths(l))e.upsertFolderIndexPathSegments(t);let t=e.collectMarkdownCopies(l);p=t.map(e=>e.docName);for(let n of t){let t={docName:n.docName,fullPath:n.fullPath,extensionRegistered:!1,dirCountIncremented:!1,fileIndexRegistered:!1};d.push(t);let r=us(n.fullPath);HW(LW(n.docName),r),t.extensionRegistered=!0,e.unmarkRecentlyRemoved?.(n.docName),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n.docName)),t.dirCountIncremented=!0),jY(n.fullPath,xY(n.content)),t.fileIndexRegistered=!0,e.mutateFileIndexCreate?.({path:n.fullPath,docName:n.docName,content:n.content}),f.push({kind:`upsert`,documentName:n.docName,markdown:n.content})}}catch(t){for(let t of d.reverse()){if(t.fileIndexRegistered)try{e.mutateFileIndexDelete?.({path:t.fullPath,docName:t.docName})}catch(e){E3.warn({docName:t.docName,err:e},`[duplicate-path] failed to roll back copied file-index row`)}t.dirCountIncremented&&e.contentFilter?.decrementMdDir(V(t.docName)),t.extensionRegistered&&JW(LW(t.docName))}e.removeFolderIndexEntries(l);try{jH(u,{recursive:!0,force:!0})}catch(e){E3.warn({destinationPath:u,err:e},`[duplicate-path] failed to clean partial folder duplicate`)}throw t}return e.recordDerivedMutationsBestEffort(f,`duplicate-path-folder`),{ok:!0,duplicatedPath:l,duplicatedDocNames:p}}}}var D3=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function O3(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return Wie(e)}}function k3(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function A3(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return Wie(e)}}const j3=q(`upload-streaming`);var qlt=class extends qae{hash=tc(`sha256`);bytes=0;digested=!1;_transform(e,t,n){this.hash.update(e),this.bytes+=e.length,n(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function Jlt(e){return W(Gq(e),`tmp`)}function Ylt(e){let t=Jlt(e);return wH(t,{recursive:!0}),W(t,`upload-${nc()}`)}function Xlt(e,t,n){let r=us(n),i=n.slice(0,n.length-r.length),a=[n,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let n of a){let r=W(t,n);try{kH(e,r);try{DH(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{DH(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new D3(`urn:ok:error:storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new D3(`urn:ok:error:storage-readonly`,t):new D3(`urn:ok:error:storage-error`,t)}}try{DH(e)}catch{}throw new D3(`urn:ok:error:collision-exhaustion`)}function Zlt(e,{ageMs:t=864e5}={}){let n=Jlt(e),r={scanned:0,deleted:0,errors:0};if(!G(n))return r;let i;try{i=ks(n)}catch(e){return j3.warn({err:e,dir:n},`[upload-tempfile-sweep] readdir failed`),r.errors++,r}let a=Date.now()-t;for(let e of i){if(!e.startsWith(`upload-`))continue;r.scanned++;let t=W(n,e);try{if(Ps(t).mtimeMs>=a)continue;DH(t),r.deleted++}catch(e){j3.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&j3.info({dir:n,scanned:r.scanned,deleted:r.deleted,errors:r.errors},`[upload-tempfile-sweep] swept ${r.deleted}/${r.scanned} (errors: ${r.errors})`),r}function Qlt(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function $lt(e){let t=lG(e);return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function eut(e,t){return new Promise((n,r)=>{let i;try{i=git(e,{files:1,fields:10,fieldSize:2048})}catch(e){r(new D3(`urn:ok:error:malformed-upload`,e));return}let a=!1,o=`upload`,s=``,c=``,l=``,u,d,f,p=!1,m=(e,t)=>{if(!a){if(a=!0,d&&u){let e=u;d.once(`close`,()=>{try{Fs(e)}catch{}})}if(d?.destroy(),u)try{Fs(u)}catch{}r(t instanceof D3?t:new D3(e,t))}},h=k3;i.on(`field`,(e,t)=>{e===`parentDocName`&&(c=t),e===`placement`&&(l=t)}),i.on(`file`,(e,r,i)=>{p=!0,o=i.filename||`upload`,s=i.mimeType||``;let g;try{g=Ylt(t)}catch(e){m(h(e),e),r.resume();return}u=g;let _=new qlt;d=Cs(g),dc(r,_,d).then(()=>{a||(a=!0,n({filename:o,mimeType:s,parentDocName:c,placement:l,tempPath:g,sha:_.digest(),byteLength:_.byteLength()}))}).catch(e=>{f=e,m(h(e),e)})}),i.on(`error`,e=>{m(`urn:ok:error:malformed-upload`,e)}),i.on(`close`,()=>{a||f||p||(a=!0,n({filename:``,mimeType:``,parentDocName:c,placement:l,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{a||f||e.complete||m(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(i)})}function tut(e){let{contentDir:t,projectDir:n,log:r,getPrincipal:i,contentFilter:a,signalChannel:o,conflicts:s,commitOkArtifactWrite:c,fileOpsService:l,assetService:u,extractAgentIdentity:d,recordDerivedDocumentBestEffort:f,invalidateReferencedAssetsCache:p,listManagedDocNamesUnderFolderFromDisk:m,resolveContentEntryPath:h,docNameForFileOperationPath:g,withPeriod:_,toManagedRenamePublicError:v,attributeRenameWriteToActor:y,renameAttributionCounter:b,_performAssetRename:S,_performDocumentToFileRename:C,_performManagedRenameForDocs:w,isValidRelativeContentPath:T}=e,E=e=>{let n;try{n=h(t,`folder`,e)}catch(e){return e instanceof QK}return g4(sq(n,W(t),r))};function D(e,t){if(!T(t))return;let n=W(e);if(PW(t)){let e=LW(t);for(let t of wi){let r=W(n,`${e}${t}`);r!==n&&!r.startsWith(`${n}${ms}`)||G(r)&&HW(e,t)}let r=W(n,t);r!==n&&r.startsWith(`${n}${ms}`)&&G(r)&&HW(e,us(t));return}for(let e of wi){let r=W(n,`${t}${e}`);if(!(r!==n&&!r.startsWith(`${n}${ms}`))&&G(r)){HW(t,e);return}}}function O(e){if(us(e))return{path:e,ambiguous:!1};let n=e.lastIndexOf(`/`),r=n===-1?``:e.slice(0,n),i=n===-1?e:e.slice(n+1),a=r?h(t,`folder`,r):t,o;try{o=ks(a,{withFileTypes:!0})}catch(t){let n=lG(t);if(n===`ENOENT`||n===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let s=o.filter(e=>e.isFile()&&e.name.startsWith(`${i}.`)).map(e=>r?`${r}/${e.name}`:e.name).filter(e=>IW(e,Yt));return s.length===1?{path:s[0],ambiguous:!1}:{path:e,ambiguous:s.length>1}}let k=Z(xre,async(e,n,a)=>{try{let e=y$(a,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let s=a.path;if(!PW(s)){X(n,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(s.includes(`..`)||s.startsWith(`/`)||s.includes(`\0`)||s.includes(`\\`)){X(n,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let c=W(t),u;try{u=h(t,`file`,s)}catch(e){if(aq(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`,cause:e});return}throw e}let d=LW(s);if(YW(d)||XW(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`});return}let p=sq(u,c,r);if(g4(s)||g4(p)||Nr(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let m=typeof a.template==`string`?a.template.trim():``,g=``,_;if(m.length>0){if(!x.test(m)){X(n,400,`urn:ok:error:invalid-request`,`Template name must use ${$i}.`,{handler:`create-page`});return}let t=s.includes(`/`)?s.slice(0,s.lastIndexOf(`/`)):``,r=x3(c,t),i=$ne(r,m);if(!i){let e=r.length===0?`(none)`:r.map(e=>`"${e.name}" (${e.scope})`).join(`, `);X(n,400,`urn:ok:error:invalid-request`,`Template "${m}" does not resolve for folder "${t||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let a=W(c,i.path),o;try{o=K(a,`utf-8`)}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${i.path}.`,{handler:`create-page`,cause:e});return}let l=nn(o),u=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;g=zlt(l,{date:Vlt(),user:u}),_=i.scope}let v=LW(s),y=l.createPage({fullPath:u,docName:v,initialContent:g});if(!y.ok){X(n,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:y.cause});return}switch(e.kind){case`agent`:case`principal`:K$(v,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}f(v,g,`create-page`),o?.(`files`),_!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:m,templateScope:_,docName:v})),Q(n,200,Jne,{docName:v},{handler:`create-page`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),ee=Z(Pte,async(e,t,n)=>{try{if(y$(n,i).kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!T(e)){X(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(g4(e)||E(e)){X(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(a?.isDirExcluded(e)){X(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}if(!l.createFolder(e).ok){X(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}Q(t,200,Jte,{path:e},{handler:`create-folder`})}catch(e){if(aq(e)){X(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-folder`,cause:e});return}X(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),A=Z(Iie,async(e,n,r)=>{try{let e=y$(r,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:a}=r,c=r.path,u=a===`file`?LW(c):c;if(!T(c)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(g4(c)||E(c)||a===`file`&&(YW(u)||XW(u))||a===`folder`&&Qlt(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}a===`file`&&D(t,c);let d=await l.duplicatePath(a,c,u);if(!d.ok)switch(d.kind){case`not-found`:X(n,404,`urn:ok:error:doc-not-found`,`${a} does not exist.`,{handler:`duplicate-path`});return;case`type-mismatch`:X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${a}.`,{handler:`duplicate-path`});return;case`conflict`:tJ(n,new $q({file:d.file}),`duplicate-path`,s.findByFile(d.file));return;case`destination-excluded`:X(n,400,`urn:ok:error:invalid-request`,a===`file`?`Duplicated document destination is excluded by the project content config.`:`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return;case`already-exists`:X(n,409,`urn:ok:error:doc-already-exists`,`A ${a} at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:d.cause});return;default:throw Error(`Unhandled duplicate outcome: ${String(d.kind)}`)}let{duplicatedPath:f,duplicatedDocNames:p}=d;switch(e.kind){case`agent`:case`principal`:for(let t of p)K$(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}o?.(`files`),Q(n,200,aee,{kind:a,path:f,duplicatedDocNames:p},{handler:`duplicate-path`})}catch(e){if(e instanceof T3){X(n,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=$lt(e);if(t){X(n,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}if(aq(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`duplicate-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),j=Z(Cre,async(e,n,o)=>{try{let e=y$(o,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:l,fromPath:u,toPath:d}=o;if(!T(u)||!T(d)){X(n,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(l===`file`&&(YW(u)||YW(d)||XW(u)||XW(d))){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(g4(u)||g4(d)||E(u)||E(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(u===d){Q(n,200,ua,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let f=l===`asset`&&PW(u)&&PW(d)?`file`:l;if(f===`asset`){let t;try{t=PW(u)&&!PW(d)?await C(u,d):await S(u,d)}catch(e){if(e instanceof $q){tJ(n,e,`rename-path`,s.findByFile(e.file));return}let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&p();let i;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let n=`Renamed asset ${u} → ${d}`;i=y(e,n,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:n})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{r.debug({kind:`asset`,fromPath:u,toPath:d,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}b().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,ua,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...i?{summary:i}:{}},{handler:`rename-path`});return}f===`file`&&D(t,u);let x=f===`file`?[g(t,u)]:m(h(t,`folder`,u));for(let e of x){let t=s.findByDocName(e);if(t!==void 0){tJ(n,new $q({file:t.file}),`rename-path`,t);return}}if(a){let e=PW(u)?us(u):UW(u);if(f===`file`?a.isExcluded(PW(d)?d:`${d}${e}`):a.isDirExcluded(d)){X(n,400,`urn:ok:error:invalid-request`,`Destination ${f===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let O=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,k;try{k=await w(u,d,f,O?{actor:O}:{})}catch(e){if(e instanceof $q){tJ(n,e,`rename-path`,s.findByFile(e.file));return}if(e instanceof JJ){X(n,409,`urn:ok:error:doc-already-exists`,_(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(k.renamed.length===0&&k.renamedAssets.length===0){Q(n,200,ua,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}k.renamedAssets.length>0&&p();let ee,A=k.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);A.length>0&&(ee=y(e,`Renamed ${u} → ${d}`,A.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:Yb(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{r.debug({kind:l,fromPath:u,toPath:d,affectedDocs:k.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),b().add(1,{kind:`rename-${f}`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,ua,{renamed:k.renamed,renamedAssets:k.renamedAssets,rewrittenDocs:k.rewrittenDocs,...ee?{summary:ee}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),M=Z(tne,async(e,n,r)=>{try{d(r);let{kind:e,path:i}=r;if(!T(i)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let a=e===`asset`?O(i):{path:i,ambiguous:!1};if(a.ambiguous){X(n,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let o=a.path,c=e===`asset`&&PW(o)?`file`:e;if(c===`file`&&D(t,o),g4(o)||E(o)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let u=await l.deletePath(c,o);if(!u.ok){u.kind===`not-found`?X(n,404,`urn:ok:error:doc-not-found`,`${c} does not exist.`,{handler:`delete-path`}):u.kind===`type-mismatch`?X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${c}.`,{handler:`delete-path`}):tJ(n,new $q({file:u.file}),`delete-path`,s.findByFile(u.file));return}Q(n,200,ete,{deletedDocNames:u.deletedDocNames},{handler:`delete-path`})}catch(e){if(aq(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`delete-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),N=Z(It,async(e,n,r)=>XV(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":r.kind,"ok.cleanup.path":fH(r.path),"ok.cleanup.path.role":pH(r.path)}},async()=>{try{if(y$(r,i).kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:a}=r;if(!T(a)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let o=e===`asset`&&PW(a)?`file`:e,s=LW(a);o===`file`&&D(t,a);let c=o===`folder`&&Qlt(a);if(o===`file`&&(YW(s)||XW(s))||c||g4(a)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`trash-cleanup`});return}let{deletedDocNames:u}=await l.trashCleanup(o,a,s,`handleTrashCleanup`);Q(n,200,Lee,{deletedDocNames:u},{handler:`trash-cleanup`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`});async function te(e,i){if(e.method!==`POST`){X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let a;try{a=await eut(e,n??t)}catch(e){if(e instanceof D3){X(i,O3(e.reason),e.reason,A3(e.reason),{handler:`upload-asset`,cause:e});return}X(i,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:o,tempPath:s,sha:c,byteLength:l,parentDocName:f,placement:p}=a,m=()=>{if(G(s))try{Fs(s)}catch{}},h=H$(bie,{parentDocName:f,placement:p||void 0},i,{handler:`upload-asset`});if(!h.ok){m();return}let{parentDocName:g,placement:_}=h.value,{agentId:v,agentName:y}=d(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(l===0){m(),X(i,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(g.includes(`\0`)||g.includes(`..`)||g.startsWith(`/`)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let b=V(g);if(b!==`.`&&!T(b)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}if(g4(g)||b!==`.`&&E(b)){m(),X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return}let x=await u.storeUpload({tempPath:s,sha:c,byteLength:l,filename:o,parentDocName:g,placement:_});if(x.ok){r.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:v,agentName:y,dedup:x.deduped,mime:x.mime,size:l,destPath:x.path,httpStatus:200},x.deduped?`[upload] dedup hit`:`[upload] write ok`),Q(i,200,rte,{src:x.src,path:x.path,deduped:x.deduped},{handler:`upload-asset`});return}switch(x.kind){case`config-error`:r.error({err:x.cause},`[upload] project config has invalid content.attachmentFolderPath`),X(i,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:x.cause});return;case`invalid-attachment-folder`:X(i,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return;case`path-escape`:X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,...x.cause===void 0?{}:{cause:x.cause}});return;case`reserved-destination`:X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return;case`dest-validation-error`:r.error({err:x.cause,destDir:x.destDir},`[upload] failed to validate destination directory`),X(i,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:x.cause});return;case`mkdir-failed`:X(i,O3(x.reason),x.reason,A3(x.reason),{handler:`upload-asset`,cause:x.cause,detail:`failed to create attachment directory`});return;case`write-failed`:r.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:Mq(e),agentId:v,agentName:y,filename:x.filename,size:l,reason:x.reason,httpStatus:O3(x.reason),err:x.cause},`[upload] write failed`),X(i,O3(x.reason),x.reason,A3(x.reason),{handler:`upload-asset`,cause:x.cause});return}}return P$({"/api/create-page":k,"/api/create-folder":ee,"/api/duplicate-path":A,"/api/rename-path":j,"/api/delete-path":M,"/api/trash/cleanup":N,"/api/upload":te},{mutating:[`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/upload`]})}function nut(e){let t=e.replace(/\\/g,`/`);return t===`..`||t.startsWith(`../`)||ds(e)}function M3(e,t){if(typeof e!=`string`||!ds(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let n=W(e),r=W(n,t),i=U(n,r);return i===``?{ok:!0,abs:r,rel:``}:nut(i)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:r,rel:i}}function N3(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const P3=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,rut=`Canonical ids: ${Zn().map(e=>e.name).join(`, `)}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`,F3=L().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),iut="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",aut=L().length(40).regex(/^[0-9a-f]+$/i).describe(iut),I3=L().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),L3=L().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),out=L().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),R3=I({value:L(),truncatedFrom:On().optional(),hint:L().optional()}).describe(`Normalized change-note summary, when one was recorded.`),z3=R(F(L(),z())),sut=F(L(),z()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),cut=R(bne).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting or busy with other writes. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.'),lut=gi.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.');function uut(e,t){for(let n of wi){let r=M3(e,`${t}${n}`);if(r.ok&&G(r.abs))return n}}const dut={summary:R3.optional(),warnings:R(Zt).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit. `link-check-deferred` means links were not checked because the server is still starting or busy with other writes — that doc is re-checked only by a later write or edit of it, or an `audit`, which can time out until startup finishes."),brokenLinks:cut,brokenLinkSuppression:lut,templateHint:R(I({name:L(),description:L().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.")};function fut(e,t,n){let r={};return e&&(r.previewUrl=e.url,r.previewUrlSource=e.source),t&&(r.warning=t),Object.keys(n).length>0&&(r.document=n),r}function B3(e){return`${typeof e.error==`string`?e.error:`request failed`}${typeof e.detail==`string`&&e.detail.length>0?` (${e.detail})`:``}${typeof e.retryAfterSeconds==`number`?` Retry after ${e.retryAfterSeconds}s.`:``}`}function V3(e,t){let n=e.type===`urn:ok:error:invalid-request`&&e.contentControlAdmission===!0&&t?` ${t}`:``;return`Error: ${B3(e)}${n}`}function $(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const put=L().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function H3(e){return{text:put,...e}}function U3(e,t,n){let r={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:r,...n?{isError:!0}:{}}}function W3(){return`Error: Hocuspocus server is not running. Start it with \`${Qi()} start\`, then retry.\nDo not fall back to native file edits for in-scope markdown; route writes through OpenKnowledge so attribution and live sync stay intact.`}async function mut(e,t){return typeof e==`function`?await e(t):e}async function hut(e,t){return typeof e==`function`?await e(t):e}async function G3(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let i=n===void 0?r:W(n);try{let e=await hut(t,r);return{ok:!0,cwd:r,executionCwd:i,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function K3(e,t,n,r){let i=await q3(e,t,n,r);return i.ok?i.url?{ok:!0,cwd:i.cwd,executionCwd:i.executionCwd,config:i.config,url:i.url}:{ok:!1,result:$(W3(),!0)}:{ok:!1,result:$(`Error: ${i.error}`,!0)}}async function q3(e,t,n,r){let i=await G3(e,t,r);if(!i.ok)return i;let{cwd:a,executionCwd:o,config:s}=i;try{return{ok:!0,cwd:a,executionCwd:o,config:s,url:await mut(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function J3(e){let t=e.replace(/^\/+/,``);return t!==`.ok`&&!t.startsWith(`.ok/`)?null:t.startsWith(`.ok/skills/`)?"Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes the SKILL.md wherever the skill lives (a NEW skill lands at the project default skill home, e.g. `.agents/skills/<name>/`). To author or improve a skill, use the `open-knowledge-write-skill` skill.":t.startsWith(`.ok/templates/`)?"Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.":"Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target."}function Y3(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let n=e,r=t;for(;r.endsWith(`.mdx`)||r.endsWith(`.md`);)n=n.slice(0,r.endsWith(`.mdx`)?-4:-3),r=n.toLowerCase();let i=mne(n);return i.ok?{ok:!0,docName:n}:{ok:!1,error:`Error: "${e}" is invalid — ${i.reason}.`}}function X3(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...n}=t;return{ok:!0,...n}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let n=t;if(typeof n.type==`string`&&typeof n.title==`string`){let{type:e,title:t,status:r,instance:i,detail:a,...o}=n;return{...o,ok:!1,error:t,type:e,...typeof r==`number`?{status:r}:{},...typeof i==`string`?{instance:i}:{},...typeof a==`string`?{detail:a}:{}}}let{ok:r,error:i,...a}=n,o=typeof i==`string`?i:typeof n.message==`string`?n.message:`Server returned HTTP ${e.status}`;return{...a,ok:!1,error:o}}function Z3(e,t){return t?{url:e,local:t}:e}function Q3(e){return e instanceof Error&&e.name===`TimeoutError`}function $3(e,t){let n=e instanceof Error?e.message:String(e);if(!Q3(e))return`${Ine} ${n}`;let r=t?.mutating===!1?``:` The server may still have applied the request, so check before retrying.`;return`${Ste} ${n}.${r}`}async function gut(e,t,n,r,i){let a;try{a=await e(t,n,r===void 0?void 0:{body:r,contentType:`application/json`})}catch(e){return{ok:!1,error:$3(e)}}if(a===null)return null;let o=a.status>=200&&a.status<=299,s;try{s=JSON.parse(a.bodyText)}catch(e){let t=e instanceof Error?e.message:String(e),n=i?{httpStatus:a.status}:{};return o?{ok:!1,...n,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,...n,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}let c=X3({ok:o,status:a.status},s);return i?{...c,httpStatus:a.status}:c}async function e6(e,t){if(typeof e!=`string`){let n=await gut(e.local,`GET`,t,void 0,!0);if(n!==null)return n;e=e.url}let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:$3(e,{mutating:!1})}}let r;try{r=await n.json()}catch(e){if(Q3(e))return{ok:!1,httpStatus:n.status,error:$3(e,{mutating:!1})};let t=e instanceof Error?e.message:String(e);return n.ok?{ok:!1,httpStatus:n.status,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,httpStatus:n.status,error:`Server returned HTTP ${n.status} with non-JSON body: ${t}`}}return{...X3(n,r),httpStatus:n.status}}async function t6(e,t,n){let r=await e6(e,t);if(!r.ok)return{error:typeof r.error==`string`?r.error:`request failed`};let{ok:i,...a}=r,o=a[n];return{rows:Array.isArray(o)?o:[],data:a}}async function n6(e,t,n,r){let i;if(r!==void 0)try{i=JSON.stringify(r)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}if(typeof t!=`string`){let r=await gut(t.local,e,n,i,!1);if(r!==null)return r;t=t.url}let a;try{a=await fetch(`${t}${n}`,{method:e,headers:i===void 0?void 0:{"Content-Type":`application/json`},body:i,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:$3(e)}}let o;try{o=await a.json()}catch(e){if(Q3(e))return{ok:!1,error:$3(e)};let t=e instanceof Error?e.message:String(e);return a.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}return X3(a,o)}function r6(e,t,n){return n6(`POST`,e,t,n)}function i6(e,t,n){return n6(`PUT`,e,t,n)}function a6(e,t){return n6(`DELETE`,e,t)}function _ut(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:n,to:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`?[{existing:t,incoming:n,to:r}]:[]}):[]}function o6(e,t,n){if(e!==void 0&&!Array.isArray(e))return{warnings:[kee]};let r=(Array.isArray(e)?e:[]).map(e=>typeof e==`string`?e:String(e)),i=Array.isArray(t)?t:[];return r.length===i.length&&i.every(e=>n.has(e))?{warnings:r,warningCodes:i}:{warnings:r}}function vut(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}const s6=vut(`the server`);function yut(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}const c6=yut(`the server`),l6="`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.",but="`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a copy differing from the current source was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md. `links-not-permitted`: the OS refused symlinks, so the named locations are copies that refresh while unedited and fork when edited.",xut=/^(?:source(?: family)?|validator) "/;function Sut(e){let t=[],n=[];for(let r of e)(xut.test(r)?t:n).push(r);let r=[...t,...n].slice(0,10);return{shownWarnings:r,omittedWarningCount:e.length-r.length}}function u6(e,t,n=0){let r=t.filter(e=>!Kn(e)),i=r.length+n;return i===0?[]:[`${e} incomplete — ${i} warning${i===1?``:`s`} (findings may be partial):`,...r.map(e=>` ⚠ ${e}`),...n>0?[` … and ${n} more warning${n===1?``:`s`}`]:[]]}function Cut(e,t,n,r){if(t===0&&n.some(Kn))return`No documents were checked${r}; this scope contains no admitted documents.`;let i=`${t} document${t===1?``:`s`}${r}`;return n.length>0?`No problems found across ${i}, but the ${e.toLowerCase()} could not fully complete.`:`No problems across ${i}.`}function d6(e){let t=e.severity===`error`?`✘`:`⚠`,n=e.range?.start?.line;return` ${t} ${n===void 0?`line ?`:`line ${n+1}`} ${e.source!==void 0&&e.code!==void 0?`${e.source}/${e.code}`:`?`}: ${e.message??``}`.trimEnd()}function f6(e,t){let n=[];return e>0&&n.push(`${e} error${e===1?``:`s`}`),t>0&&n.push(`${t} warning${t===1?``:`s`}`),n.length>0?n.join(`, `):`no problems`}function wut(e,t){let n=kut(e,t,`frontmatter.yml`);if(rq(V(n)).kind===`symlink`)return m6(`symlink`,n,`${V(n)} is a symlink — folder metadata skipped. Replace the symlink with a real directory.`),{};let r=rq(n);if(r.kind===`symlink`)return m6(`symlink`,n,`symlink at ${n} — folder metadata skipped. Replace it with a regular file.`),{};if(r.kind===`unverifiable`)return m6(`unverifiable`,n,`cannot lstat ${n} (${r.code??`unknown errno`}) — folder metadata skipped.`),{};if(!G(n))return{};try{nq(n,W(e))}catch(e){let t=e instanceof Error?e.message:String(e);return m6(aq(e)?`escape`:`canonicalize`,n,`cannot safely read ${n} — folder metadata skipped. Reason: ${t}`),{}}let i=Out(n);return i==null?{}:Tut(i)}function Tut(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const Eut=[`symlink`,`unverifiable`,`escape`,`canonicalize`,`malformed-yaml`],p6=new Set;function m6(e,t,n){let r=`${e}:${t}`;p6.has(r)||(p6.add(r),q(`folder-frontmatter`).warn({path:t,kind:e},n))}function Dut(e){for(let t of Eut)p6.delete(`${t}:${e}`)}function Out(e){let t;try{t=K(e,`utf-8`)}catch{return null}let n;try{n=(0,jc.parse)(t)}catch(t){return m6(`malformed-yaml`,e,`malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${t instanceof Error?t.message:String(t)}`),null}return typeof n!=`object`||!n||Array.isArray(n)?null:(Dut(e),n)}function kut(e,t,n){let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return r===``||r===`.`?H(e,`.ok`,n):H(e,r,`.ok`,n)}function Aut(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function jut(e){try{return Ps(W(e,`.git`)).isDirectory()}catch{return!1}}function Mut(e){return ej({baseDir:W(e),timeout:{block:5e3}})}async function Nut(e,t,n=5){if(!jut(e))return{commits:[],source:`git-absent`};let r=Mut(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,...Wt([t]))}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
|
|
1118
|
+
`)}function E(){w=null}S?.(E);function D(e){let t=n.lifecycleOf(e,e.name);return t===null?null:t.status===`conflict`?{status:t.status,reason:t.reason}:{status:t.status,reason:``}}let O=Z(La,async(e,n)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!i(s)){X(n,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let c=GW(a(s));if(YW(c)||XW(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${c}' is a reserved document name.`,{handler:`document-read`});return}let l=o(r,`file`,c),u=t.documents.get(c);if(u){Q(n,200,hte,{docName:c,content:u.getText(`source`).toString(),lifecycle:D(u)},{handler:`document-read`});return}if(!G(l)){X(n,404,`urn:ok:error:doc-not-found`,`Document not found: ${c}.`,{handler:`document-read`});return}let d=await t.openDirectConnection(c);try{let e=d.document;if(!e){X(n,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}let t=e.getText(`source`).toString();Q(n,200,hte,{docName:c,content:t,lifecycle:D(e)},{handler:`document-read`})}finally{await d.disconnect()}}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),k=Z(La,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`dir`),a=n.searchParams.get(`showAll`)===`true`,o=n.searchParams.get(`showOk`)===`true`,s=n.searchParams.get(`depth`)===`1`?1:1/0;if(i)try{m(r,i)}catch{X(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(a&&p&&Plt(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`});let n=Lq(t,`document-list`),a=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let n=()=>{t.off(`drain`,n),t.off(`close`,n),e()};t.once(`drain`,n),t.once(`close`,n)})};try{let t=h(),n=g({contentDir:r,contentFilter:p,dirFilter:i,maxEntries:t,maxDepth:s,showOk:o,signal:e.signal}),c=0,l=await n.next();for(;!l.done;)await a(`${JSON.stringify(l.value)}\n`),c+=1,l=await n.next();let{truncated:u}=l.value;u&&d.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await a(`${JSON.stringify({type:`complete`,truncated:u,count:c})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):d.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(a&&p){let e=`showAll:${s===1?`d1:`:``}${o?`ok:`:``}${i??``}`,n=C.get(e);if(!n){let t=new AbortController,a=(async()=>{let e=[],n=h(),{truncated:a}=await _({contentDir:r,contentFilter:p,dirFilter:i,documents:e,maxEntries:n,maxDepth:s,showOk:o,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),a&&d.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:a}})();n={promise:a,controller:t,waiters:0};let c=n;C.set(e,c),a.finally(()=>{C.get(e)===c&&C.delete(e)})}let a=n;a.waiters+=1;let c=!1,l=()=>{t.writableEnded||c||(c=!0,--a.waiters,a.waiters<=0&&(a.controller.abort(),C.get(e)===a&&C.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await a.promise;if(c)return;Q(t,200,Uie,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)return;X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,l)}return}f&&await f.catch(e=>{d.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let c=l(),S=[...y()],E=b?.()??new Map,D=x?.()??new Map,O=[];for(let[e,t]of E)D.has(e)||i&&!e.startsWith(`${i}/`)&&e!==i||O.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let k=[];try{let e=T(c),t=u?.();(!w||w.signature!==e||w.generation!==t||w.assets.some(e=>p?.isPathIgnored(e.path)))&&(w={signature:e,generation:t,assets:Nlt({contentDir:r,fileIndex:c,readMarkdown:e=>{try{return K(e,`utf-8`)}catch{return null}},isExcluded:p?e=>p.isPathIgnored(e):void 0})}),k=w?.assets??[]}catch(e){w=null,d.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let ee=new Set;for(let e of k)i&&!e.path.startsWith(`${i}/`)&&e.path!==i||(ee.add(e.path),O.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of S){if(t.kind===`markdown`){let n=UW(e);(!i||e.startsWith(`${i}/`)||e===i)&&O.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});let a=new Set([e]);for(let o of wY(r,e,t).members){if(o.role!==`symlink`||a.has(o.path))continue;a.add(o.path);let r=o.path;i&&!r.startsWith(`${i}/`)&&r!==i||O.push({kind:`document`,docName:r,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:o.targetPath})}continue}let n=(n,r)=>{if(i&&n!==i&&!n.startsWith(`${i}/`)||ee.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:r!==null,canonicalDocName:r===null?null:e,targetPath:r})};for(let i of wY(r,e,t).members)n(i.path,i.role===`symlink`?i.targetPath:null)}if(D.size>0){let e=e=>!i||e===i||e.startsWith(`${i}/`),t=new Map;for(let[e,n]of D){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,i]of t){let t=E.get(n),a=t?TY(r,t.canonicalPath,n):n;for(let r of i)e(r)&&O.push({kind:`folder`,path:r,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:a})}let n=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of E)n(e,n=>{O.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:TY(r,t.canonicalPath,e)})});for(let[e,t]of S){let{resolved:i,members:a}=wY(r,e,t),o=i?a:[...new Map(a.map(e=>[e.path,e])).values()];for(let r of o)n(r.path,n=>{if(t.kind===`markdown`){O.push({kind:`document`,docName:n,docExt:UW(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath});return}if(i&&ee.has(n))return;let a=v(n);O.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r.targetPath})})}}O.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),Q(t,200,Uie,{documents:O},{handler:`document-list`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),ee=Z(La,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){X(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!i(n)){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=s(n);if(!r){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!G(r)){X(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}let a=K(r,`utf-8`),o=c(a);Q(t,200,Ote,{docName:n,headings:o},{handler:`page-headings`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),A={"/api/document":O,"/api/documents":k,"/api/pages":Z(La,async(e,t)=>{try{let e=l(),n=[];for(let[t,i]of e){let e=UW(t),a,o;if(i.title!==void 0)a=i.title,o=i.icon;else{a=t;try{let n=W(r,`${t}${e}`),i=K(n,`utf-8`);a=pY(i,t),o=hY(i)}catch(e){d.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:a,docExt:e,size:i.size,modified:i.modified,icon:o})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),Q(t,200,Vne,{pages:n},{handler:`pages`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),"/api/page-headings":ee};return{paths:Object.keys(A),table:{resolve(e){let t=A[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1},invalidateReferencedAssetsCache:E}}const Ilt=[`date`,`user`],Llt=/\{\{([^{}\n]+?)\}\}/g;function Rlt(e){let t=[];for(let n of e.matchAll(Llt)){let e=(n[1]??``).trim();Blt(e)||t.push({token:e,offset:n.index??0})}return t}function zlt(e,t){return e.replace(Llt,(e,n)=>{let r=n.trim();return Blt(r)?t[r]:e})}function Blt(e){return Ilt.includes(e)}function Vlt(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}function x3(e,t,n={}){let r=Wlt(t),i=r===``?[]:r.split(`/`),a=new Set,o=[],s=n.onRefused;C3(e,r,`local`,a,o,s);for(let t=i.length-1;t>=1;t--)C3(e,i.slice(0,t).join(`/`),`inherited`,a,o,s);return i.length>0&&C3(e,``,`inherited`,a,o,s),o}async function Hlt(e){let t=[],n=new Map,r=e=>{let t=n.get(e);return t||(t=new Set,n.set(e,t)),t},i=0,a=!1,o=[``];for(;o.length>0;){let n=o.shift()??``;if(i++>=S3){a=!0,q(`templates`).warn({projectDir:e,cap:S3,queueDepth:o.length},`project scan hit the ${S3}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${o.length}.`);break}C3(e,n,`local`,r(n),t);let s=n?H(e,n):e,c;try{c=await qs(s,{withFileTypes:!0})}catch(e){if(lG(e)!==`ENOENT`&&!w3.has(s)){w3.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`failed to read directory ${s} during project scan — skipped. Reason: ${t}`)}continue}c.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of c){if(Ult.has(e.name)||e.name.startsWith(`.`))continue;let t=e.isDirectory();if(!t&&e.isSymbolicLink()){let n=H(s,e.name);try{t=(await Xs(n)).isDirectory()}catch(e){if(lG(e)!==`ENOENT`&&!w3.has(n)){w3.add(n);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({link:n,reason:t},`failed to resolve symlink ${n} during project scan — skipped. Reason: ${t}`)}continue}}if(!t)continue;let r=n?ps.join(n,e.name):e.name;o.push(r)}}return{templates:t,truncated:a}}const S3=2e3,Ult=new Set([`node_modules`,`dist`,`build`]);function C3(e,t,n,r,i,a){let o=H(e,t,`.ok`),s=H(o,`templates`);if(rq(o).kind===`symlink`){a?.({kind:`symlink`,folder:t,component:`.ok`}),w3.has(o)||(w3.add(o),q(`templates`).warn({dir:o},`${o} is a symlink — its templates are not enumerated. Replace the symlink with a real directory.`));return}let c;try{c=ws(s)}catch(e){let n=lG(e);if(n===`ENOENT`)return;if(n!==`ENOTDIR`&&a?.({kind:`unverifiable`,folder:t,component:`.ok/templates`,code:n}),!w3.has(s)){w3.add(s);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({dir:s,reason:t},`cannot stat templates directory ${s} — its templates are not enumerated. Reason: ${t}`)}return}if(!c.isDirectory()){c.isSymbolicLink()&&a?.({kind:`symlink`,folder:t,component:`.ok/templates`}),w3.has(s)||(w3.add(s),q(`templates`).warn({dir:s},`${s} is not a real directory (symlink or file) — its templates are not enumerated`));return}let l;try{l=ks(s)}catch{return}for(let a of l){if(!a.endsWith(`.md`))continue;let o=a.slice(0,-3);if(r.has(o))continue;let c=H(s,a),l;try{l=Ps(c)}catch{continue}if(!l.isFile())continue;try{nq(c,s),nq(c,e)}catch(e){if(e instanceof ZK){w3.has(c)||(w3.add(c),q(`templates`).warn({template:c,reason:e.message},`template ${c} escapes its containment boundary — excluded from the menu. Reason: ${e.message}`));continue}if(lG(e)!==`ENOENT`&&!w3.has(c)){w3.add(c);let t=e instanceof Error?e.message:String(e);q(`templates`).warn({template:c,reason:t},`failed to canonicalize template ${c} — excluded from the menu. Reason: ${t}`)}continue}let u=Glt(c),d={name:o,path:t?ps.join(t,`.ok`,`templates`,a):ps.join(`.ok`,`templates`,a),source_folder:t,scope:n};u.title!==void 0&&(d.title=u.title),u.description!==void 0&&(d.description=u.description),r.add(o),i.push(d)}}function Wlt(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const w3=new Set;function Glt(e){let t;try{t=K(e,`utf-8`)}catch(t){if(lG(t)!==`ENOENT`&&!w3.has(e)){w3.add(e);let n=t instanceof Error?t.message:String(t);q(`templates`).warn({path:e,reason:n},`failed to read template at ${e} — metadata skipped. Reason: ${n}`)}return{}}let{identity:n}=lt(t);typeof n.title!=`string`&&!w3.has(e)&&(w3.add(e),q(`templates`).warn({path:e},`template at ${e} has no title — YAML may be malformed or the title is missing.`));let r={};return typeof n.title==`string`&&(r.title=n.title),typeof n.description==`string`&&(r.description=n.description),r}var T3=class extends Error{sourcePath;constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};const E3=q(`file-ops`);function Klt(e){let{contentDir:t}=e;function n(t,n){if(e.markRecentlyRemoved)for(let r of t)YW(r)||XW(r)||(e.markRecentlyRemoved(r),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:r,kind:`deleted`,source:n})))}function r(n){for(let r of n)e.mutateFileIndexDelete?.({path:W(t,e.docNameToRelativePath(r)),docName:r})}function i(t){for(let n of t){let t=e.conflictFileForDocName(n);if(t!==null)return t}return null}return{createPage(t){let{fullPath:n,docName:r,initialContent:i}=t;wH(V(n),{recursive:!0});try{SH(n,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(cq(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}return e.unmarkRecentlyRemoved?.(r),e.contentFilter?.incrementMdDir(V(r)),jY(n,xY(i)),e.mutateFileIndexCreate?.({path:n,docName:r,content:i}),{ok:!0}},createFolder(n){let r=e.resolveContentEntryPath(t,`folder`,n);return G(r)?{ok:!1,kind:`already-exists`}:(wH(r,{recursive:!0}),e.upsertFolderIndexPathSegments(n),e.signalFiles(),{ok:!0})},async deletePath(a,o){let s=a===`asset`?e.resolveContentEntryPath(t,`folder`,o):e.resolveContentEntryPath(t,a,o);if(!G(s))return{ok:!1,kind:`not-found`};let c=Ps(s);if((a===`file`||a===`asset`)&&!c.isFile()||a===`folder`&&!c.isDirectory())return{ok:!1,kind:`type-mismatch`};a===`folder`&&(bG(s,t),e.assertContentSubtree?.(s));let l=a===`asset`?[]:a===`file`?[e.docNameForPath(o)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,o)),u=i(l);return u===null?(await e.captureAndCloseDocuments(l,`deleted-upstream`),n(l,`handleDeletePath`),a===`file`||a===`asset`?DH(s):(jH(s,{recursive:!0,force:!1}),e.removeFolderIndexEntries(o)),e.invalidateReferencedAssetsCache(),r(l),e.deleteDerivedDocumentsBestEffort(l,`delete-path`),e.signalFiles(),{ok:!0,deletedDocNames:l}):{ok:!1,kind:`conflict`,file:u}},async trashCleanup(t,i,a,o){if(t===`asset`)return e.invalidateReferencedAssetsCache(),e.signalFiles(),{deletedDocNames:[]};let s=e.getFileIndex(),c=t===`file`?s.has(a)?[a]:[]:e.listAffectedDocNames(s,`folder`,i);return e.invalidateReferencedAssetsCache(),c.length===0?{deletedDocNames:[]}:(await e.captureAndCloseDocuments(c,`deleted-upstream`),n(c,o),r(c),t===`folder`&&e.removeFolderIndexEntries(i),e.deleteDerivedDocumentsBestEffort(c,`trash-cleanup`),e.signalFiles(),{deletedDocNames:c})},async duplicatePath(n,r,a){let o=e.resolveContentEntryPath(t,n,r);if(!G(o)){if(n===`file`){let n=e.resolveContentEntryPath(t,`folder`,r);if(G(n)&&Ps(n).isDirectory())return{ok:!1,kind:`type-mismatch`}}return{ok:!1,kind:`not-found`}}let s=Ps(o);if(n===`file`&&!s.isFile()||n===`folder`&&!s.isDirectory())return{ok:!1,kind:`type-mismatch`};n===`folder`&&(bG(o,t),e.assertContentSubtree?.(o));let c=i(n===`file`?[e.docNameForPath(r)]:e.listManagedDocNamesUnderFolder(e.resolveContentEntryPath(t,`folder`,r)));if(c!==null)return{ok:!1,kind:`conflict`,file:c};if(n===`file`){let t=us(o),{docName:n}=e.nextAvailableDuplicateDocName(a);if(YW(n)||XW(n)||e.contentFilter?.isExcluded(`${n}${t}`))return{ok:!1,kind:`destination-excluded`};let r=e.resolveDuplicateDocPath(n,t),i=K(o,`utf-8`),s=V(r),c=G(s);try{wH(s,{recursive:!0}),SH(r,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(cq(e))return{ok:!1,kind:`already-exists`,cause:e};if(!c)try{MH(s)}catch(e){let t=lG(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&E3.warn({destinationDir:s,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let l=!1;try{HW(n,t),e.unmarkRecentlyRemoved?.(n),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n)),l=!0),jY(r,xY(i)),e.mutateFileIndexCreate?.({path:r,docName:n,content:i})}catch(t){try{jH(r,{force:!0})}catch(e){E3.warn({destinationPath:r,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw JW(n),e.contentFilter&&l&&e.contentFilter.decrementMdDir(V(n)),e.mutateFileIndexDelete?.({path:r,docName:n}),t}return e.recordDerivedDocumentBestEffort(n,i,`duplicate-path-file`),{ok:!0,duplicatedPath:n,duplicatedDocNames:[n]}}let{folderPath:l}=e.nextAvailableDuplicateFolderPath(r);if(e.contentFilter?.isDirExcluded(l))return{ok:!1,kind:`destination-excluded`};let u=e.resolveContentEntryPath(t,`folder`,l),d=[];try{EH(o,u,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(cq(e))return{ok:!1,kind:`already-exists`,cause:e};throw e}let f=[],p=[];try{for(let t of e.collectFolderPaths(l))e.upsertFolderIndexPathSegments(t);let t=e.collectMarkdownCopies(l);p=t.map(e=>e.docName);for(let n of t){let t={docName:n.docName,fullPath:n.fullPath,extensionRegistered:!1,dirCountIncremented:!1,fileIndexRegistered:!1};d.push(t);let r=us(n.fullPath);HW(LW(n.docName),r),t.extensionRegistered=!0,e.unmarkRecentlyRemoved?.(n.docName),e.contentFilter&&(e.contentFilter.incrementMdDir(V(n.docName)),t.dirCountIncremented=!0),jY(n.fullPath,xY(n.content)),t.fileIndexRegistered=!0,e.mutateFileIndexCreate?.({path:n.fullPath,docName:n.docName,content:n.content}),f.push({kind:`upsert`,documentName:n.docName,markdown:n.content})}}catch(t){for(let t of d.reverse()){if(t.fileIndexRegistered)try{e.mutateFileIndexDelete?.({path:t.fullPath,docName:t.docName})}catch(e){E3.warn({docName:t.docName,err:e},`[duplicate-path] failed to roll back copied file-index row`)}t.dirCountIncremented&&e.contentFilter?.decrementMdDir(V(t.docName)),t.extensionRegistered&&JW(LW(t.docName))}e.removeFolderIndexEntries(l);try{jH(u,{recursive:!0,force:!0})}catch(e){E3.warn({destinationPath:u,err:e},`[duplicate-path] failed to clean partial folder duplicate`)}throw t}return e.recordDerivedMutationsBestEffort(f,`duplicate-path-folder`),{ok:!0,duplicatedPath:l,duplicatedDocNames:p}}}}var D3=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function O3(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return Wie(e)}}function k3(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function A3(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return Wie(e)}}const j3=q(`upload-streaming`);var qlt=class extends qae{hash=tc(`sha256`);bytes=0;digested=!1;_transform(e,t,n){this.hash.update(e),this.bytes+=e.length,n(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function Jlt(e){return W(Gq(e),`tmp`)}function Ylt(e){let t=Jlt(e);return wH(t,{recursive:!0}),W(t,`upload-${nc()}`)}function Xlt(e,t,n){let r=us(n),i=n.slice(0,n.length-r.length),a=[n,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let n of a){let r=W(t,n);try{kH(e,r);try{DH(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{DH(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new D3(`urn:ok:error:storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new D3(`urn:ok:error:storage-readonly`,t):new D3(`urn:ok:error:storage-error`,t)}}try{DH(e)}catch{}throw new D3(`urn:ok:error:collision-exhaustion`)}function Zlt(e,{ageMs:t=864e5}={}){let n=Jlt(e),r={scanned:0,deleted:0,errors:0};if(!G(n))return r;let i;try{i=ks(n)}catch(e){return j3.warn({err:e,dir:n},`[upload-tempfile-sweep] readdir failed`),r.errors++,r}let a=Date.now()-t;for(let e of i){if(!e.startsWith(`upload-`))continue;r.scanned++;let t=W(n,e);try{if(Ps(t).mtimeMs>=a)continue;DH(t),r.deleted++}catch(e){j3.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&j3.info({dir:n,scanned:r.scanned,deleted:r.deleted,errors:r.errors},`[upload-tempfile-sweep] swept ${r.deleted}/${r.scanned} (errors: ${r.errors})`),r}function Qlt(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function $lt(e){let t=lG(e);return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function eut(e,t){return new Promise((n,r)=>{let i;try{i=git(e,{files:1,fields:10,fieldSize:2048})}catch(e){r(new D3(`urn:ok:error:malformed-upload`,e));return}let a=!1,o=`upload`,s=``,c=``,l=``,u,d,f,p=!1,m=(e,t)=>{if(!a){if(a=!0,d&&u){let e=u;d.once(`close`,()=>{try{Fs(e)}catch{}})}if(d?.destroy(),u)try{Fs(u)}catch{}r(t instanceof D3?t:new D3(e,t))}},h=k3;i.on(`field`,(e,t)=>{e===`parentDocName`&&(c=t),e===`placement`&&(l=t)}),i.on(`file`,(e,r,i)=>{p=!0,o=i.filename||`upload`,s=i.mimeType||``;let g;try{g=Ylt(t)}catch(e){m(h(e),e),r.resume();return}u=g;let _=new qlt;d=Cs(g),dc(r,_,d).then(()=>{a||(a=!0,n({filename:o,mimeType:s,parentDocName:c,placement:l,tempPath:g,sha:_.digest(),byteLength:_.byteLength()}))}).catch(e=>{f=e,m(h(e),e)})}),i.on(`error`,e=>{m(`urn:ok:error:malformed-upload`,e)}),i.on(`close`,()=>{a||f||p||(a=!0,n({filename:``,mimeType:``,parentDocName:c,placement:l,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{a||f||e.complete||m(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(i)})}function tut(e){let{contentDir:t,projectDir:n,log:r,getPrincipal:i,contentFilter:a,signalChannel:o,conflicts:s,commitOkArtifactWrite:c,fileOpsService:l,assetService:u,extractAgentIdentity:d,recordDerivedDocumentBestEffort:f,invalidateReferencedAssetsCache:p,listManagedDocNamesUnderFolderFromDisk:m,resolveContentEntryPath:h,docNameForFileOperationPath:g,withPeriod:_,toManagedRenamePublicError:v,attributeRenameWriteToActor:y,renameAttributionCounter:b,_performAssetRename:S,_performDocumentToFileRename:C,_performManagedRenameForDocs:w,isValidRelativeContentPath:T}=e,E=e=>{let n;try{n=h(t,`folder`,e)}catch(e){return e instanceof QK}return g4(sq(n,W(t),r))};function D(e,t){if(!T(t))return;let n=W(e);if(PW(t)){let e=LW(t);for(let t of wi){let r=W(n,`${e}${t}`);r!==n&&!r.startsWith(`${n}${ms}`)||G(r)&&HW(e,t)}let r=W(n,t);r!==n&&r.startsWith(`${n}${ms}`)&&G(r)&&HW(e,us(t));return}for(let e of wi){let r=W(n,`${t}${e}`);if(!(r!==n&&!r.startsWith(`${n}${ms}`))&&G(r)){HW(t,e);return}}}function O(e){if(us(e))return{path:e,ambiguous:!1};let n=e.lastIndexOf(`/`),r=n===-1?``:e.slice(0,n),i=n===-1?e:e.slice(n+1),a=r?h(t,`folder`,r):t,o;try{o=ks(a,{withFileTypes:!0})}catch(t){let n=lG(t);if(n===`ENOENT`||n===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let s=o.filter(e=>e.isFile()&&e.name.startsWith(`${i}.`)).map(e=>r?`${r}/${e.name}`:e.name).filter(e=>IW(e,Yt));return s.length===1?{path:s[0],ambiguous:!1}:{path:e,ambiguous:s.length>1}}let k=Z(xre,async(e,n,a)=>{try{let e=y$(a,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let s=a.path;if(!PW(s)){X(n,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(s.includes(`..`)||s.startsWith(`/`)||s.includes(`\0`)||s.includes(`\\`)){X(n,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let c=W(t),u;try{u=h(t,`file`,s)}catch(e){if(aq(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`,cause:e});return}throw e}let d=LW(s);if(YW(d)||XW(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`});return}let p=sq(u,c,r);if(g4(s)||g4(p)||Nr(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let m=typeof a.template==`string`?a.template.trim():``,g=``,_;if(m.length>0){if(!x.test(m)){X(n,400,`urn:ok:error:invalid-request`,`Template name must use ${$i}.`,{handler:`create-page`});return}let t=s.includes(`/`)?s.slice(0,s.lastIndexOf(`/`)):``,r=x3(c,t),i=$ne(r,m);if(!i){let e=r.length===0?`(none)`:r.map(e=>`"${e.name}" (${e.scope})`).join(`, `);X(n,400,`urn:ok:error:invalid-request`,`Template "${m}" does not resolve for folder "${t||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let a=W(c,i.path),o;try{o=K(a,`utf-8`)}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${i.path}.`,{handler:`create-page`,cause:e});return}let l=nn(o),u=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;g=zlt(l,{date:Vlt(),user:u}),_=i.scope}let v=LW(s),y=l.createPage({fullPath:u,docName:v,initialContent:g});if(!y.ok){X(n,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:y.cause});return}switch(e.kind){case`agent`:case`principal`:K$(v,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}f(v,g,`create-page`),o?.(`files`),_!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:m,templateScope:_,docName:v})),Q(n,200,Jne,{docName:v},{handler:`create-page`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),ee=Z(Pte,async(e,t,n)=>{try{if(y$(n,i).kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!T(e)){X(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(g4(e)||E(e)){X(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(a?.isDirExcluded(e)){X(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}if(!l.createFolder(e).ok){X(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}Q(t,200,Jte,{path:e},{handler:`create-folder`})}catch(e){if(aq(e)){X(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-folder`,cause:e});return}X(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),A=Z(Iie,async(e,n,r)=>{try{let e=y$(r,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:a}=r,c=r.path,u=a===`file`?LW(c):c;if(!T(c)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(g4(c)||E(c)||a===`file`&&(YW(u)||XW(u))||a===`folder`&&Qlt(c)){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}a===`file`&&D(t,c);let d=await l.duplicatePath(a,c,u);if(!d.ok)switch(d.kind){case`not-found`:X(n,404,`urn:ok:error:doc-not-found`,`${a} does not exist.`,{handler:`duplicate-path`});return;case`type-mismatch`:X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${a}.`,{handler:`duplicate-path`});return;case`conflict`:tJ(n,new $q({file:d.file}),`duplicate-path`,s.findByFile(d.file));return;case`destination-excluded`:X(n,400,`urn:ok:error:invalid-request`,a===`file`?`Duplicated document destination is excluded by the project content config.`:`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return;case`already-exists`:X(n,409,`urn:ok:error:doc-already-exists`,`A ${a} at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:d.cause});return;default:throw Error(`Unhandled duplicate outcome: ${String(d.kind)}`)}let{duplicatedPath:f,duplicatedDocNames:p}=d;switch(e.kind){case`agent`:case`principal`:for(let t of p)K$(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}o?.(`files`),Q(n,200,aee,{kind:a,path:f,duplicatedDocNames:p},{handler:`duplicate-path`})}catch(e){if(e instanceof T3){X(n,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=$lt(e);if(t){X(n,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}if(aq(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`duplicate-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),j=Z(Cre,async(e,n,o)=>{try{let e=y$(o,i);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:l,fromPath:u,toPath:d}=o;if(!T(u)||!T(d)){X(n,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(l===`file`&&(YW(u)||YW(d)||XW(u)||XW(d))){X(n,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(g4(u)||g4(d)||E(u)||E(d)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(u===d){Q(n,200,ua,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let f=l===`asset`&&PW(u)&&PW(d)?`file`:l;if(f===`asset`){let t;try{t=PW(u)&&!PW(d)?await C(u,d):await S(u,d)}catch(e){if(e instanceof $q){tJ(n,e,`rename-path`,s.findByFile(e.file));return}let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&p();let i;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let n=`Renamed asset ${u} → ${d}`;i=y(e,n,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:n})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{r.debug({kind:`asset`,fromPath:u,toPath:d,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}b().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,ua,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...i?{summary:i}:{}},{handler:`rename-path`});return}f===`file`&&D(t,u);let x=f===`file`?[g(t,u)]:m(h(t,`folder`,u));for(let e of x){let t=s.findByDocName(e);if(t!==void 0){tJ(n,new $q({file:t.file}),`rename-path`,t);return}}if(a){let e=PW(u)?us(u):UW(u);if(f===`file`?a.isExcluded(PW(d)?d:`${d}${e}`):a.isDirExcluded(d)){X(n,400,`urn:ok:error:invalid-request`,`Destination ${f===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let O=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,k;try{k=await w(u,d,f,O?{actor:O}:{})}catch(e){if(e instanceof $q){tJ(n,e,`rename-path`,s.findByFile(e.file));return}if(e instanceof JJ){X(n,409,`urn:ok:error:doc-already-exists`,_(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(k.renamed.length===0&&k.renamedAssets.length===0){Q(n,200,ua,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}k.renamedAssets.length>0&&p();let ee,A=k.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);A.length>0&&(ee=y(e,`Renamed ${u} → ${d}`,A.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:Yb(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{r.debug({kind:l,fromPath:u,toPath:d,affectedDocs:k.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),b().add(1,{kind:`rename-${f}`,attribution_kind:e.kind}),c(`rename-path`),Q(n,200,ua,{renamed:k.renamed,renamedAssets:k.renamedAssets,rewrittenDocs:k.rewrittenDocs,...ee?{summary:ee}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:r,error:i}=v(e);X(n,t,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),M=Z(tne,async(e,n,r)=>{try{d(r);let{kind:e,path:i}=r;if(!T(i)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let a=e===`asset`?O(i):{path:i,ambiguous:!1};if(a.ambiguous){X(n,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let o=a.path,c=e===`asset`&&PW(o)?`file`:e;if(c===`file`&&D(t,o),g4(o)||E(o)){X(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let u=await l.deletePath(c,o);if(!u.ok){u.kind===`not-found`?X(n,404,`urn:ok:error:doc-not-found`,`${c} does not exist.`,{handler:`delete-path`}):u.kind===`type-mismatch`?X(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${c}.`,{handler:`delete-path`}):tJ(n,new $q({file:u.file}),`delete-path`,s.findByFile(u.file));return}Q(n,200,ete,{deletedDocNames:u.deletedDocNames},{handler:`delete-path`})}catch(e){if(aq(e)){X(n,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`delete-path`,cause:e});return}X(n,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),N=Z(It,async(e,n,r)=>XV(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":r.kind,"ok.cleanup.path":fH(r.path),"ok.cleanup.path.role":pH(r.path)}},async()=>{try{if(y$(r,i).kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:a}=r;if(!T(a)){X(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let o=e===`asset`&&PW(a)?`file`:e,s=LW(a);o===`file`&&D(t,a);let c=o===`folder`&&Qlt(a);if(o===`file`&&(YW(s)||XW(s))||c||g4(a)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`trash-cleanup`});return}let{deletedDocNames:u}=await l.trashCleanup(o,a,s,`handleTrashCleanup`);Q(n,200,Lee,{deletedDocNames:u},{handler:`trash-cleanup`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`});async function te(e,i){if(e.method!==`POST`){X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let a;try{a=await eut(e,n??t)}catch(e){if(e instanceof D3){X(i,O3(e.reason),e.reason,A3(e.reason),{handler:`upload-asset`,cause:e});return}X(i,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:o,tempPath:s,sha:c,byteLength:l,parentDocName:f,placement:p}=a,m=()=>{if(G(s))try{Fs(s)}catch{}},h=H$(bie,{parentDocName:f,placement:p||void 0},i,{handler:`upload-asset`});if(!h.ok){m();return}let{parentDocName:g,placement:_}=h.value,{agentId:v,agentName:y}=d(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(l===0){m(),X(i,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(g.includes(`\0`)||g.includes(`..`)||g.startsWith(`/`)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let b=V(g);if(b!==`.`&&!T(b)){m(),X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}if(g4(g)||b!==`.`&&E(b)){m(),X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return}let x=await u.storeUpload({tempPath:s,sha:c,byteLength:l,filename:o,parentDocName:g,placement:_});if(x.ok){r.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:v,agentName:y,dedup:x.deduped,mime:x.mime,size:l,destPath:x.path,httpStatus:200},x.deduped?`[upload] dedup hit`:`[upload] write ok`),Q(i,200,rte,{src:x.src,path:x.path,deduped:x.deduped},{handler:`upload-asset`});return}switch(x.kind){case`config-error`:r.error({err:x.cause},`[upload] project config has invalid content.attachmentFolderPath`),X(i,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:x.cause});return;case`invalid-attachment-folder`:X(i,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return;case`path-escape`:X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,...x.cause===void 0?{}:{cause:x.cause}});return;case`reserved-destination`:X(i,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`upload-asset`});return;case`dest-validation-error`:r.error({err:x.cause,destDir:x.destDir},`[upload] failed to validate destination directory`),X(i,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:x.cause});return;case`mkdir-failed`:X(i,O3(x.reason),x.reason,A3(x.reason),{handler:`upload-asset`,cause:x.cause,detail:`failed to create attachment directory`});return;case`write-failed`:r.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:Mq(e),agentId:v,agentName:y,filename:x.filename,size:l,reason:x.reason,httpStatus:O3(x.reason),err:x.cause},`[upload] write failed`),X(i,O3(x.reason),x.reason,A3(x.reason),{handler:`upload-asset`,cause:x.cause});return}}return P$({"/api/create-page":k,"/api/create-folder":ee,"/api/duplicate-path":A,"/api/rename-path":j,"/api/delete-path":M,"/api/trash/cleanup":N,"/api/upload":te},{mutating:[`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/upload`]})}function nut(e){let t=e.replace(/\\/g,`/`);return t===`..`||t.startsWith(`../`)||ds(e)}function M3(e,t){if(typeof e!=`string`||!ds(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let n=W(e),r=W(n,t),i=U(n,r);return i===``?{ok:!0,abs:r,rel:``}:nut(i)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:r,rel:i}}function N3(e){return e?{agentId:e.connectionId,agentName:e.displayName,clientName:e.clientInfo?.name,colorSeed:e.colorSeed}:{}}const P3=`Absolute OK project/worktree path. Routed stdio: required until set unless one client root exists. Project-bound HTTP: optional, confined to its root.`,rut=`Canonical ids: ${Zn().map(e=>e.name).join(`, `)}. Call palette({components:[ids]}) before authoring for syntax/props, markdown-native forms, Mermaid and themed html preview for interactive charts/demos. Other JSX stays raw MDX when no canonical fits.`,F3=L().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`),iut="A 40-character commit SHA identifying a saved version. Produced by `checkpoint`, listed by `history` as `entries[].version`, and consumed here — the same `version` field name across all three.",aut=L().length(40).regex(/^[0-9a-f]+$/i).describe(iut),I3=L().nullable().describe("Route-only preview URL (`/#/<doc>`, no host:port), or null when no UI is running."),L3=L().optional().describe(`How the previewUrl was resolved (e.g. the UI lock).`),out=L().optional().describe(`Route of the prior/removed path, for closing a stale preview tab.`),R3=I({value:L(),truncatedFrom:On().optional(),hint:L().optional()}).describe(`Normalized change-note summary, when one was recorded.`),z3=R(F(L(),z())),sut=F(L(),z()).optional().describe("Preview-attach hint (`{ action, previewUrl?, message? }`) when relevant."),cut=R(bne).describe('Outbound internal links in the just-written doc that do not resolve. Always present — `[]` means every link resolves UNLESS `brokenLinkSuppression` is also present, in which case a project policy withheld findings, or `warnings` carries `link-check-deferred`, in which case the links were not checked because the server is still starting or busy with other writes. A withholding that arrives in a shape this build cannot validate is dropped rather than relayed, so `brokenLinkSuppression` stays absent even though findings were withheld. The `audit` tool is the surface that discloses that case, through its `warnings`. Each: `{ href (as written), resolvedTo (the docName or content-root file path it pointed at, or null), reason: "no-such-doc" | "no-such-file" | "unresolvable" | "excluded" }`. `excluded` means the file exists on disk but a .gitignore or .okignore rule keeps it out of the project; a `!` rule in .okignore re-includes it or its folder. Report-only — the write landed regardless; fix in a follow-up edit.'),lut=gi.optional().describe('Present ONLY when a project policy omitted detected broken links from `brokenLinks` — so an empty `brokenLinks` beside it does NOT mean every link resolves. `{ reason, count }`; `reason` today is `"reserved-log-policy"` (a reserved `log.md` records history whose links are expected not to resolve) and is an open token, so treat one you do not recognize as a withholding policy all the same. `count` is how many findings were withheld; the hrefs are deliberately not returned, because none of them is yours to repair.');function uut(e,t){for(let n of wi){let r=M3(e,`${t}${n}`);if(r.ok&&G(r.abs))return n}}const dut={summary:R3.optional(),warnings:R(Zt).min(1).optional().describe("Advisory entries discriminated by `kind`. Write-integrity kinds — `content-divergence` (converged Y.Text didn't byte-match what you composed) and `disk-edit-reconciled` (an out-of-band disk edit was folded in before your write) — mean re-read the doc. The renderability kind `mermaid-parse-error` means the write landed but that fence will not render — fix it and re-edit. `link-check-deferred` means links were not checked because the server is still starting or busy with other writes — that doc is re-checked only by a later write or edit of it, or an `audit`, which can time out until startup finishes."),brokenLinks:cut,brokenLinkSuppression:lut,templateHint:R(I({name:L(),description:L().optional()})).min(1).optional().describe("Templates the parent folder offers, present only when a create passed no `template`. A nudge — the write already landed; pass `template` next time to match the folder's shape.")};function fut(e,t,n){let r={};return e&&(r.previewUrl=e.url,r.previewUrlSource=e.source),t&&(r.warning=t),Object.keys(n).length>0&&(r.document=n),r}function B3(e){return`${typeof e.error==`string`?e.error:`request failed`}${typeof e.detail==`string`&&e.detail.length>0?` (${e.detail})`:``}${typeof e.retryAfterSeconds==`number`?` Retry after ${e.retryAfterSeconds}s.`:``}`}function V3(e,t){let n=e.type===`urn:ok:error:invalid-request`&&e.contentControlAdmission===!0&&t?` ${t}`:``;return`Error: ${B3(e)}${n}`}function $(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}const put=L().optional().describe("Auto-duplicated body text. `textPlusStructured` mirrors the visible body here as a Claude / Claude Desktop client-quirk workaround (those clients hide `content[]` when `structuredContent` is present). Internal — programmatic consumers should prefer the `content[0].text` channel.");function H3(e){return{text:put,...e}}function U3(e,t,n){let r={text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:r,...n?{isError:!0}:{}}}function W3(){return`Error: Hocuspocus server is not running. Start it with \`${Qi()} start\`, then retry.\nDo not fall back to native file edits for in-scope markdown; route writes through OpenKnowledge so attribution and live sync stay intact.`}async function mut(e,t){return typeof e==`function`?await e(t):e}async function hut(e,t){return typeof e==`function`?await e(t):e}async function G3(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}let i=n===void 0?r:W(n);try{let e=await hut(t,r);return{ok:!0,cwd:r,executionCwd:i,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function K3(e,t,n,r){let i=await q3(e,t,n,r);return i.ok?i.url?{ok:!0,cwd:i.cwd,executionCwd:i.executionCwd,config:i.config,url:i.url}:{ok:!1,result:$(W3(),!0)}:{ok:!1,result:$(`Error: ${i.error}`,!0)}}async function q3(e,t,n,r){let i=await G3(e,t,r);if(!i.ok)return i;let{cwd:a,executionCwd:o,config:s}=i;try{return{ok:!0,cwd:a,executionCwd:o,config:s,url:await mut(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function J3(e){let t=e.replace(/^\/+/,``);return t!==`.ok`&&!t.startsWith(`.ok/`)?null:t.startsWith(`.ok/skills/`)?"Skills are authored with the `skill` target, not a raw document path: `write({ skill: { name, description, body?, scope? } })` writes the SKILL.md wherever the skill lives (a NEW skill lands at the project default skill home, e.g. `.agents/skills/<name>/`). To author or improve a skill, use the `open-knowledge-write-skill` skill.":t.startsWith(`.ok/templates/`)?"Templates are authored with the `template` target (`write({ template: { … } })`), not a raw document path.":"Paths under `.ok/` are not addressable as documents. Edit folder config/frontmatter via the `folder` target, skills via the `skill` target, and templates via the `template` target."}function Y3(e){let t=e.toLowerCase();if(t.endsWith(`.markdown`))return{ok:!1,error:`Error: "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`};let n=e,r=t;for(;r.endsWith(`.mdx`)||r.endsWith(`.md`);)n=n.slice(0,r.endsWith(`.mdx`)?-4:-3),r=n.toLowerCase();let i=mne(n);return i.ok?{ok:!0,docName:n}:{ok:!1,error:`Error: "${e}" is invalid — ${i.reason}.`}}function X3(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...n}=t;return{ok:!0,...n}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let n=t;if(typeof n.type==`string`&&typeof n.title==`string`){let{type:e,title:t,status:r,instance:i,detail:a,...o}=n;return{...o,ok:!1,error:t,type:e,...typeof r==`number`?{status:r}:{},...typeof i==`string`?{instance:i}:{},...typeof a==`string`?{detail:a}:{}}}let{ok:r,error:i,...a}=n,o=typeof i==`string`?i:typeof n.message==`string`?n.message:`Server returned HTTP ${e.status}`;return{...a,ok:!1,error:o}}function Z3(e,t){return t?{url:e,local:t}:e}function Q3(e){return e instanceof Error&&e.name===`TimeoutError`}function $3(e,t){let n=e instanceof Error?e.message:String(e);if(!Q3(e))return`${Ine} ${n}`;let r=t?.mutating===!1?``:` The server may still have applied the request, so check before retrying.`;return`${Ste} ${n}.${r}`}async function gut(e,t,n,r,i){let a;try{a=await e(t,n,r===void 0?void 0:{body:r,contentType:`application/json`})}catch(e){return{ok:!1,error:$3(e)}}if(a===null)return null;let o=a.status>=200&&a.status<=299,s;try{s=JSON.parse(a.bodyText)}catch(e){let t=e instanceof Error?e.message:String(e),n=i?{httpStatus:a.status}:{};return o?{ok:!1,...n,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,...n,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}let c=X3({ok:o,status:a.status},s);return i?{...c,httpStatus:a.status}:c}async function e6(e,t){if(typeof e!=`string`){let n=await gut(e.local,`GET`,t,void 0,!0);if(n!==null)return n;e=e.url}let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:$3(e,{mutating:!1})}}let r;try{r=await n.json()}catch(e){if(Q3(e))return{ok:!1,httpStatus:n.status,error:$3(e,{mutating:!1})};let t=e instanceof Error?e.message:String(e);return n.ok?{ok:!1,httpStatus:n.status,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,httpStatus:n.status,error:`Server returned HTTP ${n.status} with non-JSON body: ${t}`}}return{...X3(n,r),httpStatus:n.status}}async function t6(e,t,n){let r=await e6(e,t);if(!r.ok)return{error:typeof r.error==`string`?r.error:`request failed`};let{ok:i,...a}=r,o=a[n];return{rows:Array.isArray(o)?o:[],data:a}}async function n6(e,t,n,r){let i;if(r!==void 0)try{i=JSON.stringify(r)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}if(typeof t!=`string`){let r=await gut(t.local,e,n,i,!1);if(r!==null)return r;t=t.url}let a;try{a=await fetch(`${t}${n}`,{method:e,headers:i===void 0?void 0:{"Content-Type":`application/json`},body:i,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:$3(e)}}let o;try{o=await a.json()}catch(e){if(Q3(e))return{ok:!1,error:$3(e)};let t=e instanceof Error?e.message:String(e);return a.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${a.status} with non-JSON body: ${t}`}}return X3(a,o)}function r6(e,t,n){return n6(`POST`,e,t,n)}function i6(e,t,n){return n6(`PUT`,e,t,n)}function a6(e,t){return n6(`DELETE`,e,t)}function _ut(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:n,to:r}=e;return typeof t==`string`&&typeof n==`string`&&typeof r==`string`?[{existing:t,incoming:n,to:r}]:[]}):[]}function o6(e,t,n){if(e!==void 0&&!Array.isArray(e))return{warnings:[kee]};let r=(Array.isArray(e)?e:[]).map(e=>typeof e==`string`?e:String(e)),i=Array.isArray(t)?t:[];return r.length===i.length&&i.every(e=>n.has(e))?{warnings:r,warningCodes:i}:{warnings:r}}function vut(e){return`Machine-readable codes aligned 1:1 with \`warnings\` (\`warnings[i]\` is the display text for \`warningCodes[i]\`) — switch on these, never on the English. Absent when ${e} sent warning text it did not pair with codes, or paired one with a code this build does not recognise; \`warnings\` still carries the full text either way, so treat a missing field as unknown rather than as an all-clear.`}const s6=vut(`the server`);function yut(e){return`Always emitted, \`[]\` when there were none. \`warningCodes\` accompanies this list 1:1 whenever ${e} paired every warning it sent with a code this build recognises; otherwise \`warningCodes\` is absent and this list still carries the full text. \`content[0].text\` lists every warning either way. A \`warnings\` payload in a shape this build cannot read at all becomes one entry saying so, with \`warningCodes\` absent — \`[]\` never means "unreadable".`}const c6=yut(`the server`),l6="`skill-name-vendor-word`: the name contains a vendor word. `skill-body-too-long`: the body exceeds the 500-line soft cap.",but="`no-targets`: nothing was projected, no editor is configured for this project. `scripts-present`: the skill ships executable `scripts/` (projected, never auto-run). `no-description`: installed, but its `description` is empty, so agents cannot route to it. `name-conflict`: a DIFFERENT skill already holds that name at a location. `place-path-invalid`: a named location is not a placeable root. `place-fork-refused`: a copy differing from the current source was left alone rather than deleted. `skill-fork-name-unpatched`: a fork rename moved the folder but could not rewrite `name` in its SKILL.md. `links-not-permitted`: the OS refused symlinks, so the named locations are copies that refresh while unedited and fork when edited.",xut=/^(?:source(?: family)?|validator) "/;function Sut(e){let t=[],n=[];for(let r of e)(xut.test(r)?t:n).push(r);let r=[...t,...n].slice(0,10);return{shownWarnings:r,omittedWarningCount:e.length-r.length}}function u6(e,t,n=0){let r=t.filter(e=>!Kn(e)),i=r.length+n;return i===0?[]:[`${e} incomplete — ${i} warning${i===1?``:`s`} (findings may be partial):`,...r.map(e=>` ⚠ ${e}`),...n>0?[` … and ${n} more warning${n===1?``:`s`}`]:[]]}function Cut(e,t,n,r){if(t===0&&n.some(Kn))return`No documents were checked${r}; this scope contains no admitted documents.`;let i=`${t} document${t===1?``:`s`}${r}`;return n.length>0?`No problems found across ${i}, but the ${e.toLowerCase()} could not fully complete.`:`No problems across ${i}.`}function d6(e){let t=e.severity===`error`?`✘`:`⚠`,n=e.range?.start?.line;return` ${t} ${n===void 0?`line ?`:`line ${n+1}`} ${e.source!==void 0&&e.code!==void 0?`${e.source}/${e.code}`:`?`}: ${e.message??``}`.trimEnd()}function f6(e,t){let n=[];return e>0&&n.push(`${e} error${e===1?``:`s`}`),t>0&&n.push(`${t} warning${t===1?``:`s`}`),n.length>0?n.join(`, `):`no problems`}function wut(e,t){let n=kut(e,t,`frontmatter.yml`);if(rq(V(n)).kind===`symlink`)return m6(`symlink`,n,`${V(n)} is a symlink — folder metadata skipped. Replace the symlink with a real directory.`),{};let r=rq(n);if(r.kind===`symlink`)return m6(`symlink`,n,`symlink at ${n} — folder metadata skipped. Replace it with a regular file.`),{};if(r.kind===`unverifiable`)return m6(`unverifiable`,n,`cannot lstat ${n} (${r.code??`unknown errno`}) — folder metadata skipped.`),{};if(!G(n))return{};try{nq(n,W(e))}catch(e){let t=e instanceof Error?e.message:String(e);return m6(aq(e)?`escape`:`canonicalize`,n,`cannot safely read ${n} — folder metadata skipped. Reason: ${t}`),{}}let i=Out(n);return i==null?{}:Tut(i)}function Tut(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const Eut=[`symlink`,`unverifiable`,`escape`,`canonicalize`,`malformed-yaml`],p6=new Set;function m6(e,t,n){let r=`${e}:${t}`;p6.has(r)||(p6.add(r),q(`folder-frontmatter`).warn({path:t,kind:e},n))}function Dut(e){for(let t of Eut)p6.delete(`${t}:${e}`)}function Out(e){let t;try{t=K(e,`utf-8`)}catch{return null}let n;try{n=(0,jc.parse)(t)}catch(t){return m6(`malformed-yaml`,e,`malformed YAML at ${e} — folder metadata skipped. Fix the file or delete it. Reason: ${t instanceof Error?t.message:String(t)}`),null}return typeof n!=`object`||!n||Array.isArray(n)?null:(Dut(e),n)}function kut(e,t,n){let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);return r===``||r===`.`?H(e,`.ok`,n):H(e,r,`.ok`,n)}function Aut(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function jut(e){try{return Ps(W(e,`.git`)).isDirectory()}catch{return!1}}function Mut(e){return ej({baseDir:W(e),timeout:{block:5e3}})}async function Nut(e,t,n=5){if(!jut(e))return{commits:[],source:`git-absent`};let r=Mut(e),i=``;try{i=await r.raw(`log`,`-${Math.max(1,n)}`,`--format=%H|%aI|%an|%s`,`--follow`,...Wt([t]))}catch{return{commits:[],source:`git`}}let a=[];for(let e of i.split(`
|
|
1119
1119
|
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let n=e.indexOf(`|`,t+1);if(n<0)continue;let r=e.indexOf(`|`,n+1);r<0||a.push({hash:e.slice(0,t),date:e.slice(t+1,n),authorName:e.slice(n+1,r),subject:e.slice(r+1)})}return{commits:a,source:`git`}}const Put=5e3;async function Fut(e){try{let t=(await ej({baseDir:e,timeout:{block:Put}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function Iut(e,t){return ej({baseDir:t,timeout:{block:Put}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function Lut(e,t){let n=Bb(t);return e.startsWith(n)?e.slice(n.length):e}async function Rut(e,t,n,r,i){let a=``;try{a=await e.raw(`log`,t,`-${Math.max(1,i*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,...Wt([n]))}catch{return[]}let o=Lut(t,r),s=Qb(o),c=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,i=``,a=``,l=``,u=``]=t.split(`\0`),d=n.trim();d.length===40&&c.push({hash:d,date:i,writerName:a,message:l,contributors:Gb(u),writerId:o,isAgent:s.isAgent,writerClassification:s.classification,branch:r})}return c}async function zut(e,t,n,r,i){let a;try{a=await uH(e,t)}catch(e){return q(`shadow-log`).warn({branch:t,relPath:n,err:e},`[shadow-log] chain anchors unresolved; per-path history degraded to empty`),[]}if(a.length===0)return[];let o=``;try{o=await e.raw(`log`,...a,`-${Math.max(r*3,20)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,...Wt([n]))}catch(e){return q(`shadow-log`).warn({branch:t,relPath:n,anchorCount:a.length,err:e},`[shadow-log] ancestry walk failed; per-path history degraded to empty`),[]}let s=[];for(let e of o.split(``)){if(s.length>=r)break;let n=e.trimStart();if(!n)continue;let[a=``,o=``,c=``,l=``,u=``]=n.split(`\0`),d=a.trim();if(d.length!==40||i.has(d)||l.startsWith(`checkpoint:`)||l.startsWith(`park:`)||l.startsWith(`import:`)||l.startsWith(`upstream:`))continue;let f=Gve(u),p=f?.writer_id??``,m=Qb(p);i.add(d),s.push({hash:d,date:o,writerName:f?.display_name??c,message:l,contributors:Gb(u),writerId:p,isAgent:m.isAgent,writerClassification:m.classification,branch:t})}return s}async function But(e,t,n=5){let r=Hve(e);if(!r)return{commits:[],source:`shadow-repo-absent`};let i=await Fut(e);if(!i)return{commits:[],source:`shadow-repo`};let a=Iut(r,W(e)),o=``;try{o=await a.raw(`for-each-ref`,Bb(i),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let s=o.split(`
|
|
1120
1120
|
`).map(e=>e.trim()).filter(Boolean),c=(s.length===0?[]:await Promise.all(s.map(e=>Rut(a,e,t,i,n)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n);if(c.length<n){let e=new Set(c.map(e=>e.hash)),r=await zut(a,i,t,n-c.length,e);r.length>0&&(c=[...c,...r].sort((e,t)=>t.date.localeCompare(e.date)).slice(0,n))}return{commits:c,source:`shadow-repo`}}const Vut=1e3,Hut=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),Uut=/\.(md|mdx)$/i;function Wut(e,t){if(e===null||t===null)return null;let n=e,r=t;return n===0&&r===0?`orphan`:n>=5?`hub`:n>0&&r>0?`connector`:`leaf`}function Gut(e,t){let n=e.frontmatterSchemas;if(!n||n.length===0)return[];let r=e.contentDir??e.projectDir,i=U(r,W(e.projectDir,t));if(i.startsWith(`..`))return[];let a=[];for(let e of n)e.enabled!==!1&>e(e.appliesTo).matches(i)&&(a.includes(e.file)||a.push(e.file));return a}function Kut(e,t){return Gut(e,t===``?`⁂`:`${t}/⁂`)}function h6(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const qut=new Set;async function Jut(e){try{let t=await Ks(e,`utf-8`);return{frontmatter:k(t)??{},firstHeading:mY(wa(t).body)}}catch(t){if(t?.code!==`ENOENT`&&!qut.has(e)){qut.add(e);let n=t instanceof Error?t.message:String(t);q(`enrichment`).warn({path:e,reason:n},`failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${n}`)}return null}}async function Yut(e,t){if(!e)return null;let n=await e6(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.backlinks??n.results??n.links;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,n=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;n&&i.push({source:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}async function Xut(e,t){if(!e)return null;let n=await e6(e,`/api/comments?doc=${encodeURIComponent(t)}`);return n.ok?Zut(n.threads):null}function Zut(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n,r=e.state;if(r!==`anchored`&&r!==`orphaned`||typeof e.threadId!=`string`||e.threadId===``)continue;let i=(typeof e.anchor==`object`&&e.anchor!==null?e.anchor:{}).exact;t.push({threadId:e.threadId,body:typeof e.latestComment==`string`?e.latestComment:``,quote:typeof i==`string`?i:``,state:r,queued:e.queued===!0})}return t}async function Qut(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));let i=await Promise.all(r.map(async t=>{let n=await e6(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})),a=new Map,o=!1;for(let e of i)if(e){o=!0;for(let[t,n]of Object.entries(e))typeof n==`number`&&Number.isFinite(n)&&a.set(t,n)}return o?a:null}async function $ut(e,t){if(!e||t.length===0)return null;let n=[...new Set(t)],r=[];for(let e=0;e<n.length;e+=100)r.push(n.slice(e,e+100));return tdt(await Promise.all(r.map(async t=>{let n=await e6(e,`/api/comment-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return n.ok?n.counts??{}:null})))}async function edt(e,t){if(!e)return null;let n=await e6(e,`/api/comment-counts?prefix=${encodeURIComponent(t)}`);return n.ok?tdt([n.counts??{}]):null}function tdt(e){let t=new Map,n=!1;for(let r of e)if(r){n=!0;for(let[e,n]of Object.entries(r))typeof n==`number`&&Number.isFinite(n)&&t.set(e,n)}return n?t:null}async function ndt(e,t){if(!e)return null;let n=await e6(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!n.ok)return null;let r=n.forwardLinks??n.links??n.results;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){i.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let n=typeof t.docName==`string`?t.docName:void 0;n&&i.push({kind:`doc`,docName:n,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return i}function rdt(e,t){let n=e?.title;if(typeof n!=`string`)return t;let r=n.trim();return r===``?t:r}function idt(e,t){let n=e??{};return{title:rdt(n,t),description:typeof n.description==`string`?n.description:void 0,tags:Array.isArray(n.tags)?n.tags.filter(e=>typeof e==`string`):[],frontmatter:n}}async function adt(e,t,n={}){let r=M3(t.projectDir,e);if(!r.ok)throw Error(`enrichPath: ${r.reason}`);let i=r.rel,a=r.abs,o=t.historyDepth??5,s=n.includeRichFields===!0,c=Jut(a),l=Gut(t,i),u=l.length>0?{schemas_applicable:l}:{};if(!s){let e=await c,t=idt(e?.frontmatter??null,e?.firstHeading);return{path:i,title:t.title,description:t.description,tags:t.tags,frontmatter:t.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null,graphRole:null,commentCount:null,comments:null,...u}}let[d,f,p,m,h,g]=await Promise.all([c,Yut(t.serverUrl,h6(i)).catch(()=>null),ndt(t.serverUrl,h6(i)).catch(()=>null),But(t.projectDir,i,o).catch(()=>({commits:[],source:`shadow-repo`})),Nut(t.projectDir,i,o).catch(()=>({commits:[],source:`git`})),Xut(t.serverUrl,h6(i)).catch(()=>null)]),_=idt(d?.frontmatter??null,d?.firstHeading);return{path:i,title:_.title,description:_.description,tags:_.tags,frontmatter:_.frontmatter,backlinkCount:f?.length??null,backlinks:f,forwardLinkCount:p?.length??null,forwardLinks:p,history:m.commits,historySource:m.source,projectHistory:h.commits,projectHistorySource:h.source,graphRole:Wut(f?.length??null,p?.length??null),commentCount:g?.length??null,comments:g,...u}}async function odt(e,t){let n={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},r=0,i=[{path:e,depth:0}];for(;i.length>0;){let e=i.shift();if(!e)break;if(r>=Vut){n.truncated=!0;break}let a;try{a=await qs(e.path,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=Vut){n.truncated=!0;break}r++;let a=o.name;if(o.isDirectory()){if(Hut.has(a)||a.startsWith(`.`))continue;e.depth===0&&n.childDirCount++,i.push({path:`${e.path}/${a}`,depth:e.depth+1})}else if(o.isFile()&&Uut.test(a)){n.recursiveMdCount++,e.depth===0&&n.directMdCount++;let r=`${e.path}/${a}`;try{let e=await Xs(r);(!n.mostRecent||e.mtimeMs>n.mostRecent.mtimeMs)&&(n.mostRecent={absPath:r,relPath:U(t,r).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return n}async function sdt(e,t,n={}){let r=M3(t.projectDir,e);if(!r.ok)throw Error(`enrichDirectory: ${r.reason}`);let i=r.rel,a=r.abs,o=await odt(a,t.projectDir),s;if(o.mostRecent){let e=await Jut(o.mostRecent.absPath);s={path:o.mostRecent.relPath,title:rdt(e?.frontmatter,e?.firstHeading)??cs(o.mostRecent.relPath),updatedAt:new Date(o.mostRecent.mtimeMs).toISOString()}}let c={path:i,type:`directory`,directMdCount:o.directMdCount,recursiveMdCount:o.recursiveMdCount,childDirCount:o.childDirCount,mostRecentMd:s,truncated:o.truncated},l=wut(t.projectDir,i);l.title!==void 0&&(c.title=l.title),l.description!==void 0&&(c.description=l.description),(l.tags?.length??0)>0&&(c.tags=l.tags);let u=x3(t.projectDir,i,{onRefused:n.onTemplateRefused});u.length>0&&(c.templates_available=u);let d=Kut(t,i);d.length>0&&(c.schemas_applicable=d);let f=await edt(t.serverUrl,i).catch(()=>null);if(f&&f.size>0){let e=0;for(let t of f.values())e+=t;c.commentCount=e,c.commentedDocs=[...f].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,cdt).map(([e,t])=>({docName:e,count:t}))}return c}const cdt=5;async function ldt(e,t,n){let r=await sdt(e,n);if(t<=1)return r;let i=r.path,a=W(n.projectDir,i),o;try{o=await qs(a,{withFileTypes:!0})}catch{return r}let s=[];for(let e of o){if(!e.isDirectory()||udt.has(e.name)||e.name.startsWith(`.`))continue;let r=await ldt(i?`${i}/${e.name}`:e.name,t-1,n);s.push(r)}return s.length>0&&(r.subfolders=s),r}const udt=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function g6(e,t){let n={...e};for(let[e,r]of Object.entries(t))if(r!==void 0){if(ddt(r)){delete n[e];continue}n[e]=r}return n}function ddt(e){return hne(e)}function fdt(e){if(!ds(e.anchorDir))return{ok:!1,error:{code:`BAD_CONTENT_DIR`,message:`anchorDir must be absolute`}};let t=W(e.anchorDir),n=e.folderRel.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(n.split(`/`).some(e=>e===`..`))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Folder path escapes the content directory: ${e.folderRel}`}};let r=n===``?t:W(t,n);if(r!==t&&!r.startsWith(t+ms))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder escapes the content directory: ${r}`}};let i=H(r,`.ok`),a=H(i,`frontmatter.yml`);if(rq(a).kind===`symlink`)return{ok:!1,error:{code:`SYMLINK_REFUSED`,message:`Refusing to operate on "${n===``?``:`${n}/`}.ok/frontmatter.yml": it is a symlink. Replace the symlink with a real file or directory and retry.`}};try{let n=pdt(a),r=Object.keys(e.patch).length===0?{}:g6(n,e.patch);if(Object.keys(r).length===0)return G(a)?(Fs(a),mdt(i),{ok:!0,path:_6(t,a),action:`deleted`}):{ok:!0,path:_6(t,a),action:`noop`};Ts(i,{recursive:!0});let o=(0,jc.stringify)(r),s=mx(a);return Is(s,o,`utf-8`),js(s,a),{ok:!0,path:_6(t,a),action:`written`}}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write folder frontmatter for "${n||`.`}": ${e.message}`}}}}function pdt(e){if(!G(e))return{};let t=K(e,`utf-8`),n=(0,jc.parse)(t);return typeof n!=`object`||!n||Array.isArray(n)?{}:{...n}}function mdt(e){if(!G(e))return;let t;try{t=ks(e)}catch{return}if(t.length===0)try{Ns(e)}catch{}}function _6(e,t){return t.startsWith(e+ms)?t.slice(e.length+1).split(ms).join(`/`):t}const hdt=x;function v6(e){if(!hdt.test(e.name))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must use ${$i} (got: ${JSON.stringify(e.name)}).`}};let t=bdt(e.frontmatter.title);if(!t.ok)return{ok:!1,error:t.error};let n=xdt(e.body);if(!n.ok)return{ok:!1,error:n.error};let r=Sdt(e.body);if(!r.ok)return{ok:!1,error:r.error};let i={};e.frontmatter.title!==void 0&&(i.title=e.frontmatter.title),e.frontmatter.description!==void 0&&(i.description=e.frontmatter.description),Array.isArray(e.frontmatter.tags)&&e.frontmatter.tags.length>0&&(i.tags=e.frontmatter.tags);let a=ge(i,e.body),o=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&o.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,content:a,warnings:o}}function gdt(e){let t=y6(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let n=v6({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!n.ok)return{ok:!1,error:n.error};let{content:r,warnings:i}=n,{templatesDir:a,filePath:o}=b6(e.projectDir,t.folderRel,e.name);try{Ts(a,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${x6(e.projectDir,a)}: ${t.message}`}}}let s=!G(o),c=mx(o);try{Is(c,r,`utf-8`),js(c,o)}catch(t){try{Fs(c)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${x6(e.projectDir,o)}: ${t.message}`}}}return{ok:!0,path:x6(e.projectDir,o),created:s,warnings:i}}function _dt(e){let t=y6(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:n,okDir:r,filePath:i}=b6(e.projectDir,t.folderRel,e.name),a=G(i);if(a)try{Fs(i)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${x6(e.projectDir,i)}: ${t.message}`}}}return{ok:!0,path:x6(e.projectDir,i),existed:a,cleanedEmpty:vdt(n,r)}}function vdt(e,t){let n=!1,r=!1;if(G(e)&&Cdt(e))try{Ns(e),n=!0}catch{}if(G(t)&&Cdt(t))try{Ns(t),r=!0}catch{}return{templatesDir:n,okDir:r}}async function ydt(e){let t=y6(e.projectDir,e.fromFolder,e.fromName);if(!t.ok)return{ok:!1,error:t.error};let n=y6(e.projectDir,e.toFolder,e.toName);if(!n.ok)return{ok:!1,error:n.error};let r=b6(e.projectDir,t.folderRel,e.fromName),i=b6(e.projectDir,n.folderRel,e.toName);if(r.filePath===i.filePath)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same template.`}};if(!G(r.filePath))return{ok:!1,error:{code:`TEMPLATE_NOT_FOUND`,message:`No template at ${x6(e.projectDir,r.filePath)}.`}};if(G(i.filePath))return{ok:!1,error:{code:`TEMPLATE_EXISTS`,message:`A template already exists at ${x6(e.projectDir,i.filePath)}.`}};try{Ts(i.templatesDir,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create destination template directory at ${x6(e.projectDir,i.templatesDir)}: ${t.message}`}}}let a;try{a=await e.relocate(r.filePath,i.filePath)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move template: ${e.message}`}}}let o=vdt(r.templatesDir,r.okDir);return{ok:!0,fromPath:x6(e.projectDir,r.filePath),toPath:x6(e.projectDir,i.filePath),committed:a,cleanedEmpty:o}}function y6(e,t,n){if(!ds(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!hdt.test(n))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must use ${$i} (got: ${JSON.stringify(n)}).`}};let r=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(r.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let i=r?W(e,r):e,a=W(e);return!i.startsWith(a+ms)&&i!==a?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${i}`}}:{ok:!0,folderRel:r}}function bdt(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function xdt(e){let t=Rlt(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function b6(e,t,n){let r=t?H(e,t,`.ok`):H(e,`.ok`),i=H(r,`templates`);return{okDir:r,templatesDir:i,filePath:H(i,`${n}.md`)}}function x6(e,t){let n=t.startsWith(e+ms)?t.slice(e.length+1):t;return fs(n).split(ms).join(`/`)}function Sdt(e){let{frontmatter:t}=wa(e);if(t===``)return{ok:!0};let n=fa(t);return RegExp(`^template:`,`m`).test(n)?{ok:!1,error:{code:`TEMPLATE_RESERVED_KEY`,message:`Template starter content may not declare a top-level \`${Aie}:\` frontmatter key — it is reserved for the template's identity.`}}:{ok:!0}}function Cdt(e){try{return ks(e).length===0}catch{return!1}}const wdt={BAD_CONTENT_DIR:{status:400,urn:`urn:ok:error:invalid-request`},PATH_ESCAPE:{status:400,urn:`urn:ok:error:path-escape`},SYMLINK_REFUSED:{status:400,urn:`urn:ok:error:symlink-refused`},WRITE_ERROR:{status:500,urn:`urn:ok:error:internal-server-error`}};function Tdt(e){let{contentDir:t,projectDir:n,ephemeral:r,log:i,hocuspocus:a,sessionManager:o,getPrincipal:s,signalChannel:c,conflicts:l,recentlyRemovedDocs:d,isSafeDocName:f,resolveAlias:p,resolveContentEntryPath:m,validateFolderRel:h,extractAgentIdentity:g,extractActorIdentityFromQuery:_,okArtifactKey:v,attributeOkArtifactWrite:y,scheduleOkArtifactFlush:b,flushDiskAndDetectOutcome:S,respondPersistenceFailure:C,respondDiskDivergence:w,respondStaleExternalWrite:T,registerWrittenDocInFileIndex:E,captureAndCloseDocuments:D,captureNamespaceMove:O,renameTrackedPathInGit:k,renamePathOnDisk:ee,splitContentPath:A,mutateFileIndex:j}=e;function M(e,t,n=`template`){return!e||!x.test(e)?(X(t,400,`urn:ok:error:invalid-request`,`Invalid name: must use ${$i}, without the \`.md\` extension.`,{handler:n}),!1):!0}function te(e,t,n){let r=t===``?[]:t.split(`/`);for(let t=r.length;t>=0;t--){let i=t===0?``:r.slice(0,t).join(`/`),a=i===``?e:W(e,i);if(a!==e&&!a.startsWith(`${e}${ms}`))continue;let o=W(a,`.ok`),s=rq(o);if(s.kind===`symlink`)return{kind:`refused`,folder:i};if(s.kind===`unverifiable`&&s.code!==`ENOTDIR`)return{kind:`unverifiable`,folder:i,code:s.code};let c=W(o,`templates`),l=rq(c);if(l.kind===`symlink`)return{kind:`refused`,folder:i};if(l.kind===`unverifiable`&&l.code!==`ENOTDIR`)return{kind:`unverifiable`,folder:i,code:l.code};let u=W(c,`${n}.md`);if(G(u))return{kind:`found`,abs:u,folder:i,scope:t===r.length?`local`:`inherited`}}return{kind:`absent`}}function ne(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function P(e,t){return Dn(e,t)}let re=new Set;function ie(e,t){let n=W(e,`${t}.md`);return re.has(n)||G(n)}let ae=i2({GET:Z(La,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=h(n.searchParams.get(`path`)??``,t,`path`,`folder-config-get`,`ok`);if(!r)return;let a=W(r.resolvedContentDir,r.folderRel,`.ok`),o=W(a,`frontmatter.yml`),s=[],c=[],l=(e,t)=>{s.push(t),c.push(e)},u=await sdt(r.folderRel,{projectDir:r.resolvedContentDir},{onTemplateRefused:e=>{let t=`${e.folder||`.`}/${e.component}`,n=W(r.resolvedContentDir,e.folder,e.component);switch(e.kind){case`symlink`:l(`templates-symlink-refused`,`${t} is a symlink — its templates are not enumerated. Replace the symlink with a real file or directory and retry.`),i.warn({path:n,folder:r.folderRel||`.`},`[folder-config:get] ${t} is a symlink — templates_available skips it.`);break;case`unverifiable`:l(`templates-unverifiable`,`${t} could not be inspected (${e.code??`unknown errno`}) — its templates are not enumerated. The errno may come from ${e.folder||`.`}/.ok itself; check its permissions.`),i.warn({path:n,folder:r.folderRel||`.`,code:e.code},`[folder-config:get] cannot lstat ${t} (${e.code??`unknown errno`}) — templates_available skips it.`);break;default:throw Error(`Unhandled template refusal kind in handleFolderConfigGet: ${String(e.kind)}`)}}}),d=null,f=rq(o);if(f.kind===`symlink`)l(`symlink-refused`,`${r.folderRel||`.`}/.ok/frontmatter.yml is a symlink — refusing to read through it. Replace the symlink with a real file or directory and retry.`),i.warn({path:o,folder:r.folderRel||`.`},`[folder-config:get] ${r.folderRel||`.`}/.ok/frontmatter.yml is a symlink — refusing to read through it.`);else if(f.kind===`unverifiable`)l(`unverifiable`,`${r.folderRel||`.`}/.ok/frontmatter.yml could not be inspected (${f.code??`unknown errno`}) — folder properties skipped.`),i.warn({path:o,code:f.code},`[folder-config:get] cannot lstat ${o} (${f.code??`unknown errno`}) — frontmatter_local skipped.`);else if(G(o))try{let e=await Ks(o,`utf-8`),t=(0,jc.parse)(e);d=t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch(e){let t=e instanceof Error?e.message:String(e);l(`malformed-yaml`,`${r.folderRel||`.`}/.ok/frontmatter.yml has malformed YAML.`),i.warn({path:o,reason:t},`[folder-config:get] malformed YAML in ${o}: ${t}`),d=null}Q(t,200,Ir,{folder:u,frontmatter_local:d,...c.length>0?{warnings:s,warningCodes:c}:{}},{handler:`folder-config-get`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:Z(Fe,async(e,t,n)=>{try{if(r){X(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=y$(n,s);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let i=h(n.path,t,`path`,`folder-config-put`,`ok`);if(!i)return;let a=[];if(n.frontmatter!==void 0){let r=fdt({anchorDir:i.resolvedContentDir,folderRel:i.folderRel,patch:n.frontmatter});if(!r.ok){let{status:e,urn:n}=wdt[r.error.code];X(t,e,n,e===500?`Failed to write folder config.`:r.error.message,{handler:`folder-config-put`,detail:r.error.code,cause:Error(r.error.message)});return}a.push({path:r.path,action:r.action}),r.action!==`noop`&&(y(e,v(`folder-frontmatter`,i.folderRel),`folder-frontmatter-${r.action===`deleted`?`delete`:`edit`}: ${r.path}`),b(`folder-config-put`))}Q(t,200,Se,{applied:a},{handler:`folder-config-put`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function oe(e,t,n){let r=l.findByDocName(e);return r!==void 0&&(tJ(n,new $q({file:r.file}),t,r),!0)}let se=Z(La,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!M(r,t,`template-get`))return;let i=h(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`,`ok-and-templates`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=te(o,a,r);if(s.kind===`refused`){X(t,400,`urn:ok:error:symlink-refused`,`"${s.folder||`.`}/.ok" or its templates directory is a symlink — refusing to resolve templates through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-get`,detail:s.folder||`.`});return}if(s.kind===`unverifiable`){X(t,500,`urn:ok:error:internal-server-error`,`Cannot inspect "${s.folder||`.`}/.ok" (${s.code??`unknown errno`}) — refusing to resolve templates through it.`,{handler:`template-get`,detail:s.code??`unknown-errno`});return}if(s.kind===`absent`){X(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s;if(rq(c).kind===`symlink`){X(t,400,`urn:ok:error:symlink-refused`,`Template "${r}" at "${l||`.`}/.ok/templates/${r}.md" is a symlink — refusing to read through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-get`,detail:l||`.`});return}try{nq(c,o)}catch(e){if(aq(e)){X(t,400,`urn:ok:error:symlink-refused`,`Template "${r}" resolves through a symlink outside the content directory — refusing to read through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-get`,detail:l||`.`});return}throw e}let d=await Ks(c,`utf-8`),f=lt(d),p=f.identity,m=f.starterContent,g=U(o,c).split(/[\\/]/).filter(Boolean).join(`/`);Q(t,200,We,{template:{name:r,folder:l,scope:u,path:g,frontmatter:p,body:m}},{handler:`template-get`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),ce=Z(N,async(e,t,n)=>{try{if(r){X(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=y$(n,s);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let i=n.name;if(!M(i,t,`template-put`))return;let a=h(n.folder,t,`folder`,`template-put`,`ok-and-templates`);if(!a)return;let c=W(a.resolvedContentDir,a.folderRel,`.ok`,`templates`,`${i}.md`);if(rq(c).kind===`symlink`){X(t,400,`urn:ok:error:symlink-refused`,`${a.folderRel||`.`}/.ok/templates/${i}.md is a symlink — refusing to write through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-put`,detail:a.folderRel||`.`});return}if(oe(P(a.folderRel,i),`template-put`,t))return;let l=v6({name:i,body:typeof n.body==`string`?n.body:``,frontmatter:ne(n.frontmatter)});if(!l.ok){X(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:l.error.code,cause:Error(l.error.message)});return}let u=!G(c),d=U(a.resolvedContentDir,c).split(/[\\/]/).filter(Boolean).join(`/`),f=P(a.folderRel,i),{agentId:p,agentName:m,colorSeed:_,clientName:x}=g(n),D=await o.getSession(f,p,{displayName:m,colorSeed:_,clientName:x});D.dc.document.transact(()=>{rH(D.dc.document,l.content,`agent`)},D.origin);let O=await S(f);if(O?.kind===`failure`){C(t,O.failure,`template-put`);return}if(O?.kind===`divergence`){w(t,`template-put`);return}if(O?.kind===`stale-external-write`){T(t,`template-put`,f);return}E(f,l.content),y(e,v(`template`,a.folderRel,i),`${u?`template-create`:`template-edit`}: ${d}`),b(`template-put`),Q(t,200,pee,{path:d,created:u,warnings:l.warnings},{handler:`template-put`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),le=Z(La,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!M(r,t,`template-delete`))return;let i=h(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`,`ok-and-templates`);if(!i)return;let a=_(n,s);if(a.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(oe(P(i.folderRel,r),`template-delete`,t))return;await D([P(i.folderRel,r)],`deleted-upstream`);let o=_dt({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!o.ok){let e=o.error.code===`WRITE_ERROR`||o.error.code===`UNLINK_FAILED`||o.error.code===`BAD_PROJECT_DIR`?500:400;X(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:o.error.code,cause:Error(o.error.message)});return}o.existed&&(y(a,v(`template`,i.folderRel,r),`template-delete: ${o.path}`),b(`template-delete`),d?.setDeleted(P(i.folderRel,r))),Q(t,200,$n,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0});return P$({"/api/folder-config":ae,"/api/template":i2({GET:se,PUT:ce,POST:Z(br,async(e,t,r)=>{try{let e=y$(r,s);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!M(r.fromName,t,`template-move`)||!M(r.toName,t,`template-move`))return;let a=h(r.fromFolder,t,`folder`,`template-move`,`ok-and-templates`);if(!a)return;let o=h(r.toFolder,t,`folder`,`template-move`,`ok-and-templates`);if(!o||oe(P(a.folderRel,r.fromName),`template-move`,t))return;await D([P(a.folderRel,r.fromName)],`renamed`);let l=O?.(P(o.folderRel,r.toName)),u=await ydt({projectDir:a.resolvedContentDir,fromFolder:a.folderRel,fromName:r.fromName,toFolder:o.folderRel,toName:r.toName,relocate:async(e,t)=>{let r=await k(n,e,t);return r||ee(e,t),r}});if(!u.ok){if(u.error.code===`TEMPLATE_NOT_FOUND`){let e=te(a.resolvedContentDir,a.folderRel,r.fromName);if(e.kind===`refused`){X(t,400,`urn:ok:error:symlink-refused`,`"${e.folder||`.`}/.ok" or its templates directory is a symlink — refusing to resolve templates through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-move`,detail:e.folder||`.`});return}if(e.kind===`unverifiable`){X(t,500,`urn:ok:error:internal-server-error`,`Cannot inspect "${e.folder||`.`}/.ok" (${e.code??`unknown errno`}) — refusing to resolve templates through it.`,{handler:`template-move`,detail:e.code??`unknown-errno`});return}if(e.kind===`found`&&e.scope===`inherited`){X(t,400,`urn:ok:error:invalid-request`,`Template "${r.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${a.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}X(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:u.error.message});return}if(u.error.code===`TEMPLATE_EXISTS`){X(t,409,`urn:ok:error:doc-already-exists`,u.error.message,{handler:`template-move`,detail:u.error.code});return}let e=u.error.code===`WRITE_ERROR`||u.error.code===`MOVE_FAILED`?500:400;X(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:u.error.code,cause:Error(u.error.message)});return}l?.(),d?.setDeleted(P(a.folderRel,r.fromName));let f=W(o.resolvedContentDir,u.toPath),p=rq(f).kind===`symlink`;if(y(e,v(`template`,o.folderRel,r.toName),`template-rename: ${u.fromPath} -> ${u.toPath}`,[{from:u.fromPath,to:u.toPath}]),b(`template-move`),c?.(`files`),p){if(i.warn({path:f,folder:o.folderRel||`.`},`[template-move] moved template "${u.toPath}" is a symlink — skipping content read-back and index registration.`),r.body!==void 0||r.frontmatter!==void 0){X(t,400,`urn:ok:error:symlink-refused`,`Template moved to "${u.toPath}", but it is a symlink — refusing to read or rewrite through it. Replace it with a regular file and retry the edit.`,{handler:`template-move`,detail:o.folderRel||`.`});return}Q(t,200,qie,{from:u.fromPath,to:u.toPath,committed:u.committed},{handler:`template-move`});return}let m=null;if(r.body!==void 0||r.frontmatter!==void 0){let e;if(typeof r.body==`string`)e=r.body;else try{e=nn(K(f,`utf-8`))}catch{e=null}if(e===null)m={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=gdt({projectDir:o.resolvedContentDir,folder:o.folderRel,name:r.toName,body:e,frontmatter:ne(r.frontmatter)});t.ok||(m=t.error)}}try{E(P(o.folderRel,r.toName),K(f,`utf-8`))}catch{}if(m){let e=m.code===`WRITE_ERROR`||m.code===`READ_FAILED`;X(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${u.toPath}", but updating its content failed.`,{handler:`template-move`,detail:m.code,cause:Error(m.message)});return}Q(t,200,qie,{from:u.fromPath,to:u.toPath,committed:u.committed},{handler:`template-move`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:le},{handler:`template`}),"/api/template/import":Z(wt,async(e,n,i)=>{let _;try{if(r){X(n,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=y$(i,s);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let x=i.sourcePath;if(!f(x)){X(n,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let O=p(x);if(YW(O)||XW(O)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`template-import`});return}let k=m(t,`file`,O);if(!G(k)){X(n,404,`urn:ok:error:doc-not-found`,`Source document not found: ${O}.`,{handler:`template-import`});return}let ee=a.documents.get(O);if(i.deleteSource){let e=l.findByDocName(O);if(e!==void 0){tJ(n,new $q({file:e.file}),`template-import`,e);return}}let N=``;if(ee)N=ee.getText(`source`).toString();else{let e=await a.openDirectConnection(O);try{let t=e.document;if(!t){X(n,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}N=t.getText(`source`).toString()}finally{await e.disconnect()}}let te=i.name;if(!te){let{basename:e}=A(x),t=e.replace(/\.(md|mdx)$/i,``);te=u(t).replace(/[^\p{L}\p{M}\p{N}_-]|\p{DI}/gu,`-`).toLowerCase(),te=te.replace(/^[-_]+|[-_]+$/g,``),te||=`imported-template`}if(!M(te,n,`template-import`))return;let ne=h(i.targetFolder,n,`folder`,`template-import`,`ok-and-templates`);if(!ne)return;let ae=W(ne.resolvedContentDir,ne.folderRel,`.ok`,`templates`);if(!i.name){let e=te;for(let t=2;ie(ae,te);t++)te=`${e}-${t}`}let se=W(ae,`${te}.md`);if(rq(se).kind===`symlink`){X(n,400,`urn:ok:error:symlink-refused`,`${ne.folderRel||`.`}/.ok/templates/${te}.md is a symlink — refusing to write through it. Replace the symlink with a real file or directory and retry.`,{handler:`template-import`,detail:ne.folderRel||`.`});return}if(oe(P(ne.folderRel,te),`template-import`,n))return;if(ie(ae,te)){X(n,409,`urn:ok:error:doc-already-exists`,`Template "${te}" already exists in "${ne.folderRel||`(root)`}". Choose another name, or edit the existing template instead.`,{handler:`template-import`,detail:`TEMPLATE_EXISTS`});return}re.add(se),_=se;let{frontmatter:ce,body:le}=wa(N),ue=fa(ce),de={};try{ue.trim()&&(de=(0,jc.parse)(ue))}catch{}let fe=i.title||de?.title||pY(N,te),pe=de?.description||``,me=Array.isArray(de?.tags)?de.tags:[],he={...de};delete he.template,delete he.title;let ge=``;Object.keys(he).length>0&&(ge=`${(0,jc.stringify)(he).trim()}\n`),ge=ge?`---\n${ge}---\n${le}`:le;let _e=v6({name:te,body:ge,frontmatter:{title:fe,description:pe,tags:me}});if(!_e.ok){X(n,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:_e.error.code,cause:Error(_e.error.message)});return}let ve=!G(se),ye=U(ne.resolvedContentDir,se).split(/[\\/]/).filter(Boolean).join(`/`),be=P(ne.folderRel,te),{agentId:xe,agentName:Se,colorSeed:Ce,clientName:we}=g(i),Te=await o.getSession(be,xe,{displayName:Se,colorSeed:Ce,clientName:we});Te.dc.document.transact(()=>{rH(Te.dc.document,_e.content,`agent`)},Te.origin);let Ee=await S(be);if(Ee?.kind===`failure`){C(n,Ee.failure,`template-import`);return}if(Ee?.kind===`divergence`){w(n,`template-import`);return}if(Ee?.kind===`stale-external-write`){T(n,`template-import`,be);return}E(be,_e.content),y(e,v(`template`,ne.folderRel,te),`template-import: ${ye}`),i.deleteSource&&(await D([O],`deleted-upstream`),d&&d.setDeleted(O),DH(k),j?.({kind:`delete`,path:k,docName:O})),b(`template-import`),c?.(`files`),Q(n,200,on,{path:ye,created:ve,warnings:_e.warnings},{handler:`template-import`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}finally{_!==void 0&&re.delete(_)}},{handler:`template-import`,method:`POST`})},{mutating:[`/api/folder-config`,`/api/template`,`/api/template/import`]})}function S6(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}async function Edt(e,t){let{git:n}=dK(e,{credentialConfig:[]}),[r,i]=await Promise.allSettled([JXe(n,IH),zH(n,[`diff`,`--name-only`,`HEAD..${t}`])]);if(i.status===`rejected`)throw i.reason;if(r.status===`rejected`)throw r.reason;let a=r.value,o=i.value,s=new Set(a);if(s.size===0||o.length===0)return{conflicts:!1,files:[]};let c=new Set;for(let e of o)s.has(e)&&c.add(e);return c.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(c).sort()}}function Ddt(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function Odt(e,t,n,r){let{git:i}=dK(e,{credentialConfig:[]});await i.raw([`rev-parse`,`--git-dir`]);let a=(async()=>{try{let e=(await i.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await i.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),o=a.then(async e=>{if(r===`folder`&&n===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await i.raw([`cat-file`,`-e`,`${t}:${n}`]),!0}catch{return!1}}),s=i.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),c=(async()=>{let e=`origin/${t}`;if(await i.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return r===`folder`&&n===``||i.raw([`cat-file`,`-e`,`${e}:${n}`]).then(()=>!0).catch(()=>!1)})(),l=Edt(e,t).catch(e=>(kdt(e)||q(`git-branch-info`).warn({branch:t,err:e},`action=dirty-overlap-failed branch=${t} error=${S6(e)}`),{conflicts:!1,files:[]})),[u,d,f,p,m]=await Promise.all([a,o,s,l,c]);return u.detached?{detached:!0,currentBranch:null,currentHeadSha:u.currentHeadSha,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}:{detached:!1,currentBranch:u.currentBranch,currentHeadSha:null,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}}const C6=`git-branch-info`;function kdt(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const w6=q(`git-checkout`),Adt=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function jdt(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(Adt);if(t===null)return{held:!1};let n=t[1];if(n===void 0||n.length===0)return{held:!1};let r;try{r=As(n)}catch{r=n}return{held:!0,path:r}}const T6=`git-checkout`,Mdt=m;async function Ndt(e,t,n){if(n.fastForward&&await Pdt(e,t,n.credentialConfig)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:r,env:i}=dK(e,{credentialConfig:n.credentialConfig}),a=await r.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!a)try{await r.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:Mdt(e)?`branch-not-found`:`fetch-failed`}}let o;try{o=await HK(r,a?`refs/heads/${t}`:`refs/remotes/origin/${t}`)}catch(e){return w6.warn({branch:t,err:e},`action=checkout-failed branch=${t}`),{ok:!1,reason:`checkout-failed`}}let s=await Edt(e,o);if(s.conflicts)return{ok:!1,reason:`dirty-conflict`,files:s.files};try{await GK(r,o,`checkout`,i)}catch(e){return e instanceof WK?(w6.warn({event:`unsafe-incoming-symlinks`,branch:t,target:o,links:e.unsafe.slice(0,50),refusedCount:e.unsafe.length},`action=checkout-refused branch=${t}`),{ok:!1,reason:`unsafe-symlinks`,refusedSymlinkPaths:e.displayPaths()}):(w6.warn({branch:t,target:o,err:e},`action=symlink-check-failed branch=${t}`),{ok:!1,reason:`symlink-check-failed`})}let c=()=>r.raw([`symbolic-ref`,`--quiet`,`HEAD`]).then(e=>e.trim()).catch(()=>``),l=`refs/heads/${t}`,u=await c(),d=!1;try{return a||(await r.raw([`branch`,`--no-track`,t,o]),d=!0,await r.raw([`branch`,`--set-upstream-to=refs/remotes/origin/${t}`,t])),await r.raw([`checkout`,t]),{ok:!0}}catch(e){if(u!==l&&await c()===l)return w6.warn({branch:t,target:o,err:e},`action=checkout-hook-failed branch=${t} error=${S6(e)}`),{ok:!0};d&&await r.raw([`branch`,`-D`,t]).catch(e=>{w6.warn({branch:t,target:o,err:e},`action=checkout-cleanup-failed branch=${t}`)});let n=jdt(e);return n.held?(w6.warn({branch:t,heldAt:n.path},`reason=branch-in-other-worktree branch=${t} held_at=${n.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:n.path}):(w6.warn({branch:t,err:e},`action=checkout-failed branch=${t} error=${S6(e)}`),{ok:!1,reason:`checkout-failed`})}}async function Pdt(e,t,n){let{git:r}=dK(e,{timeoutMs:15e3,credentialConfig:n}),i=e=>r.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await r.raw([`fetch`,`origin`,t])}catch(e){return w6.warn({branch:t,err:e},`action=ff-fetch-failed branch=${t} error=${S6(e)}`),`unavailable`}let a=await i(`refs/remotes/origin/${t}`);if(!a)return`unavailable`;let o=await i(`refs/heads/${t}`);if(!o||o===a)return`up-to-date`;let s=await r.raw([`merge-base`,o,a]).then(e=>e.trim()).catch(()=>``);if(s===o){try{await r.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){return w6.warn({branch:t,err:e},`action=ff-advance-failed branch=${t} error=${S6(e)}`),`unavailable`}return await i(`refs/heads/${t}`)===a?`advanced`:`unavailable`}return s===a?`up-to-date`:`diverged`}const E6=q(`git-worktree-status`);function D6(e){return jne.includes(e)?e:`M`}function Fdt(e,t){let n=[],r=[],i=[];for(let a of e){let e=t(a.path);if(a.x===`?`||a.y===`?`){i.push({path:a.path,code:`?`,syncScoped:e});continue}a.x!==`!`&&a.y!==`!`&&(a.x!==` `&&a.x!==``&&n.push({path:a.path,code:D6(a.x),syncScoped:e,...a.origPath===void 0?{}:{origPath:a.origPath}}),a.y!==` `&&a.y!==``&&r.push({path:a.path,code:D6(a.y),syncScoped:e,...a.origPath===void 0?{}:{origPath:a.origPath}}))}let a=n.length>100||r.length>100||i.length>100,o=e=>[...e.filter(e=>e.syncScoped),...e.filter(e=>!e.syncScoped)].slice(0,100);return{staged:o(n),notStaged:o(r),untracked:o(i),truncated:a}}const Idt=[`unknown revision or path not in the working tree`,`no upstream configured for branch`,`does not point to a branch`,`no such branch`];function Ldt(e){let t=e instanceof Error?e.message:String(e??``);return Idt.some(e=>t.includes(e))}async function Rdt(e,t){let n;try{n=await VH(e,[`diff`,`--name-status`,`HEAD...@{upstream}`])}catch(e){return!t?.aborted&&!Ldt(e)&&E6.warn({event:`worktree-incoming-read-failed`,err:e},`[sync] incoming-change read failed — panel shows nothing incoming`),[]}return n.map(e=>({path:e.to,code:D6(e.status.charAt(0)),syncScoped:!0,...e.status.charAt(0)===`R`||e.status.charAt(0)===`C`?{origPath:e.from}:{}}))}async function zdt(e,t,n,r={}){let i={readable:!0,branch:null,detached:!1,upstream:null,staged:[],notStaged:[],untracked:[],incoming:[],truncated:!1},{git:a}=dK(e,{credentialConfig:[],timeoutMs:r.timeoutMs??1e4,...r.abortSignal===void 0?{}:{abortSignal:r.abortSignal}}),o=Date.now(),[s,c,l,u]=await Promise.allSettled([BH(a,IH),a.raw([`rev-parse`,`--symbolic-full-name`,`--abbrev-ref`,`HEAD`]),a.raw([`rev-parse`,`--symbolic-full-name`,`--abbrev-ref`,`@{upstream}`]),Rdt(a,r.abortSignal)]),d=c.status===`fulfilled`?c.value.trim():``,f=d===`HEAD`,p=f||d===``?null:d,m=r.abortSignal?.aborted===!0,h=s.status===`rejected`,g=(e,t,n)=>{e.status===`rejected`&&(m||h||Ldt(e.reason)||E6.warn({event:t,err:e.reason,elapsedMs:Date.now()-o,branch:p},`[sync] ${n}`))};if(g(c,`worktree-branch-read-failed`,`branch read failed — panel shows no branch`),g(l,`worktree-upstream-read-failed`,`upstream read failed — panel shows no upstream`),s.status===`rejected`)return m||E6.error({event:`worktree-read-failed`,err:s.reason,elapsedMs:Date.now()-o,branch:p},`[sync] worktree status read failed — panel listing marked unreadable`),{...i,readable:!1};let _=l.status===`fulfilled`&&l.value.trim()||null,v=u.status===`fulfilled`?u.value:[],y=Fdt(s.value,t),b=e=>n?e.map(e=>{let t=n(e.path);return t===void 0?e:{...e,open:t}}):e;return{readable:!0,branch:p,detached:f,upstream:_,staged:b(y.staged),notStaged:b(y.notStaged),untracked:b(y.untracked),truncated:y.truncated||v.length>100,incoming:b(v.slice(0,100))}}function Bdt(e){let{projectDir:t,contentDir:n,contentFilter:r,getFileIndex:i,checkLocalOpSecurity:a,getSyncEngine:o,getPrincipal:s,resolveCredentialConfig:c}=e;function l(e){let a=H(t??n,e),o=oG(U(n,a));if(!o||o.startsWith(`..`))return;let s=LW(o);if(i().has(s))return{kind:`doc`,docName:s};if(r&&!r.isExcluded(o,{bypassFilters:!0,showOk:!0})&&G(a))return{kind:`asset`,path:o}}async function u(e,r){if(!a(e,r,{handler:`git-worktree-status`}))return;if(e.method!==`GET`){X(r,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`git-worktree-status`,extraHeaders:{Allow:`GET`}});return}let i=new AbortController;r.on(`close`,()=>{r.writableEnded||i.abort()});try{let e=o?.(),a=await zdt(t??n,e?t=>e.isSyncScopedPath(t):()=>!1,l,{abortSignal:i.signal});if(r.writableEnded||r.destroyed)return;Q(r,200,Mn,a,{handler:`git-worktree-status`})}catch(e){if(r.writableEnded||r.destroyed)return;X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`git-worktree-status`,cause:e})}}return P$({"/api/git/branch-info":Z(La,async(e,n)=>{try{if(!t){X(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:C6});return}let r=cG(e),i=r.get(`branch`),a=r.get(`path`),o=r.get(`kind`)===`folder`?`folder`:`doc`;if(!Ca(i)){X(n,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:C6});return}if(!Ddt(a,o)){X(n,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:C6});return}let s=await Odt(t,i,a,o);Q(n,200,vte,s,{handler:C6})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:C6,cause:e})}},{handler:C6,method:`GET`,skipBodyParse:!0}),"/api/git/worktree-status":u,"/api/git/checkout":Z(oee,async(e,n,r)=>{if(y$(r,s).kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:T6});return}if(!t){X(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:T6});return}try{let e=await c(),i=await uK(()=>Ndt(t,r.branch,{fastForward:r.fastForward===!0,credentialConfig:e}));Q(n,200,pe,i,{handler:T6})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:T6,cause:e})}},{handler:T6,method:`POST`})},{mutating:[`/api/git/checkout`]})}function Vdt(){let e=new Map;return{run(t,n){let r=e.get(t);if(r)return{promise:r,coalesced:!0};let i=n();e.set(t,i);let a=()=>{e.get(t)===i&&e.delete(t)};return i.then(a,a),{promise:i,coalesced:!1}},get size(){return e.size}}}const O6=q(`managed-artifact-persistence`);function k6(e){return e.homedirOverride??zs()}function Hdt(e){let t=Bn(e);return t===null||t.kind!==`skill`||t.scope!==`project`?null:{docKey:`${ja}/${t.name}`,subject:`skill-edit: ${t.name}/SKILL.md`}}function A6(e){if(!Bn(e))return{managed:!1};let t=Hdt(e);return t?{managed:!0,versioned:!0,docKey:t.docKey,filePath:`${t.docKey}/SKILL.md`}:{managed:!0,versioned:!1}}function Udt(e){let t=k6(e);return crt(t).filter(e=>G(W(t,Ia(U(t,e).split(ms).join(`/`)))))}function Wdt(e){return G(`${e}.md`)?`${e}.md`:G(`${e}.mdx`)?`${e}.mdx`:`${e}.md`}function Gdt(e,t,n,r=null){if(!Ba.test(t)||t.length>64)throw Error(`managedSkillBundleDir: invalid skill name: ${JSON.stringify(t)}`);if(r!==null&&(!Ba.test(r)||r.length>64))throw Error(`managedSkillBundleDir: invalid host qualifier: ${JSON.stringify(r)}`);let i=e===`global`?k6(n):n.projectDir;if(e!==`global`)return W(i,`.ok`,`skills`,t);if(r!==null){let e=f0(i,`global`).find(e=>e.editor===r);return e===void 0?null:W(i,e.root,t)}let a=C0(i,t),o=W(i,`.ok`,`skills`,t);if(a!==null)return a;if(G(W(o,`SKILL.md`)))return o;let s=h0(i,`global`);return s===null?null:W(i,s,t)}function Kdt(e,t){let n=Ae(e);if(n!==null){let e=s0(n.name,null);return e===null?null:V(e)}let r=Bn(e);return r===null||r.kind!==`skill`?null:Gdt(r.scope,r.name,t,r.host)}function j6(e,t){let n=Ae(e);if(n!==null){let t=s0(n.name,n.rel);if(t===null)throw Error(`managedArtifactAbsPath: external skill not registered: ${e}`);return n.rel===null?t:Wdt(t)}let r=Bn(e);if(r===null||r.kind!==`skill`)throw Error(`managedArtifactAbsPath: not a managed skill doc name: ${e}`);let i=Gdt(r.scope,r.name,t,r.host);if(i===null)throw Error(`managedArtifactAbsPath: no usable skill home for ${e}`);let a;if(r.rel===null)a=W(i,`SKILL.md`);else{let t=r.rel.split(`/`).filter(e=>e!==``&&e!==`.`);if(t.length===0||t.some(e=>e===`..`))throw Error(`managedArtifactAbsPath: invalid skill file path for ${e}`);a=Wdt(W(i,...t))}if(!a.startsWith(i+ms))throw Error(`managedArtifactAbsPath: path escape for ${e}`);return a}function qdt(e,t){let n=W(e),r=k6(t),i=f0(r,`global`);for(let e of crt(r)){let t=W(e);if(!n.startsWith(t+ms))continue;let a=n.slice(t.length+1).split(ms),o=a[0];if(o&&Ba.test(o)&&o.length<=64&&a.length>=2){let e=W(t,o),n=C0(r,o),s=``;if(n!==null&&W(n)!==e){let e=i.find(e=>W(r,e.root)===t)?.editor;e!==void 0&&(s=`@${e}`)}let c=a.slice(1);if(c.length===1&&c[0]===`SKILL.md`)return`${yi}global/${o}${s}`;let l=c[c.length-1]??``;if(/\.mdx?$/i.test(l)&&!c.includes(`..`)){let e=c.join(`/`).replace(/\.mdx?$/i,``);return`${yi}global/${o}${s}/${e}`}}return null}return null}function Jdt(e,t,n){let r=Bn(t);if(r?.kind===`skill`&&r.scope===`project`||t.startsWith(`__template__/`))return;let i=Ae(t);if(i&&s0(i.name,i.rel)===null||e.getXmlFragment(`default`).length>0)return;let a=j6(t,n);if(!G(a))return;let o;try{o=K(a,`utf-8`)}catch(e){O6.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}e.transact(()=>{Y$(e,o,void 0,t),e.getMap(`lifecycle`).set(Tc,crypto.randomUUID())},J$),n.setReconciledBase(t,o),n.lkgCache.set(t,o)}const Ydt=/^(?!.*__)[A-Za-z0-9.-](?:[A-Za-z0-9._-]*[A-Za-z0-9.-])?$/;function Xdt(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`__`),n=[yi,Mie,Vie].find(t=>e.startsWith(t));if((n===void 0?e:e.slice(n.length)).split(`/`).every(e=>Ydt.test(e)))return t;let r=e.normalize(`NFC`),i=tc(`sha256`).update(r).digest(`hex`).slice(0,12);return`${r.replace(/[^A-Za-z0-9._-]+/g,`__`).replace(/^\.+/,`_`).slice(0,100)}-${i}`}async function Zdt(e,t,n){try{let r=W(dx(k6(n)),`edit-backups`,`discarded`,Xdt(e));await xH(r,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,`-`);await gx(W(r,`${i}.md`),t,{fs:NH});let a=ks(r).sort();for(let e of a.slice(0,Math.max(0,a.length-5)))try{DH(W(r,e))}catch{}}catch(t){O6.warn({documentName:e,err:t},`discarded-edit stash failed`)}}async function Qdt(e,t,n){if(t.rel===null)try{if(!G(e))return;let r=W(dx(k6(n)),`edit-backups`,t.name),i=W(r,`SKILL.md.bak`);if(G(i))return;await xH(r,{recursive:!0}),await gx(i,K(e,`utf-8`),{fs:NH})}catch(e){O6.warn({name:t.name,err:e},`external-skill backup failed`)}}async function $dt(e,t,n,r){let i=Bn(t);if(i?.kind===`skill`&&i.scope===`project`||t.startsWith(`__template__/`))return`no-op`;let a=Ae(t);if(a&&s0(a.name,a.rel)===null||n===J$)return`no-op`;let o=e.getText(`source`).toString(),s=r.lkgCache.get(t);if(o===s)return`no-op`;let c=Kdt(t,r);if(c===null)return`no-op`;if(!G(c))return O6.warn({documentName:t,containerDir:c},`store: artifact container is gone (deleted or moved); dropping the write rather than resurrecting it`),`no-op`;let l=j6(t,r);try{return await xH(W(l,`..`),{recursive:!0}),a&&await Qdt(l,a,r),await vx(`${l}.lock`,async()=>{if(G(l)){let n=null;try{n=K(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&O6.warn({documentName:t,err:e},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),n=null}if(n!==null&&n!==s&&n!==o){oQe();let i=r.beforeReconcileDivergence?.(e,t,o,n);return await Zdt(t,o,r),e.transact(()=>{Y$(e,n,void 0,t,void 0,i)},J$),r.setReconciledBase(t,n),r.lkgCache.set(t,n),`reconciled`}}return await gx(l,o,{fs:NH}),r.lkgCache.set(t,o),r.setReconciledBase(t,o),`persisted`})}catch(e){return e instanceof _x?(O6.warn({documentName:t},`store: file lock timeout; skipping write`),`write-failed`):(O6.warn({documentName:t,err:e},`store: write failed`),`write-failed`)}}function eft(e,t,n,r){if(!e)return`no-op`;let i=r.lkgCache.get(t);return i!==void 0&&i===n?`no-op`:(e.transact(()=>{Y$(e,n,void 0,t)},J$),r.setReconciledBase(t,n),r.lkgCache.set(t,n),`applied`)}function tft(e){return e<=0?`0`:e===1?`1`:e<=5?`2-5`:e<=20?`6-20`:e<=50?`21-50`:`50+`}function nft(e){return e<=0?`0`:e<=50?`1-50`:e<=200?`51-200`:e<=500?`201-500`:`500+`}let rft=null,ift=null;function aft(){return rft||=YV().createHistogram(`ok.timeline.query_duration_ms`,{description:`Wall-clock duration of one history query. Bounded labels: width_bucket (ref fan-out), commits_bucket (commits gathered), capped (depth bound hit), error (the walk threw — e.g. the PRD-6972 git timeout). The error label is what separates a timeout storm from a burst of legitimately-empty docs, both of which otherwise record width/commits 0.`,unit:`ms`}),rft}function oft(){return ift||=YV().createCounter(`ok.timeline.coalesced_total`,{description:`History requests served by an in-flight single-flight walk instead of a fresh git walk. Bounded label: mode ∈ {doc, folder}. A high value is the poll-storm / fan-out signal.`}),ift}function sft(e){aft().record(Math.max(0,e.durationMs),{width_bucket:tft(e.width),commits_bucket:nft(e.commits),capped:e.capped,error:e.error??!1})}function cft(e){oft().add(1,{mode:e})}const M6=q(`timeline`);function lft(e,t){return Math.min(500,3*(Math.max(0,e)+Math.max(1,t)))}const N6=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,P6={entries:[],total:0,hasMore:!1},uft=/^(template-(create|edit|rename|move|delete)|folder-frontmatter-(edit|delete)|folder-create): /;function dft(e){return uft.test(e)}function fft(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`import:`)||e.startsWith(`upstream:`)?`upstream`:e.startsWith(`park:`)?`park`:`wip`}function F6(e){return e.trim()?e.split(``).map(e=>{let t=e.trimStart();if(!t)return null;let[n=``,r=``,i=``,a=``,o=``,s=``]=t.split(`\0`),c=fft(o);return{sha:n.trim(),timestamp:r,author:i,authorEmail:a,type:c,message:o,contributors:Gb(s),checkpoint:c===`checkpoint`?Wi(s):null,rawBody:s}}).filter(e=>e!==null&&e.sha.length===40):[]}function I6(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}let pft=null;function mft(){return pft||=YV().createHistogram(`rename.predecessor_chain_depth_histogram`,{description:`Predecessor chain depth observed per timeline query`}),pft}let hft=null;function gft(){return hft||=YV().createCounter(`rename.transient_skip_total`,{description:`Count of empty-commitSha entries encountered (lazy-population transient skip)`}),hft}function L6(e,t){return t.length===0||t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}function _ft(e,t,n){return e.length===0||t.length===0?e:e.filter(e=>{let r=Wb(e.rawBody);if(r.length===0)return!0;let i=new Set;for(let e of r){for(let t of e.docs)i.add(t);if(e.previous_paths)for(let t of e.previous_paths)i.add(t.from),i.add(t.to)}if(i.size===0)return!0;for(let r=0;r<t.length;r++){let a=t[r],o=n[r];if(!(o!==null&&!o.has(e.sha))&&i.has(a.path))return!0}return!1})}async function vft(e,t,n,r,i,a,o){if(t.length===0||n.length===0)return t;let s=await Promise.all(n.map(async t=>{if(t.renameCommit===null)return null;let n=await h1(e,t.renameCommit,r,o);return n.length===0?new Set:_1(e,n,r,a)})),c=[];for(let e=0;e<t.length;e++){let r=t[e];for(let t=0;t<n.length;t++){let a=n[t],o=s[t];if(!(o!==null&&!o.has(r.sha)))for(let t of i(a.path))c.push({entryIdx:e,sha:r.sha,path:t})}}if(c.length===0)return[];let l=await gtt(e,c.map(e=>({sha:e.sha,path:e.path}))),u=new Set;for(let e=0;e<c.length;e++)l[e]&&u.add(c[e].entryIdx);return t.filter((e,t)=>u.has(t))}async function yft(e,t,n,r,i){if(t.length<2||n.length===0)return t;let a=new Set(n.map(e=>e.renameCommit).filter(e=>e!==null)),o=e=>e.type===`checkpoint`||a.has(e.sha),s=[];for(let e=0;e<t.length;e++)if(!o(t[e]))for(let a=0;a<n.length;a++){let o=r[a];o!==null&&!o.has(t[e].sha)||s.push({entryIdx:e,sha:t[e].sha,path:i(n[a].path)})}if(s.length===0)return t;let c=await _tt(e,s.map(e=>({sha:e.sha,path:e.path}))),l=t.map(()=>null);for(let e=0;e<s.length;e++){let t=s[e].entryIdx;l[t]===null&&c[e]!==null&&(l[t]=c[e])}let u=new Set,d=null,f=-1;for(let e=t.length-1;e>=0;e--){if(o(t[e]))continue;let n=l[e];if(n!==null){if(d!==null&&n===d){t[e].type!==`upstream`&&t[f].type===`upstream`?(u.add(f),f=e):u.add(e);continue}d=n,f=e}}return u.size===0?t:t.filter((e,t)=>!u.has(t))}async function bft(e,t,n=`.`,r){if(!G(e.workTree)||!G(e.gitDir)||t.docName&&(t.docName.includes(`..`)||t.docName.includes(`\0`)))return P6;let i=t.branch??`main`,a=Math.max(1,t.limit??50),o=Math.max(0,t.offset??0),s=lft(o,a),c=performance.now(),l=!1,u=(e,t,n=!1)=>sft({durationMs:performance.now()-c,width:e,commits:t,capped:l,error:n}),d=I6(t.type),f=I6(t.author),p=I6(t.excludeAuthor),m=t.includeAutoCheckpoints??!1,h=n===`.`?``:n.replace(/^\.\//,``),g=e=>h?`${h}/${e}${UW(e)}`:`${e}${UW(e)}`,_=e=>{let t=g(e),n=qW(t,e);return n?[t,n]:[t]},v=t.docName?A6(t.docName):{managed:!1};if(v.managed&&!v.versioned)return P6;let y=v.managed&&v.versioned?v.filePath:void 0,b=v.managed&&v.versioned?v.docKey:t.docName,x=t.docName?y?h?`${h}/${y}`:y:g(t.docName):void 0;try{let n=r?.renameLogIndex??f1(e.gitDir),{chain:c,skipped:h}=await XV(`rename.expandPredecessors`,void 0,async()=>t.docName?utt(b,i,n):{chain:[],skipped:0}),v=c.length>1;t.docName&&mft().record(c.length),h>0&&gft().add(h);let y=dtt(),S=m1(),C=uW(e);if(d.length===1&&d[0]===`checkpoint`){let t=(await C.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${i}/`)).trim().split(`
|
|
1121
1121
|
`).filter(e=>e.length===40),n=[];if(i!==`main`)try{n=(await C.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Cc as e,Et as t,Ot as n,S as r,X as i,Za as a,ac as o,fc as s,v as c}from"./md-manager-BGnqyqi1-I7NmBKjQ.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,As as x,At as S,B as C,Ba as w,Bi as T,Bn as E,Bo as D,Br as O,Bs as k,Bt as A,C as j,Ca as M,Ci as N,Cn as P,Co as F,Cr as I,Cs as L,Ct as R,D as z,Da as B,Di as V,Dn as H,Do as U,Dr as W,Dt as G,E as K,Ea as q,Ei as J,En as Y,Eo as X,Er as Z,Et as Q,F as $,Fa as ee,Fi as te,Fn as ne,Fo as re,Fr as ie,Fs as ae,Ft as oe,G as se,Ga as ce,Gi as le,Gn as ue,Go as de,Gr as fe,Gt as pe,H as me,Ha as he,Hi as ge,Hn as _e,Ho as ve,Hr as ye,Hs as be,Ht as xe,I as Se,Ia as Ce,Ii as we,In as Te,Io as Ee,Ir as De,Is as Oe,It as ke,J as Ae,Ja as je,Ji as Me,Jn as Ne,Jo as Pe,Jr as Fe,Jt as Ie,K as Le,Ka as Re,Ki as ze,Kn as Be,Ko as Ve,Kr as He,Kt as Ue,L as We,La as Ge,Li as Ke,Ln as qe,Lo as Je,Lr as Ye,Lt as Xe,M as Ze,Ma as Qe,Mi as $e,Mn as et,Mo as tt,Mr as nt,Ms as rt,Mt as it,N as at,Na as ot,Ni as st,Nn as ct,No as lt,Nr as ut,Ns as dt,Nt as ft,O as pt,Oa as mt,Oi as ht,On as gt,Oo as _t,Or as vt,Os as yt,Ot as bt,P as xt,Pa as St,Pi as Ct,Pn as wt,Po as Tt,Pr as Et,Ps as Dt,Pt as Ot,Q as kt,Qa as At,Qi as jt,Qn as Mt,Qr as Nt,Qt as Pt,R as Ft,Ra as It,Ri as Lt,Rn as Rt,Ro as zt,Rr as Bt,Rt as Vt,S as Ht,Sa as Ut,Si as Wt,Sn as Gt,So as Kt,Sr as qt,St as Jt,T as Yt,Ta as Xt,Ti as Zt,Tn as Qt,To as $t,Tr as en,Tt as tn,U as nn,Ua as rn,Ui as an,Un as on,Uo as sn,Ur as cn,Ut as ln,V as un,Va as dn,Vi as fn,Vn as pn,Vo as mn,Vr as hn,Vs as gn,Vt as _n,W as vn,Wa as yn,Wi as bn,Wn as xn,Wo as Sn,Wr as Cn,Wt as wn,X as Tn,Xa as En,Xi as Dn,Xn as On,Xo as kn,Xr as An,Xt as jn,Y as Mn,Ya as Nn,Yi as Pn,Yn as Fn,Yo as In,Yr as Ln,Yt as Rn,Z as zn,Za as Bn,Zi as Vn,Zn as Hn,Zo as Un,Zr as Wn,Zt as Gn,_ as Kn,_a as qn,_i as Jn,_n as Yn,_o as Xn,_r as Zn,_t as Qn,a as $n,aa as er,ai as tr,an as nr,ao as rr,ar as ir,at as ar,b as or,ba as sr,bi as cr,bn as lr,bo as ur,br as dr,bt as fr,c as pr,ca as mr,ci as hr,cn as gr,co as _r,cr as vr,ct as yr,d as br,da as xr,di as Sr,dn as Cr,do as wr,dr as Tr,dt as Er,ea as Dr,ei as Or,en as kr,eo as Ar,er as jr,et as Mr,f as Nr,fa as Pr,fi as Fr,fn as Ir,fo as Lr,fr as Rr,ft as zr,g as Br,ga as Vr,gi as Hr,gn as Ur,go as Wr,gr as Gr,gt as Kr,h as qr,ha as Jr,hi as Yr,hn as Xr,ho as Zr,hr as Qr,ht as $r,i as ei,ia as ti,ii as ni,in as ri,io as ii,ir as ai,it as oi,j as si,ja as ci,ji as li,jn as ui,jo as di,jr as fi,js as pi,jt as mi,k as hi,ka as gi,ki as _i,kn as vi,ko as yi,kr as bi,ks as xi,kt as Si,l as Ci,la as wi,li as Ti,ln as Ei,lo as Di,lr as Oi,lt as ki,m as Ai,ma as ji,mi as Mi,mn as Ni,mo as Pi,mr as Fi,mt as Ii,n as Li,na as Ri,ni as zi,nn as Bi,no as Vi,nr as Hi,nt as Ui,o as Wi,oa as Gi,oi as Ki,on as qi,oo as Ji,or as Yi,ot as Xi,p as Zi,pa as Qi,pi as $i,pn as ea,po as ta,pr as na,pt as ra,q as ia,qa as aa,qi as oa,qn as sa,qo as ca,qr as la,qt as ua,r as da,ra as fa,ri as pa,rn as ma,ro as ha,rr as ga,rt as _a,s as va,sa as ya,si as ba,sn as xa,so as Sa,sr as Ca,st as wa,t as Ta,ta as Ea,ti as Da,tn as Oa,to as ka,tr as Aa,tt as ja,u as Ma,ua as Na,ui as Pa,un as Fa,uo as Ia,ur as La,ut as Ra,v as za,va as Ba,vi as Va,vn as Ha,vo as Ua,vr as Wa,vt as Ga,w as Ka,wa as qa,wi as Ja,wn as Ya,wo as Xa,wr as Za,ws as Qa,wt as $a,x as eo,xa as to,xi as no,xn as ro,xo as io,xr as ao,xt as oo,y as so,ya as co,yi as lo,yn as uo,yo as fo,yr as po,yt as mo,z as ho,za as go,zi as _o,zn as vo,zo as yo,zr as bo,zs as xo,zt as So}from"./dist-0gI1oLbO.mjs";export{Ta as AGENT_ID_MAX_LEN,Li as AGENT_ID_RE,da as AGENT_WRITE_ORIGIN,a as AUDIT_EMPTY_SCOPE_WARNING,ei as AcpPermissionStore,$n as AcpRegistry,Wi as AcpThreadManager,va as AgentFocusBroadcaster,pr as AgentPresenceBroadcaster,Ci as AgentSessionCapacityError,Ma as AgentSessionManager,br as AutoStartDisabledError,Nr as BUNDLE_IDS,Zi as BUNDLE_SCOPE,Ai as BUNDLE_SKILL_NAME,qr as BacklinkIndex,Br as CC1Broadcaster,s as CC1_CONTRACT_VERSION,Kn as CONCURRENT_REPLACE_WINDOW_MS,za as CONFIG_FILENAME,so as CONFLICT_MARKER_RE,or as CURSOR_BUNDLE_PATHS_BY_PLATFORM,eo as ConfigSchema,Ht as ConflictAuthority,j as DEFAULT_CHECKPOINT_RETENTION,Ka as DEFAULT_EMBEDDINGS_DIMENSIONS,Yt as DEFAULT_PACK_ID,K as DocumentDurabilityState,z as DocumentDurabilityStateError,pt as EMBEDDINGS_API_KEY_ENV,hi as EPHEMERAL_PROJECT_DIR_PREFIX,h as ExposureConsentError,si as FEATURED_AGENT_IDS,Ze as FILE_SYSTEM_WRITER,at as FILE_WATCHER_ORIGIN,xt as FileEmbeddingsBackend,$ as FilesystemRootProjectError,Se as GIT_PREFLIGHT_FAIL_SPAN_NAME,We as GIT_UPSTREAM_WRITER,L as GitDirAccessError,Ft as GitNotAvailableError,ho as GitTooOldError,C as HOCUSPOCUS_AUTH_REJECTION_REASONS,un as HocuspocusAuthRejection,me as HocuspocusAuthTokenSchema,nn as HomeProjectRootError,vn as INSTALLED_AGENTS_SCHEMES,se as JSON_SCHEMA_DIALECT_2020_12,gn as LINEAGE_EPOCH_KEY,Le as LIVE_DERIVED_INDEX_DEBOUNCE_MS,ia as LOCK_FILE_ACCESS_REMEDY,Ae as MANAGED_RENAME_ORIGIN,Mn as MAX_ACP_THREADS,Tn as MAX_AGENT_SESSIONS,zn as MCP_CONNECTION_ID_HEADER,o as MCP_SERVER_NAME,kt as MIN_EVICTABLE_IDLE_MS,l as MIN_GIT_VERSION,Qa as MalformedGitPointerError,Mr as McpLogger,ja as MissingOkConfigError,Ui as OBSERVER_SYNC_ORIGIN,_a as OK_OKIGNORE_TEMPLATE,oi as ONBOARDING_BUNDLE_IDS,xo as ORPHAN_MODES,be as PROTOCOL_VERSION,yt as PinoLogger,ar as ProcessLockCollisionError,Xi as ProcessLockFileError,wa as ProjectGitInitError,yr as ROLLBACK_ORIGIN,ki as ROOT_GITIGNORE_TEMPLATE,Ra as RUNTIME_VERSION,Er as SERVICE_WRITER,zr as SKILL_INSTALL_EVENTS_FILENAME,c as SKILL_STATE_TARGETS,ra as STARTER_FOLDER_FRONTMATTER_FILENAME,Ii as STARTER_PACKS,$r as STARTER_PACK_IDS,Kr as STATE_MANIFEST_FILENAME,Qn as STATE_SCHEMA_VERSION,Ga as SYMLINK_MERGE_MIN_GIT_LABEL,mo as SYMLINK_MERGE_MIN_GIT_VERSION,e as SYSTEM_DOC_NAME,fr as SeedPrerequisiteError,oo as SeedRootDirError,Jt as ServerAuthorityCollisionError,R as ServerAuthorityRegistryError,$a as ServerLockCollisionError,tn as SingleFileNotAFileError,Q as SingleFileNotFoundError,G as SingleFileNotMarkdownError,bt as SingleFileProjectOverrideError,Si as StateManifestError,r as TEST_LOOP_CORE_MARKER,S as TEST_LOOP_SERVER_MARKER,mi as TagIndex,it as USER_GLOBAL_BUNDLE_IDS,ft as UnsafeIncomingSymlinkError,Ot as __getShowAllWalkStatsForTesting,oe as __resetShowAllWalkStatsForTesting,ke as acpThreadStoreRoots,Xe as acpThreadsDir,Vt as acquireProcessLock,So as acquireServerLock,A as applyAgentMarkdownWrite,_n as applyExternalChange,xe as applySeed,ln as assertCheckoutSymlinksSafe,wn as assertCompatibleStateManifest,pe as assertGitAvailable,Ue as assertIncomingSymlinksSafe,ua as assertMergeNameResolvesTo,Ie as assertNeverDiskEvent,Rn as assertRepoCheckoutSymlinksSafe,jn as assertSafeProjectRoot,Gn as assessLockHolder,Pt as attachAcpThreadSocket,m as attachCollabClientCounter,kr as attachIdleShutdown,Oa as auditScopeNotFoundTitle,Bi as bindConflictAuthority,ma as bootServer,ri as buildAndOpenSkill,nr as buildConfigYmlContent,qi as buildExecResult,xa as buildIngressPolicy,gr as buildOkMcpStdioCommand,Ei as buildSkillZip,Fa as buildStarterFolderFrontmatterYaml,Cr as buildWipTree,Ir as bundleSkillMdPath,ea as canonicalProjectKey,Ni as canonicalizeForCompare,Xr as classifyEvents,Ur as classifyFsPath,Yn as classifyLockHolder,Ha as clearAllEmbeddingsKeys,uo as coercePackId,lr as collectServerHostSnapshot,t as colorFromSeed,ro as commitUpstreamImport,Gt as commitWip,P as commitWipFromTree,Ya as compareSemver,Qt as composeEffectiveLinterConfig,Y as composeFrontmatterSchemasConfig,H as containsConflictMarkers,gt as contentHash,vi as contributorCount,v as countShadowObjects,ui as countStaleAgentWipRefs,et as countWipRefs,ct as createApiExtension,wt as createAssetServeMiddleware,ne as createCollaborationHost,Te as createContentFilter,qe as createContentFilterAsync,Rt as createEmbeddingsSecretStore,vo as createEphemeralProjectDir,E as createExternalChangeHandler,pn as createFileLogger,_e as createLiveDerivedIndexExtension,on as createMcpHttpHandler,xn as createOsProbe,ue as createPersistenceExtension,Be as createProbeFailureReporter,sa as createServer,Ne as createServerObserverExtension,Fn as createServerProbeResolver,On as createStreamingErrorWriter,xi as createTestLogger,Hn as describeStoredEmbeddingsKey,Mt as detectClaudeDesktopPresence,f as detectGit,jr as detectProjectShape,Aa as detectUserSkillHosts,Hi as discoverLockDirs,ga as discoverMarkdownlintConfig,ai as emitPreflightFailureSpan,ir as encodeDocName,Yi as encodeFolderRoute,Ca as encodeSkillRoute,vr as ensureProjectGit,Oi as errorResponse,La as evictStaleTrackerEntries,Tr as extractHeadings,Rr as extractOkBinaryPath,na as extractWikiLinksFromMarkdown,Fi as fallbackPaths,Qr as findEnclosingGitRoot,Gr as findEnclosingProjectRoot,Zn as findNativeMarkdownlintFile,Wa as flushFileLogger,po as formatAuditBrokenLinkSuppressionLine,dr as formatAuthRejectionWire,ao as formatContributorsFrom,qt as formatPackRationale,I as gcCheckpointRefs,Za as getCurrentMcpLogger,en as getIngressContext,Z as getLocalDir,W as getLogFilePath,x as getLogger,vt as getLogsDir,bi as getMachineId,b as getMeter,fi as getMetrics,nt as getTracer,ut as handleCollabSocketError,Et as handleSpawnCursor,ie as hasForwardingHeaders,De as hasGcLogLatch,n as iconFromClientName,Ye as incrementCollabSocketFilteredError,Bt as incrementServerObserverFire,bo as initContent,O as initShadowRepo,hn as initTelemetry,ye as initToleranceTelemetryWriter,cn as installJsonSchemaDialect,Cn as installPrettyZodErrors,pi as installTestLoggers,fe as installUserSkill,He as isAllowedApiOrigin,la as isAllowedWorkspaceHostHeader,Fe as isConfigDoc,Ln as isDefunctProcess,An as isDocInConflict,Wn as isFilesystemRoot,Nt as isHocuspocusAuthRejectionReason,p as isHomeDir,Or as isHostAdmitted,Da as isKnownPackId,zi as isLinkIndexExcludedDoc,pa as isLockFromThisMachine,ni as isLockProcessRunning,tr as isLoopbackAddress,Ki as isManagedArtifactDoc,ba as isMintedThreadId,hr as isOriginAdmitted,k as isOrphanMode,Ti as isPairedWriteOrigin,Pa as isPathWithinDir,Sr as isPeerAdmitted,Fr as isProcessAlive,$i as isProjectRoot,Mi as isReservedForUserTree,Yr as isSelfWrite,Hr as isSkillInstallReportEnvOptOut,Jn as isSystemDoc,Va as isToleranceTelemetryEnabled,lo as isValidLockPid,cr as lastKnownHash,no as listRescueCheckpoints,Wt as listStarterPacks,N as loadCustomAgents,Ja as loadPrincipal,Zt as lockAdvertisesUi,J as lockBaseUrl,V as lockFilePath,rt as loggerFactory,ht as loginShapedUserinfoUser,dt as logsCurrentPath,Dt as logsPreviousPath,_i as machineIdFilePath,_ as makeLazyEmbeddingsKeyStore,li as markServerLockDraining,$e as missingOkConfigMessage,st as mountMcpAndApi,Ct as normalizeFsPath,te as observeReadiness,we as packageVersionMajorMinor,Ke as parseAuthRejectionWire,Lt as parseGitVersion,_o as parseHocuspocusAuthToken,T as parseKeepaliveConnectionId,fn as parseProcessStartToken,ge as pathToDocName,an as planSeed,bn as prepareSingleFileOpen,le as processCommand,ze as processStartToken,oa as processUsage,Me as readAgentBrowserTools,Pn as readAllTargets,Dn as readBundleDecision,Vn as readDeclaredGitHubHosts,jt as readOriginCredentialHost,d as readOriginGitHubRepo,Dr as readOwnNativeRules,Ea as readProcessLock,Ri as readProcessLockDetailed,fa as readProcessStart,ti as readProcessState,er as readProjectHeadState,Gi as readProjectLocalSemanticConfig,ya as readServerLock,mr as readServerPackageVersion,wi as readSkillInstallStateSnapshot,Na as readStateManifest,xr as readTargetRecordedAt,Pr as readTargetVersion,Qi as reconcile,ji as recordContributor,Jr as recordSkillInstallEvent,Vr as recordsLockOwner,qn as redactShareSubprocessStderr,Ba as registerAllTools,co as registerNativeProcessStartReader,sr as registerWrite,to as releaseProcessLock,Ut as releaseServerLock,M as removeLastKnownHash,qa as removeLockIfUnchanged,Xt as removeProjectSkillGitignoreBlock,q as reportSkillInstall,B as resetMetrics,mt as resolveAuditScope,gi as resolveBuiltinSkillHosts,i as resolveBundleEnabled,g as resolveBundledSkillDir,ci as resolveContentDir,Qe as resolveCursorBinaryDefault,ot as resolveCursorSpawnInvocation,St as resolveEffectiveLinterConfig,ee as resolveEmbeddingsCredential,Ce as resolveGitHubAccountFromUrl,Ge as resolveGitHubAuthHost,It as resolveLockDir,go as resolveNativeConfigForDoc,w as resolveNativeMarkdownlintConfig,dn as resolvePack,he as resolvePackageVersion,rn as resolveSkillInstallReportSettings,yn as resolveUiInfo,ce as restoreContributors,Re as rewriteMarkdownLinksForDocumentRename,aa as rewriteWikiLinksForDocumentRename,je as runAuthReposSubprocess,Nn as runAuthStatusSubprocess,En as runCloneSubprocess,Bn as runDeviceFlowSubprocess,At as runWithMcpLogger,u as safeContentPath,Ar as safeSubdir,ka as safetyCheckpoint,Vi as sameGitHubLogin,ha as sanitizeClientName,ii as saveInMemoryCheckpoint,rr as saveVersion,Ji as scanLockProcesses,Sa as seedBasenameIndex,_r as seedEphemeralProjectDir,Di as serializeError,Ia as setActiveSpanAttributes,wr as setupServerObservers,Lr as shadowGit,ta as shutdownTelemetry,ae as spansCurrentPath,Oe as spansPreviousPath,Pi as spawnDetached,Zr as splitMarkdownBlocks,Wr as startWatcher,Xn as strategiesFor,Ua as streamedChunkOf,fo as streamingProblemEvent,ur as swapContributors,io as teardownToleranceTelemetryWriter,Kt as toBroadcasterKey,F as toProcessLockMetadata,Xa as tracedAppendFileSync,$t as tracedLinkSync,X as tracedMkdir,U as tracedMkdirSync,_t as tracedRename,yi as tracedRenameSync,y as tracedRmSync,di as tracedRmdirSync,tt as tracedUnlinkSync,lt as tracedWriteFile,Tt as tracedWriteFileSync,re as trustSystemCertificates,Ee as updateLastKnownHash,Je as updateProcessLockPort,zt as updateServerLockPort,yo as validateAgentId,D as validateCloneInputs,mn as validateSkillZip,ve as waitForServerLockDrain,sn as withHiddenWindowsConsole,Sn as withSpan,de as withSpanSync,Ve as writeBundleDecision,ca as writeMarkdownlintRule,Pe as writeRootGitignoreForNewRepo,In as writeStateManifest,kn as writeTargetVersion,Un as writeTracker};
|
|
1
|
+
import{Cc as e,Et as t,Ot as n,S as r,X as i,Za as a,ac as o,fc as s,v as c}from"./md-manager-BGnqyqi1-I7NmBKjQ.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,As as x,At as S,B as C,Ba as w,Bi as T,Bn as E,Bo as D,Br as O,Bs as k,Bt as A,C as j,Ca as M,Ci as N,Cn as P,Co as F,Cr as I,Cs as L,Ct as R,D as z,Da as B,Di as V,Dn as H,Do as U,Dr as W,Dt as G,E as K,Ea as q,Ei as J,En as Y,Eo as X,Er as Z,Et as Q,F as $,Fa as ee,Fi as te,Fn as ne,Fo as re,Fr as ie,Fs as ae,Ft as oe,G as se,Ga as ce,Gi as le,Gn as ue,Go as de,Gr as fe,Gt as pe,H as me,Ha as he,Hi as ge,Hn as _e,Ho as ve,Hr as ye,Hs as be,Ht as xe,I as Se,Ia as Ce,Ii as we,In as Te,Io as Ee,Ir as De,Is as Oe,It as ke,J as Ae,Ja as je,Ji as Me,Jn as Ne,Jo as Pe,Jr as Fe,Jt as Ie,K as Le,Ka as Re,Ki as ze,Kn as Be,Ko as Ve,Kr as He,Kt as Ue,L as We,La as Ge,Li as Ke,Ln as qe,Lo as Je,Lr as Ye,Lt as Xe,M as Ze,Ma as Qe,Mi as $e,Mn as et,Mo as tt,Mr as nt,Ms as rt,Mt as it,N as at,Na as ot,Ni as st,Nn as ct,No as lt,Nr as ut,Ns as dt,Nt as ft,O as pt,Oa as mt,Oi as ht,On as gt,Oo as _t,Or as vt,Os as yt,Ot as bt,P as xt,Pa as St,Pi as Ct,Pn as wt,Po as Tt,Pr as Et,Ps as Dt,Pt as Ot,Q as kt,Qa as At,Qi as jt,Qn as Mt,Qr as Nt,Qt as Pt,R as Ft,Ra as It,Ri as Lt,Rn as Rt,Ro as zt,Rr as Bt,Rt as Vt,S as Ht,Sa as Ut,Si as Wt,Sn as Gt,So as Kt,Sr as qt,St as Jt,T as Yt,Ta as Xt,Ti as Zt,Tn as Qt,To as $t,Tr as en,Tt as tn,U as nn,Ua as rn,Ui as an,Un as on,Uo as sn,Ur as cn,Ut as ln,V as un,Va as dn,Vi as fn,Vn as pn,Vo as mn,Vr as hn,Vs as gn,Vt as _n,W as vn,Wa as yn,Wi as bn,Wn as xn,Wo as Sn,Wr as Cn,Wt as wn,X as Tn,Xa as En,Xi as Dn,Xn as On,Xo as kn,Xr as An,Xt as jn,Y as Mn,Ya as Nn,Yi as Pn,Yn as Fn,Yo as In,Yr as Ln,Yt as Rn,Z as zn,Za as Bn,Zi as Vn,Zn as Hn,Zo as Un,Zr as Wn,Zt as Gn,_ as Kn,_a as qn,_i as Jn,_n as Yn,_o as Xn,_r as Zn,_t as Qn,a as $n,aa as er,ai as tr,an as nr,ao as rr,ar as ir,at as ar,b as or,ba as sr,bi as cr,bn as lr,bo as ur,br as dr,bt as fr,c as pr,ca as mr,ci as hr,cn as gr,co as _r,cr as vr,ct as yr,d as br,da as xr,di as Sr,dn as Cr,do as wr,dr as Tr,dt as Er,ea as Dr,ei as Or,en as kr,eo as Ar,er as jr,et as Mr,f as Nr,fa as Pr,fi as Fr,fn as Ir,fo as Lr,fr as Rr,ft as zr,g as Br,ga as Vr,gi as Hr,gn as Ur,go as Wr,gr as Gr,gt as Kr,h as qr,ha as Jr,hi as Yr,hn as Xr,ho as Zr,hr as Qr,ht as $r,i as ei,ia as ti,ii as ni,in as ri,io as ii,ir as ai,it as oi,j as si,ja as ci,ji as li,jn as ui,jo as di,jr as fi,js as pi,jt as mi,k as hi,ka as gi,ki as _i,kn as vi,ko as yi,kr as bi,ks as xi,kt as Si,l as Ci,la as wi,li as Ti,ln as Ei,lo as Di,lr as Oi,lt as ki,m as Ai,ma as ji,mi as Mi,mn as Ni,mo as Pi,mr as Fi,mt as Ii,n as Li,na as Ri,ni as zi,nn as Bi,no as Vi,nr as Hi,nt as Ui,o as Wi,oa as Gi,oi as Ki,on as qi,oo as Ji,or as Yi,ot as Xi,p as Zi,pa as Qi,pi as $i,pn as ea,po as ta,pr as na,pt as ra,q as ia,qa as aa,qi as oa,qn as sa,qo as ca,qr as la,qt as ua,r as da,ra as fa,ri as pa,rn as ma,ro as ha,rr as ga,rt as _a,s as va,sa as ya,si as ba,sn as xa,so as Sa,sr as Ca,st as wa,t as Ta,ta as Ea,ti as Da,tn as Oa,to as ka,tr as Aa,tt as ja,u as Ma,ua as Na,ui as Pa,un as Fa,uo as Ia,ur as La,ut as Ra,v as za,va as Ba,vi as Va,vn as Ha,vo as Ua,vr as Wa,vt as Ga,w as Ka,wa as qa,wi as Ja,wn as Ya,wo as Xa,wr as Za,ws as Qa,wt as $a,x as eo,xa as to,xi as no,xn as ro,xo as io,xr as ao,xt as oo,y as so,ya as co,yi as lo,yn as uo,yo as fo,yr as po,yt as mo,z as ho,za as go,zi as _o,zn as vo,zo as yo,zr as bo,zs as xo,zt as So}from"./dist-Nf304EbD.mjs";export{Ta as AGENT_ID_MAX_LEN,Li as AGENT_ID_RE,da as AGENT_WRITE_ORIGIN,a as AUDIT_EMPTY_SCOPE_WARNING,ei as AcpPermissionStore,$n as AcpRegistry,Wi as AcpThreadManager,va as AgentFocusBroadcaster,pr as AgentPresenceBroadcaster,Ci as AgentSessionCapacityError,Ma as AgentSessionManager,br as AutoStartDisabledError,Nr as BUNDLE_IDS,Zi as BUNDLE_SCOPE,Ai as BUNDLE_SKILL_NAME,qr as BacklinkIndex,Br as CC1Broadcaster,s as CC1_CONTRACT_VERSION,Kn as CONCURRENT_REPLACE_WINDOW_MS,za as CONFIG_FILENAME,so as CONFLICT_MARKER_RE,or as CURSOR_BUNDLE_PATHS_BY_PLATFORM,eo as ConfigSchema,Ht as ConflictAuthority,j as DEFAULT_CHECKPOINT_RETENTION,Ka as DEFAULT_EMBEDDINGS_DIMENSIONS,Yt as DEFAULT_PACK_ID,K as DocumentDurabilityState,z as DocumentDurabilityStateError,pt as EMBEDDINGS_API_KEY_ENV,hi as EPHEMERAL_PROJECT_DIR_PREFIX,h as ExposureConsentError,si as FEATURED_AGENT_IDS,Ze as FILE_SYSTEM_WRITER,at as FILE_WATCHER_ORIGIN,xt as FileEmbeddingsBackend,$ as FilesystemRootProjectError,Se as GIT_PREFLIGHT_FAIL_SPAN_NAME,We as GIT_UPSTREAM_WRITER,L as GitDirAccessError,Ft as GitNotAvailableError,ho as GitTooOldError,C as HOCUSPOCUS_AUTH_REJECTION_REASONS,un as HocuspocusAuthRejection,me as HocuspocusAuthTokenSchema,nn as HomeProjectRootError,vn as INSTALLED_AGENTS_SCHEMES,se as JSON_SCHEMA_DIALECT_2020_12,gn as LINEAGE_EPOCH_KEY,Le as LIVE_DERIVED_INDEX_DEBOUNCE_MS,ia as LOCK_FILE_ACCESS_REMEDY,Ae as MANAGED_RENAME_ORIGIN,Mn as MAX_ACP_THREADS,Tn as MAX_AGENT_SESSIONS,zn as MCP_CONNECTION_ID_HEADER,o as MCP_SERVER_NAME,kt as MIN_EVICTABLE_IDLE_MS,l as MIN_GIT_VERSION,Qa as MalformedGitPointerError,Mr as McpLogger,ja as MissingOkConfigError,Ui as OBSERVER_SYNC_ORIGIN,_a as OK_OKIGNORE_TEMPLATE,oi as ONBOARDING_BUNDLE_IDS,xo as ORPHAN_MODES,be as PROTOCOL_VERSION,yt as PinoLogger,ar as ProcessLockCollisionError,Xi as ProcessLockFileError,wa as ProjectGitInitError,yr as ROLLBACK_ORIGIN,ki as ROOT_GITIGNORE_TEMPLATE,Ra as RUNTIME_VERSION,Er as SERVICE_WRITER,zr as SKILL_INSTALL_EVENTS_FILENAME,c as SKILL_STATE_TARGETS,ra as STARTER_FOLDER_FRONTMATTER_FILENAME,Ii as STARTER_PACKS,$r as STARTER_PACK_IDS,Kr as STATE_MANIFEST_FILENAME,Qn as STATE_SCHEMA_VERSION,Ga as SYMLINK_MERGE_MIN_GIT_LABEL,mo as SYMLINK_MERGE_MIN_GIT_VERSION,e as SYSTEM_DOC_NAME,fr as SeedPrerequisiteError,oo as SeedRootDirError,Jt as ServerAuthorityCollisionError,R as ServerAuthorityRegistryError,$a as ServerLockCollisionError,tn as SingleFileNotAFileError,Q as SingleFileNotFoundError,G as SingleFileNotMarkdownError,bt as SingleFileProjectOverrideError,Si as StateManifestError,r as TEST_LOOP_CORE_MARKER,S as TEST_LOOP_SERVER_MARKER,mi as TagIndex,it as USER_GLOBAL_BUNDLE_IDS,ft as UnsafeIncomingSymlinkError,Ot as __getShowAllWalkStatsForTesting,oe as __resetShowAllWalkStatsForTesting,ke as acpThreadStoreRoots,Xe as acpThreadsDir,Vt as acquireProcessLock,So as acquireServerLock,A as applyAgentMarkdownWrite,_n as applyExternalChange,xe as applySeed,ln as assertCheckoutSymlinksSafe,wn as assertCompatibleStateManifest,pe as assertGitAvailable,Ue as assertIncomingSymlinksSafe,ua as assertMergeNameResolvesTo,Ie as assertNeverDiskEvent,Rn as assertRepoCheckoutSymlinksSafe,jn as assertSafeProjectRoot,Gn as assessLockHolder,Pt as attachAcpThreadSocket,m as attachCollabClientCounter,kr as attachIdleShutdown,Oa as auditScopeNotFoundTitle,Bi as bindConflictAuthority,ma as bootServer,ri as buildAndOpenSkill,nr as buildConfigYmlContent,qi as buildExecResult,xa as buildIngressPolicy,gr as buildOkMcpStdioCommand,Ei as buildSkillZip,Fa as buildStarterFolderFrontmatterYaml,Cr as buildWipTree,Ir as bundleSkillMdPath,ea as canonicalProjectKey,Ni as canonicalizeForCompare,Xr as classifyEvents,Ur as classifyFsPath,Yn as classifyLockHolder,Ha as clearAllEmbeddingsKeys,uo as coercePackId,lr as collectServerHostSnapshot,t as colorFromSeed,ro as commitUpstreamImport,Gt as commitWip,P as commitWipFromTree,Ya as compareSemver,Qt as composeEffectiveLinterConfig,Y as composeFrontmatterSchemasConfig,H as containsConflictMarkers,gt as contentHash,vi as contributorCount,v as countShadowObjects,ui as countStaleAgentWipRefs,et as countWipRefs,ct as createApiExtension,wt as createAssetServeMiddleware,ne as createCollaborationHost,Te as createContentFilter,qe as createContentFilterAsync,Rt as createEmbeddingsSecretStore,vo as createEphemeralProjectDir,E as createExternalChangeHandler,pn as createFileLogger,_e as createLiveDerivedIndexExtension,on as createMcpHttpHandler,xn as createOsProbe,ue as createPersistenceExtension,Be as createProbeFailureReporter,sa as createServer,Ne as createServerObserverExtension,Fn as createServerProbeResolver,On as createStreamingErrorWriter,xi as createTestLogger,Hn as describeStoredEmbeddingsKey,Mt as detectClaudeDesktopPresence,f as detectGit,jr as detectProjectShape,Aa as detectUserSkillHosts,Hi as discoverLockDirs,ga as discoverMarkdownlintConfig,ai as emitPreflightFailureSpan,ir as encodeDocName,Yi as encodeFolderRoute,Ca as encodeSkillRoute,vr as ensureProjectGit,Oi as errorResponse,La as evictStaleTrackerEntries,Tr as extractHeadings,Rr as extractOkBinaryPath,na as extractWikiLinksFromMarkdown,Fi as fallbackPaths,Qr as findEnclosingGitRoot,Gr as findEnclosingProjectRoot,Zn as findNativeMarkdownlintFile,Wa as flushFileLogger,po as formatAuditBrokenLinkSuppressionLine,dr as formatAuthRejectionWire,ao as formatContributorsFrom,qt as formatPackRationale,I as gcCheckpointRefs,Za as getCurrentMcpLogger,en as getIngressContext,Z as getLocalDir,W as getLogFilePath,x as getLogger,vt as getLogsDir,bi as getMachineId,b as getMeter,fi as getMetrics,nt as getTracer,ut as handleCollabSocketError,Et as handleSpawnCursor,ie as hasForwardingHeaders,De as hasGcLogLatch,n as iconFromClientName,Ye as incrementCollabSocketFilteredError,Bt as incrementServerObserverFire,bo as initContent,O as initShadowRepo,hn as initTelemetry,ye as initToleranceTelemetryWriter,cn as installJsonSchemaDialect,Cn as installPrettyZodErrors,pi as installTestLoggers,fe as installUserSkill,He as isAllowedApiOrigin,la as isAllowedWorkspaceHostHeader,Fe as isConfigDoc,Ln as isDefunctProcess,An as isDocInConflict,Wn as isFilesystemRoot,Nt as isHocuspocusAuthRejectionReason,p as isHomeDir,Or as isHostAdmitted,Da as isKnownPackId,zi as isLinkIndexExcludedDoc,pa as isLockFromThisMachine,ni as isLockProcessRunning,tr as isLoopbackAddress,Ki as isManagedArtifactDoc,ba as isMintedThreadId,hr as isOriginAdmitted,k as isOrphanMode,Ti as isPairedWriteOrigin,Pa as isPathWithinDir,Sr as isPeerAdmitted,Fr as isProcessAlive,$i as isProjectRoot,Mi as isReservedForUserTree,Yr as isSelfWrite,Hr as isSkillInstallReportEnvOptOut,Jn as isSystemDoc,Va as isToleranceTelemetryEnabled,lo as isValidLockPid,cr as lastKnownHash,no as listRescueCheckpoints,Wt as listStarterPacks,N as loadCustomAgents,Ja as loadPrincipal,Zt as lockAdvertisesUi,J as lockBaseUrl,V as lockFilePath,rt as loggerFactory,ht as loginShapedUserinfoUser,dt as logsCurrentPath,Dt as logsPreviousPath,_i as machineIdFilePath,_ as makeLazyEmbeddingsKeyStore,li as markServerLockDraining,$e as missingOkConfigMessage,st as mountMcpAndApi,Ct as normalizeFsPath,te as observeReadiness,we as packageVersionMajorMinor,Ke as parseAuthRejectionWire,Lt as parseGitVersion,_o as parseHocuspocusAuthToken,T as parseKeepaliveConnectionId,fn as parseProcessStartToken,ge as pathToDocName,an as planSeed,bn as prepareSingleFileOpen,le as processCommand,ze as processStartToken,oa as processUsage,Me as readAgentBrowserTools,Pn as readAllTargets,Dn as readBundleDecision,Vn as readDeclaredGitHubHosts,jt as readOriginCredentialHost,d as readOriginGitHubRepo,Dr as readOwnNativeRules,Ea as readProcessLock,Ri as readProcessLockDetailed,fa as readProcessStart,ti as readProcessState,er as readProjectHeadState,Gi as readProjectLocalSemanticConfig,ya as readServerLock,mr as readServerPackageVersion,wi as readSkillInstallStateSnapshot,Na as readStateManifest,xr as readTargetRecordedAt,Pr as readTargetVersion,Qi as reconcile,ji as recordContributor,Jr as recordSkillInstallEvent,Vr as recordsLockOwner,qn as redactShareSubprocessStderr,Ba as registerAllTools,co as registerNativeProcessStartReader,sr as registerWrite,to as releaseProcessLock,Ut as releaseServerLock,M as removeLastKnownHash,qa as removeLockIfUnchanged,Xt as removeProjectSkillGitignoreBlock,q as reportSkillInstall,B as resetMetrics,mt as resolveAuditScope,gi as resolveBuiltinSkillHosts,i as resolveBundleEnabled,g as resolveBundledSkillDir,ci as resolveContentDir,Qe as resolveCursorBinaryDefault,ot as resolveCursorSpawnInvocation,St as resolveEffectiveLinterConfig,ee as resolveEmbeddingsCredential,Ce as resolveGitHubAccountFromUrl,Ge as resolveGitHubAuthHost,It as resolveLockDir,go as resolveNativeConfigForDoc,w as resolveNativeMarkdownlintConfig,dn as resolvePack,he as resolvePackageVersion,rn as resolveSkillInstallReportSettings,yn as resolveUiInfo,ce as restoreContributors,Re as rewriteMarkdownLinksForDocumentRename,aa as rewriteWikiLinksForDocumentRename,je as runAuthReposSubprocess,Nn as runAuthStatusSubprocess,En as runCloneSubprocess,Bn as runDeviceFlowSubprocess,At as runWithMcpLogger,u as safeContentPath,Ar as safeSubdir,ka as safetyCheckpoint,Vi as sameGitHubLogin,ha as sanitizeClientName,ii as saveInMemoryCheckpoint,rr as saveVersion,Ji as scanLockProcesses,Sa as seedBasenameIndex,_r as seedEphemeralProjectDir,Di as serializeError,Ia as setActiveSpanAttributes,wr as setupServerObservers,Lr as shadowGit,ta as shutdownTelemetry,ae as spansCurrentPath,Oe as spansPreviousPath,Pi as spawnDetached,Zr as splitMarkdownBlocks,Wr as startWatcher,Xn as strategiesFor,Ua as streamedChunkOf,fo as streamingProblemEvent,ur as swapContributors,io as teardownToleranceTelemetryWriter,Kt as toBroadcasterKey,F as toProcessLockMetadata,Xa as tracedAppendFileSync,$t as tracedLinkSync,X as tracedMkdir,U as tracedMkdirSync,_t as tracedRename,yi as tracedRenameSync,y as tracedRmSync,di as tracedRmdirSync,tt as tracedUnlinkSync,lt as tracedWriteFile,Tt as tracedWriteFileSync,re as trustSystemCertificates,Ee as updateLastKnownHash,Je as updateProcessLockPort,zt as updateServerLockPort,yo as validateAgentId,D as validateCloneInputs,mn as validateSkillZip,ve as waitForServerLockDrain,sn as withHiddenWindowsConsole,Sn as withSpan,de as withSpanSync,Ve as writeBundleDecision,ca as writeMarkdownlintRule,Pe as writeRootGitignoreForNewRepo,In as writeStateManifest,kn as writeTargetVersion,Un as writeTracker};
|
package/dist/index.mjs
CHANGED
|
@@ -1549,6 +1549,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
|
|
|
1549
1549
|
`);re(e,o)}function M9(e,t){let n=S(e,`utf-8`);if(n.trim().length!==0)try{let r=A9(JSON.parse(n),t),i=n.endsWith(`
|
|
1550
1550
|
`)?`
|
|
1551
1551
|
`:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDirSpellings);r!==n&&re(e,r)}}function N9(e,t){let n=S(e,`utf-8`),r=k9(n,t.contentDirSpellings);r!==n&&re(e,r)}function P9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>j(e,t.name))}catch{return[]}}const xFe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function SFe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const CFe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function wFe(e){let t={contentDirSpellings:O9(e.contentDir)};for(let n of CFe)for(let r of P9(j(e.stagingDir,n)))SFe(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(j(e.stagingDir,`state`))){let e=ae(n);n.endsWith(`.jsonl`)?j9(n,t):xFe.has(e)?M9(n,t):N9(n,t)}}const I9=[`.ok`,`local`,`telemetry`],L9=[`.ok`,`local`,`logs`],R9=[`.ok`,`local`,`loss-capture`],z9=`spans-current.jsonl`,B9=`spans-prev.jsonl`,V9=`server-current.jsonl`,H9=`server-prev.jsonl`,U9=`loss-current.jsonl`,W9=`loss-prev.jsonl`;function TFe(e){return j(e,...I9,z9)}function EFe(e){return j(e,...I9,B9)}function DFe(e){return j(e,...L9,V9)}function OFe(e){return j(e,...L9,H9)}function kFe(e){return j(e,...R9,U9)}function AFe(e){return j(e,...R9,W9)}const G9=1e3;async function jFe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function MFe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function NFe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}function PFe(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(`
|
|
1552
|
-
`)}\n`:null}catch{return null}}function FFe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],R6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function IFe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],R6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){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 LFe(){return{nodeVersion:process.version,platform:ye(),arch:me()}}function RFe(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,Ms.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function zFe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return zFe(e.maxBytes)}function BFe(e){let t=J9(CJ(`project`,e)),n=J9(CJ(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function VFe(e){return Te(`sha256`).update(e).digest(`hex`)}function HFe(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const UFe=[`"doc.name"`,`"docName"`];function WFe(e){let t=S(e,`utf-8`),n=0;for(let e of UFe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(k(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,Y5(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const GFe=new Set([`.jsonl`]);function KFe(e){let t=e.lastIndexOf(`.`);return t!==-1&&GFe.has(e.slice(t))}const qFe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function JFe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&qFe.has(e.slice(t))}function YFe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!JFe(r))continue;let{redacted:i,patterns:a,lineCount:o}=_P(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return M(e,t).split(le).join(`/`)}async function XFe(e){let t=N(e.contentDir),n=N(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??jFe,a=r.fetchAgentEffects??MFe,o=r.fetchWatcherRecent??NFe,s=r.readShadowHead??FFe,c=r.readCheckpointRefs??IFe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.87.0-beta.
|
|
1552
|
+
`)}\n`:null}catch{return null}}function FFe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],R6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function IFe(e){let t=j(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],R6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){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 LFe(){return{nodeVersion:process.version,platform:ye(),arch:me()}}function RFe(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,Ms.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function zFe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return zFe(e.maxBytes)}function BFe(e){let t=J9(CJ(`project`,e)),n=J9(CJ(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function VFe(e){return Te(`sha256`).update(e).digest(`hex`)}function HFe(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const UFe=[`"doc.name"`,`"docName"`];function WFe(e){let t=S(e,`utf-8`),n=0;for(let e of UFe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(k(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,Y5(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const GFe=new Set([`.jsonl`]);function KFe(e){let t=e.lastIndexOf(`.`);return t!==-1&&GFe.has(e.slice(t))}const qFe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function JFe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&qFe.has(e.slice(t))}function YFe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!JFe(r))continue;let{redacted:i,patterns:a,lineCount:o}=_P(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return M(e,t).split(le).join(`/`)}async function XFe(e){let t=N(e.contentDir),n=N(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??jFe,a=r.fetchAgentEffects??MFe,o=r.fetchWatcherRecent??NFe,s=r.readShadowHead??FFe,c=r.readCheckpointRefs??IFe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.87.0-beta.3`),d=r.readDesktopEnv??K9,f=r.readLanguage??D9,p=r.readRuntime??LFe,h=r.isOtlpPushEnabled??RFe,_=y(j(xe(),`ok-bundle-`));try{v(j(_,`telemetry`),{recursive:!0}),v(j(_,`logs`),{recursive:!0}),v(j(_,`state`),{recursive:!0}),Z9(TFe(n),j(_,`telemetry`,z9)),Z9(EFe(n),j(_,`telemetry`,B9)),Z9(DFe(n),j(_,`logs`,V9)),Z9(OFe(n),j(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,j(_,`logs`,ae(t)));for(let t of e.userStateFiles??[])Z9(t,j(_,rJ,ae(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,j(_,`diagnostic-reports`,ae(t)))&&(y+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,j(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(j(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(j(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=PFe(n);e!==null&&re(j(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(j(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(j(_,`state`,`checkpoint-refs.txt`),D),Z9(kFe(n),j(_,`state`,U9)),Z9(AFe(n),j(_,`state`,W9)),Z9(j(b,`last-spawn-error.log`),j(_,`state`,`last-spawn-error.log`)),Z9(j(b,Nd),j(_,`state`,Nd)),Z9(j(b,Pd),j(_,`state`,Pd)),Z9(j(b,Md),j(_,`state`,Md));let ee=p(),ne=d(),ie=f(),k={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(j(_,`state`,`runtime.json`),`${JSON.stringify(k,null,2)}\n`);let oe=C===`running`?`running
|
|
1553
1553
|
`:`not-running (${w})\n`;re(j(_,`state`,`server-status.txt`),oe);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:J5(e.diagnosticReports,y);if(re(j(_,`state`,`diagnostic-reports-status.txt`),`${A}\n`),re(j(_,Q5),y7(e.osTerminationEvidence)),e.processDir&&g(e.processDir)){let t=j(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let se=e.redact===!0;se&&wFe({stagingDir:_,contentDir:t}),e.note&&re(j(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=YFe(_));for(let t of e.extraFiles??[]){let e=t.zipName??ae(t.sourcePath);if(!Z9(t.sourcePath,j(_,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=x7(t,`extra/${e}`);n!==null&&(ce??={redactions:[],redactedLineCount:0},ce.redactions.push(n),ce.redactedLineCount+=n.lineCount)}let M=BFe(n),N=Q9(_),le=[],ue=0,de=0;for(let e of N){let t=$9(_,e),n=te(e).size,r=KFe(t)?HFe(e):0;le.push({path:t,bytes:n,lines:r}),ue+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=WFe(e))}let fe={applied:se};ce!==null&&(fe.secretScrub=ce);let P={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie},contentDir:{pathSha256:VFe(t),absolutePath:se?`<CONTENT_DIR>`:t},telemetry:{localSink:M,otlpPushEnabled:h()},redaction:fe,serverStatus:C,files:le};re(j(_,`manifest.json`),`${JSON.stringify(P,null,2)}\n`);let pe=O9(t),me=N.some(e=>{try{let t=S(e,`utf-8`);return pe.some(e=>t.includes(e))}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:ue,fileCount:le.length,docNameCount:de,contentDirVisible:me,redacted:se},ge=!1;return{stagingDir:_,manifest:P,summary:he,cleanup:()=>{ge||(ge=!0,O(_,{recursive:!0,force:!0}))}}}catch(e){throw O(_,{recursive:!0,force:!0}),e}}async function ZFe(e){let{collected:t,outputPath:n}=e,r=k(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new KDe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function QFe(e,t){let n=j(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,Ms.parse)(S(n,`utf-8`)),r=UJ(t)?t.content:void 0,i=UJ(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return N(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return N(e)}async function $Fe(e,t,n,r,i,a){let o=S7(t,e.logger),s=await XFe({contentDir:QFe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...ZNe(o,e.userLogsDir??j(gJ(),`logs`)),...w7(e.cachesDir??j(_e(),`Library`,`Caches`))],userStateFiles:T7(e.bugReportsDir??b7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(k(e.outputPath),{recursive:!0}),await ZFe({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 eIe(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??D9,i=()=>CNe(e.diagnosticReportsDir??j(_e(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return $Fe(e,t,n,r,i(),await v7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await nPe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:w7(e.cachesDir??j(_e(),`Library`,`Caches`)),bugReportLedgerFiles:T7(e.bugReportsDir??b7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await v7(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{QJ as ALL_EDITOR_IDS,$J as EDITOR_LABELS,NY as EDITOR_TARGETS,$be as HOSTS_WITH_USER_SKILL_DIR,dNe as LAUNCH_CONFIG_NAME,rFe as PATH_SHIM_BEGIN,aFe as PATH_SHIM_BLOCK_RE,iFe as PATH_SHIM_END,c5 as ProjectPathSafetyError,HMe as addOkPathsToGitExclude,l5 as assertProjectPathSafe,mY as buildManagedServerEntry,zPe as buildMcpConfigDeclineEvent,BPe as buildMcpConfigMigrateEvent,wY as canonicalEntryFor,G5 as classifyExistingMcpEntry,eIe as collectReportBundle,uFe as createCliProbeResolver,kJ as createTokenStore,JNe as defaultBugReportZipPath,Ke as detectGh,Ye as detectGhAccounts,hNe as detectInstalledEditors,CY as droppedManagedKeys,bxe as editorConfigPathDisplay,yxe as editorEntryLocator,OPe as ensurePiBridge,kNe as findJetsamKillSync,C5 as formatTrackedRemediation,GMe as getExcludedOkPaths,x5 as getInstalledSkillProjectionPaths,Qbe as getNativeTomlMcpEditor,b5 as getOkArtifactPaths,fY as isEntryUpToDate,hY as isOwnManagedEntry,eFe as loadConfig,Ebe as makeLazyProbeTokenStore,b7 as okBugReportsDir,y9 as parseGitHubBlobUrl,tFe as parseGitHubShareUrl,b9 as parseGitHubTreeUrl,v9 as parseGitUrl,oFe as pathInstallMarkerPath,DMe as previewContent,gNe as probeOwnManagedEditorMcpEntry,EPe as probePiBridgeState,S5 as probeTrackedOkPaths,U5 as readExistingMcpEntry,WMe as readSharingMode,_P as redactContent,oPe as registerWindowsProcessStartReader,UMe as removeOkPathsFromGitExclude,FPe as removeOwnMcpEntry,RMe as removeProjectSkill,fFe as removeUserGlobalSkillBundle,vFe as removeUserSkill,MMe as resolveProjectRoot,JPe as runStop,f9 as truncatePriorEntry,T9 as userGlobalSkillBundleTargets,_Fe as userSkillPresentAnywhere,nFe as validateLocalFolderForShare,H5 as writeEditorMcpConfig,hFe as writeProjectAiIntegrations,h5 as writeProjectSkill,mNe as writeUserMcpConfigs,gFe as writeUserSkill};
|
|
1554
1554
|
//# sourceMappingURL=index.mjs.map
|