@beehexa/hexasync-template-ide-mcp 2611.8.3 → 2612.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +14 -11
  2. package/dist/index.d.ts +5 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +3 -0
  5. package/dist/index.js.map +1 -1
  6. package/dist/installedKnowledge.node.d.ts.map +1 -1
  7. package/dist/installedKnowledge.node.js +3 -1
  8. package/dist/installedKnowledge.node.js.map +1 -1
  9. package/dist/knowledgeBase.generated.d.ts +1 -1
  10. package/dist/knowledgeBase.generated.d.ts.map +1 -1
  11. package/dist/knowledgeBase.generated.js +515 -422
  12. package/dist/knowledgeBase.generated.js.map +1 -1
  13. package/dist/mcp/prebuilds/integrity.json +2 -2
  14. package/dist/mcp/prebuilds/win32-arm64/root-authority.node +0 -0
  15. package/dist/mcp/prebuilds/win32-x64/root-authority.node +0 -0
  16. package/dist/mcp/server-build.json +3 -3
  17. package/dist/mcp/server.js +4665 -4048
  18. package/dist/mcp/wikiHostWorker.js +4 -0
  19. package/dist/mcpServer.node.d.ts +7 -3
  20. package/dist/mcpServer.node.d.ts.map +1 -1
  21. package/dist/mcpServer.node.js +181 -77
  22. package/dist/mcpServer.node.js.map +1 -1
  23. package/dist/wikiCliCache.node.d.ts +23 -0
  24. package/dist/wikiCliCache.node.d.ts.map +1 -0
  25. package/dist/wikiCliCache.node.js +64 -0
  26. package/dist/wikiCliCache.node.js.map +1 -0
  27. package/dist/wikiCliSecretSlot.node.d.ts +7 -0
  28. package/dist/wikiCliSecretSlot.node.d.ts.map +1 -0
  29. package/dist/wikiCliSecretSlot.node.js +62 -0
  30. package/dist/wikiCliSecretSlot.node.js.map +1 -0
  31. package/dist/wikiCliSession.node.d.ts +31 -0
  32. package/dist/wikiCliSession.node.d.ts.map +1 -0
  33. package/dist/wikiCliSession.node.js +65 -0
  34. package/dist/wikiCliSession.node.js.map +1 -0
  35. package/dist/wikiCliStartup.node.d.ts +23 -0
  36. package/dist/wikiCliStartup.node.d.ts.map +1 -0
  37. package/dist/wikiCliStartup.node.js +142 -0
  38. package/dist/wikiCliStartup.node.js.map +1 -0
  39. package/dist/wikiResources.node.d.ts +14 -0
  40. package/dist/wikiResources.node.d.ts.map +1 -0
  41. package/dist/wikiResources.node.js +131 -0
  42. package/dist/wikiResources.node.js.map +1 -0
  43. package/package.json +10 -9
@@ -0,0 +1,4 @@
1
+ "use strict";function B(e){if(!(typeof e!="object"||e===null)){if("code"in e&&(e.code==="busy"||e.code==="capacity"))return e.code;if("errcode"in e&&typeof e.errcode=="number"){let r=e.errcode&255;if(r===5||r===6)return"busy";if(r===13)return"capacity"}if(e instanceof Error&&e.message==="Wiki reservation capacity exceeded")return"capacity"}}var K=require("node:worker_threads");async function k(e,r=d=>new Promise(a=>setTimeout(a,d))){for(let d=0;;d++)try{return await e()}catch(a){let i=typeof a=="object"&&a!==null&&"errcode"in a?a.errcode:void 0;if(typeof i!="number"||(i&255)!==5&&(i&255)!==6||d>=3)throw a;await r(20*2**d)}}var I=require("node:fs/promises"),q=require("node:path"),J=require("node:sqlite");var E=require("node:fs/promises"),y=require("node:path");async function N(e="/var/tmp"){let r=process.getuid?.();if(process.platform==="win32"||r===void 0||!Number.isSafeInteger(r)||!(0,y.isAbsolute)(e)||(0,y.resolve)(e)!==e)throw new Error("Private wiki storage is unavailable on this host");let d=(0,y.parse)(e).root,a=e.slice(d.length).split(y.sep).filter(Boolean),i=async t=>{let o=await(0,E.lstat)(t),l=(o.mode&18)!==0;if(!o.isDirectory()||o.isSymbolicLink()||o.uid!==0&&o.uid!==r||l&&!(o.uid===0&&(o.mode&512)!==0))throw new Error("Wiki storage ancestor is not trusted")};await i(d);for(let t of a)d=(0,y.join)(d,t),await i(d);let s=await(0,E.lstat)(e);if(!(s.uid===0&&(s.mode&512)!==0||s.uid===r&&(s.mode&63)===0))throw new Error("Wiki storage parent is not private or sticky");let n=(0,y.join)(e,`hexasync-wiki-${r}`);try{await(0,E.mkdir)(n,{mode:448})}catch(t){if(!(t instanceof Error)||!("code"in t)||t.code!=="EEXIST")throw t}let c=await(0,E.lstat)(n);if(!c.isDirectory()||c.isSymbolicLink()||c.uid!==r||(c.mode&63)!==0)throw new Error("Wiki storage directory is not private");return n}var z=/^[a-f0-9]{64}$/u;function Y(e){e.exec(`CREATE TABLE IF NOT EXISTS wiki_sessions (session TEXT PRIMARY KEY, account TEXT NOT NULL) STRICT;
2
+ CREATE INDEX IF NOT EXISTS wiki_sessions_account ON wiki_sessions(account);`);let r=i=>{if(!z.test(i))throw new Error("Invalid wiki cache identity")},d=i=>{e.exec("BEGIN IMMEDIATE");try{let s=i();return e.exec("COMMIT"),s}catch(s){try{e.exec("ROLLBACK")}catch{throw s}throw s}},a=(i,s)=>!!e.prepare("SELECT 1 FROM wiki_sessions WHERE account = ? AND session = ?").get(i,s);return{register:(i,s)=>(r(i),r(s),d(()=>{let n=e.prepare("SELECT account FROM wiki_sessions WHERE session = ?").get(s);if(n&&n.account!==i)throw new Error("Wiki session belongs to another account");let c=e.prepare("SELECT COUNT(*) AS count FROM wiki_sessions").get();if(!n&&Number(c?.count)>=1024)throw new Error("Wiki session capacity exceeded");let t=e.prepare("INSERT OR IGNORE INTO wiki_sessions(session, account) VALUES (?, ?)").run(s,i);return Number(t.changes)===1})),join:(i,s,n)=>(r(i),r(s),r(n),d(()=>{if(!a(i,s))throw new Error("Wiki session is not active");let c=e.prepare("SELECT account FROM wiki_sessions WHERE session = ?").get(n);if(c&&c.account!==i)throw new Error("Wiki session belongs to another account");let t=e.prepare("SELECT COUNT(*) AS count FROM wiki_sessions").get();if(!c&&Number(t?.count)>=1024)throw new Error("Wiki session capacity exceeded");let o=e.prepare("INSERT OR IGNORE INTO wiki_sessions(session, account) VALUES (?, ?)").run(n,i);return Number(o.changes)===1})),isActive:(i,s)=>(r(i),r(s),d(()=>a(i,s))),otherSession:(i,s)=>(r(i),r(s),d(()=>{if(!a(i,s))throw new Error("Wiki session is not active");let n=e.prepare("SELECT session FROM wiki_sessions WHERE account=? AND session<>? ORDER BY session LIMIT 1").get(i,s)?.session;if(n!==void 0&&(typeof n!="string"||!z.test(n)))throw new Error("Invalid wiki session");return n})),logout:(i,s)=>(r(i),r(s),d(()=>{let n=e.prepare("DELETE FROM wiki_sessions WHERE account = ? AND session = ?").run(i,s);return Number(n.changes)===0?!1:(e.prepare("SELECT 1 FROM wiki_sessions WHERE account = ? LIMIT 1").get(i)||(e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='wiki_snapshots'").get()&&e.prepare("DELETE FROM wiki_snapshots WHERE account = ?").run(i),e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='wiki_current'").get()&&(e.prepare("DELETE FROM wiki_current WHERE account = ?").run(i),e.prepare("DELETE FROM wiki_generations WHERE account = ?").run(i))),!0)}))}}function X(e,r=57344){if(!Number.isSafeInteger(r)||r<32||r>57344)throw new Error("Invalid wiki database limit");let d=e.prepare("PRAGMA page_size").get()?.page_size,a=e.prepare("PRAGMA page_count").get()?.page_count;if(d!==4096||typeof a!="number"||a>r)throw new Error("Wiki database exceeds its page limit");if(e.prepare("PRAGMA journal_mode = DELETE").get()?.journal_mode!=="delete")throw new Error("Wiki database journal mode is unavailable");if(e.exec("PRAGMA temp_store = MEMORY; PRAGMA busy_timeout = 0; PRAGMA trusted_schema = OFF; PRAGMA secure_delete = ON;"),e.prepare(`PRAGMA max_page_count = ${r}`).get()?.max_page_count!==r)throw new Error("Wiki database page limit is unavailable")}async function Q(e="/var/tmp"){if(process.getuid?.()===void 0)throw new Error("Private wiki storage is unavailable on this host");let r=await N(e),d=(0,q.join)(r,"wiki.sqlite");try{await(0,I.writeFile)(d,"",{flag:"wx",mode:384})}catch(s){if(!(s instanceof Error)||!("code"in s)||s.code!=="EEXIST")throw s}let a=await(0,I.lstat)(d);if(!a.isFile()||a.isSymbolicLink()||a.uid!==process.getuid()||a.nlink!==1||(a.mode&63)!==0)throw new Error("Wiki database is not private");let i=new J.DatabaseSync(d);try{let s=await(0,I.lstat)(d);if(!s.isFile()||s.isSymbolicLink()||s.dev!==a.dev||s.ino!==a.ino||s.uid!==a.uid||s.nlink!==1||(s.mode&63)!==0)throw new Error("Wiki database changed while opening");return X(i),i}catch(s){throw i.close(),s}}var j=require("node:crypto");var ht=Object.freeze({});var mt=Object.freeze([]);var ee=new Map([["TASK","objects"],["SELF",void 0],["PROFILE",void 0]]),Ce=new Map([["PULLER","pullers"],["REPORT","reports"],["SCHEMA","schemas"],["SCHEDULER","startupTasks"]]),te=[{property:"taskId",collection:"objects"},{property:"objectId",collection:"objects"},{property:"object_id",collection:"objects"},{property:"objectIds",collection:"objects"},{property:"pusherId",collection:"pushers"},{property:"pullerId",collection:"pullers"},{property:"tableId",collection:"tables"},{property:"dependedOn",collection:"objects"},{property:"connectionId",collection:"connectors"},{property:"fromConnectionId",collection:"connectors"},{property:"connectorId",collection:"connectors",opaqueInCollections:["connectors"]},{property:"entityId",tokenFormOnly:!0,discriminator:{siblings:["entityType"],byValue:ee,fallback:"objects"}},{property:"targetId",tokenFormOnly:!0,discriminator:{siblings:["targetType","entityType"],byValue:new Map([...Ce,...ee]),fallback:"objects"}}];var St=te.map(e=>e.property),Tt=new Map(te.map(e=>[e.property,e]));var _e=[{property:"table",collection:"tables"},{property:"puller",collection:"pullers"},{property:"pusher",collection:"pushers"}],bt=new Map(_e.map(e=>[e.property,e]));var Me="support@beehexa.com";var It=`Not supported. Request this connector: email **${Me}** with the system name, website URL, up-to-date API docs, and a sandbox environment.`;var ne={call:"\u2197",control:"\u25C6",orchestrate:"\u21BB",query:"\u2261",state:"\u25A3",terminal:"\u25C9",transform:"\u21C4",ui:"\u25A4",wait:"\u25D4",write:"\u21E9"},m={family:"unmapped",glyph:"\u25A1"},w={"call.dialect":"call","call.event":"call","call.http":"call","call.webhook":"call","control.if":"control","control.switch":"control","orchestrate.composite":"orchestrate","orchestrate.enqueue":"orchestrate","orchestrate.pull":"orchestrate","query.dsl":"query","query.file":"query","query.history":"query","query.kv":"query","query.metrics":"query","query.record":"query","query.sql":"query","state.cache":"state","state.item":"state","state.kv":"state","state.removal":"state","state.task-data":"state","terminal.begin":"terminal","terminal.end":"terminal","terminal.error":"terminal","transform.decode":"transform","transform.filter":"transform","transform.template":"transform","wait.sleep":"wait","write.delete":"write","write.index":"write","write.push":"write","write.seed":"write"};function re(e){if(!e)return m.glyph;let r=Object.hasOwn(w,e)?w[e]:e;return Object.hasOwn(ne,r)?ne[r]:m.glyph}var Le={"call.http":'<path d="M14 3h7v7"/><path d="M21 3l-9 9"/><path d="M19 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5"/>',"call.webhook":'<path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z"/>',"call.event":'<path d="M12 11.5v.01"/><path d="M8.6 8.6a5 5 0 0 0 0 6.8"/><path d="M15.4 15.4a5 5 0 0 0 0-6.8"/><path d="M5.6 5.6a9 9 0 0 0 0 12.8"/><path d="M18.4 18.4a9 9 0 0 0 0-12.8"/>',"call.dialect":'<path d="M4 17l6-6-6-6"/><path d="M12 19h8"/>',"query.dsl":'<path d="M8 3H7a2 2 0 0 0-2 2v4a2 2 0 0 1-2 2 2 2 0 0 1 2 2v4a2 2 0 0 0 2 2h1"/><path d="M16 21h1a2 2 0 0 0 2-2v-4a2 2 0 0 1 2-2 2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1"/><path d="M9 12h6"/>',"query.sql":'<ellipse cx="12" cy="5" rx="8" ry="3"/><path d="M4 5v14c0 1.66 3.58 3 8 3s8-1.34 8-3V5"/><path d="M4 12c0 1.66 3.58 3 8 3s8-1.34 8-3"/>',"query.record":'<path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3.5 6h.01"/><path d="M3.5 12h.01"/><path d="M3.5 18h.01"/>',"query.metrics":'<path d="M3 3v16a2 2 0 0 0 2 2h16"/><path d="M7 16v-4"/><path d="M12 16V8"/><path d="M17 16v-6"/>',"query.history":'<path d="M3 12a9 9 0 1 0 2.6-6.4L3 8"/><path d="M3 3v5h5"/><path d="M12 7.5V12l3 2"/>',"query.kv":'<circle cx="8" cy="15" r="4"/><path d="M10.85 12.15 19 4"/><path d="M18 5l2 2"/><path d="M15 8l2 2"/>',"query.file":'<path d="M15 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V6z"/><path d="M14 2v4a2 2 0 0 0 2 2h3"/><path d="M8.5 13h7"/><path d="M8.5 17h7"/>',"state.kv":'<path d="M12.6 2.6A2 2 0 0 0 11.2 2H4a2 2 0 0 0-2 2v7.2a2 2 0 0 0 .6 1.4l8.7 8.7a2.4 2.4 0 0 0 3.4 0l6.6-6.6a2.4 2.4 0 0 0 0-3.4z"/><path d="M7.5 7.5h.01"/>',"state.cache":'<path d="M4 8.5h16V19a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z"/><rect x="2" y="3.5" width="20" height="5" rx="1"/><path d="M10 12.5h4"/>',"state.task-data":'<path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"/><path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"/><path d="M7 3v4a1 1 0 0 0 1 1h6"/>',"state.item":'<path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1"/><path d="M9 13.5l2 2 4-4"/>',"state.removal":'<path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><path d="M4 22v-7"/>',"write.push":'<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M17 8l-5-5-5 5"/><path d="M12 3v12"/>',"write.index":'<path d="M12 2v8"/><path d="M16 6l-4 4-4-4"/><path d="M3 14h18"/><path d="M22 14v5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5l3.4-6.8A2 2 0 0 1 7.2 6H8"/><path d="M6.5 17.5h.01"/>',"write.seed":'<path d="M7 21h10"/><path d="M12 21v-8"/><path d="M12 13C12 9 9 6 5 6c0 4 3 7 7 7z"/><path d="M12 13c0-3.5 2.5-6.5 6.5-6.5 0 3.5-2.5 6.5-6.5 6.5z"/>',"write.delete":'<path d="M3 6h18"/><path d="M8 6V4.5A1.5 1.5 0 0 1 9.5 3h5A1.5 1.5 0 0 1 16 4.5V6"/><path d="M18.5 6l-.9 13.1A2 2 0 0 1 15.6 21H8.4a2 2 0 0 1-2-1.9L5.5 6"/><path d="M10 11v6"/><path d="M14 11v6"/>',"orchestrate.enqueue":'<path d="M2 12h8"/><path d="M7 9l3 3-3 3"/><path d="M14 4h6a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6"/><path d="M14 8v8"/>',"orchestrate.pull":'<path d="M4.4 14.9A7 7 0 1 1 15.7 7h1.8a4.5 4.5 0 0 1 2.4 8.3"/><path d="M12 12v9"/><path d="M8.5 17.5 12 21l3.5-3.5"/>',"orchestrate.composite":'<path d="M12 2.5 3.5 7v10l8.5 4.5 8.5-4.5V7z"/><path d="M3.5 7 12 11.5 20.5 7"/><path d="M12 11.5v10"/>',"transform.template":'<path d="M8 3H7a2 2 0 0 0-2 2v4a2 2 0 0 1-2 2 2 2 0 0 1 2 2v4a2 2 0 0 0 2 2h1"/><path d="M16 21h1a2 2 0 0 0 2-2v-4a2 2 0 0 1 2-2 2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1"/>',"transform.filter":'<path d="M21.5 3.5H2.5l7.6 9v7.2l3.8 1.8v-9z"/>',"transform.decode":'<path d="M8 3 4 7l4 4"/><path d="M4 7h16"/><path d="M16 21l4-4-4-4"/><path d="M20 17H4"/>',"control.if":'<path d="M16 3h5v5"/><path d="M8 3H3v5"/><path d="M12 22v-8.3a4 4 0 0 0-1.2-2.8L3 3"/><path d="M15 9l6-6"/>',"control.switch":'<path d="M4 4v14a2 2 0 0 0 2 2h2"/><path d="M4 7h10"/><path d="M4 13h10"/><path d="M8 20h6"/><path d="M17 4h3"/><path d="M17 10h3"/><path d="M17 17h3"/>',"terminal.begin":'<circle cx="12" cy="12" r="9"/><path d="M10 8.5 16 12l-6 3.5z"/>',"terminal.end":'<circle cx="12" cy="12" r="9"/><rect x="9" y="9" width="6" height="6" rx="1"/>',"terminal.error":'<path d="M10.3 4 2.6 17.5A2 2 0 0 0 4.3 20.5h15.4a2 2 0 0 0 1.7-3L13.7 4a2 2 0 0 0-3.4 0z"/><path d="M12 9.5v4"/><path d="M12 17h.01"/>',"wait.sleep":'<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3.5 2"/>'},Fe=e=>{let r=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">${e}</svg>`;return`url("data:image/svg+xml,${encodeURIComponent(r)}")`};function C(e){return`ic-${(e!==void 0&&Object.hasOwn(w,e)?e:m.family).replaceAll(".","-")}`}var De={},oe=(e,r,d,a)=>{let i;Object.defineProperty(De,e,{enumerable:!0,get:()=>(i??={family:e,parent:r,className:C(e),strictGlyph:d,looseMaskImage:Fe(a),tint:"currentColor"},i)})};for(let e of Object.keys(w)){let r=w[e];oe(e,r,re(r),Le[e])}oe(m.family,m.family,m.glyph,'<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M8 8l8 8M16 8l-8 8"/>');var ie=["Begin","Composite","cURL","End","GraphQL","Liquid","OData","QueryDSL","Restful"],Lt=Object.fromEntries(ie.map(e=>[e,!0]));var Ve=["semantic","interaction","accessibility","performance","sourceRoundTrip"];var Ke=()=>Object.freeze(Object.fromEntries(Ve.map(e=>[e,Object.freeze({status:"pending",evidence:Object.freeze([])})]))),Be=(e,r,d,a)=>Object.freeze({adapter:"@beehexa/hexasync-workflow-adapter",capability:e,theme:`${r}-theme`,storage:"host-configured",cspAsset:"deny-by-default",featureFlag:d,parity:`${r}-parity`,rollback:a}),ze=(e,r)=>Object.freeze({...e,phase:"candidate",legacyAvailable:!0,removeLegacy:!1,gates:Ke(),evidence:Object.freeze([r])}),R=e=>ze({...e,bindings:Be(e.adoptionMode,e.id.replace(":","-"),e.flag,e.rollback)},e.evidence),Gt=Object.freeze([R({id:"dashboard-v2:profile-task-flow",host:"dashboard-v2",route:"/monitoring/profiles/:profileId/tasks/:taskId/flow",legacyTechnology:"vue-flow",adoptionMode:"explorer",owner:"dashboard",flag:"VITE_DASHBOARD_SHARED_TASK_FLOW",rollback:"legacy-task-flow",evidence:"dashboard-v2/src/pages/monitoring/profiles/tasks/TaskFlow.vue"}),R({id:"dashboard-v2:connector-workflow-preview",host:"dashboard-v2",route:"/__dev/connector-workflow-preview",legacyTechnology:"mermaid",adoptionMode:"editable",owner:"dashboard",flag:"VITE_DASHBOARD_SHARED_CONNECTOR_WORKFLOW",rollback:"mermaid-preview",evidence:"dashboard-v2/src/pages/__dev/ui/ConnectorWorkflowPreview.vue"}),R({id:"dashboard-v2:workflow-editor-callbacks",host:"dashboard-v2",route:"/callbacks/*",legacyTechnology:"bespoke-vue",adoptionMode:"editable",owner:"dashboard",flag:"VITE_DASHBOARD_SHARED_WORKFLOW_EDITOR",rollback:"legacy-workflow-editor",evidence:"dashboard-v2/src/widgets/workflow-editor"}),R({id:"control-center:workflow-designer",host:"control-center",route:"/workflow/designer/:name",legacyTechnology:"mermaid",adoptionMode:"editable",owner:"control-center",flag:"CONTROL_CENTER_SHARED_WORKFLOW_DESIGNER",rollback:"mermaid-canvas",evidence:"control-center workflow surface inventory"}),R({id:"workflows-automation:workflow-designer",host:"workflows-automation",route:"workflow-designer",legacyTechnology:"bespoke-steps",adoptionMode:"editable",owner:"workflows-automation",flag:"WORKFLOWS_AUTOMATION_SHARED_DESIGNER",rollback:"legacy-step-editor",evidence:"workflows-automation workflow surface inventory"}),R({id:"vscode:workflow-preview-designer",host:"vscode",route:"hexasync.workflowDesigner.open",legacyTechnology:"mermaid-webview",adoptionMode:"editable",owner:"vscode-extension",flag:"hexasync.workflowDesigner.enabled",rollback:"legacy-preview-command",evidence:"hexasync-templates-vscode-ext workflow surface inventory"})]);var zn=Object.freeze({productName:"HexaSync Template IDE",serverName:"HexaSync Template IDE MCP Server",shortLabel:"Template IDE MCP",productId:"hexasync-template-ide",vscodeProviderId:"hexasync.templateIdeMcp",serverPackageName:"@beehexa/hexasync-template-ide-mcp",commandPrefix:"HexaSync IDE:"});function A(e){if(e!==e.normalize("NFC")||new TextEncoder().encode(e).length>1024||/[\\\u0000-\u001f\u007f-\u009f]/u.test(e)||/%(?:2f|5c|2e)/iu.test(e)||/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/u.test(e)||/^[a-z][a-z0-9+.-]*:/iu.test(e)||e.split("/").some(r=>!r||r==="."||r===".."))throw new Error("Unsafe wiki document path")}var f=/^[a-f0-9]{64}$/u,O=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,G=2*1024*1024,le=100*1024*1024,pe=200*1024*1024,ue=1e4;function M(e,r){let d=e.prepare("SELECT account, previous, pending FROM wiki_current WHERE generation=?").get(r);if(d&&d.pending===1)if(typeof d.previous=="string"){if(!e.prepare("SELECT 1 FROM wiki_generations WHERE generation=? AND account=?").get(d.previous,d.account))throw new Error("Wiki previous revision is unavailable");e.prepare("UPDATE wiki_current SET generation=?, previous=NULL, pending=0 WHERE account=?").run(d.previous,d.account)}else if(d.previous===null)e.prepare("DELETE FROM wiki_current WHERE account=?").run(d.account);else throw new Error("Invalid wiki previous revision");e.prepare("DELETE FROM wiki_generations WHERE generation=? AND generation NOT IN (SELECT generation FROM wiki_current) AND generation NOT IN (SELECT previous FROM wiki_current WHERE previous IS NOT NULL)").run(r)}function fe(e,r,d=pe){if(!Number.isSafeInteger(d)||d<0||d>pe)throw new Error("Invalid wiki row limit");e.exec(`PRAGMA foreign_keys=ON; CREATE TABLE IF NOT EXISTS wiki_generations (generation TEXT PRIMARY KEY, account TEXT NOT NULL, session TEXT NOT NULL, namespace TEXT NOT NULL, mcp_id TEXT NOT NULL, etag TEXT NOT NULL, budget INTEGER NOT NULL) STRICT;
3
+ CREATE TABLE IF NOT EXISTS wiki_files (generation TEXT NOT NULL, path TEXT NOT NULL, data BLOB NOT NULL, digest TEXT NOT NULL, PRIMARY KEY(generation, path), FOREIGN KEY(generation) REFERENCES wiki_generations(generation) ON DELETE CASCADE) STRICT;
4
+ CREATE TABLE IF NOT EXISTS wiki_current (account TEXT PRIMARY KEY, generation TEXT NOT NULL, previous TEXT, pending INTEGER NOT NULL CHECK(pending IN (0,1)), FOREIGN KEY(generation) REFERENCES wiki_generations(generation)) STRICT;`);let a=n=>{e.exec("BEGIN IMMEDIATE");try{let c=n();return e.exec("COMMIT"),c}catch(c){try{e.exec("ROLLBACK")}catch{throw c}throw c}},i=(n,c)=>{if(!f.test(n)||!f.test(c)||!e.prepare("SELECT 1 FROM wiki_sessions WHERE account=? AND session=?").get(n,c))throw new Error("Wiki session is not active")},s=(n,c,t)=>{if(i(n,c),!f.test(t)||!r(t,n,c,0))throw new Error("Wiki staging reservation is unavailable");let o=e.prepare("SELECT budget FROM wiki_generations WHERE generation=? AND account=? AND session=? AND generation NOT IN (SELECT generation FROM wiki_current) AND generation NOT IN (SELECT previous FROM wiki_current WHERE previous IS NOT NULL)").get(t,n,c);if(!o||typeof o.budget!="number")throw new Error("Wiki staging revision is unavailable");return o.budget};return{begin:(n,c,t,o)=>a(()=>{if(i(n,c),!f.test(t.generation)||!f.test(t.namespace)||!O.test(t.mcpId)||!O.test(t.etag)||!r(t.generation,n,c,o)||!Number.isSafeInteger(o)||o<0||o>le)throw new Error("Invalid wiki staging revision");let p=!!e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='wiki_snapshots'").get()?Number(e.prepare("SELECT COALESCE(SUM(length(content)),0) AS bytes FROM wiki_snapshots").get()?.bytes):0,u=Number(e.prepare("SELECT COALESCE(SUM(budget),0) AS bytes FROM wiki_generations").get()?.bytes)+p;if(!Number.isSafeInteger(u)||u+o>d)throw new Error("Wiki row capacity exceeded");if(Number(e.prepare("SELECT COUNT(*) AS count FROM wiki_generations").get()?.count)>=16)throw new Error("Wiki row capacity exceeded");e.prepare("INSERT INTO wiki_generations(generation, account, session, namespace, mcp_id, etag, budget) VALUES (?, ?, ?, ?, ?, ?, ?)").run(t.generation,n,c,t.namespace,t.mcpId.toLowerCase(),t.etag.toLowerCase(),o)}),put:(n,c,t,o,l,p)=>a(()=>{let u=s(n,c,t);if(A(o),!(l instanceof Uint8Array)||l.byteLength>G||!f.test(p)||(0,j.createHash)("sha256").update(l).digest("hex")!==p)throw new Error("Invalid wiki file");let h=e.prepare("SELECT COUNT(*) AS count, COALESCE(SUM(length(data)), 0) AS bytes FROM wiki_files WHERE generation=?").get(t);if(Number(h?.count)>=ue||Number(h?.bytes)+l.byteLength>u)throw new Error("Wiki staging capacity exceeded");e.prepare("INSERT INTO wiki_files(generation, path, data, digest) VALUES (?, ?, ?, ?)").run(t,o,l,p)}),activate:(n,c,t)=>a(()=>{s(n,c,t);let o=e.prepare("SELECT generation, pending FROM wiki_current WHERE account=?").get(n);if(o&&o.pending!==0)throw new Error("Wiki revision switch is incomplete");let l=typeof o?.generation=="string"?o.generation:null,p=Number(e.prepare("SELECT COALESCE(SUM(length(data)),0) AS bytes FROM wiki_files WHERE generation=?").get(t)?.bytes);if(!Number.isSafeInteger(p)||p<0||p>le)throw new Error("Invalid wiki revision size");e.prepare("UPDATE wiki_generations SET budget=? WHERE generation=?").run(p,t),e.prepare("INSERT INTO wiki_current(account, generation, previous, pending) VALUES (?, ?, ?, 1) ON CONFLICT(account) DO UPDATE SET generation=excluded.generation, previous=excluded.previous, pending=1").run(n,t,l)}),finalize:(n,c,t)=>a(()=>{if(i(n,c),!f.test(t)||!r(t,n,c,0))throw new Error("Wiki staging reservation is unavailable");let o=e.prepare("SELECT previous FROM wiki_current WHERE account=? AND generation=? AND pending=1").get(n,t);if(!o)throw new Error("Wiki revision switch changed");e.prepare("UPDATE wiki_current SET previous=NULL, pending=0 WHERE account=? AND generation=?").run(n,t),typeof o.previous=="string"&&e.prepare("DELETE FROM wiki_generations WHERE generation=? AND account=?").run(o.previous,n)}),discard:(n,c,t)=>a(()=>{if(i(n,c),!f.test(t)||!r(t,n,c,0))throw new Error("Wiki staging reservation is unavailable");if(!e.prepare("SELECT 1 FROM wiki_generations WHERE generation=? AND account=? AND session=?").get(t,n,c))throw new Error("Wiki staging revision is unavailable");M(e,t)}),revoke:(n,c,t,o)=>a(()=>{if(i(n,c),!O.test(t)||!f.test(o))throw new Error("Invalid wiki source");let l=e.prepare("SELECT c.generation, c.previous, c.pending, g.mcp_id FROM wiki_current c JOIN wiki_generations g ON g.generation=c.generation WHERE c.account=?").get(n);if(l&&l.pending!==0)throw new Error("Wiki revision switch is incomplete");return!l||l.generation!==o||l.mcp_id!==t.toLowerCase()?!1:(e.prepare("DELETE FROM wiki_current WHERE account=?").run(n),e.prepare("DELETE FROM wiki_generations WHERE account=? AND mcp_id=? AND generation NOT IN (SELECT generation FROM wiki_current) AND generation NOT IN (SELECT previous FROM wiki_current WHERE previous IS NOT NULL)").run(n,t.toLowerCase()),!0)}),current:(n,c)=>a(()=>{i(n,c);let t=e.prepare("SELECT g.generation, g.namespace, g.mcp_id, g.etag FROM wiki_current c JOIN wiki_generations g ON g.generation=c.generation WHERE c.account=? AND c.pending=0").get(n);if(t){if(typeof t.generation!="string"||!f.test(t.generation)||typeof t.namespace!="string"||!f.test(t.namespace)||typeof t.mcp_id!="string"||!O.test(t.mcp_id)||typeof t.etag!="string"||!O.test(t.etag))throw new Error("Invalid wiki revision");return{generation:t.generation,namespace:t.namespace,mcpId:t.mcp_id,etag:t.etag}}}),list:(n,c,t)=>a(()=>{if(i(n,c),!f.test(t)||!e.prepare("SELECT 1 FROM wiki_current WHERE account=? AND ((generation=? AND pending=0) OR (previous=? AND pending=1))").get(n,t,t))throw new Error("Wiki revision changed");let o=e.prepare("SELECT path FROM wiki_files WHERE generation=? ORDER BY path").all(t);if(o.length>ue)throw new Error("Invalid wiki inventory");return o.map(l=>{if(typeof l.path!="string")throw new Error("Invalid wiki inventory");return A(l.path),l.path})}),read:(n,c,t,o,l)=>a(()=>{if(i(n,c),A(o),!f.test(t)||!e.prepare("SELECT 1 FROM wiki_current WHERE account=? AND ((generation=? AND pending=0) OR (previous=? AND pending=1))").get(n,t,t))throw new Error("Wiki revision changed");if(!f.test(l)||!r(l,n,c,G))throw new Error("Wiki read reservation is unavailable");let p=e.prepare("SELECT length(data) AS size, digest FROM wiki_files WHERE generation=? AND path=?").get(t,o);if(!p)return;if(typeof p.size!="number"||!Number.isSafeInteger(p.size)||p.size<0||p.size>G||typeof p.digest!="string"||!f.test(p.digest))throw new Error("Invalid wiki file");let u=e.prepare("SELECT data FROM wiki_files WHERE generation=? AND path=?").get(t,o)?.data;if(!(u instanceof Uint8Array)||u.byteLength!==p.size||(0,j.createHash)("sha256").update(u).digest("hex")!==p.digest)throw new Error("Invalid wiki file");return u})}}var he=require("node:sqlite"),me=require("node:path"),v=require("node:fs"),ge=512*1024*1024,ye=16,L=/^[a-f0-9]{64}$/u;function Ee(e,r,d=ge){if(!Number.isSafeInteger(d)||d<0||d>ge)throw new Error("Invalid wiki reservation limit");e.exec("CREATE TABLE IF NOT EXISTS wiki_reservations (slot INTEGER PRIMARY KEY, id TEXT NOT NULL UNIQUE, bytes INTEGER NOT NULL, device TEXT NOT NULL, inode TEXT NOT NULL) STRICT;");let a=new Map,i=t=>{e.exec("BEGIN IMMEDIATE");try{let o=t();return e.exec("COMMIT"),o}catch(o){try{e.exec("ROLLBACK")}catch{throw o}throw o}},s=(t,o)=>{let l=(0,me.join)(r,`reservation-${t}.sqlite`);if(!o)try{(0,v.writeFileSync)(l,"",{flag:"wx",mode:384})}catch(g){if(!(g instanceof Error)||!("code"in g)||g.code!=="EEXIST")throw g}let p=(0,v.lstatSync)(l,{bigint:!0});if(!p.isFile()||p.isSymbolicLink()||p.uid!==BigInt(process.getuid())||p.nlink!==1n||(p.mode&0o077n)!==0n)throw new Error("Wiki reservation lock is not private");let u=String(p.dev),h=String(p.ino);if(o&&(o.device!==u||o.inode!==h))throw new Error("Wiki reservation lock changed");let T=new he.DatabaseSync(l);try{let g=(0,v.lstatSync)(l,{bigint:!0});if(!g.isFile()||g.dev!==p.dev||g.ino!==p.ino)throw new Error("Wiki reservation lock changed");return T.exec("PRAGMA busy_timeout=0; BEGIN IMMEDIATE;"),{connection:T,device:u,inode:h}}catch(g){throw T.close(),g}},n=t=>typeof t=="object"&&t!==null&&"errcode"in t&&typeof t.errcode=="number"&&((t.errcode&255)===5||(t.errcode&255)===6),c=()=>{let t=e.prepare("SELECT slot, id, bytes, device, inode FROM wiki_reservations").all();for(let o of t){if(typeof o.slot!="number"||!Number.isInteger(o.slot)||o.slot<0||o.slot>=ye||typeof o.id!="string"||!L.test(o.id)||typeof o.bytes!="number"||!Number.isSafeInteger(o.bytes)||o.bytes<0||o.bytes>d||typeof o.device!="string"||typeof o.inode!="string")throw new Error("Invalid wiki reservations");try{let l=s(o.slot,{device:o.device,inode:o.inode});try{e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='wiki_generations'").get()&&M(e,o.id),e.prepare("DELETE FROM wiki_reservations WHERE slot = ? AND id = ?").run(o.slot,o.id)}finally{l.connection.close()}}catch(l){if(!n(l))throw l}}};return{reserve:(t,o,l,p)=>{if(!L.test(l)||!L.test(p)||!L.test(t)||!Number.isSafeInteger(o)||o<0||o>d||a.has(t))throw new Error("Invalid wiki reservation");let u;try{i(()=>{if(!e.prepare("SELECT 1 FROM wiki_sessions WHERE account = ? AND session = ?").get(l,p))throw new Error("Wiki session is not active");c();let h=e.prepare("SELECT slot, bytes FROM wiki_reservations").all(),T=h.reduce((x,b)=>x+Number(b.bytes),0),Ie=!!e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='wiki_snapshots'").get()?Number(e.prepare("SELECT COALESCE(SUM(length(content)),0) AS bytes FROM wiki_snapshots").get()?.bytes):0,Ae=!!e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='wiki_generations'").get()?Number(e.prepare("SELECT COALESCE(SUM(g.budget),0) AS bytes FROM wiki_generations g WHERE NOT EXISTS (SELECT 1 FROM wiki_reservations r WHERE r.id=g.generation)").get()?.bytes):0,D=T+Ie+Ae;if(!Number.isSafeInteger(D)||D<0||D+o>d)throw new Error("Wiki reservation capacity exceeded");let P=Array.from({length:ye},(x,b)=>b).find(x=>!h.some(b=>b.slot===x));if(P===void 0)throw new Error("Wiki reservation capacity exceeded");let W=s(P);u=W.connection,e.prepare("INSERT INTO wiki_reservations(slot, id, bytes, device, inode) VALUES (?, ?, ?, ?, ?)").run(P,t,o,W.device,W.inode)}),a.set(t,{connection:u,account:l,session:p,bytes:o})}catch(h){throw u?.close(),h}},recover:()=>i(c),owns:(t,o,l,p)=>{let u=a.get(t);return!!u&&u.account===o&&u.session===l&&Number.isSafeInteger(p)&&p>=0&&u.bytes>=p},release:t=>{let o=a.get(t);if(!o)throw new Error("Wiki reservation is not owned");i(()=>{e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='wiki_generations'").get()&&M(e,t);let l=e.prepare("DELETE FROM wiki_reservations WHERE id = ?").run(t);if(Number(l.changes)!==1)throw new Error("Wiki reservation changed")}),a.delete(t),o.connection.close()},close:()=>{for(let t of a.values())t.connection.close();a.clear()}}}var we=require("node:sqlite"),F=require("node:fs"),Re=require("node:path");function Se(e,r){e.exec("CREATE TABLE IF NOT EXISTS wiki_join_gate (singleton INTEGER PRIMARY KEY CHECK(singleton=1), device TEXT NOT NULL, inode TEXT NOT NULL) STRICT;");let d=(0,Re.join)(r,"join-gate.sqlite"),a,i=()=>{let n=(0,F.lstatSync)(d,{bigint:!0});if(!n.isFile()||n.isSymbolicLink()||n.uid!==BigInt(process.getuid())||n.nlink!==1n||(n.mode&0o077n)!==0n)throw new Error("Wiki join gate is not private");return{device:String(n.dev),inode:String(n.ino)}},s=()=>{if(!a)throw new Error("Wiki join gate is not held");let n=a;a=void 0,n.close()};return{acquire:()=>{if(a)throw new Error("Wiki join gate is already held");e.exec("BEGIN IMMEDIATE");let n;try{let c=e.prepare("SELECT device, inode FROM wiki_join_gate WHERE singleton=1").get();if(!c)try{(0,F.writeFileSync)(d,"",{flag:"wx",mode:384})}catch(l){if(!(l instanceof Error)||!("code"in l)||l.code!=="EEXIST")throw l}let t=i();if(c&&(c.device!==t.device||c.inode!==t.inode))throw new Error("Wiki join gate changed");n=new we.DatabaseSync(d);let o=i();if(t.device!==o.device||t.inode!==o.inode)throw new Error("Wiki join gate changed");n.exec("PRAGMA busy_timeout=0; BEGIN IMMEDIATE;"),c||e.prepare("INSERT INTO wiki_join_gate(singleton, device, inode) VALUES (1, ?, ?)").run(t.device,t.inode),e.exec("COMMIT"),a=n}catch(c){throw e.exec("ROLLBACK"),n?.close(),c}},release:s,close:()=>{a&&s()}}}function Te(e,r,d){return k(async()=>{let a=await e();try{let i=Y(a);return d?.(a),{db:a,store:i}}catch(i){throw a.close(),i}},r)}if(!K.parentPort)throw new Error("Wiki storage worker has no parent");var S=K.parentPort,be=(async()=>{let e=await N(),r,d,a;return{...await Te(()=>Q(),void 0,s=>{r=Ee(s,e),d=Se(s,e),a=fe(s,(n,c,t,o)=>r.owns(n,c,t,o))}),reservations:r,gate:d,rows:a}})().then(e=>e,()=>{}),V=Promise.resolve(),ke=!1;S.on("message",e=>{V=V.then(async()=>{try{let r=await be;if(!r)throw new Error("Wiki storage is unavailable");let{store:d}=r,{id:a,operation:i,account:s,session:n,content:c}=e;if(i==="close"){r.reservations.close(),r.gate.close(),r.db.close(),ke=!0,S.close();return}if(i==="acquireGate"||i==="releaseGate"){await k(()=>{i==="acquireGate"?r.gate.acquire():r.gate.release()}),S.postMessage({id:a,result:!0});return}if(!Number.isSafeInteger(a)||typeof s!="string"||typeof n!="string")throw new Error("Invalid wiki storage request");let t=await k(()=>{if(i==="reserve"&&typeof e.reservation=="string"&&typeof e.bytes=="number")return r.reservations.reserve(e.reservation,e.bytes,s,n),!0;if(i==="release"&&typeof e.reservation=="string")return r.reservations.release(e.reservation),!0;if(i==="beginRows"&&e.revision&&typeof e.bytes=="number")return r.rows.begin(s,n,e.revision,e.bytes),!0;if(i==="putRow"&&typeof e.reservation=="string"&&typeof e.path=="string"&&typeof e.digest=="string"&&c instanceof Uint8Array)return r.rows.put(s,n,e.reservation,e.path,c,e.digest),!0;if(i==="activateRows"&&typeof e.reservation=="string")return r.rows.activate(s,n,e.reservation),!0;if(i==="finalizeRows"&&typeof e.reservation=="string")return r.rows.finalize(s,n,e.reservation),!0;if(i==="discardRows"&&typeof e.reservation=="string")return r.rows.discard(s,n,e.reservation),!0;if(i==="revokeRows"&&typeof e.newSession=="string"&&typeof e.reservation=="string")return r.reservations.recover(),r.rows.revoke(s,n,e.newSession,e.reservation);if(i==="currentRows")return r.reservations.recover(),r.rows.current(s,n);if(i==="listRows"&&typeof e.reservation=="string")return r.rows.list(s,n,e.reservation);if(i==="readRow"&&typeof e.reservation=="string"&&typeof e.path=="string"&&typeof e.newSession=="string")return r.rows.read(s,n,e.reservation,e.path,e.newSession);if(i==="register")return d.register(s,n);if(i==="join"&&typeof e.newSession=="string")return d.join(s,n,e.newSession);if(i==="otherSession")return d.otherSession(s,n);if(i==="isActive")return d.isActive(s,n);if(i==="logout")return d.logout(s,n);throw new Error("Invalid wiki storage request")});S.postMessage({id:a,result:t})}catch(r){S.postMessage({id:e.id,error:"Wiki storage operation failed",errorCode:B(r)})}})});S.on("close",()=>{V.then(()=>be).then(e=>{e&&!ke&&(e.reservations.close(),e.gate.close(),e.db.close())},()=>{})});
@@ -1,13 +1,17 @@
1
1
  import { type AgentSession, type ProjectIdentity } from '@beehexa/hexasync-template-agent-core';
2
2
  import { type StdioServerHandle } from '@modelcontextprotocol/server/stdio';
3
3
  import type { ServerBuildIdentity } from './buildIdentity.node.js';
4
- import { type AgentToolFailure, type AgentToolResult } from '@beehexa/hexasync-template-validate';
4
+ import { type AgentToolFailure, type AgentToolResult, type AgentSharedKnowledgeSnapshot } from '@beehexa/hexasync-template-validate';
5
5
  type ExpectedLaunchProject = Pick<ProjectIdentity, 'componentUri' | 'descriptorUri' | 'detectorType'>;
6
6
  /** Genuine pre-envelope invocation used by the packaged server. */
7
- export declare function answerMcpTool(name: string, args: Record<string, unknown>, roots: readonly string[], _version: string, signal: AbortSignal, rootFailure?: AgentToolFailure, session?: AgentSession, expectedProject?: ExpectedLaunchProject): Promise<AgentToolResult>;
7
+ export declare function answerMcpTool(name: string, args: Record<string, unknown>, roots: readonly string[], _version: string, signal: AbortSignal, rootFailure?: AgentToolFailure, session?: AgentSession, expectedProject?: ExpectedLaunchProject, selectedKnowledge?: McpSelectedKnowledgePort): Promise<AgentToolResult>;
8
8
  export interface McpDiagnosticPort {
9
9
  report(code: 'MCP_TRANSPORT_FAILURE'): void;
10
10
  }
11
- export declare function startMcpServer(argv: readonly string[], version: string, diagnostics?: McpDiagnosticPort, buildIdentity?: ServerBuildIdentity): Promise<StdioServerHandle>;
11
+ /** Provider returns an authorized, revision-fenced snapshot; absent means no selected shared source. */
12
+ export interface McpSelectedKnowledgePort {
13
+ snapshot(signal: AbortSignal): Promise<AgentSharedKnowledgeSnapshot | undefined>;
14
+ }
15
+ export declare function startMcpServer(argv: readonly string[], version: string, diagnostics?: McpDiagnosticPort, buildIdentity?: ServerBuildIdentity, selectedKnowledge?: McpSelectedKnowledgePort, onClose?: () => void): Promise<StdioServerHandle>;
12
16
  export {};
13
17
  //# sourceMappingURL=mcpServer.node.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcpServer.node.d.ts","sourceRoot":"","sources":["../src/mcpServer.node.ts"],"names":[],"mappings":"AAKA,OAAO,EACS,KAAK,YAAY,EAAE,KAAK,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAYvG,OAAO,EAAc,KAAK,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAExF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AACnE,OAAO,EAcL,KAAK,gBAAgB,EACrB,KAAK,eAAe,EAErB,MAAM,qCAAqC,CAAC;AAmD7C,KAAK,qBAAqB,GAAG,IAAI,CAAC,eAAe,EAAE,cAAc,GAAG,eAAe,GAAG,cAAc,CAAC,CAAC;AAoQtG,mEAAmE;AACnE,wBAAsB,aAAa,CACjC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,WAAW,EACnB,WAAW,CAAC,EAAE,gBAAgB,EAC9B,OAAO,CAAC,EAAE,YAAY,EACtB,eAAe,CAAC,EAAE,qBAAqB,GACtC,OAAO,CAAC,eAAe,CAAC,CAqB1B;AAGD,MAAM,WAAW,iBAAiB;IAAG,MAAM,CAAC,IAAI,EAAE,uBAAuB,GAAG,IAAI,CAAA;CAAE;AAClF,wBAAsB,cAAc,CAClC,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,OAAO,EAAE,MAAM,EACf,WAAW,CAAC,EAAE,iBAAiB,EAC/B,aAAa,CAAC,EAAE,mBAAmB,GAClC,OAAO,CAAC,iBAAiB,CAAC,CA2M5B"}
1
+ {"version":3,"file":"mcpServer.node.d.ts","sourceRoot":"","sources":["../src/mcpServer.node.ts"],"names":[],"mappings":"AAOA,OAAO,EACS,KAAK,YAAY,EAAE,KAAK,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAYvG,OAAO,EAAc,KAAK,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAExF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AACnE,OAAO,EAcL,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,4BAA4B,EAElC,MAAM,qCAAqC,CAAC;AAyE7C,KAAK,qBAAqB,GAAG,IAAI,CAAC,eAAe,EAAE,cAAc,GAAG,eAAe,GAAG,cAAc,CAAC,CAAC;AA2TtG,mEAAmE;AACnE,wBAAsB,aAAa,CACjC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,WAAW,EACnB,WAAW,CAAC,EAAE,gBAAgB,EAC9B,OAAO,CAAC,EAAE,YAAY,EACtB,eAAe,CAAC,EAAE,qBAAqB,EACvC,iBAAiB,CAAC,EAAE,wBAAwB,GAC3C,OAAO,CAAC,eAAe,CAAC,CAwB1B;AAGD,MAAM,WAAW,iBAAiB;IAAG,MAAM,CAAC,IAAI,EAAE,uBAAuB,GAAG,IAAI,CAAA;CAAE;AAClF,wGAAwG;AACxG,MAAM,WAAW,wBAAwB;IAAG,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,4BAA4B,GAAG,SAAS,CAAC,CAAA;CAAE;AAC9H,wBAAsB,cAAc,CAClC,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,OAAO,EAAE,MAAM,EACf,WAAW,CAAC,EAAE,iBAAiB,EAC/B,aAAa,CAAC,EAAE,mBAAmB,EACnC,iBAAiB,CAAC,EAAE,wBAAwB,EAC5C,OAAO,CAAC,EAAE,MAAM,IAAI,GACnB,OAAO,CAAC,iBAAiB,CAAC,CAuN5B"}
@@ -1,7 +1,9 @@
1
+ import { listWikiResources, readWikiResource } from './wikiResources.node.js';
1
2
  /** The sole portable Template IDE MCP composition: one contract and one dual-era stdio lifecycle. */
2
3
  import { relative, resolve, sep, delimiter, isAbsolute } from 'node:path';
3
4
  import { fileURLToPath, pathToFileURL } from 'node:url';
4
5
  import { DEFAULT_IGNORED_PATH_SEGMENTS, detectorFor, describeFailure, locateComposedFrontendField } from '@beehexa/hexasync-template-index';
6
+ import { CONNECTOR_WORKFLOW_KEYS, FRONTEND_WORKFLOW_KEYS } from '@beehexa/hexasync-template-frontend-flow';
5
7
  import { nodeTemplateReader, nodeRootAuthorityPort, nodeProjectDiscoveryPort } from '@beehexa/hexasync-template-io-node';
6
8
  import { resolveRootSet, selectRootProject, createAgentSession, rootFailure, projectWorkspaceText } from '@beehexa/hexasync-template-agent-core';
7
9
  import { composeProject, readerResolverIO, seedRootMainEvents } from '@beehexa/hexasync-template-compose';
@@ -19,55 +21,74 @@ const PROJECT_IGNORED_PATH_SEGMENTS = [...DEFAULT_IGNORED_PATH_SEGMENTS, '.hexas
19
21
  * The connector catalog the extension ships, through the model's one catalog parser, with the overlay schema's
20
22
  * entry definition an authored `hexasync-connectors.json` row is held to.
21
23
  *
22
- * Bundled rather than read from a Root: it is product data, the same asset the editor's Problems panel judges with.
24
+ * Read from the selected wiki revision, or from the bundle when no wiki is selected, never from a Root.
23
25
  * Absent only when that asset is unusable — then `CONN-0` says the catalog checks were skipped, which is loud.
24
26
  */
25
- function shippedConnectorCatalog() {
27
+ async function shippedConnectorCatalog(selected) {
26
28
  try {
27
- const text = readBundledAgentKnowledge('connectors/catalog.json')?.text;
28
- const schemaText = readBundledAgentKnowledge('connectors/catalog.schema.json')?.text;
29
+ const text = selected ? await selected.read('connectors/catalog.json') : readBundledAgentKnowledge('connectors/catalog.json')?.text;
30
+ const schemaText = selected ? await selected.read('connectors/catalog.schema.json') : readBundledAgentKnowledge('connectors/catalog.schema.json')?.text;
29
31
  const catalog = text === undefined ? undefined : connectorCatalogOf(JSON.parse(text));
30
32
  const entrySchema = schemaText === undefined ? undefined : catalogEntrySchemaOf(JSON.parse(schemaText));
31
33
  return { ...(catalog === undefined ? {} : { catalog }), ...(entrySchema === undefined ? {} : { entrySchema }) };
32
34
  }
33
- catch {
35
+ catch (error) {
36
+ if (selected)
37
+ throw error;
34
38
  return {};
35
39
  }
36
40
  }
37
41
  const SCHEMA_ASSET_BASE = 'https://hexasync.local/assets/';
42
+ /** Resolve schema references within the selected revision or the bundle, without network access. */
43
+ async function loadSchemaAsset(uri, selected) {
44
+ if (!uri.startsWith(SCHEMA_ASSET_BASE))
45
+ throw new Error('Nonlocal schema reference.');
46
+ const path = uri.slice(SCHEMA_ASSET_BASE.length);
47
+ const text = selected ? await selected.read(path) : readBundledAgentKnowledge(path)?.text;
48
+ if (text === undefined)
49
+ throw new Error('Canonical frontend schema is missing.');
50
+ const schema = JSON.parse(text);
51
+ const refs = (node) => {
52
+ if (node === null || typeof node !== 'object')
53
+ return;
54
+ for (const [key, value] of Object.entries(node)) {
55
+ if (key === '$ref' && typeof value === 'string' && !value.startsWith('#')) {
56
+ node[key] = new URL(value.replace(/^file:/u, ''), uri).href;
57
+ }
58
+ else
59
+ refs(value);
60
+ }
61
+ };
62
+ refs(schema);
63
+ delete schema.$schema;
64
+ return { ...schema, $id: uri };
65
+ }
38
66
  let groupedSchema;
39
- /** Canonical bundled shape, with file/relative refs resolved locally. No network schema loader exists. */
40
- function groupedFrontendSchema() {
41
- return groupedSchema ??= (async () => {
42
- const load = async (uri) => {
43
- if (!uri.startsWith(SCHEMA_ASSET_BASE))
44
- throw new Error('Nonlocal schema reference.');
45
- const asset = readBundledAgentKnowledge(uri.slice(SCHEMA_ASSET_BASE.length));
46
- if (!asset)
47
- throw new Error('Canonical grouped frontend schema is missing.');
48
- const schema = JSON.parse(asset.text);
49
- const refs = (node) => {
50
- if (node === null || typeof node !== 'object')
51
- return;
52
- for (const [key, value] of Object.entries(node)) {
53
- if (key === '$ref' && typeof value === 'string' && !value.startsWith('#')) {
54
- node[key] = new URL(value.replace(/^file:/u, ''), uri).href;
55
- }
56
- else
57
- refs(value);
58
- }
59
- };
60
- refs(schema);
61
- delete schema.$schema;
62
- return { ...schema, $id: uri };
63
- };
67
+ /** Canonical `getReadyFlows` shape for the selected source. */
68
+ function groupedFrontendSchema(selected) {
69
+ const compile = async () => {
70
+ const load = (uri) => loadSchemaAsset(uri, selected);
64
71
  const main = await load(`${SCHEMA_ASSET_BASE}main.json`);
65
72
  const property = main['definitions']?.template?.properties?.getReadyFlows;
66
73
  if (property === undefined)
67
74
  throw new Error('Canonical grouped schema coverage is unavailable.');
68
75
  const ajv = new Ajv2020({ strict: false, allErrors: true, validateFormats: false, loadSchema: load });
69
76
  return ajv.compileAsync({ type: 'object', properties: { getReadyFlows: property } });
70
- })();
77
+ };
78
+ return selected ? compile() : groupedSchema ??= compile();
79
+ }
80
+ let workflowSchema;
81
+ /** Canonical direct workflow properties preserve declaration shape and per-workflow nullability. */
82
+ function frontendWorkflowSchema(selected) {
83
+ const compile = async () => {
84
+ const ajv = new Ajv2020({ strict: false, allErrors: true, validateFormats: false, loadSchema: (uri) => loadSchemaAsset(uri, selected) });
85
+ return ajv.compileAsync({ type: 'object', properties: Object.fromEntries(FRONTEND_WORKFLOW_KEYS.map((workflow) => [
86
+ workflow, { $ref: workflow === 'creationSteps'
87
+ ? `${SCHEMA_ASSET_BASE}frontend/templates/creationSteps.json`
88
+ : `${SCHEMA_ASSET_BASE}frontend/connectors/main.json#/properties/${workflow}` },
89
+ ])) });
90
+ };
91
+ return selected ? compile() : workflowSchema ??= compile();
71
92
  }
72
93
  /** Appended to every Root failure: standalone Clients often launch the server outside the project. */
73
94
  const ROOT_SELECTION_HINT = ' To select the project explicitly, add `--root <absolute project path>` to the MCP server args '
@@ -142,9 +163,10 @@ function projectSelectorUri(selector) {
142
163
  return undefined;
143
164
  }
144
165
  }
145
- function nodeHost(roots, callSignal, rootSet, rootFailure, session, expectedProject) {
166
+ function nodeHost(roots, callSignal, rootSet, rootFailure, session, expectedProject, selected) {
146
167
  return {
147
168
  ...createInstalledKnowledgeReader(roots, callSignal, rootSet, rootFailure),
169
+ ...(selected === undefined ? {} : { selectedKnowledge: () => selected }),
148
170
  rootAuthority: () => rootSet?.describe(),
149
171
  readBundled: async (relativePath) => readBundledAgentKnowledge(relativePath),
150
172
  knowledgeDocs: () => BUNDLED_KNOWLEDGE_DOCS,
@@ -221,7 +243,7 @@ function nodeHost(roots, callSignal, rootSet, rootFailure, session, expectedProj
221
243
  * "not in the catalog" here while the Problems panel catalogued it. Absent is ordinary and silent; a file that
222
244
  * cannot be read, or whose rows were skipped, is named — the verdicts then rest on less than the author declared.
223
245
  */
224
- const shipped = shippedConnectorCatalog();
246
+ const shipped = await shippedConnectorCatalog(selected);
225
247
  let connectorCatalog = shipped.catalog;
226
248
  const rootUri = rootSet.roots.find((candidate) => candidate.id === project.rootId)?.uri;
227
249
  const overlayUri = rootUri === undefined ? undefined : joinUri(rootUri, WORKSPACE_CATALOG_FILE);
@@ -247,6 +269,7 @@ function nodeHost(roots, callSignal, rootSet, rootFailure, session, expectedProj
247
269
  const componentPath = project.componentUri;
248
270
  const rootMainPath = joinUri(componentPath, 'main.yaml');
249
271
  let findings = [];
272
+ let frontendValidationIncomplete = false;
250
273
  try {
251
274
  const mainYml = await reader.read(rootMainPath);
252
275
  if (mainYml === undefined)
@@ -274,48 +297,108 @@ function nodeHost(roots, callSignal, rootSet, rootFailure, session, expectedProj
274
297
  relative: relativeUri,
275
298
  connectorCatalog,
276
299
  });
277
- findings = locateValidationIssues(runValidation(context), context, result.sources).map(({ issue, file, line }) => ({
278
- ruleId: issue.ruleId,
279
- // Rule messages quote authored values; the same projection every agent-bound workspace text gets.
280
- message: projectWorkspaceText(issue.message, 'markdown') === '[REDACTED]'
300
+ const issues = await runValidation(context, undefined, { signal });
301
+ frontendValidationIncomplete = issues.some((issue) => issue.ruleId === 'FFE-0');
302
+ findings = locateValidationIssues(issues, context, result.sources).map(({ issue, file, line, range }) => {
303
+ const message = projectWorkspaceText(issue.message, 'markdown') === '[REDACTED]'
281
304
  ? `${issue.ruleId} message withheld: it quotes workspace content that may be sensitive or executable. Open the file at this line.`
282
- : issue.message,
283
- sourceFile: relativeFile(file),
284
- line: line ?? 0,
285
- }));
305
+ : issue.message;
306
+ return {
307
+ ruleId: issue.ruleId,
308
+ // Rule messages quote authored values; the same projection every agent-bound workspace text gets.
309
+ // An unlocated FFE finding names main.yaml only as a fallback, so say so as the editor does; a finding with
310
+ // no authored field (FFE-0, the rule-crash notice) is not missing a location (findingsFromIssues.ts).
311
+ message: issue.family === 'FFE' && issue.componentPath && range === undefined
312
+ ? `${message} Authored field location unavailable.` : message,
313
+ sourceFile: relativeFile(file),
314
+ line: line ?? 0,
315
+ };
316
+ });
317
+ /** One JSON Schema finding per Ajv leaf, located on its authored field exactly as semantic findings are. */
318
+ const schemaFindings = (errors, label, prefix) => {
319
+ for (const error of errors ?? []) {
320
+ // allErrors reports every failing `then` leaf beside an `if` cascade error on the step; the leaf is the finding.
321
+ if (error.keyword === 'if')
322
+ continue;
323
+ const path = [...prefix.map(String), ...error.instancePath.split('/').slice(1).map((part) => part.replace(/~1/gu, '/').replace(/~0/gu, '~'))];
324
+ const missing = error.keyword === 'required' ? error.params['missingProperty']
325
+ : error.keyword === 'additionalProperties' ? error.params['additionalProperty'] : undefined;
326
+ if (typeof missing === 'string')
327
+ path.push(missing);
328
+ // Missing properties attach to their nearest existing parent, exactly as semantic findings do.
329
+ let value = result.tokenForm;
330
+ const existing = [];
331
+ for (const segment of path) {
332
+ const key = Array.isArray(value) && /^\d+$/u.test(segment) ? Number(segment) : segment;
333
+ if (value === null || typeof value !== 'object' || !Object.hasOwn(value, key))
334
+ break;
335
+ existing.push(key);
336
+ value = Reflect.get(value, key);
337
+ }
338
+ const location = locateComposedFrontendField({ document: result.tokenForm, path: existing,
339
+ rootFile: rootMainPath, sources: result.sources, worklist: result.worklist });
340
+ const message = `${label} schema ${error.keyword} at ${path.join('.')}: ${error.message ?? 'invalid value'}`;
341
+ const projected = projectWorkspaceText(message, 'markdown') === '[REDACTED]' ? 'JSON Schema finding withheld: open the source field to inspect sensitive authored content.' : message;
342
+ findings.push({ ruleId: 'JSON Schema',
343
+ // Unlocated, main.yaml is only a fallback: state the limitation as unlocated FFE findings do.
344
+ message: location ? projected : `${projected} Authored field location unavailable.`,
345
+ sourceFile: relativeFile(location?.file ?? rootMainPath), line: location ? location.range.start.line + 1 : 0 });
346
+ }
347
+ };
286
348
  if (result.tokenForm && Object.hasOwn(result.tokenForm, 'getReadyFlows')) {
287
349
  try {
288
- const validate = await groupedFrontendSchema();
350
+ const validate = await groupedFrontendSchema(selected);
289
351
  validate(result.tokenForm);
290
- for (const error of validate.errors ?? []) {
291
- const path = error.instancePath.split('/').slice(1).map((part) => part.replace(/~1/gu, '/').replace(/~0/gu, '~'));
292
- const missing = error.keyword === 'required' ? error.params['missingProperty']
293
- : error.keyword === 'additionalProperties' ? error.params['additionalProperty'] : undefined;
294
- if (typeof missing === 'string')
295
- path.push(missing);
296
- // Missing properties attach to their nearest existing parent, exactly as semantic findings do.
297
- let value = result.tokenForm;
298
- const existing = [];
299
- for (const segment of path) {
300
- const key = Array.isArray(value) && /^\d+$/u.test(segment) ? Number(segment) : segment;
301
- if (value === null || typeof value !== 'object' || !Object.hasOwn(value, key))
302
- break;
303
- existing.push(key);
304
- value = Reflect.get(value, key);
305
- }
306
- const location = locateComposedFrontendField({ document: result.tokenForm, path: existing,
307
- rootFile: rootMainPath, sources: result.sources, worklist: result.worklist });
308
- const message = `getReadyFlows schema ${error.keyword} at ${path.join('.')}: ${error.message ?? 'invalid value'}`;
309
- findings.push({ ruleId: 'JSON Schema',
310
- message: projectWorkspaceText(message, 'markdown') === '[REDACTED]' ? 'JSON Schema finding withheld: open the source field to inspect sensitive authored content.' : message,
311
- sourceFile: relativeFile(location?.file ?? rootMainPath), line: location ? location.range.start.line + 1 : 0 });
312
- }
352
+ schemaFindings(validate.errors, 'getReadyFlows', []);
313
353
  }
314
354
  catch {
315
- unavailable.set('frontend-schema', { file: 'frontend/templates/getReadyFlows.json', reason: 'open-failed',
355
+ // Unavailable entries name Project documents: the file holding getReadyFlows, which semantic rules checked
356
+ // but no JSON Schema did — never the bundled asset path, which no workspace contains.
357
+ const source = locateComposedFrontendField({ document: result.tokenForm, path: ['getReadyFlows'],
358
+ rootFile: rootMainPath, sources: result.sources, worklist: result.worklist });
359
+ unavailable.set('frontend-schema', { file: relativeFile(source?.file ?? rootMainPath), reason: 'schema-uncovered',
316
360
  detail: 'Canonical grouped frontend schema coverage is unavailable. Semantic findings alone cannot certify shape validity.' });
317
361
  }
318
362
  }
363
+ // Validate raw registered declarations, not drawable graph locations: malformed values and owners without
364
+ // addressable ids still need schema coverage. Never search nested user payloads for workflow-like names.
365
+ const workflows = [];
366
+ const declared = (owner, path, keys) => {
367
+ if (owner === null || typeof owner !== 'object' || Array.isArray(owner))
368
+ return;
369
+ for (const workflow of keys) {
370
+ if (Object.hasOwn(owner, workflow))
371
+ workflows.push({ workflow, steps: Reflect.get(owner, workflow), stepsPath: [...path, workflow] });
372
+ }
373
+ };
374
+ declared(result.tokenForm, [], FRONTEND_WORKFLOW_KEYS);
375
+ for (const collection of ['connectors', 'connections']) {
376
+ const owners = result.tokenForm?.[collection];
377
+ if (!Array.isArray(owners))
378
+ continue;
379
+ owners.forEach((owner, index) => declared(owner, [collection, index], collection === 'connectors' ? CONNECTOR_WORKFLOW_KEYS : ['setupSteps']));
380
+ }
381
+ if (workflows.length > 0) {
382
+ let validate;
383
+ try {
384
+ validate = await frontendWorkflowSchema(selected);
385
+ }
386
+ catch {
387
+ validate = undefined;
388
+ }
389
+ for (const location of workflows) {
390
+ if (validate) {
391
+ validate({ [location.workflow]: location.steps });
392
+ schemaFindings(validate.errors, location.workflow, location.stepsPath.slice(0, -1));
393
+ continue;
394
+ }
395
+ const source = locateComposedFrontendField({ document: result.tokenForm, path: location.stepsPath,
396
+ rootFile: rootMainPath, sources: result.sources, worklist: result.worklist });
397
+ const at = location.stepsPath.join('.');
398
+ unavailable.set(`frontend-schema:${at}`, { file: relativeFile(source?.file ?? rootMainPath), reason: 'schema-uncovered',
399
+ detail: `Canonical frontend Step schema coverage is unavailable for workflow \`${at}\`; only semantic rules checked it, so its shape is not certified.` });
400
+ }
401
+ }
319
402
  }
320
403
  catch (error) {
321
404
  if (signal.aborted)
@@ -343,9 +426,9 @@ function nodeHost(roots, callSignal, rootSet, rootFailure, session, expectedProj
343
426
  findings,
344
427
  scope: {
345
428
  kind: 'composed-project',
346
- completeness: unavailable.size > 0 ? 'incomplete' : 'complete',
429
+ completeness: frontendValidationIncomplete || unavailable.size > 0 ? 'incomplete' : 'complete',
347
430
  description: AGENT_COMPOSED_PROJECT_SCOPE_DESCRIPTION +
348
- ' Shared semantic rules execute; getReadyFlows additionally uses the canonical bundled JSON Schema. Other JSON Schema coverage, dynamic expression results, browser execution, event authorization and delivery are not certified.',
431
+ ' Shared semantic rules execute; a failed frontend rule makes coverage incomplete even when its notice is filtered or paged out. getReadyFlows additionally uses the canonical bundled JSON Schema, and every other frontend workflow (creation, setup, connection or connector steps) is held to the canonical frontend Step schema. A frontend workflow whose schema cannot be compiled is listed as schema-uncovered and makes the scope incomplete. Other JSON Schema coverage, dynamic expression results, browser execution, event authorization and delivery are not certified.',
349
432
  },
350
433
  unavailableFiles: [...unavailable.values()].sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0),
351
434
  discoveryIncomplete: false,
@@ -354,7 +437,7 @@ function nodeHost(roots, callSignal, rootSet, rootFailure, session, expectedProj
354
437
  };
355
438
  }
356
439
  /** Genuine pre-envelope invocation used by the packaged server. */
357
- export async function answerMcpTool(name, args, roots, _version, signal, rootFailure, session, expectedProject) {
440
+ export async function answerMcpTool(name, args, roots, _version, signal, rootFailure, session, expectedProject, selectedKnowledge) {
358
441
  try {
359
442
  const cancelled = () => agentToolFailure({
360
443
  code: AGENT_TOOL_FAILURE_CODES.discoveryCancelled, message: 'The request was cancelled before its answer could be published.',
@@ -363,7 +446,10 @@ export async function answerMcpTool(name, args, roots, _version, signal, rootFai
363
446
  return cancelled();
364
447
  const outcome = session?.context.roots ?? await resolveRootSet({ launch: roots.map((root) => pathToFileURL(root).href) }, nodeRootAuthorityPort(), signal);
365
448
  const failure = rootFailure ?? (outcome.status === 'failed' ? { code: toolRootCode(outcome.code), message: outcome.message } : undefined);
366
- const invoke = async () => answerAgentTool(name, args, nodeHost(roots, session ? AbortSignal.any([signal, session.context.signal]) : signal, outcome.status === 'ready' ? outcome.rootSet : undefined, failure, session, expectedProject));
449
+ const selected = await selectedKnowledge?.snapshot(signal);
450
+ if (signal.aborted)
451
+ return cancelled();
452
+ const invoke = async () => answerAgentTool(name, args, nodeHost(roots, session ? AbortSignal.any([signal, session.context.signal]) : signal, outcome.status === 'ready' ? outcome.rootSet : undefined, failure, session, expectedProject, selected));
367
453
  const answer = session ? await session.run(invoke) : await invoke();
368
454
  if ('status' in answer)
369
455
  return agentToolFailure({ code: AGENT_TOOL_FAILURE_CODES.preparationIncomplete, message: answer.message });
@@ -371,14 +457,16 @@ export async function answerMcpTool(name, args, roots, _version, signal, rootFai
371
457
  return cancelled();
372
458
  return answer;
373
459
  }
374
- catch {
460
+ catch (error) {
461
+ if (error instanceof AgentToolPreconditionError)
462
+ return agentToolFailure(error.failure);
375
463
  return agentToolFailure({
376
464
  code: AGENT_TOOL_FAILURE_CODES.unexpectedFault,
377
465
  message: 'Unexpected Tool failure. This call could not be completed; other tools remain available.',
378
466
  });
379
467
  }
380
468
  }
381
- export async function startMcpServer(argv, version, diagnostics, buildIdentity) {
469
+ export async function startMcpServer(argv, version, diagnostics, buildIdentity, selectedKnowledge, onClose) {
382
470
  const launch = parseMcpLaunch(argv);
383
471
  const explicit = launch.roots;
384
472
  // Clients without roots/list (e.g. Claude Code) export their project directory; it is used only when the
@@ -413,7 +501,7 @@ export async function startMcpServer(argv, version, diagnostics, buildIdentity)
413
501
  let rootIdentity;
414
502
  let launchProjectApplied = false;
415
503
  let rootRefreshGeneration = 0;
416
- server.server.onclose = () => session?.dispose();
504
+ server.server.onclose = () => { session?.dispose(); onClose?.(); };
417
505
  const refreshRoots = async () => {
418
506
  if (eraContext.era === 'modern' || server.server.getClientCapabilities()?.roots === undefined) {
419
507
  negotiated = undefined;
@@ -527,7 +615,7 @@ export async function startMcpServer(argv, version, diagnostics, buildIdentity)
527
615
  const useLaunchProject = request.params.name === 'hexasync_validate' && !launchProjectApplied &&
528
616
  args['project'] === undefined && launch.project !== undefined;
529
617
  const effectiveArgs = useLaunchProject ? { ...args, project: launch.project } : args;
530
- const answered = await answerMcpTool(request.params.name, effectiveArgs, context.roots, version, extra.mcpReq.signal, context.failure, session, useLaunchProject ? launch.expectedProject : undefined);
618
+ const answered = await answerMcpTool(request.params.name, effectiveArgs, context.roots, version, extra.mcpReq.signal, context.failure, session, useLaunchProject ? launch.expectedProject : undefined, selectedKnowledge);
531
619
  // Nothing selected a Root, so the server fell back to its working directory and found no project there:
532
620
  // the usual standalone case of a client that starts servers outside the project.
533
621
  const answer = answered.isError && answered.code === AGENT_TOOL_FAILURE_CODES.projectNotFound && answered.rootAuthority?.source === 'cwd'
@@ -547,7 +635,7 @@ export async function startMcpServer(argv, version, diagnostics, buildIdentity)
547
635
  if (needed)
548
636
  return needed;
549
637
  const context = await rootsNow();
550
- const result = encodeMcpToolResult(await answerMcpTool('hexasync_orientation', {}, context.roots, version, extra.mcpReq.signal, context.failure, session));
638
+ const result = encodeMcpToolResult(await answerMcpTool('hexasync_orientation', {}, context.roots, version, extra.mcpReq.signal, context.failure, session, undefined, selectedKnowledge));
551
639
  return { messages: [{ role: 'user', content: result.content[0] }] };
552
640
  });
553
641
  /**
@@ -565,9 +653,25 @@ export async function startMcpServer(argv, version, diagnostics, buildIdentity)
565
653
  * `#heading` fragment reads the section holding that heading.
566
654
  */
567
655
  const listedResources = KNOWLEDGE_BASE.map(({ uri, name, title, description, mimeType, text }) => ({ uri, name, title, description, mimeType, size: Buffer.byteLength(text, 'utf8') }));
568
- server.server.setRequestHandler('resources/list', async () => ({ resources: listedResources }));
656
+ server.server.setRequestHandler('resources/list', async (_request, extra) => {
657
+ if (!selectedKnowledge)
658
+ return { resources: listedResources };
659
+ const snapshot = await selectedKnowledge.snapshot(extra.mcpReq.signal);
660
+ if (!snapshot)
661
+ throw new Error('Selected wiki source is unavailable');
662
+ return { resources: await listWikiResources(snapshot) };
663
+ });
569
664
  server.server.setRequestHandler('resources/templates/list', async () => ({ resourceTemplates: [] }));
570
- server.server.setRequestHandler('resources/read', async (request) => {
665
+ server.server.setRequestHandler('resources/read', async (request, extra) => {
666
+ if (selectedKnowledge) {
667
+ const snapshot = await selectedKnowledge.snapshot(extra.mcpReq.signal);
668
+ if (!snapshot)
669
+ throw new Error('Selected wiki source is unavailable');
670
+ const selected = await readWikiResource(snapshot, request.params.uri);
671
+ if (!selected)
672
+ throw new ResourceNotFoundError(request.params.uri);
673
+ return { contents: [{ ...selected, _meta: { knowledgeSource: 'shared_cache', manifestEtag: snapshot.manifestEtag, state: 'Complete' } }] };
674
+ }
571
675
  const resource = bundledKnowledgeResource(request.params.uri);
572
676
  if (resource === undefined)
573
677
  throw new ResourceNotFoundError(request.params.uri);