borgmcp 1.0.35 → 1.0.36

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.
@@ -39,6 +39,9 @@ export interface ActiveCube {
39
39
  sessionToken: string;
40
40
  droneLabel: string;
41
41
  apiUrl: string;
42
+ roleName?: string;
43
+ roleClass?: 'queen' | 'worker';
44
+ isHumanSeat?: boolean;
42
45
  }
43
46
  export interface AssimilateDeps {
44
47
  runSync: (cmd: string, args: string[], cwd?: string) => {
@@ -3,35 +3,35 @@ import{dirname as re,basename as E}from"node:path";import{randomUUID as ne}from"
3
3
  `),1}let i=await e.getCachedAuth();if(!i){if(!e.isTTY()&&!r.flags.yes)return e.stderr("borg setup required and stdin is non-interactive. Run `borg setup` first in an interactive terminal, then `borg assimilate`.\n"),1;i=await e.runSetup()}const a=e.findProjectRoot(e.cwd());let n;if(r.flags.cubeName)n=r.flags.cubeName;else{const t=e.runSync("git",["remote","get-url","origin"],a),o=t.status===0?t.stdout:null;if(n=se(a,o),o){const u=ce(o),m=u?le(u):null;u&&!m&&n&&e.stderr(`couldn't parse git remote '${u}' \u2014 using directory name '${n}' as cube name
4
4
  `)}}let s=null;if(n&&n.includes("@")&&n.includes(":")){const t=n.lastIndexOf(":");s={ownerEmail:n.substring(0,t),cubeName:n.substring(t+1)},n=s.cubeName}const R=e.cwd();e.stderr(`Checking your cubes\u2026
5
5
  `);let N;try{N=await e.listCubes(i.apiUrl,i.token)}catch(t){const o=t instanceof Error?t.message:String(t);if(o.includes("Authentication required")||o.includes("Authentication expired"))e.stderr(`Re-authenticating...
6
- `),i=await e.runSetup(),N=await e.listCubes(i.apiUrl,i.token);else throw t}const T=N.find(t=>t.name===n);if(!T&&s)return e.stderr(`No cube named '${s.cubeName}' accessible to you owned by '${s.ownerEmail}'. Did you accept their invite? See borgmcp.ai/dashboard.
7
- `),1;let l,A;if(T)l=await e.getCube(i.apiUrl,i.token,T.id),A=!1;else{let t;if(r.flags.template)t=r.flags.template;else if(r.flags.noTemplate)t=void 0;else if(e.isTTY())if(r.flags.yes)t="starter";else{const o=await e.listTemplates(i.apiUrl,i.token),u=["First drone joining a new cube. Apply a template?"];o.forEach((y,v)=>{const C=v===0?" (default)":"";u.push(` ${v+1}) ${y.name}${C} \u2014 ${y.description}`)}),u.push(` ${o.length+1}) skip \u2014 no template`);const m=(await e.prompt(u.join(`
6
+ `),i=await e.runSetup(),N=await e.listCubes(i.apiUrl,i.token);else throw t}const _=N.find(t=>t.name===n);if(!_&&s)return e.stderr(`No cube named '${s.cubeName}' accessible to you owned by '${s.ownerEmail}'. Did you accept their invite? See borgmcp.ai/dashboard.
7
+ `),1;let l,T;if(_)l=await e.getCube(i.apiUrl,i.token,_.id),T=!1;else{let t;if(r.flags.template)t=r.flags.template;else if(r.flags.noTemplate)t=void 0;else if(e.isTTY())if(r.flags.yes)t="starter";else{const o=await e.listTemplates(i.apiUrl,i.token),u=["First drone joining a new cube. Apply a template?"];o.forEach((v,p)=>{const C=p===0?" (default)":"";u.push(` ${p+1}) ${v.name}${C} \u2014 ${v.description}`)}),u.push(` ${o.length+1}) skip \u2014 no template`);const m=(await e.prompt(u.join(`
8
8
  `)+`
9
- [1]: `)).trim(),k=m===""?1:parseInt(m,10);if(Number.isNaN(k)||k<1||k>o.length+1)return e.stderr(`invalid choice "${m}"
10
- `),1;t=k<=o.length?o[k-1].name:void 0}else{if(!r.flags.yes)return e.stderr(`cube creation needs a template choice but stdin is non-interactive.
9
+ [1]: `)).trim(),y=m===""?1:parseInt(m,10);if(Number.isNaN(y)||y<1||y>o.length+1)return e.stderr(`invalid choice "${m}"
10
+ `),1;t=y<=o.length?o[y-1].name:void 0}else{if(!r.flags.yes)return e.stderr(`cube creation needs a template choice but stdin is non-interactive.
11
11
  Pass --template <name>, --no-template, or --yes (defaults to starter).
12
12
  `),1;t="starter"}e.stderr(n?`Creating cube '${n}'\u2026
13
13
  `:`Creating your cube\u2026
14
- `),l=await e.createCube(i.apiUrl,i.token,t?{name:n??void 0,template:t}:{name:n??void 0}),A=!0}let d;if(r.role!==void 0){if(d=ie(l.roles,r.role),!d){const t=l.roles.map(m=>m.name).join(", "),o=Se(r.role,l.roles.map(m=>m.name)),u=o?` Did you mean "${o}"?`:"";return e.stderr(`no role matching "${r.role}" in cube "${l.name}". Available: ${t}.${u}
14
+ `),l=await e.createCube(i.apiUrl,i.token,t?{name:n??void 0,template:t}:{name:n??void 0}),T=!0}let d;if(r.role!==void 0){if(d=ie(l.roles,r.role),!d){const t=l.roles.map(m=>m.name).join(", "),o=Se(r.role,l.roles.map(m=>m.name)),u=o?` Did you mean "${o}"?`:"";return e.stderr(`no role matching "${r.role}" in cube "${l.name}". Available: ${t}.${u}
15
15
  (Use --template <name> on first-drone setup or run \`borg_create-role\` from inside Claude.)
16
- `),1}}else if(d=ae(l.roles,{isFirstDrone:A}),!d)return e.stderr(`cube "${l.name}" has no default or human-seat role; cannot infer a role. Either pass a role argument explicitly (e.g. \`borg assimilate builder\`) or run \`borg_create-role\` from inside Claude to set up roles.
17
- `),1;const p=await e.getActiveCube();let $;if(p&&r.flags.here)if(p.cubeId===l.id)$=p.droneId;else return e.stderr(`this directory already hosts an active drone; remove --here or run from a fresh worktree
18
- `),1;const M=r.flags.worktree!==void 0||p!==null&&!r.flags.here,V=$??p?.droneId??null,_=M?null:await e.getLaunchModel(l.id,a,V),g=r.flags.model??_?.model??d.default_model??null,I=ve(process.env,g!=null&&g===_?.model?_?.ollamaBaseUrl:void 0);if(g){const t=await e.checkModelReachable(g,e.fetch,I);if(!t.ok)return e.stderr(`${t.message}
16
+ `),1}}else if(d=ae(l.roles,{isFirstDrone:T}),!d)return e.stderr(`cube "${l.name}" has no default or human-seat role; cannot infer a role. Either pass a role argument explicitly (e.g. \`borg assimilate builder\`) or run \`borg_create-role\` from inside Claude to set up roles.
17
+ `),1;const $=await e.getActiveCube();let x;if($&&r.flags.here)if($.cubeId===l.id)x=$.droneId;else return e.stderr(`this directory already hosts an active drone; remove --here or run from a fresh worktree
18
+ `),1;const M=r.flags.worktree!==void 0||$!==null&&!r.flags.here,V=x??$?.droneId??null,A=M?null:await e.getLaunchModel(l.id,a,V),g=r.flags.model??A?.model??d.default_model??null,I=ve(process.env,g!=null&&g===A?.model?A?.ollamaBaseUrl:void 0);if(g){const t=await e.checkModelReachable(g,e.fetch,I);if(!t.ok)return e.stderr(`${t.message}
19
19
  `),1}const w=await e.resolveCli(r.flags.cli);e.stderr(`Joining cube '${l.name}' as ${d.name}\u2026
20
- `);let c;try{c=await e.assimilate(i.apiUrl,i.token,{cube_id:l.id,role_id:d.id,hostname:e.getHostname(),agent_kind:w,model:g,...$?{prior_drone_id:$}:{}})}catch(t){if(t instanceof be&&$!=null)return e.stderr(`seat evicted \u2014 this worktree's saved seat was evicted from the cube. Re-assimilate fresh from a terminal, or remove this worktree.
20
+ `);let c;try{c=await e.assimilate(i.apiUrl,i.token,{cube_id:l.id,role_id:d.id,hostname:e.getHostname(),agent_kind:w,model:g,...x?{prior_drone_id:x}:{}})}catch(t){if(t instanceof be&&x!=null)return e.stderr(`seat evicted \u2014 this worktree's saved seat was evicted from the cube. Re-assimilate fresh from a terminal, or remove this worktree.
21
21
  `),1;const o=t instanceof Error?t.message:String(t);return e.stderr(`assimilate failed: ${o}
22
- `),1}const x=l.roles.find(t=>t.id===c.role_id)??d;c.reattached?e.stderr(`re-attached to existing seat ${c.drone_label} (session token rotated, no new drone minted)
23
- `):x.id!==d.id&&e.stderr(`Note: your invite didn't grant the "${d.name}" role \u2014 assimilated as "${x.name}" instead.
22
+ `),1}const b=l.roles.find(t=>t.id===c.role_id)??d;c.reattached?e.stderr(`re-attached to existing seat ${c.drone_label} (session token rotated, no new drone minted)
23
+ `):b.id!==d.id&&e.stderr(`Note: your invite didn't grant the "${d.name}" role \u2014 assimilated as "${b.name}" instead.
24
24
  `);const J=M;let f=null;if(J){const t=e.runSync("git",["rev-parse","--verify","HEAD"],a);if(t.status!==0)return e.stderr(`sibling worktree spawn requires HEAD pointing at a commit.
25
25
  Fix: create at least one commit (\`git commit --allow-empty -m "initial"\`)
26
26
  OR: pass --here to skip the sibling spawn and use the current directory
27
- `),1;e.runSync("git",["fetch","origin"],a);let o="origin/main";e.runSync("git",["rev-parse","--verify","origin/main"],a).status!==0&&e.runSync("git",["rev-parse","--verify","origin/master"],a).status===0&&(o="origin/master");const m=t.stdout.trim(),k=e.runSync("git",["rev-parse",o],a).stdout.trim();m!==k&&e.stderr(`note: local HEAD (${m.slice(0,7)}) differs from ${o} (${k.slice(0,7)}); new worktree will start on ${o}
28
- `);const y=E(a),v=r.flags.worktree??oe(x.name);if(v.length===0)return e.stderr(`cannot derive a worktree name from role "${x.name}"; pass an explicit --worktree <name>
29
- `),1;const C=e.homedir();let b=z(C,y,v),F=2;for(;e.pathExists(b)||Re(e,a,b);)b=z(C,y,v,F),F++;e.mkdirp(re(b));const O=q(E(b),y),Y=e.runSync("git",["worktree","add","-b",O,b,o],a);if(Y.status!==0)return e.stderr(`git worktree add failed: ${K(Y.stderr)}
30
- `),1;e.stderr(`spawned sibling worktree at ${b} on branch ${O} (${o}); original dir is registered as active (edit ~/.config/borgmcp/cubes.json if stale).
31
- `),e.chdir(b),e.stderr($e(b,O,a)),f=e.cwd()}try{await e.setActiveCube({cubeId:c.cube_id,droneId:c.drone_id,name:l.name,sessionToken:c.session_token,droneLabel:c.drone_label,apiUrl:i.apiUrl})}catch(t){const o=t instanceof Error?t.message:String(t);if(e.stderr(`setActiveCube failed: ${o}
27
+ `),1;e.runSync("git",["fetch","origin"],a);let o="origin/main";e.runSync("git",["rev-parse","--verify","origin/main"],a).status!==0&&e.runSync("git",["rev-parse","--verify","origin/master"],a).status===0&&(o="origin/master");const m=t.stdout.trim(),y=e.runSync("git",["rev-parse",o],a).stdout.trim();m!==y&&e.stderr(`note: local HEAD (${m.slice(0,7)}) differs from ${o} (${y.slice(0,7)}); new worktree will start on ${o}
28
+ `);const v=E(a),p=r.flags.worktree??oe(b.name);if(p.length===0)return e.stderr(`cannot derive a worktree name from role "${b.name}"; pass an explicit --worktree <name>
29
+ `),1;const C=e.homedir();let k=z(C,v,p),F=2;for(;e.pathExists(k)||Re(e,a,k);)k=z(C,v,p,F),F++;e.mkdirp(re(k));const O=q(E(k),v),Y=e.runSync("git",["worktree","add","-b",O,k,o],a);if(Y.status!==0)return e.stderr(`git worktree add failed: ${K(Y.stderr)}
30
+ `),1;e.stderr(`spawned sibling worktree at ${k} on branch ${O} (${o}); original dir is registered as active (edit ~/.config/borgmcp/cubes.json if stale).
31
+ `),e.chdir(k),e.stderr($e(k,O,a)),f=e.cwd()}try{await e.setActiveCube({cubeId:c.cube_id,droneId:c.drone_id,name:l.name,sessionToken:c.session_token,droneLabel:c.drone_label,apiUrl:i.apiUrl,roleName:b.name,isHumanSeat:b.is_human_seat,...b.role_class?{roleClass:b.role_class}:{}})}catch(t){const o=t instanceof Error?t.message:String(t);if(e.stderr(`setActiveCube failed: ${o}
32
32
  `),f){const u=e.runSync("git",["worktree","remove","--force",f],a);u.status===0?e.stderr(`rolled back spawned worktree at ${f}
33
33
  `):e.stderr(`manual cleanup needed: \`git worktree remove --force ${f}\` (rollback attempt failed: ${K(u.stderr).trim()||"unknown"})
34
- `)}return 1}e.setTerminalTitle(c.drone_label,l.name);const Q=e.isTTY()&&!process.env.NO_COLOR&&!process.env.CI;e.stdout(ue(x.name,l.name,Q));const h=e.cwd();try{e.installProjectSessionHook(h)}catch{e.stderr(`warning: could not install the project-local SessionStart hook in ${h}; it will be re-attempted on the next borg launch
34
+ `)}return 1}e.setTerminalTitle(c.drone_label,l.name);const Q=e.isTTY()&&!process.env.NO_COLOR&&!process.env.CI;e.stdout(ue(b.name,l.name,Q));const h=e.cwd();try{e.installProjectSessionHook(h)}catch{e.stderr(`warning: could not install the project-local SessionStart hook in ${h}; it will be re-attempted on the next borg launch
35
35
  `)}if(!f){e.runSync("git",["fetch","origin","--prune"],h);const t=q(E(h),E(a)),o=we(e.runSync,h,t,"origin/main");o.action==="adopted"?(e.stderr(`worktree: adopted branch ${t} at origin/main
36
36
  `),e.stderr(xe(h,t))):o.message&&e.stderr(`worktree sync: ${o.message}
37
37
  `)}await e.probeMcpReady()||e.stderr(`warning: borg-mcp readiness probe did not complete within the timeout; launching ${w} anyway \u2014 the kickoff prompt's ToolSearch fallback will recover if the MCP server takes longer to start.
package/dist/cubes.d.ts CHANGED
@@ -15,6 +15,7 @@
15
15
  * SessionStart hook firing borg-regen) don't need BORG_API_URL in their env
16
16
  * to know which worker to talk to.
17
17
  */
18
+ import { writeFile, unlink, rename } from 'node:fs/promises';
18
19
  export type BorgCli = 'claude' | 'codex';
19
20
  export interface ActiveCube {
20
21
  cubeId: string;
@@ -23,6 +24,9 @@ export interface ActiveCube {
23
24
  sessionToken: string;
24
25
  droneLabel: string;
25
26
  apiUrl: string;
27
+ roleName?: string;
28
+ roleClass?: 'queen' | 'worker';
29
+ isHumanSeat?: boolean;
26
30
  }
27
31
  export interface CodexWakeTargetRecord {
28
32
  threadId: string;
@@ -36,6 +40,14 @@ export interface CodexWakeTargetRecord {
36
40
  */
37
41
  export declare function findProjectRoot(cwd?: string): string;
38
42
  export declare function inboxPathForDrone(cubeId: string, droneId: string): string;
43
+ export declare function atomicWriteFile(filePath: string, data: string, opts?: {
44
+ mode?: number;
45
+ io?: {
46
+ writeFile: typeof writeFile;
47
+ rename: typeof rename;
48
+ unlink: typeof unlink;
49
+ };
50
+ }): Promise<void>;
39
51
  /**
40
52
  * Get the currently-active cube for the current project, or null if not
41
53
  * assimilated in this project. Entries written by older client versions
package/dist/cubes.js CHANGED
@@ -1,5 +1,5 @@
1
- import{existsSync as $}from"node:fs";import{mkdir as f,readFile as d,writeFile as p,unlink as L}from"node:fs/promises";import{homedir as v}from"node:os";import{dirname as l,join as i,resolve as I}from"node:path";import{pruneDeadWakeTargets as _}from"./codex-wake-resolve.js";import{MODEL_DESCRIPTOR_REGEX as U}from"./model-presets.js";const u=i(v(),".config","borgmcp"),y=i(u,"cubes.json"),m=i(u,"launch.json"),h=i(u,"codex-wake-targets.json"),j=i(u,"launch-models.json"),R=i(u,"inboxes");function c(t=process.cwd()){let e=I(t);for(;;){if($(i(e,".git")))return e;const r=l(e);if(r===e)return I(t);e=r}}const a=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Q(t,e){if(!a.test(t))throw new Error(`Invalid cubeId: ${t}`);if(!a.test(e))throw new Error(`Invalid droneId: ${e}`);return i(R,t,`${e}.log`)}function W(t){return t!==null&&typeof t=="object"&&typeof t.projects=="object"&&t.projects!==null&&!Array.isArray(t.projects)}async function w(){let t;try{t=await d(y,"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}let e;try{e=JSON.parse(t)}catch{return null}return W(e)?e:null}async function S(t){await f(l(y),{recursive:!0}),await p(y,JSON.stringify(t,null,2)+`
2
- `,{mode:384})}function D(t){return t!==null&&typeof t=="object"&&typeof t.projects=="object"&&t.projects!==null&&!Array.isArray(t.projects)}async function x(){let t;try{t=await d(m,"utf8")}catch(e){if(e?.code==="ENOENT")return null;throw e}try{const e=JSON.parse(t);return D(e)?e:null}catch{return null}}async function P(t){await f(l(m),{recursive:!0}),await p(m,JSON.stringify(t,null,2)+`
3
- `,{mode:384})}function A(t,e){if(!a.test(t))throw new Error(`Invalid cubeId: ${t}`);if(!a.test(e))throw new Error(`Invalid droneId: ${e}`);return`${t}:${e}`}function B(t){return t!==null&&typeof t=="object"&&typeof t.targets=="object"&&t.targets!==null&&!Array.isArray(t.targets)}async function E(){let t;try{t=await d(h,"utf8")}catch(e){if(e?.code==="ENOENT")return null;throw e}try{const e=JSON.parse(t);return B(e)?e:null}catch{return null}}async function T(t){await f(l(h),{recursive:!0}),await p(h,JSON.stringify(t,null,2)+`
4
- `,{mode:384})}async function V(){const t=await w();if(!t)return null;const e=c(),r=t.projects[e];return!r||typeof r.cubeId!="string"||!r.cubeId||typeof r.droneId!="string"||!r.droneId?null:r}async function Y(t){const e=await w()??{projects:{}};e.projects[c()]=t,await S(e)}function Z(t,e){const r=e.cube?.name??t.name,n=e.drone?.label??t.droneLabel;return r===t.name&&n===t.droneLabel?t:{...t,name:r,droneLabel:n}}async function tt(){const t=await w();if(!t)return;const e=c();if(e in t.projects){if(delete t.projects[e],Object.keys(t.projects).length===0){try{await L(y)}catch(r){if(r?.code!=="ENOENT")throw r}return}await S(t)}}async function et(){const t=await x();if(!t)return null;const e=t.projects[c()];return e?.cli==="claude"||e?.cli==="codex"?e.cli:null}async function rt(t){const e=await x();if(!e)return null;const r=e.projects[c(t)];return r?.cli==="claude"||r?.cli==="codex"?r.cli:null}async function nt(){const t=await w();return t?Object.entries(t.projects).filter(([,e])=>e!==null&&typeof e=="object"&&typeof e.cubeId=="string"&&e.cubeId.length>0&&typeof e.droneId=="string"&&e.droneId.length>0).map(([e,r])=>({projectPath:e,cube:r})):[]}async function ot(t){const e=await x()??{projects:{}};e.projects[c()]={cli:t},await P(e)}async function it(t,e,r){const n=await E()??{targets:{}};n.targets[A(t,e)]={...r,updatedAt:new Date().toISOString()},await T(n)}async function at(t,e){const r=await E();if(!r)return null;const n=r.targets[A(t,e)];return!n||typeof n.threadId!="string"||typeof n.socketPath!="string"?null:n}async function ct(t){const e=await E();if(!e)return;const{targets:r,changed:n}=_(e.targets,t);n&&await T({...e,targets:r})}function b(t,e){if(!a.test(t))throw new Error(`Invalid cubeId: ${t}`);if(typeof e!="string"||e.length===0)throw new Error(`Invalid worktree path: ${e}`);return`${t}:${e}`}function J(t,e){if(!a.test(t))throw new Error(`Invalid cubeId: ${t}`);if(!a.test(e))throw new Error(`Invalid droneId: ${e}`);return`${t}:${e}`}function k(t){return!t||typeof t.model!="string"||!U.test(t.model)?null:{model:t.model,ollamaBaseUrl:typeof t.ollamaBaseUrl=="string"?t.ollamaBaseUrl:null}}function M(t){return t!==null&&typeof t=="object"&&typeof t.models=="object"&&t.models!==null&&!Array.isArray(t.models)}async function N(t){let e;try{e=await d(t,"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}try{const r=JSON.parse(e);return M(r)?r:null}catch{return null}}async function O(t,e){await f(l(t),{recursive:!0}),await p(t,JSON.stringify(e,null,2)+`
5
- `,{mode:384})}async function st(t,e,r,n=j){const o=await N(n)??{models:{}};o.models[b(t,e)]={model:r.model,ollamaBaseUrl:r.ollamaBaseUrl},await O(n,o)}async function lt(t,e,r=null,n=j){const o=await N(n);if(!o)return null;const s=b(t,e),C=k(o.models[s]);if(C)return C;if(!r||!a.test(r))return null;const F=J(t,r),g=k(o.models[F]);return g?(o.models[s]=g,delete o.models[F],await O(n,o),g):null}async function ut(t,e,r=j){const n=await N(r);if(!n)return;const o=b(t,e);if(o in n.models){if(delete n.models[o],Object.keys(n.models).length===0){try{await L(r)}catch(s){if(s?.code!=="ENOENT")throw s}return}await O(r,n)}}export{Z as activeCubeWithFreshRegenIdentity,tt as clearActiveCube,ut as clearLaunchModel,c as findProjectRoot,V as getActiveCube,at as getCodexWakeTarget,lt as getLaunchModel,et as getProjectCliPreference,rt as getProjectCliPreferenceForPath,Q as inboxPathForDrone,ct as pruneDeadCodexWakeTargets,nt as readAllProjectIdentities,Y as setActiveCube,it as setCodexWakeTarget,st as setLaunchModel,ot as setProjectCliPreference};
1
+ import{existsSync as v}from"node:fs";import{mkdir as w,readFile as f,writeFile as g,unlink as m,rename as _}from"node:fs/promises";import{homedir as U}from"node:os";import{dirname as d,join as c,resolve as I}from"node:path";import{pruneDeadWakeTargets as W}from"./codex-wake-resolve.js";import{MODEL_DESCRIPTOR_REGEX as R}from"./model-presets.js";const l=c(U(),".config","borgmcp"),h=c(l,"cubes.json"),j=c(l,"launch.json"),x=c(l,"codex-wake-targets.json"),E=c(l,"launch-models.json"),D=c(l,"inboxes");function s(t=process.cwd()){let e=I(t);for(;;){if(v(c(e,".git")))return e;const r=d(e);if(r===e)return I(t);e=r}}const a=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Z(t,e){if(!a.test(t))throw new Error(`Invalid cubeId: ${t}`);if(!a.test(e))throw new Error(`Invalid droneId: ${e}`);return c(D,t,`${e}.log`)}function B(t){return t!==null&&typeof t=="object"&&typeof t.projects=="object"&&t.projects!==null&&!Array.isArray(t.projects)}async function p(){let t;try{t=await f(h,"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}let e;try{e=JSON.parse(t)}catch{return null}return B(e)?e:null}async function $(t){await S(h,JSON.stringify(t,null,2)+`
2
+ `)}let J=0;async function S(t,e,r={}){const n=r.io??{writeFile:g,rename:_,unlink:m},o=r.mode??384;await w(d(t),{recursive:!0});const i=`${t}.${process.pid}.${J++}.tmp`;try{await n.writeFile(i,e,{mode:o}),await n.rename(i,t)}catch(u){try{await n.unlink(i)}catch{}throw u}}function M(t){return t!==null&&typeof t=="object"&&typeof t.projects=="object"&&t.projects!==null&&!Array.isArray(t.projects)}async function b(){let t;try{t=await f(j,"utf8")}catch(e){if(e?.code==="ENOENT")return null;throw e}try{const e=JSON.parse(t);return M(e)?e:null}catch{return null}}async function P(t){await w(d(j),{recursive:!0}),await g(j,JSON.stringify(t,null,2)+`
3
+ `,{mode:384})}function T(t,e){if(!a.test(t))throw new Error(`Invalid cubeId: ${t}`);if(!a.test(e))throw new Error(`Invalid droneId: ${e}`);return`${t}:${e}`}function K(t){return t!==null&&typeof t=="object"&&typeof t.targets=="object"&&t.targets!==null&&!Array.isArray(t.targets)}async function C(){let t;try{t=await f(x,"utf8")}catch(e){if(e?.code==="ENOENT")return null;throw e}try{const e=JSON.parse(t);return K(e)?e:null}catch{return null}}async function k(t){await w(d(x),{recursive:!0}),await g(x,JSON.stringify(t,null,2)+`
4
+ `,{mode:384})}async function tt(){const t=await p();if(!t)return null;const e=s(),r=t.projects[e];return!r||typeof r.cubeId!="string"||!r.cubeId||typeof r.droneId!="string"||!r.droneId?null:r}async function et(t){const e=await p()??{projects:{}};e.projects[s()]=t,await $(e)}function rt(t,e){const r=e.cube?.name??t.name,n=e.drone?.label??t.droneLabel;return r===t.name&&n===t.droneLabel?t:{...t,name:r,droneLabel:n}}async function nt(){const t=await p();if(!t)return;const e=s();if(e in t.projects){if(delete t.projects[e],Object.keys(t.projects).length===0){try{await m(h)}catch(r){if(r?.code!=="ENOENT")throw r}return}await $(t)}}async function ot(){const t=await b();if(!t)return null;const e=t.projects[s()];return e?.cli==="claude"||e?.cli==="codex"?e.cli:null}async function it(t){const e=await b();if(!e)return null;const r=e.projects[s(t)];return r?.cli==="claude"||r?.cli==="codex"?r.cli:null}async function ct(){const t=await p();return t?Object.entries(t.projects).filter(([,e])=>e!==null&&typeof e=="object"&&typeof e.cubeId=="string"&&e.cubeId.length>0&&typeof e.droneId=="string"&&e.droneId.length>0).map(([e,r])=>({projectPath:e,cube:r})):[]}async function at(t){const e=await b()??{projects:{}};e.projects[s()]={cli:t},await P(e)}async function st(t,e,r){const n=await C()??{targets:{}};n.targets[T(t,e)]={...r,updatedAt:new Date().toISOString()},await k(n)}async function lt(t,e){const r=await C();if(!r)return null;const n=r.targets[T(t,e)];return!n||typeof n.threadId!="string"||typeof n.socketPath!="string"?null:n}async function ut(t){const e=await C();if(!e)return;const{targets:r,changed:n}=W(e.targets,t);n&&await k({...e,targets:r})}function F(t,e){if(!a.test(t))throw new Error(`Invalid cubeId: ${t}`);if(typeof e!="string"||e.length===0)throw new Error(`Invalid worktree path: ${e}`);return`${t}:${e}`}function X(t,e){if(!a.test(t))throw new Error(`Invalid cubeId: ${t}`);if(!a.test(e))throw new Error(`Invalid droneId: ${e}`);return`${t}:${e}`}function A(t){return!t||typeof t.model!="string"||!R.test(t.model)?null:{model:t.model,ollamaBaseUrl:typeof t.ollamaBaseUrl=="string"?t.ollamaBaseUrl:null}}function G(t){return t!==null&&typeof t=="object"&&typeof t.models=="object"&&t.models!==null&&!Array.isArray(t.models)}async function N(t){let e;try{e=await f(t,"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}try{const r=JSON.parse(e);return G(r)?r:null}catch{return null}}async function O(t,e){await S(t,JSON.stringify(e,null,2)+`
5
+ `)}async function ft(t,e,r,n=E){const o=await N(n)??{models:{}};o.models[F(t,e)]={model:r.model,ollamaBaseUrl:r.ollamaBaseUrl},await O(n,o)}async function dt(t,e,r=null,n=E){const o=await N(n);if(!o)return null;const i=F(t,e),u=A(o.models[i]);if(u)return u;if(!r||!a.test(r))return null;const L=X(t,r),y=A(o.models[L]);return y?(o.models[i]=y,delete o.models[L],await O(n,o),y):null}async function pt(t,e,r=E){const n=await N(r);if(!n)return;const o=F(t,e);if(o in n.models){if(delete n.models[o],Object.keys(n.models).length===0){try{await m(r)}catch(i){if(i?.code!=="ENOENT")throw i}return}await O(r,n)}}export{rt as activeCubeWithFreshRegenIdentity,S as atomicWriteFile,nt as clearActiveCube,pt as clearLaunchModel,s as findProjectRoot,tt as getActiveCube,lt as getCodexWakeTarget,dt as getLaunchModel,ot as getProjectCliPreference,it as getProjectCliPreferenceForPath,Z as inboxPathForDrone,ut as pruneDeadCodexWakeTargets,ct as readAllProjectIdentities,et as setActiveCube,st as setCodexWakeTarget,ft as setLaunchModel,at as setProjectCliPreference};
package/dist/index.js CHANGED
@@ -1,27 +1,27 @@
1
1
  #!/usr/bin/env node
2
- import{Server as Q}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as V}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as z,ListToolsRequestSchema as X,ListPromptsRequestSchema as G,GetPromptRequestSchema as Y}from"@modelcontextprotocol/sdk/types.js";import{getCubeInfo as J,getRoleInfo as j,getRoster as Z,readLog as ee,appendLog as te,submitReport as re,ackLogEntry as oe,regen as O,listCubes as ie,createCube as ne,updateCube as T,deleteCube as se,createRole as ae,updateRole as ce,patchRoleSection as $,patchTaxonomyClass as A,deleteRole as le,reassignDrone as de,evictDrone as pe,getCube as _,checkSubscriptionStatus as ue,createBillingPortalSession as me,createSubscription as he,syncRoles as be,applyTemplate as ge,whoami as ye,roleRationale as fe,getValidToken as _e}from"./remote-client.js";import{startHealthBeatTick as we}from"./health-beat.js";import{getTemplate as U,listTemplateNames as S,resolveCubeDirectiveForCreate as ve,resolveCubeDirectiveForApply as xe,resolveMessageTaxonomyForCreate as ke}from"./templates.js";import{activeCubeWithFreshRegenIdentity as N,getActiveCube as y,setActiveCube as P,inboxPathForDrone as E}from"./cubes.js";import{addSessionStartHook as $e,addUserPromptSubmitHook as Ue}from"./config-utils.js";import{humanAgo as L,formatLogEntryMarkdown as Se,formatRegenMarkdown as M,getDronePlaybook as Ee,nullTaxonomyTip as Ie,regenWakePathDroneLabel as qe}from"./regen-format.js";import{startLogStream as Ce,getStreamStatus as I}from"./log-stream.js";import{renderRoleList as Re}from"./list-roles-render.js";import{getPackageVersion as w,getOnDiskVersion as De,handleVersionFlag as je}from"./version.js";import{renderStreamStatus as Oe,checkInboxMonitorHealthy as q,formatWakePathPrefix as Te,shouldShowWakePathWarning as Ae}from"./stream-status.js";import{formatRoleAgentLabel as Ne,renderRoster as Pe}from"./roster-render.js";import{resolveDroneIdByLabel as Le,isUuidShape as Me}from"./evict-drone.js";import{authRecoveryMessage as Be}from"./auth-recovery.js";import{DroneEvictedError as Fe,DroneFrozenError as We,formatEvictedToolResult as He,formatFrozenToolResult as Ke}from"./drone-lifecycle.js";import{classifyInSessionAssimilate as Qe,reattachOnlyRefusal as Ve,reattachFailureMessage as ze}from"./assimilate-guard.js";import{gateAllowsActivation as Xe,borgSessionToolNotice as Ge}from"./launch-gate.js";import{renderSyncRolesResult as Ye}from"./sync-roles-render.js";import{initConsolePrefix as Je,consolePrefix as v}from"./console-prefix.js";import{isCodexRemoteWakeEnabled as C,resolveSessionAgentKind as Ze,probeCodexBridgeArmed as et}from"./codex-app-wake.js";import{lifecycleSignalForMessage as tt,recordLifecycleLog as B,shouldSuppressLifecycleLog as rt}from"./lifecycle-log-guard.js";import{normalizeDirectLogRecipients as ot}from"./direct-log.js";import F from"open";import it from"os";function nt(){try{const p=it.hostname();return p&&p.trim()?p.trim().slice(0,255):null}catch{return null}}async function W(p,x){return await ge(p,x.name)}async function f(){const p=await y();if(!p)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");return p}async function st(){je();try{$e()}catch{}try{Ue()}catch{}try{Ce()}catch{}try{we({getActiveCube:y,getStreamConnected:()=>I().connected,getInboxPath:m=>E(m.cubeId,m.droneId),checkMonitor:q,isCodexRemoteWake:C,probeBridgeArmed:m=>et({cubeId:m.cubeId,droneId:m.droneId}),resolveAgentKind:Ze,resolveHostname:nt,resolveVersion:w,getToken:_e,fetchImpl:globalThis.fetch.bind(globalThis)})}catch{}const p=new Q({name:"borg-mcp-client",version:w()},{capabilities:{tools:{},prompts:{}}});p.setRequestHandler(X,async()=>({tools:[{name:"borg_subscribe",description:"Create Stripe checkout session for Cube tier ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_upgrade-subscription",description:"Open the Stripe Billing Portal to manage Cube tier quantity ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_subscription_status",description:"Check subscription status",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_open_dashboard",description:"Open Borg MCP dashboard in browser to manage cubes, roles, and drones",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_regen",description:"Refresh your context as a Drone. Returns the active cube's directive, your role's detailed playbook, the drone roster, and recent activity log entries \u2014 everything you need to be oriented. Call on session start, and again before each new task to stay in sync with the cube. Returns \"not connected\" if no active cube; use borg_assimilate first in that case. Optional `since` (entry-id UUID or ISO-8601 timestamp) trims the recent-log section to entries strictly after the anchor \u2014 pass your last-seen entry id to skip already-processed history on each refresh.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional cursor. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple) OR an ISO-8601 timestamp. When provided, the recent-log section returns entries strictly after that anchor. Non-existent UUID falls back to default recent window."},mode:{type:"string",enum:["full","lite"],description:"Optional output mode. Use full at session start and after context compaction. Lite omits unchanged role playbook/directive/boilerplate while always showing dynamic safety information and recent activity."}},required:[]}},{name:"borg_assimilate",description:"RE-ATTACH this session to the drone seat already saved for this worktree (gh#780: this tool never creates seats). Provide the cube's name; on a match it returns the cube directive, your role's instructions, and recent activity for the EXISTING seat. To create a seat or switch cubes, run `borg assimilate` in a terminal instead.",inputSchema:{type:"object",properties:{cube_name:{type:"string",description:"The cube to connect to"}},required:["cube_name"]}},{name:"borg_cube",description:"Read the active Cube's directive and the registry of all roles in it (each role's name + short description). Use to remind yourself of cube-wide context.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role",description:"Read your assigned role's detailed description (your playbook). Other drones cannot see this \u2014 only you (drones in this role).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_version",description:"Returns the installed borgmcp client version. Use to verify which version is running in this MCP session.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_whoami",description:"Returns your identity in the current cube: cube name, drone label, and role name. Use to confirm which cube/role/drone you are.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role-rationale",description:"Fetch an on-demand rationale/case-study section for a role playbook. Pass a role name/id and a plain-label section key to read the rationale without expanding every regen.",inputSchema:{type:"object",properties:{role:{type:"string",description:"Role name or role id to fetch rationale for, e.g. Builder."},section:{type:"string",description:"Plain-label role section key, e.g. Workflow rationale."}},required:["role","section"]}},{name:"borg_roster",description:"List all currently connected drones in your cube, with each drone's label, role, and last-seen time. Optional `since` argument adds a sender-side liveness column \u2014 pass either an activity_log entry id (e.g., from a dispatch you posted) or an ISO-8601 timestamp; each drone is marked `awake` if they've posted a log entry after that point, otherwise `stale-since-X`. Useful for confirming a dispatch reached its named recipients (catches the silent-wake-path-failure class where SSE delivered but the drone's /loop never woke).",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional liveness reference point. Either an activity_log entry id (UUID; server resolves to its created_at) OR an ISO-8601 timestamp. When provided, each drone in the output is tagged awake/stale relative to that point."}},required:[]}},{name:"borg_stream-status",description:"Diagnostic probe for the SSE log-stream consumer. Returns the live state of the local stream connection \u2014 `connected`, `lastContentEventAt` (most recent log/bookmark event), `lastWireActivityAt` (most recent event of any type, incl. heartbeats), `lastHeartbeatAt`, `lastPersistedEventId`, and `reconnectAttempts` \u2014 plus a wake-path completeness check that surfaces if SSE is attached but no inbox-Monitor is watching the file (the silent-failure mode where Claude's `/loop` never wakes on incoming entries). Reads in-process state from the running borgmcp client; does NOT re-open the stream, so calling it cannot perturb the very thing it's observing. Useful when troubleshooting wake-up issues, verifying the stream is alive without other drones logging, or pre-checking before fault-injection tests.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_read-log",description:"Read entries from the cube's activity log. Each entry is tagged with the drone that wrote it and that drone's role. For wake triage, prefer `unread_only=true` with a modest limit and drain until `has_more=false`; this reads oldest-unread-first from your server cursor and advances the watermark so bursts are not skipped. Optional `since` is a strict-after cursor for explicit bounded reads only; do not use it with the same timestamp as a notification preview because it can skip the boundary entry.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional strict-after cursor for explicit bounded reads. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple for deterministic tie-break) OR an ISO-8601 timestamp. Do not use for routine wake triage; prefer unread_only."},limit:{type:"number",description:"max entries to return (1-500)"},unread_only:{type:"boolean",description:"When true, read only entries posted after this drone last called read-log, oldest-unread-first. Server advances the watermark to the newest returned entry on every call; if has_more=true, call again until has_more=false."}}}},{name:"borg_ack",description:"Mark a log entry as explicitly acknowledged. Replaces the convention of posting `ACK: <dispatch-id>` log entries. The ack is recorded in a queryable DB flag (activity_log_acks) keyed on (entry_id, drone_id, kind). Idempotent \u2014 repeated calls on the same entry are no-ops. Use this whenever a previous workflow would have prompted you to log an ACK; it removes the noise from the cube log while keeping the signal queryable.",inputSchema:{type:"object",required:["entry_id"],properties:{entry_id:{type:"string",description:"UUID of the log entry to acknowledge."}}}},{name:"borg_log",description:"Append a message to the cube's activity log. By default entries broadcast to all drones. When a cube declares a message taxonomy, borg_log applies class-based smart defaults: prefix-matched directed classes route to their default recipients unless you pass `to:`, `class:`, or explicit visibility. Pass `to: [...]` to direct by exact drone label, drone id, role name, or role slug.",inputSchema:{type:"object",properties:{message:{type:"string",description:"The log message (max 10KB)."},to:{type:"array",items:{type:"string"},description:"Optional direct-message recipients by exact drone label, drone id, role name, or role slug (resolves to all drones in that role). Omit to let class-based routing or broadcast defaults apply."},class:{type:"string",description:"Optional declared message class. Overrides prefix auto-classification when the cube declares a message taxonomy."},visibility:{type:"string",enum:["broadcast","direct"],description:"Optional explicit visibility. Overrides class-based routing defaults."}},required:["message"]}},{name:"borg_report-friction",description:"Report friction or a bug directly to the borgmcp dev team. WRITE-ONLY \u2014 you cannot read reports back. Use it when something about borg itself slowed you down, confused you, or broke: awkward UX, an unclear playbook, a missing affordance, or a bug you hit while using borg. Secrets (tokens, keys) are auto-scrubbed server-side before storage, but avoid pasting them anyway.",inputSchema:{type:"object",properties:{message:{type:"string",description:"What hit you + what you expected instead (max 10KB). Concrete and specific helps the dev team most."},kind:{type:"string",enum:["friction","bug"],description:"'friction' (default) for UX/workflow friction; 'bug' for something broken."},metadata:{type:"object",description:"Optional non-secret context. Allowed keys only: version, cube_id, os. Any other key is rejected."}},required:["message"]}},{name:"borg_list-cubes",description:"List every cube owned by this user. Returns id, name, cube_directive, and timestamps for each. Useful before assimilate to see what's available, or as a starting point for any management action.",inputSchema:{type:"object",properties:{}}},{name:"borg_create-cube",description:'Create a new cube. The server seeds a default "Drone" role atomically so the cube is assimilatable immediately. Pass an optional `template` name to apply a richer role set instead (see borg_list-templates / borg_apply-template).',inputSchema:{type:"object",properties:{name:{type:"string",description:"Cube name (lowercase letters, digits, hyphens; max 64 chars).",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"Markdown text every drone in this cube will see in regen. Anything project-specific."},template:{type:"string",description:'Optional template name to apply after cube creation (e.g. "software-dev"). Roles are merged by name; the default Drone role gets overwritten by the template if a same-named role is in the template.'}},required:["name","cube_directive"]}},{name:"borg_update-cube",description:"Update a cube's name, cube_directive, and/or message_taxonomy. Pass only what changes.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to update."},name:{type:"string",description:"New name (optional). Lowercase letters, digits, hyphens; max 64 chars.",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"New cube directive markdown (optional)."},message_taxonomy:{type:"array",description:"New message-class taxonomy (optional). REPLACES the whole taxonomy; the worker re-validates the full array (non-overlapping prefixes, unique class names, directed classes need default_to). Pass [] to clear. To change ONE class without resending the whole array, use borg_patch-taxonomy-class instead. In default_to, pass @human-seat to route to drones in the cube human-seat role(s); literal role names/slugs/labels still work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",items:{type:"object",properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (role name/slug/label, or @human-seat) for a directed class."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}}}}},required:["cube_id"]}},{name:"borg_patch-taxonomy-class",description:"Surgically patch ONE message-class within a cube's message_taxonomy, leaving other classes unchanged. Use this instead of borg_update-cube when adding/changing a single class so you don't resend (and risk clobbering) the whole taxonomy. action=add appends a new class; action=replace overwrites the class with the same name (case-insensitive); action=remove drops a class. The whole resulting taxonomy is re-validated (non-overlapping prefixes, unique class names, directed classes need default_to) \u2014 a single-class patch that breaks a cross-class rule against an untouched class is rejected. In default_to, pass @human-seat to route to drones in the cube human-seat role(s); literal role names/slugs/labels still work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to patch."},action:{type:"string",enum:["add","replace","remove"],description:"add / replace / remove a single class."},class_def:{type:"object",description:'The class definition (for add/replace). Shape: { class, prefixes?, routing: "broadcast"|"directed", default_to?, lifecycle? }.',properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (required for directed classes): role name/slug/label, or @human-seat."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}},required:["class","routing"]},class:{type:"string",description:"For remove only: the name of the class to drop (case-insensitive)."}},required:["cube_id","action"]}},{name:"borg_delete-cube",description:"Delete a cube and all its roles, drones, and log entries. Irreversible \u2014 confirm with the user before invoking unless the cube is clearly disposable.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to delete."}},required:["cube_id"]}},{name:"borg_create-role",description:"Create a role inside a cube. The detailed_description is the role's playbook \u2014 only drones assigned to this role see it. Setting is_default=true demotes any existing default; a cube has exactly one default role at a time.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube this role belongs to."},name:{type:"string",description:'Role name (e.g. "Builder", "Reviewer").'},short_description:{type:"string",description:"One-line summary, shown to every drone in the cube."},detailed_description:{type:"string",description:"Full playbook for drones in this role \u2014 workflow, conventions, log signals to post."},is_default:{type:"boolean",description:"If true, new drones assimilating into this cube are assigned this role. Demotes the previous default."},is_human_seat:{type:"boolean",description:"If true, this role represents the cube's human-occupied seat (where the human Queen sits directly). The class-hierarchy guard in reassign-drone allows promotion FROM a human-seat role TO the platform Queen role; promotion from non-human-seat roles is rejected."},can_broadcast:{type:"boolean",description:"If true, drones in this role may post broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"If true, drones in this role can see direct log entries as observer/audit recipients."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["cube_id","name","short_description","detailed_description"]}},{name:"borg_update-role",description:"Update a role. Pass only the fields that change. Promoting to is_default demotes the previous default in the same cube.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to update."},name:{type:"string",description:"New role name (optional)."},short_description:{type:"string",description:"New short description (optional)."},detailed_description:{type:"string",description:"New detailed playbook (optional)."},is_default:{type:"boolean",description:"Set true to make this the cube's default role (optional)."},is_human_seat:{type:"boolean",description:"Set true/false to mark/unmark this as the cube's human-occupied seat (the elevation source for the platform Queen role)."},can_broadcast:{type:"boolean",description:"Set true/false to allow or deny broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"Set true/false to grant or remove observer visibility into direct log entries."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["role_id"]}},{name:"borg_patch-role-section",description:"Surgically patch ONE named section of a role's detailed_description, leaving the rest of the field byte-identical. Sections are delimited by plain-label lines (e.g. `Workflow:`, `Project conventions:`) \u2014 NOT markdown headings; text before the first label is the preamble. Use this instead of borg_update-role when changing a single section so you don't have to resend (and risk clobbering) the whole playbook. action=replace overwrites a section's body; action=insert adds a new section (optionally after a named one, else appended); action=delete removes a section.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to patch."},action:{type:"string",enum:["replace","insert","delete"],description:"replace / insert / delete a single section."},heading:{type:"string",description:'The section label WITHOUT the trailing colon (e.g. "Workflow"). Matched case-insensitively.'},body:{type:"string",description:"New text BELOW the heading (for replace/insert). Omit for delete."},after:{type:"string",description:"For insert only: place the new section after the section with this heading. Omit/null to append at the end."}},required:["role_id","action","heading"]}},{name:"borg_delete-role",description:"Delete a role. Refuses if any drone is still assigned \u2014 reassign or evict those drones from the dashboard first.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to delete."}},required:["role_id"]}},{name:"borg_reassign-drone",description:"Reassign a drone to a different role in the same cube. Coordinator-shaped: the cube's Coordinator drone is the one expected to call this when dispatching new drones to specific work. Server refuses if you try to assign to the Coordinator role when another drone already holds it (evict or reassign that drone first).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to reassign."},role_id:{type:"string",description:"UUID of the target role. Must belong to the same cube as the drone."}},required:["drone_id","role_id"]}},{name:"borg_evict-drone",description:"Evict (soft-delete) a drone from its cube. Coordinator-shaped: the cube's Coordinator/Queen seat calls this to remove a dead, stuck, or surplus drone \u2014 it drops out of the roster and frees its slot (incl. a held Coordinator/Queen-class seat), while its activity-log history is preserved with anonymized attribution. Owner-scoped: you can only evict drones in cubes you own. Identify the drone EITHER by drone_id (UUID) OR by label + cube_id (the label as it appears in the roster/regen).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to evict. Provide this OR (label + cube_id)."},label:{type:"string",description:'Drone label to evict, e.g. "two-of-seventeen-builder". Requires cube_id. Ignored when drone_id is given.'},cube_id:{type:"string",description:"UUID of the cube the labelled drone belongs to. Required when evicting by label."}}}},{name:"borg_list-drones",description:"List every drone in a cube (owner-scoped). Returns id, label, role_id, agent_kind, last_seen, and wake_path_alert_class for each \u2014 gives the Coordinator a roster they can act on with borg_reassign-drone.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose drones to list."}},required:["cube_id"]}},{name:"borg_list-roles",description:"List every role in a cube (owner-scoped). Returns id, name, short_description, is_default, is_human_seat, can_broadcast, receives_all_direct, and role_class for each \u2014 gives Coordinator-class drones the role UUIDs they need for borg_reassign-drone (e.g. to promote a drone to the Queen role). Closes the gh#153 Queen-role-promotion UX gap (Coordinator drones previously had no way to discover role IDs without operator help).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose roles to list."}},required:["cube_id"]}},{name:"borg_list-templates",description:"List available cube templates that can be applied via borg_apply-template or passed to borg_create-cube.",inputSchema:{type:"object",properties:{}}},{name:"borg_apply-template",description:"Apply a named template to an existing cube, NON-CLOBBERINGLY. Roles are merged by name: new roles are created; existing template-named roles get template sections/classes the cube LACKS auto-applied, but EVOLVED (conflicting) text is preserved, never overwritten. Use this to retrofit an existing cube with a richer role set (e.g. add Coordinator/Reviewer/UX Expert). To review + selectively accept conflicting fragments, use borg_sync-roles (which surfaces each conflict + takes per-fragment accept decisions).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to apply the template to."},template_name:{type:"string",description:"Template to apply (see borg_list-templates)."}},required:["cube_id","template_name"]}},{name:"borg_sync-roles",description:"Non-clobbering sync of an existing cube's roles + message_taxonomy against the current built-in template. The dry-run (default) classifies each FRAGMENT (role-text section, short_description, role flags, or taxonomy class) as ADD (the cube lacks it \u2014 safe auto-apply), UNCHANGED, or CONFLICT (the cube has EVOLVED text that differs from the template). On apply, ADDs auto-apply; CONFLICTs are applied ONLY when you explicitly accept them via `decisions` (keyed on the stable fragment key shown in the dry-run, e.g. `role:Builder:section:Workflow`). Unspecified conflicts default to KEEP (reject) \u2014 your cube's evolved coordination text is NEVER silently overwritten. Custom roles (names not in the template) are never touched.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to sync."},template_name:{type:"string",description:"Template to sync against (default: software-dev)."},apply:{type:"boolean",description:"If true, commit (auto-apply ADDs + accepted conflicts). If false (default), dry-run only \u2014 classify + surface conflicts."},decisions:{type:"object",description:'Per-conflict accept/reject map, keyed on the fragment key from the dry-run (e.g. {"role:Builder:section:Workflow":"accept"}). Unspecified conflicts default to "reject" (keep the cube version).',additionalProperties:{type:"string",enum:["accept","reject"]}}},required:["cube_id"]}}]})),p.setRequestHandler(z,async m=>{const{name:g,arguments:r}=m.params;if(!Xe(`tool ${g}`))return{content:[{type:"text",text:Ge(g)}],isError:!0};try{switch(g){case"borg_regen":{const e=await y();if(!e)return{content:[{type:"text",text:'Not connected to a cube. Use `borg_assimilate cube_name="<name>"` to join one.'}]};const t=typeof r?.since=="string"?r.since:void 0,i=r?.mode==="lite"?"lite":"full",o=await O(e.sessionToken,e.apiUrl,{since:t}),s=N(e,o);s!==e&&await P(s);const n=I(),a=E(s.cubeId,s.droneId),c=C()?!0:q(a),d=Ae(n,c)?Te({inboxPath:a,droneLabel:qe(o,s.droneLabel),cubeName:s.name}):"";let u="";try{const h=w(),l=De();if(h!=="unknown"&&l!=="unknown"&&l!==h){const[b,R,H]=h.split(".").map(Number),[k,D,K]=l.split(".").map(Number);(k>b||k===b&&D>R||k===b&&D===R&&K>H)&&(u=`## \u{1F504} borgmcp ${l} installed \u2014 run /mcp and reconnect (or restart Claude Code) to apply. Currently running ${h}.
2
+ import{Server as K}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as z}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as X,ListToolsRequestSchema as Y,ListPromptsRequestSchema as G,GetPromptRequestSchema as J}from"@modelcontextprotocol/sdk/types.js";import{getCubeInfo as Z,getRoleInfo as j,getRoster as ee,readLog as te,appendLog as re,submitReport as oe,ackLogEntry as ie,regen as T,listCubes as ne,createCube as se,updateCube as O,deleteCube as ae,createRole as ce,updateRole as le,patchRoleSection as $,patchTaxonomyClass as N,deleteRole as de,reassignDrone as pe,evictDrone as ue,getCube as w,checkSubscriptionStatus as me,createBillingPortalSession as be,createSubscription as he,syncRoles as ge,applyTemplate as ye,whoami as fe,roleRationale as _e,getValidToken as we}from"./remote-client.js";import{startHealthBeatTick as ve}from"./health-beat.js";import{getTemplate as S,listTemplateNames as U,resolveCubeDirectiveForCreate as xe,resolveCubeDirectiveForApply as ke,resolveMessageTaxonomyForCreate as $e}from"./templates.js";import{activeCubeWithFreshRegenIdentity as P,getActiveCube as y,setActiveCube as A,inboxPathForDrone as q}from"./cubes.js";import{addSessionStartHook as Se,addUserPromptSubmitHook as Ue}from"./config-utils.js";import{humanAgo as L,formatLogEntryMarkdown as qe,formatRegenMarkdown as M,getDronePlaybook as Ie,nullTaxonomyTip as Ee,regenWakePathDroneLabel as Ce}from"./regen-format.js";import{startLogStream as Re,getStreamStatus as I}from"./log-stream.js";import{renderRoleList as De}from"./list-roles-render.js";import{filterToolsForRole as je}from"./tool-scope.js";import{getPackageVersion as v,getOnDiskVersion as Te,handleVersionFlag as Oe}from"./version.js";import{renderStreamStatus as Ne,checkInboxMonitorHealthy as E,formatWakePathPrefix as Pe,shouldShowWakePathWarning as Ae}from"./stream-status.js";import{formatRoleAgentLabel as Le,renderRoster as Me}from"./roster-render.js";import{resolveDroneIdByLabel as Be,isUuidShape as Fe}from"./evict-drone.js";import{authRecoveryMessage as We}from"./auth-recovery.js";import{DroneEvictedError as He,DroneFrozenError as Qe,formatEvictedToolResult as Ve,formatFrozenToolResult as Ke}from"./drone-lifecycle.js";import{classifyInSessionAssimilate as ze,reattachOnlyRefusal as Xe,reattachFailureMessage as Ye}from"./assimilate-guard.js";import{gateAllowsActivation as Ge,borgSessionToolNotice as Je}from"./launch-gate.js";import{renderSyncRolesResult as Ze}from"./sync-roles-render.js";import{initConsolePrefix as et,consolePrefix as x}from"./console-prefix.js";import{isCodexRemoteWakeEnabled as C,resolveSessionAgentKind as tt,probeCodexBridgeArmed as rt}from"./codex-app-wake.js";import{lifecycleSignalForMessage as ot,recordLifecycleLog as B,shouldSuppressLifecycleLog as it}from"./lifecycle-log-guard.js";import{normalizeDirectLogRecipients as nt}from"./direct-log.js";import F from"open";import st from"os";function at(){try{const p=st.hostname();return p&&p.trim()?p.trim().slice(0,255):null}catch{return null}}async function W(p,_){return await ye(p,_.name)}async function f(){const p=await y();if(!p)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");return p}async function ct(){Oe();try{Se()}catch{}try{Ue()}catch{}try{Re()}catch{}try{ve({getActiveCube:y,getStreamConnected:()=>I().connected,getInboxPath:u=>q(u.cubeId,u.droneId),checkMonitor:E,isCodexRemoteWake:C,probeBridgeArmed:u=>rt({cubeId:u.cubeId,droneId:u.droneId}),resolveAgentKind:tt,resolveHostname:at,resolveVersion:v,getToken:we,fetchImpl:globalThis.fetch.bind(globalThis)})}catch{}const p=new K({name:"borg-mcp-client",version:v()},{capabilities:{tools:{},prompts:{}}}),_=[{name:"borg_subscribe",description:"Create Stripe checkout session for Cube tier ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_upgrade-subscription",description:"Open the Stripe Billing Portal to manage Cube tier quantity ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_subscription_status",description:"Check subscription status",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_open_dashboard",description:"Open Borg MCP dashboard in browser to manage cubes, roles, and drones",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_regen",description:"Refresh your context as a Drone. Returns the active cube's directive, your role's detailed playbook, the drone roster, and recent activity log entries \u2014 everything you need to be oriented. Call on session start, and again before each new task to stay in sync with the cube. Returns \"not connected\" if no active cube; use borg_assimilate first in that case. Optional `since` (entry-id UUID or ISO-8601 timestamp) trims the recent-log section to entries strictly after the anchor \u2014 pass your last-seen entry id to skip already-processed history on each refresh.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional cursor. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple) OR an ISO-8601 timestamp. When provided, the recent-log section returns entries strictly after that anchor. Non-existent UUID falls back to default recent window."},mode:{type:"string",enum:["full","lite"],description:"Optional output mode. Use full at session start and after context compaction. Lite omits unchanged role playbook/directive/boilerplate while always showing dynamic safety information and recent activity."}},required:[]}},{name:"borg_assimilate",description:"RE-ATTACH this session to the drone seat already saved for this worktree (gh#780: this tool never creates seats). Provide the cube's name; on a match it returns the cube directive, your role's instructions, and recent activity for the EXISTING seat. To create a seat or switch cubes, run `borg assimilate` in a terminal instead.",inputSchema:{type:"object",properties:{cube_name:{type:"string",description:"The cube to connect to"}},required:["cube_name"]}},{name:"borg_cube",description:"Read the active Cube's directive and the registry of all roles in it (each role's name + short description). Use to remind yourself of cube-wide context.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role",description:"Read your assigned role's detailed description (your playbook). Other drones cannot see this \u2014 only you (drones in this role).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_version",description:"Returns the installed borgmcp client version. Use to verify which version is running in this MCP session.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_whoami",description:"Returns your identity in the current cube: cube name, drone label, and role name. Use to confirm which cube/role/drone you are.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role-rationale",description:"Fetch an on-demand rationale/case-study section for a role playbook. Pass a role name/id and a plain-label section key to read the rationale without expanding every regen.",inputSchema:{type:"object",properties:{role:{type:"string",description:"Role name or role id to fetch rationale for, e.g. Builder."},section:{type:"string",description:"Plain-label role section key, e.g. Workflow rationale."}},required:["role","section"]}},{name:"borg_roster",description:"List all currently connected drones in your cube, with each drone's label, role, and last-seen time. Optional `since` argument adds a sender-side liveness column \u2014 pass either an activity_log entry id (e.g., from a dispatch you posted) or an ISO-8601 timestamp; each drone is marked `awake` if they've posted a log entry after that point, otherwise `stale-since-X`. Useful for confirming a dispatch reached its named recipients (catches the silent-wake-path-failure class where SSE delivered but the drone's /loop never woke).",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional liveness reference point. Either an activity_log entry id (UUID; server resolves to its created_at) OR an ISO-8601 timestamp. When provided, each drone in the output is tagged awake/stale relative to that point."}},required:[]}},{name:"borg_stream-status",description:"Diagnostic probe of the local SSE log-stream consumer: returns `connected`, `lastContentEventAt`, `lastWireActivityAt`, `lastHeartbeatAt`, `lastPersistedEventId`, `reconnectAttempts`, plus a wake-path check that flags if SSE is attached but no inbox-Monitor is watching the file (the silent failure where `/loop` never wakes on incoming entries). Read-only in-process state; does NOT re-open the stream. Use when troubleshooting wake-ups or verifying the stream is alive.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_read-log",description:"Read entries from the cube's activity log. Each entry is tagged with the drone that wrote it and that drone's role. For wake triage, prefer `unread_only=true` with a modest limit and drain until `has_more=false`; this reads oldest-unread-first from your server cursor and advances the watermark so bursts are not skipped. Optional `since` is a strict-after cursor for explicit bounded reads only; do not use it with the same timestamp as a notification preview because it can skip the boundary entry.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional strict-after cursor for explicit bounded reads. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple for deterministic tie-break) OR an ISO-8601 timestamp. Do not use for routine wake triage; prefer unread_only."},limit:{type:"number",description:"max entries to return (1-500)"},unread_only:{type:"boolean",description:"When true, read only entries posted after this drone last called read-log, oldest-unread-first. Server advances the watermark to the newest returned entry on every call; if has_more=true, call again until has_more=false."}}}},{name:"borg_ack",description:"Mark a log entry as explicitly acknowledged. Replaces the convention of posting `ACK: <dispatch-id>` log entries. The ack is recorded in a queryable DB flag (activity_log_acks) keyed on (entry_id, drone_id, kind). Idempotent \u2014 repeated calls on the same entry are no-ops. Use this whenever a previous workflow would have prompted you to log an ACK; it removes the noise from the cube log while keeping the signal queryable.",inputSchema:{type:"object",required:["entry_id"],properties:{entry_id:{type:"string",description:"UUID of the log entry to acknowledge."}}}},{name:"borg_log",description:"Append a message to the cube's activity log. By default entries broadcast to all drones. When a cube declares a message taxonomy, borg_log applies class-based smart defaults: prefix-matched directed classes route to their default recipients unless you pass `to:`, `class:`, or explicit visibility. Pass `to: [...]` to direct by exact drone label, drone id, role name, or role slug.",inputSchema:{type:"object",properties:{message:{type:"string",description:"The log message (max 10KB)."},to:{type:"array",items:{type:"string"},description:"Optional direct-message recipients by exact drone label, drone id, role name, or role slug (resolves to all drones in that role). Omit to let class-based routing or broadcast defaults apply."},class:{type:"string",description:"Optional declared message class. Overrides prefix auto-classification when the cube declares a message taxonomy."},visibility:{type:"string",enum:["broadcast","direct"],description:"Optional explicit visibility. Overrides class-based routing defaults."}},required:["message"]}},{name:"borg_report-friction",description:"Report friction or a bug directly to the borgmcp dev team. WRITE-ONLY \u2014 you cannot read reports back. Use it when something about borg itself slowed you down, confused you, or broke: awkward UX, an unclear playbook, a missing affordance, or a bug you hit while using borg. Secrets (tokens, keys) are auto-scrubbed server-side before storage, but avoid pasting them anyway.",inputSchema:{type:"object",properties:{message:{type:"string",description:"What hit you + what you expected instead (max 10KB). Concrete and specific helps the dev team most."},kind:{type:"string",enum:["friction","bug"],description:"'friction' (default) for UX/workflow friction; 'bug' for something broken."},metadata:{type:"object",description:"Optional non-secret context. Allowed keys only: version, cube_id, os. Any other key is rejected."}},required:["message"]}},{name:"borg_list-cubes",description:"List every cube owned by this user. Returns id, name, cube_directive, and timestamps for each. Useful before assimilate to see what's available, or as a starting point for any management action.",inputSchema:{type:"object",properties:{}}},{name:"borg_create-cube",description:'Create a new cube. The server seeds a default "Drone" role atomically so the cube is assimilatable immediately. Pass an optional `template` name to apply a richer role set instead (see borg_list-templates / borg_apply-template).',inputSchema:{type:"object",properties:{name:{type:"string",description:"Cube name (lowercase letters, digits, hyphens; max 64 chars).",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"Markdown text every drone in this cube will see in regen. Anything project-specific."},template:{type:"string",description:'Optional template name to apply after cube creation (e.g. "software-dev"). Roles are merged by name; the default Drone role gets overwritten by the template if a same-named role is in the template.'}},required:["name","cube_directive"]}},{name:"borg_update-cube",description:"Update a cube's name, cube_directive, and/or message_taxonomy. Pass only what changes.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to update."},name:{type:"string",description:"New name (optional). Lowercase letters, digits, hyphens; max 64 chars.",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"New cube directive markdown (optional)."},message_taxonomy:{type:"array",description:"New message-class taxonomy (optional). REPLACES the whole taxonomy; the worker re-validates the full array (non-overlapping prefixes, unique class names, directed classes need default_to). Pass [] to clear. To change ONE class without resending the whole array, use borg_patch-taxonomy-class instead. In default_to, pass @human-seat to route to drones in the cube human-seat role(s); literal role names/slugs/labels still work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",items:{type:"object",properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (role name/slug/label, or @human-seat) for a directed class."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}}}}},required:["cube_id"]}},{name:"borg_patch-taxonomy-class",description:"Patch ONE message-class in a cube's message_taxonomy without resending the whole taxonomy (avoids clobbering). action=add|replace|remove (replace/remove match name case-insensitively). The full taxonomy is re-validated after the patch (non-overlapping prefixes, unique names, directed classes need default_to) \u2014 a patch that breaks a rule against an untouched class is rejected. In default_to, @human-seat routes to the cube's human-seat role(s); literal names/slugs/labels also work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to patch."},action:{type:"string",enum:["add","replace","remove"],description:"add / replace / remove a single class."},class_def:{type:"object",description:'The class definition (for add/replace). Shape: { class, prefixes?, routing: "broadcast"|"directed", default_to?, lifecycle? }.',properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (required for directed classes): role name/slug/label, or @human-seat."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}},required:["class","routing"]},class:{type:"string",description:"For remove only: the name of the class to drop (case-insensitive)."}},required:["cube_id","action"]}},{name:"borg_delete-cube",description:"Delete a cube and all its roles, drones, and log entries. Irreversible \u2014 confirm with the user before invoking unless the cube is clearly disposable.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to delete."}},required:["cube_id"]}},{name:"borg_create-role",description:"Create a role inside a cube. The detailed_description is the role's playbook \u2014 only drones assigned to this role see it. Setting is_default=true demotes any existing default; a cube has exactly one default role at a time.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube this role belongs to."},name:{type:"string",description:'Role name (e.g. "Builder", "Reviewer").'},short_description:{type:"string",description:"One-line summary, shown to every drone in the cube."},detailed_description:{type:"string",description:"Full playbook for drones in this role \u2014 workflow, conventions, log signals to post."},is_default:{type:"boolean",description:"If true, new drones assimilating into this cube are assigned this role. Demotes the previous default."},is_human_seat:{type:"boolean",description:"If true, this role represents the cube's human-occupied seat (where the human Queen sits directly). The class-hierarchy guard in reassign-drone allows promotion FROM a human-seat role TO the platform Queen role; promotion from non-human-seat roles is rejected."},can_broadcast:{type:"boolean",description:"If true, drones in this role may post broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"If true, drones in this role can see direct log entries as observer/audit recipients."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["cube_id","name","short_description","detailed_description"]}},{name:"borg_update-role",description:"Update a role. Pass only the fields that change. Promoting to is_default demotes the previous default in the same cube.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to update."},name:{type:"string",description:"New role name (optional)."},short_description:{type:"string",description:"New short description (optional)."},detailed_description:{type:"string",description:"New detailed playbook (optional)."},is_default:{type:"boolean",description:"Set true to make this the cube's default role (optional)."},is_human_seat:{type:"boolean",description:"Set true/false to mark/unmark this as the cube's human-occupied seat (the elevation source for the platform Queen role)."},can_broadcast:{type:"boolean",description:"Set true/false to allow or deny broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"Set true/false to grant or remove observer visibility into direct log entries."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["role_id"]}},{name:"borg_patch-role-section",description:"Surgically patch ONE named section of a role's detailed_description, leaving the rest of the field byte-identical. Sections are delimited by plain-label lines (e.g. `Workflow:`, `Project conventions:`) \u2014 NOT markdown headings; text before the first label is the preamble. Use this instead of borg_update-role when changing a single section so you don't have to resend (and risk clobbering) the whole playbook. action=replace overwrites a section's body; action=insert adds a new section (optionally after a named one, else appended); action=delete removes a section.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to patch."},action:{type:"string",enum:["replace","insert","delete"],description:"replace / insert / delete a single section."},heading:{type:"string",description:'The section label WITHOUT the trailing colon (e.g. "Workflow"). Matched case-insensitively.'},body:{type:"string",description:"New text BELOW the heading (for replace/insert). Omit for delete."},after:{type:"string",description:"For insert only: place the new section after the section with this heading. Omit/null to append at the end."}},required:["role_id","action","heading"]}},{name:"borg_delete-role",description:"Delete a role. Refuses if any drone is still assigned \u2014 reassign or evict those drones from the dashboard first.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to delete."}},required:["role_id"]}},{name:"borg_reassign-drone",description:"Reassign a drone to a different role in the same cube. Coordinator-shaped: the cube's Coordinator drone is the one expected to call this when dispatching new drones to specific work. Server refuses if you try to assign to the Coordinator role when another drone already holds it (evict or reassign that drone first).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to reassign."},role_id:{type:"string",description:"UUID of the target role. Must belong to the same cube as the drone."}},required:["drone_id","role_id"]}},{name:"borg_evict-drone",description:"Evict (soft-delete) a drone from its cube. Coordinator-shaped: the cube's Coordinator/Queen seat calls this to remove a dead, stuck, or surplus drone \u2014 it drops out of the roster and frees its slot (incl. a held Coordinator/Queen-class seat), while its activity-log history is preserved with anonymized attribution. Owner-scoped: you can only evict drones in cubes you own. Identify the drone EITHER by drone_id (UUID) OR by label + cube_id (the label as it appears in the roster/regen).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to evict. Provide this OR (label + cube_id)."},label:{type:"string",description:'Drone label to evict, e.g. "two-of-seventeen-builder". Requires cube_id. Ignored when drone_id is given.'},cube_id:{type:"string",description:"UUID of the cube the labelled drone belongs to. Required when evicting by label."}}}},{name:"borg_list-drones",description:"List every drone in a cube (owner-scoped). Returns id, label, role_id, agent_kind, last_seen, and wake_path_alert_class for each \u2014 gives the Coordinator a roster they can act on with borg_reassign-drone.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose drones to list."}},required:["cube_id"]}},{name:"borg_list-roles",description:"List every role in a cube (owner-scoped). Returns id, name, short_description, is_default, is_human_seat, can_broadcast, receives_all_direct, and role_class for each \u2014 gives Coordinator-class drones the role UUIDs they need for borg_reassign-drone (e.g. to promote a drone to the Queen role). Closes the gh#153 Queen-role-promotion UX gap (Coordinator drones previously had no way to discover role IDs without operator help).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose roles to list."}},required:["cube_id"]}},{name:"borg_list-templates",description:"List available cube templates that can be applied via borg_apply-template or passed to borg_create-cube.",inputSchema:{type:"object",properties:{}}},{name:"borg_apply-template",description:"Apply a named template to an existing cube, NON-CLOBBERINGLY. Roles are merged by name: new roles are created; existing template-named roles get template sections/classes the cube LACKS auto-applied, but EVOLVED (conflicting) text is preserved, never overwritten. Use this to retrofit an existing cube with a richer role set (e.g. add Coordinator/Reviewer/UX Expert). To review + selectively accept conflicting fragments, use borg_sync-roles (which surfaces each conflict + takes per-fragment accept decisions).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to apply the template to."},template_name:{type:"string",description:"Template to apply (see borg_list-templates)."}},required:["cube_id","template_name"]}},{name:"borg_sync-roles",description:"Non-clobbering sync of a cube's roles + message_taxonomy against the built-in template. Dry-run (default) classifies each fragment (role-text section, short_description, role flags, taxonomy class) as ADD (cube lacks it \u2014 safe auto-apply), UNCHANGED, or CONFLICT (cube has EVOLVED text). On apply, ADDs auto-apply; CONFLICTs apply ONLY via an explicit `decisions` accept (keyed on the dry-run fragment key, e.g. `role:Builder:section:Workflow`); unspecified conflicts default to reject \u2014 evolved text is NEVER silently overwritten. Custom roles untouched.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to sync."},template_name:{type:"string",description:"Template to sync against (default: software-dev)."},apply:{type:"boolean",description:"If true, commit (auto-apply ADDs + accepted conflicts). If false (default), dry-run only \u2014 classify + surface conflicts."},decisions:{type:"object",description:'Per-conflict accept/reject map, keyed on the fragment key from the dry-run (e.g. {"role:Builder:section:Workflow":"accept"}). Unspecified conflicts default to "reject" (keep the cube version).',additionalProperties:{type:"string",enum:["accept","reject"]}}},required:["cube_id"]}},{name:"borg_tool",description:`Dispatcher: invoke ANY borg tool by name, including tools not pre-loaded in your role-scoped surface. Pass {"name":"<borg_tool>","arguments":{...}}. Routes through the identical auth + validation path as a direct call. Call borg_describe-tool first to learn a deferred tool's arguments.`,inputSchema:{type:"object",properties:{name:{type:"string",description:'The borg tool to invoke, e.g. "borg_evict-drone".'},arguments:{type:"object",description:"The arguments object for that tool (same shape as a direct call)."}},required:["name"]}},{name:"borg_describe-tool",description:"Return the description + input schema for any borg tool by name \u2014 including deferred tools not pre-loaded in your surface. Schema-only; never executes the tool. Pair with borg_tool to invoke a deferred tool.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The borg tool to describe."}},required:["name"]}}];p.setRequestHandler(Y,async()=>{let u=null;try{const m=await y();m&&(u={roleName:m.roleName,roleClass:m.roleClass,isHumanSeat:m.isHumanSeat})}catch{u=null}return{tools:je(_,u)}}),p.setRequestHandler(X,async u=>{let{name:m,arguments:r}=u.params;if(m==="borg_describe-tool"){const e=typeof r?.name=="string"?r.name:"",t=_.find(i=>i.name===e);return t?{content:[{type:"text",text:JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema},null,2)}]}:{content:[{type:"text",text:`Unknown borg tool: ${e||"(none)"}. Pass { name: "<borg_tool>" }.`}],isError:!0}}if(m==="borg_tool"){const e=typeof r?.name=="string"?r.name:"";if(!e||e==="borg_tool"||e==="borg_describe-tool")return{content:[{type:"text",text:'borg_tool: pass { name: "<borg_tool>", arguments: {...} } naming a real borg tool (not the dispatcher itself).'}],isError:!0};r=r?.arguments&&typeof r.arguments=="object"?r.arguments:{},m=e}if(!Ge(`tool ${m}`))return{content:[{type:"text",text:Je(m)}],isError:!0};try{switch(m){case"borg_regen":{const e=await y();if(!e)return{content:[{type:"text",text:'Not connected to a cube. Use `borg_assimilate cube_name="<name>"` to join one.'}]};const t=typeof r?.since=="string"?r.since:void 0,i=r?.mode==="lite"?"lite":"full",o=await T(e.sessionToken,e.apiUrl,{since:t}),s=P(e,o);s!==e&&await A(s);const n=I(),a=q(s.cubeId,s.droneId),c=C()?!0:E(a),d=Ae(n,c)?Pe({inboxPath:a,droneLabel:Ce(o,s.droneLabel),cubeName:s.name}):"";let b="";try{const h=v(),l=Te();if(h!=="unknown"&&l!=="unknown"&&l!==h){const[g,R,Q]=h.split(".").map(Number),[k,D,V]=l.split(".").map(Number);(k>g||k===g&&D>R||k===g&&D===R&&V>Q)&&(b=`## \u{1F504} borgmcp ${l} installed \u2014 run /mcp and reconnect (or restart Claude Code) to apply. Currently running ${h}.
3
3
 
4
- `)}}catch{}return{content:[{type:"text",text:u+d+M(o,{mode:i})}]}}case"borg_subscribe":return{content:[{type:"text",text:`Complete your subscription at: ${await he()}`}]};case"borg_upgrade-subscription":{const e=await me();try{await F(e)}catch{}return{content:[{type:"text",text:`Manage your Borg MCP subscription at: ${e}`}]}}case"borg_subscription_status":{const e=await ue();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}case"borg_open_dashboard":{const e="https://borgmcp.ai/dashboard";return await F(e),{content:[{type:"text",text:`\u25FC Opened dashboard in browser: ${e}`}]}}case"borg_assimilate":{const e=r?.cube_name;if(!e)throw new Error("cube_name is required");const t=await y(),i=Qe(t,e);if(i.kind!=="reattach")return{content:[{type:"text",text:Ve(i,e)}],isError:!0};try{const o=await O(t.sessionToken,t.apiUrl,{}),s=N(t,o);return s!==t&&await P(s),{content:[{type:"text",text:[`# Re-attached to cube: ${s.name}`,"",`**Drone label:** ${s.droneLabel}`,"**Seat:** existing identity reused \u2014 no new drone minted (gh#780)","",""].join(`
5
- `)+M(o,{mode:"full"})}]}}catch(o){const s=ze(o??{});if(!s)throw o;return{content:[{type:"text",text:s}],isError:!0}}}case"borg_version":return{content:[{type:"text",text:`borgmcp ${w()}`}]};case"borg_whoami":{const e=await f(),t=await ye(e.sessionToken,e.apiUrl);return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}case"borg_cube":{const e=await f(),[{cube:t,roles:i}]=await Promise.all([J(e.sessionToken,e.apiUrl),j(e.sessionToken,e.apiUrl)]),o=[];o.push(`# Cube: ${t.name}`),o.push(""),o.push("## Cube directive"),o.push(t.cube_directive||"_(none)_"),o.push("");const s=Ie(t.message_taxonomy);if(s&&(o.push(s),o.push("")),o.push("## Roles in this cube"),!i.length)o.push("_(no roles defined)_");else{for(const n of i){const a=[n.role_class==="queen"?"Queen":null,n.is_human_seat?"human-seat":null,n.is_default?"default":null].filter(Boolean).join(", "),c=a?` (${a})`:"",d=n.short_description||"_(no description)_";o.push(`- **${n.name}**${c} \u2014 ${d}`)}o.push(""),o.push("_(Coordinator-class drones can fetch role IDs via `borg_list-roles` for use with `borg_reassign-drone`.)_")}return o.push(""),o.push(Ee()),{content:[{type:"text",text:o.join(`
4
+ `)}}catch{}return{content:[{type:"text",text:b+d+M(o,{mode:i})}]}}case"borg_subscribe":return{content:[{type:"text",text:`Complete your subscription at: ${await he()}`}]};case"borg_upgrade-subscription":{const e=await be();try{await F(e)}catch{}return{content:[{type:"text",text:`Manage your Borg MCP subscription at: ${e}`}]}}case"borg_subscription_status":{const e=await me();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}case"borg_open_dashboard":{const e="https://borgmcp.ai/dashboard";return await F(e),{content:[{type:"text",text:`\u25FC Opened dashboard in browser: ${e}`}]}}case"borg_assimilate":{const e=r?.cube_name;if(!e)throw new Error("cube_name is required");const t=await y(),i=ze(t,e);if(i.kind!=="reattach")return{content:[{type:"text",text:Xe(i,e)}],isError:!0};try{const o=await T(t.sessionToken,t.apiUrl,{}),s=P(t,o);return s!==t&&await A(s),{content:[{type:"text",text:[`# Re-attached to cube: ${s.name}`,"",`**Drone label:** ${s.droneLabel}`,"**Seat:** existing identity reused \u2014 no new drone minted (gh#780)","",""].join(`
5
+ `)+M(o,{mode:"full"})}]}}catch(o){const s=Ye(o??{});if(!s)throw o;return{content:[{type:"text",text:s}],isError:!0}}}case"borg_version":return{content:[{type:"text",text:`borgmcp ${v()}`}]};case"borg_whoami":{const e=await f(),t=await fe(e.sessionToken,e.apiUrl);return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}case"borg_cube":{const e=await f(),[{cube:t,roles:i}]=await Promise.all([Z(e.sessionToken,e.apiUrl),j(e.sessionToken,e.apiUrl)]),o=[];o.push(`# Cube: ${t.name}`),o.push(""),o.push("## Cube directive"),o.push(t.cube_directive||"_(none)_"),o.push("");const s=Ee(t.message_taxonomy);if(s&&(o.push(s),o.push("")),o.push("## Roles in this cube"),!i.length)o.push("_(no roles defined)_");else{for(const n of i){const a=[n.role_class==="queen"?"Queen":null,n.is_human_seat?"human-seat":null,n.is_default?"default":null].filter(Boolean).join(", "),c=a?` (${a})`:"",d=n.short_description||"_(no description)_";o.push(`- **${n.name}**${c} \u2014 ${d}`)}o.push(""),o.push("_(Coordinator-class drones can fetch role IDs via `borg_list-roles` for use with `borg_reassign-drone`.)_")}return o.push(""),o.push(Ie()),{content:[{type:"text",text:o.join(`
6
6
  `)}]}}case"borg_role":{const e=await f(),{role:t}=await j(e.sessionToken,e.apiUrl);return{content:[{type:"text",text:[`# Your role: ${t.name}`,"",t.detailed_description||"_(no detailed description set)_"].join(`
7
- `)}]}}case"borg_role-rationale":{const e=await f(),t=typeof r?.role=="string"?r.role:"",i=typeof r?.section=="string"?r.section:"",o=await fe(e.sessionToken,e.apiUrl,t,i);return{content:[{type:"text",text:[`# Role rationale: ${o.role} \u2014 ${o.section}`,"",o.body||"_(empty)_"].join(`
8
- `)}]}}case"borg_roster":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,{drones:i,roles:o,since:s}=await Z(e.sessionToken,e.apiUrl,t);return{content:[{type:"text",text:Pe({cubeName:e.name,drones:i,roles:o,resolvedSince:s??null,humanAgo:L})}]}}case"borg_stream-status":{const e=I(),t=await y(),i=t?E(t.cubeId,t.droneId):null,o=t?C()?!0:q(i):null;let s="";e.runLoopHealth==="silent-inert"&&(s=`## \u26A0 SSE stream loop silent-inert \u2014 run /mcp and reconnect to restart
7
+ `)}]}}case"borg_role-rationale":{const e=await f(),t=typeof r?.role=="string"?r.role:"",i=typeof r?.section=="string"?r.section:"",o=await _e(e.sessionToken,e.apiUrl,t,i);return{content:[{type:"text",text:[`# Role rationale: ${o.role} \u2014 ${o.section}`,"",o.body||"_(empty)_"].join(`
8
+ `)}]}}case"borg_roster":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,{drones:i,roles:o,since:s}=await ee(e.sessionToken,e.apiUrl,t);return{content:[{type:"text",text:Me({cubeName:e.name,drones:i,roles:o,resolvedSince:s??null,humanAgo:L})}]}}case"borg_stream-status":{const e=I(),t=await y(),i=t?q(t.cubeId,t.droneId):null,o=t?C()?!0:E(i):null;let s="";e.runLoopHealth==="silent-inert"&&(s=`## \u26A0 SSE stream loop silent-inert \u2014 run /mcp and reconnect to restart
9
9
 
10
10
  The log-stream consumer started but never connected. This drone will not receive real-time cube events.
11
11
 
12
- `);const n=Oe({status:e,inboxMonitorHealthy:o,inboxPath:i,droneLabel:t?.droneLabel??null,cubeName:t?.name??null,humanAgo:L});return{content:[{type:"text",text:s+n}]}}case"borg_read-log":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,i=typeof r?.limit=="number"?r.limit:void 0,o=r?.unread_only===!0||r?.unread_only==="true",{entries:s,drones:n,roles:a,behind_by:c,has_more:d}=await ee(e.sessionToken,e.apiUrl,{since:t,limit:i,unreadOnly:o}),u=new Map;for(const b of n)u.set(b.id,b);const h=new Map;for(const b of a)h.set(b.id,b);const l=[];if(l.push(`# Activity log: ${e.name}`),l.push(""),!s.length)l.push("_(no entries)_");else for(const b of s)l.push(Se(b,u,h));return d===!0?(l.push(""),l.push("\u26A0 has_more: true \u2014 call `borg_read-log unread_only=true` again until has_more=false so you finish draining unread entries.")):typeof c=="number"&&c>0&&(l.push(""),l.push(`\u26A0 behind_by: ${c} more unread ${c===1?"entry":"entries"} addressed to you \u2014 call \`borg_read-log unread_only=true\` again until behind_by=0 so you don't skip messages.`)),{content:[{type:"text",text:l.join(`
13
- `)}]}}case"borg_log":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");if(tt(e)){const l=await rt(t,e);if(l.suppress)return await B(t,e),{content:[{type:"text",text:`Suppressed duplicate ${l.signal?.toUpperCase()} lifecycle log for ${t.droneLabel}; recent cube log already contains this signal.`}]}}const i=Object.prototype.hasOwnProperty.call(r??{},"to"),o=i?ot(r?.to):void 0,s=typeof r?.class=="string"?r.class:void 0,n=r?.visibility==="broadcast"||r?.visibility==="direct"?r.visibility:void 0,a={...s?{class:s}:{},...i?{to:o??[]}:{},...n?{visibility:n}:{}},c=await te(t.sessionToken,t.apiUrl,e,a);await B(t,e);const d=c.routing?.message?`
14
- ${c.routing.message}`:"",u=c.unreachableRecipients?.length?`
15
- \u26A0 ${c.unreachableRecipients.length} directed recipient(s) currently unreachable (wake-path:deaf): ${c.unreachableRecipients.map(l=>l.label).join(", ")}. Message delivered \u2014 they'll read it when they return.`:"";return{content:[{type:"text",text:`Logged to cube "${t.name}" as ${t.droneLabel}. (entry id: ${c.entry.id})${d}${u}`}]}}case"borg_report-friction":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");const i=r?.kind==="bug"?"bug":"friction",o=r?.metadata&&typeof r.metadata=="object"&&!Array.isArray(r.metadata)?r.metadata:void 0;return{content:[{type:"text",text:(await re(t.sessionToken,t.apiUrl,{kind:i,message:e,metadata:o})).ok?"Report submitted \u2014 thank you. The borgmcp team will see it. (Write-only: you cannot read reports back.)":"Report did not submit. Try again, or raise it in the cube log."}]}}case"borg_ack":{const e=r?.entry_id;if(!e||typeof e!="string")throw new Error("entry_id is required");const t=await f();return await oe(t.sessionToken,t.apiUrl,e),{content:[{type:"text",text:`Acked entry ${e} in cube "${t.name}".`}]}}case"borg_list-cubes":{const{cubes:e}=await ie();if(!e.length)return{content:[{type:"text",text:"No cubes yet. Use borg_create-cube to make your first one."}]};const t=e.map(i=>`- **${i.name}** (id: ${i.id})
12
+ `);const n=Ne({status:e,inboxMonitorHealthy:o,inboxPath:i,droneLabel:t?.droneLabel??null,cubeName:t?.name??null,humanAgo:L});return{content:[{type:"text",text:s+n}]}}case"borg_read-log":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,i=typeof r?.limit=="number"?r.limit:void 0,o=r?.unread_only===!0||r?.unread_only==="true",{entries:s,drones:n,roles:a,behind_by:c,has_more:d}=await te(e.sessionToken,e.apiUrl,{since:t,limit:i,unreadOnly:o}),b=new Map;for(const g of n)b.set(g.id,g);const h=new Map;for(const g of a)h.set(g.id,g);const l=[];if(l.push(`# Activity log: ${e.name}`),l.push(""),!s.length)l.push("_(no entries)_");else for(const g of s)l.push(qe(g,b,h));return d===!0?(l.push(""),l.push("\u26A0 has_more: true \u2014 call `borg_read-log unread_only=true` again until has_more=false so you finish draining unread entries.")):typeof c=="number"&&c>0&&(l.push(""),l.push(`\u26A0 behind_by: ${c} more unread ${c===1?"entry":"entries"} addressed to you \u2014 call \`borg_read-log unread_only=true\` again until behind_by=0 so you don't skip messages.`)),{content:[{type:"text",text:l.join(`
13
+ `)}]}}case"borg_log":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");if(ot(e)){const l=await it(t,e);if(l.suppress)return await B(t,e),{content:[{type:"text",text:`Suppressed duplicate ${l.signal?.toUpperCase()} lifecycle log for ${t.droneLabel}; recent cube log already contains this signal.`}]}}const i=Object.prototype.hasOwnProperty.call(r??{},"to"),o=i?nt(r?.to):void 0,s=typeof r?.class=="string"?r.class:void 0,n=r?.visibility==="broadcast"||r?.visibility==="direct"?r.visibility:void 0,a={...s?{class:s}:{},...i?{to:o??[]}:{},...n?{visibility:n}:{}},c=await re(t.sessionToken,t.apiUrl,e,a);await B(t,e);const d=c.routing?.message?`
14
+ ${c.routing.message}`:"",b=c.unreachableRecipients?.length?`
15
+ \u26A0 ${c.unreachableRecipients.length} directed recipient(s) currently unreachable (wake-path:deaf): ${c.unreachableRecipients.map(l=>l.label).join(", ")}. Message delivered \u2014 they'll read it when they return.`:"";return{content:[{type:"text",text:`Logged to cube "${t.name}" as ${t.droneLabel}. (entry id: ${c.entry.id})${d}${b}`}]}}case"borg_report-friction":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");const i=r?.kind==="bug"?"bug":"friction",o=r?.metadata&&typeof r.metadata=="object"&&!Array.isArray(r.metadata)?r.metadata:void 0;return{content:[{type:"text",text:(await oe(t.sessionToken,t.apiUrl,{kind:i,message:e,metadata:o})).ok?"Report submitted \u2014 thank you. The borgmcp team will see it. (Write-only: you cannot read reports back.)":"Report did not submit. Try again, or raise it in the cube log."}]}}case"borg_ack":{const e=r?.entry_id;if(!e||typeof e!="string")throw new Error("entry_id is required");const t=await f();return await ie(t.sessionToken,t.apiUrl,e),{content:[{type:"text",text:`Acked entry ${e} in cube "${t.name}".`}]}}case"borg_list-cubes":{const{cubes:e}=await ne();if(!e.length)return{content:[{type:"text",text:"No cubes yet. Use borg_create-cube to make your first one."}]};const t=e.map(i=>`- **${i.name}** (id: ${i.id})
16
16
  ${(i.cube_directive||"_(no directive set)_").split(`
17
17
  `)[0].slice(0,120)}`);return{content:[{type:"text",text:`Your cubes (${e.length}):
18
18
 
19
19
  ${t.join(`
20
20
 
21
- `)}`}]}}case"borg_create-cube":{const e=r?.name,t=r?.cube_directive,i=r?.template;if(!e)throw new Error("name is required");if(t===void 0)throw new Error("cube_directive is required (pass empty string if none)");let o=null;if(i&&(o=U(i),!o))throw new Error(`Unknown template "${i}". Available: ${S().join(", ")}`);const s=ve(t,o),n=ke(void 0,o),a=await ne(e,s,{message_taxonomy:n});if(o){const d=await W(a.id,o),u=s!==t?" Template cube directive applied (operator passed empty).":"";return{content:[{type:"text",text:`Created cube **${a.name}** (id: ${a.id}) with template **${i}** applied \u2014 ${d.created} role(s) created, ${d.updated} updated.${u} Use borg_assimilate ${a.name} to join as a drone.`}]}}return{content:[{type:"text",text:`Created cube **${a.name}** (id: ${a.id}). A default "Drone" role was seeded \u2014 rename or replace it via borg_update-role / borg_create-role / borg_delete-role. Use borg_assimilate ${a.name} to join as a drone.`}]}}case"borg_update-cube":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const t={};if(typeof r?.name=="string"&&(t.name=r.name),typeof r?.cube_directive=="string"&&(t.cube_directive=r.cube_directive),Array.isArray(r?.message_taxonomy)&&(t.message_taxonomy=r.message_taxonomy),Object.keys(t).length===0)throw new Error("Pass at least one of: name, cube_directive, message_taxonomy.");const{cube:i}=await T(e,t);return{content:[{type:"text",text:`Updated cube **${i.name}** (id: ${i.id}).`}]}}case"borg_patch-taxonomy-class":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const t=r?.action;if(t!=="add"&&t!=="replace"&&t!=="remove")throw new Error("action must be one of: add, replace, remove.");let i,o;if(t==="remove"){const n=r?.class;if(!n)throw new Error("class is required for remove.");({cube:i}=await A(e,{action:t,class:n})),o=n}else{const n=r?.class_def;if(n==null||typeof n!="object"||Array.isArray(n))throw new Error("class_def (object) is required for add/replace.");({cube:i}=await A(e,{action:t,class_def:n})),o=String(n.class??"")}return{content:[{type:"text",text:`${t==="add"?"Added":t==="replace"?"Replaced":"Removed"} taxonomy class **${o}** in cube **${i.name}** (id: ${i.id}).`}]}}case"borg_delete-cube":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");return await se(e),{content:[{type:"text",text:`Deleted cube ${e} (and all its roles, drones, log entries).`}]}}case"borg_create-role":{const e=r?.cube_id,t=r?.name,i=r?.short_description,o=r?.detailed_description;if(!e)throw new Error("cube_id is required");if(!t)throw new Error("name is required");if(i===void 0)throw new Error("short_description is required (pass empty string if none)");if(o===void 0)throw new Error("detailed_description is required (pass empty string if none)");const s=r?.is_default===!0,n=r?.is_human_seat===!0,a=r?.can_broadcast===!0,c=r?.receives_all_direct===!0,{role:d}=await ae(e,{name:t,short_description:i,detailed_description:o,is_default:s,is_human_seat:n,can_broadcast:a,receives_all_direct:c,...typeof r?.default_model=="string"?{default_model:r.default_model}:{}}),u=[d.role_class==="queen"?"Queen":null,d.is_human_seat?"human-seat":null,d.is_default?"default":null].filter(Boolean).join(", "),h=u?` (${u})`:"";return{content:[{type:"text",text:`Created role **${d.name}**${h} (id: ${d.id}) in cube ${e}.`}]}}case"borg_update-role":{const e=r?.role_id;if(!e)throw new Error("role_id is required");const t={};if(typeof r?.name=="string"&&(t.name=r.name),typeof r?.short_description=="string"&&(t.short_description=r.short_description),typeof r?.detailed_description=="string"&&(t.detailed_description=r.detailed_description),typeof r?.is_default=="boolean"&&(t.is_default=r.is_default),typeof r?.is_human_seat=="boolean"&&(t.is_human_seat=r.is_human_seat),typeof r?.can_broadcast=="boolean"&&(t.can_broadcast=r.can_broadcast),typeof r?.receives_all_direct=="boolean"&&(t.receives_all_direct=r.receives_all_direct),typeof r?.default_model=="string"&&(t.default_model=r.default_model),Object.keys(t).length===0)throw new Error("Pass at least one of: name, short_description, detailed_description, is_default, is_human_seat, can_broadcast, receives_all_direct, default_model.");const{role:i}=await ce(e,t),o=[i.role_class==="queen"?"Queen":null,i.is_human_seat?"human-seat":null,i.is_default?"default":null].filter(Boolean).join(", "),s=o?` (${o})`:"";return{content:[{type:"text",text:`Updated role **${i.name}**${s} (id: ${i.id}).`}]}}case"borg_patch-role-section":{const e=r?.role_id;if(!e)throw new Error("role_id is required");const t=r?.action;if(t!=="replace"&&t!=="insert"&&t!=="delete")throw new Error("action must be one of: replace, insert, delete.");const i=r?.heading;if(!i)throw new Error("heading is required");let o;if(t==="delete")({role:o}=await $(e,{action:t,heading:i}));else{const n=r?.body;if(typeof n!="string")throw new Error("body is required for replace/insert (pass empty string for an empty section).");if(t==="insert"){const a=typeof r?.after=="string"?r.after:null;({role:o}=await $(e,{action:t,heading:i,body:n,after:a}))}else({role:o}=await $(e,{action:t,heading:i,body:n}))}return{content:[{type:"text",text:`${t==="replace"?"Replaced":t==="insert"?"Inserted":"Deleted"} section **${i}** in role **${o.name}** (id: ${o.id}).`}]}}case"borg_delete-role":{const e=r?.role_id;if(!e)throw new Error("role_id is required");return await le(e),{content:[{type:"text",text:`Deleted role ${e}.`}]}}case"borg_reassign-drone":{const e=r?.drone_id,t=r?.role_id;if(!e)throw new Error("drone_id is required");if(!t)throw new Error("role_id is required");const{drone:i}=await de(e,t);return{content:[{type:"text",text:`Reassigned drone ${i.label} (${i.id}) to role ${i.role_id}.`}]}}case"borg_evict-drone":{const e=r?.drone_id?.trim(),t=r?.label?.trim(),i=r?.cube_id?.trim();let o,s;if(e){if(!Me(e))throw new Error(`drone_id "${e}" is not a UUID \u2014 if that's a drone label, pass it as label + cube_id instead.`);o=e,s=e}else if(t){if(!i)throw new Error("cube_id is required when evicting by label");const{drones:n}=await _(i),a=Le(n,t);if(!a)throw new Error(`No active drone labelled "${t}" in cube ${i} (it may already be evicted; check borg_list-drones).`);o=a.id,s=a.label}else throw new Error("Provide drone_id, or label + cube_id, to identify the drone to evict");return await pe(o),{content:[{type:"text",text:`Evicted drone ${s} (${o}). Soft-deleted: removed from the roster and freed its seat; log history preserved with anonymized attribution.`}]}}case"borg_list-drones":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{drones:t,roles:i}=await _(e);if(!t.length)return{content:[{type:"text",text:"No drones in this cube yet."}]};const o=new Map(i.map(n=>[n.id,n])),s=t.map(n=>{const a=o.get(n.role_id),c=Ne(a?.name??"?",n.agent_kind),d=n.wake_path_alert_class&&n.wake_path_alert_class!=="independent"?` \u2014 wake-path-class: ${n.wake_path_alert_class}`:"";return`- **${n.label}** (id: ${n.id}) \u2014 role: ${c} (${n.role_id}) \u2014 last seen ${n.last_seen}${d}`});return{content:[{type:"text",text:`Drones in cube ${e} (${t.length}):
21
+ `)}`}]}}case"borg_create-cube":{const e=r?.name,t=r?.cube_directive,i=r?.template;if(!e)throw new Error("name is required");if(t===void 0)throw new Error("cube_directive is required (pass empty string if none)");let o=null;if(i&&(o=S(i),!o))throw new Error(`Unknown template "${i}". Available: ${U().join(", ")}`);const s=xe(t,o),n=$e(void 0,o),a=await se(e,s,{message_taxonomy:n});if(o){const d=await W(a.id,o),b=s!==t?" Template cube directive applied (operator passed empty).":"";return{content:[{type:"text",text:`Created cube **${a.name}** (id: ${a.id}) with template **${i}** applied \u2014 ${d.created} role(s) created, ${d.updated} updated.${b} Use borg_assimilate ${a.name} to join as a drone.`}]}}return{content:[{type:"text",text:`Created cube **${a.name}** (id: ${a.id}). A default "Drone" role was seeded \u2014 rename or replace it via borg_update-role / borg_create-role / borg_delete-role. Use borg_assimilate ${a.name} to join as a drone.`}]}}case"borg_update-cube":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const t={};if(typeof r?.name=="string"&&(t.name=r.name),typeof r?.cube_directive=="string"&&(t.cube_directive=r.cube_directive),Array.isArray(r?.message_taxonomy)&&(t.message_taxonomy=r.message_taxonomy),Object.keys(t).length===0)throw new Error("Pass at least one of: name, cube_directive, message_taxonomy.");const{cube:i}=await O(e,t);return{content:[{type:"text",text:`Updated cube **${i.name}** (id: ${i.id}).`}]}}case"borg_patch-taxonomy-class":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const t=r?.action;if(t!=="add"&&t!=="replace"&&t!=="remove")throw new Error("action must be one of: add, replace, remove.");let i,o;if(t==="remove"){const n=r?.class;if(!n)throw new Error("class is required for remove.");({cube:i}=await N(e,{action:t,class:n})),o=n}else{const n=r?.class_def;if(n==null||typeof n!="object"||Array.isArray(n))throw new Error("class_def (object) is required for add/replace.");({cube:i}=await N(e,{action:t,class_def:n})),o=String(n.class??"")}return{content:[{type:"text",text:`${t==="add"?"Added":t==="replace"?"Replaced":"Removed"} taxonomy class **${o}** in cube **${i.name}** (id: ${i.id}).`}]}}case"borg_delete-cube":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");return await ae(e),{content:[{type:"text",text:`Deleted cube ${e} (and all its roles, drones, log entries).`}]}}case"borg_create-role":{const e=r?.cube_id,t=r?.name,i=r?.short_description,o=r?.detailed_description;if(!e)throw new Error("cube_id is required");if(!t)throw new Error("name is required");if(i===void 0)throw new Error("short_description is required (pass empty string if none)");if(o===void 0)throw new Error("detailed_description is required (pass empty string if none)");const s=r?.is_default===!0,n=r?.is_human_seat===!0,a=r?.can_broadcast===!0,c=r?.receives_all_direct===!0,{role:d}=await ce(e,{name:t,short_description:i,detailed_description:o,is_default:s,is_human_seat:n,can_broadcast:a,receives_all_direct:c,...typeof r?.default_model=="string"?{default_model:r.default_model}:{}}),b=[d.role_class==="queen"?"Queen":null,d.is_human_seat?"human-seat":null,d.is_default?"default":null].filter(Boolean).join(", "),h=b?` (${b})`:"";return{content:[{type:"text",text:`Created role **${d.name}**${h} (id: ${d.id}) in cube ${e}.`}]}}case"borg_update-role":{const e=r?.role_id;if(!e)throw new Error("role_id is required");const t={};if(typeof r?.name=="string"&&(t.name=r.name),typeof r?.short_description=="string"&&(t.short_description=r.short_description),typeof r?.detailed_description=="string"&&(t.detailed_description=r.detailed_description),typeof r?.is_default=="boolean"&&(t.is_default=r.is_default),typeof r?.is_human_seat=="boolean"&&(t.is_human_seat=r.is_human_seat),typeof r?.can_broadcast=="boolean"&&(t.can_broadcast=r.can_broadcast),typeof r?.receives_all_direct=="boolean"&&(t.receives_all_direct=r.receives_all_direct),typeof r?.default_model=="string"&&(t.default_model=r.default_model),Object.keys(t).length===0)throw new Error("Pass at least one of: name, short_description, detailed_description, is_default, is_human_seat, can_broadcast, receives_all_direct, default_model.");const{role:i}=await le(e,t),o=[i.role_class==="queen"?"Queen":null,i.is_human_seat?"human-seat":null,i.is_default?"default":null].filter(Boolean).join(", "),s=o?` (${o})`:"";return{content:[{type:"text",text:`Updated role **${i.name}**${s} (id: ${i.id}).`}]}}case"borg_patch-role-section":{const e=r?.role_id;if(!e)throw new Error("role_id is required");const t=r?.action;if(t!=="replace"&&t!=="insert"&&t!=="delete")throw new Error("action must be one of: replace, insert, delete.");const i=r?.heading;if(!i)throw new Error("heading is required");let o;if(t==="delete")({role:o}=await $(e,{action:t,heading:i}));else{const n=r?.body;if(typeof n!="string")throw new Error("body is required for replace/insert (pass empty string for an empty section).");if(t==="insert"){const a=typeof r?.after=="string"?r.after:null;({role:o}=await $(e,{action:t,heading:i,body:n,after:a}))}else({role:o}=await $(e,{action:t,heading:i,body:n}))}return{content:[{type:"text",text:`${t==="replace"?"Replaced":t==="insert"?"Inserted":"Deleted"} section **${i}** in role **${o.name}** (id: ${o.id}).`}]}}case"borg_delete-role":{const e=r?.role_id;if(!e)throw new Error("role_id is required");return await de(e),{content:[{type:"text",text:`Deleted role ${e}.`}]}}case"borg_reassign-drone":{const e=r?.drone_id,t=r?.role_id;if(!e)throw new Error("drone_id is required");if(!t)throw new Error("role_id is required");const{drone:i}=await pe(e,t);return{content:[{type:"text",text:`Reassigned drone ${i.label} (${i.id}) to role ${i.role_id}.`}]}}case"borg_evict-drone":{const e=r?.drone_id?.trim(),t=r?.label?.trim(),i=r?.cube_id?.trim();let o,s;if(e){if(!Fe(e))throw new Error(`drone_id "${e}" is not a UUID \u2014 if that's a drone label, pass it as label + cube_id instead.`);o=e,s=e}else if(t){if(!i)throw new Error("cube_id is required when evicting by label");const{drones:n}=await w(i),a=Be(n,t);if(!a)throw new Error(`No active drone labelled "${t}" in cube ${i} (it may already be evicted; check borg_list-drones).`);o=a.id,s=a.label}else throw new Error("Provide drone_id, or label + cube_id, to identify the drone to evict");return await ue(o),{content:[{type:"text",text:`Evicted drone ${s} (${o}). Soft-deleted: removed from the roster and freed its seat; log history preserved with anonymized attribution.`}]}}case"borg_list-drones":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{drones:t,roles:i}=await w(e);if(!t.length)return{content:[{type:"text",text:"No drones in this cube yet."}]};const o=new Map(i.map(n=>[n.id,n])),s=t.map(n=>{const a=o.get(n.role_id),c=Le(a?.name??"?",n.agent_kind),d=n.wake_path_alert_class&&n.wake_path_alert_class!=="independent"?` \u2014 wake-path-class: ${n.wake_path_alert_class}`:"";return`- **${n.label}** (id: ${n.id}) \u2014 role: ${c} (${n.role_id}) \u2014 last seen ${n.last_seen}${d}`});return{content:[{type:"text",text:`Drones in cube ${e} (${t.length}):
22
22
 
23
23
  ${s.join(`
24
- `)}`}]}}case"borg_list-roles":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{roles:t}=await _(e);return{content:[{type:"text",text:Re(t,e)}]}}case"borg_list-templates":return{content:[{type:"text",text:`Available templates:
24
+ `)}`}]}}case"borg_list-roles":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{roles:t}=await w(e);return{content:[{type:"text",text:De(t,e)}]}}case"borg_list-templates":return{content:[{type:"text",text:`Available templates:
25
25
 
26
- ${S().map(i=>{const o=U(i);return`- **${i}**: ${o.description}`}).join(`
27
- `)}`}]};case"borg_sync-roles":{const e=r?.cube_id,t=r?.template_name||"software-dev",i=r?.apply===!0,o=r?.decisions&&typeof r.decisions=="object"?r.decisions:void 0;if(!e)throw new Error("cube_id is required");const s=await be(e,t,i,o);return{content:[{type:"text",text:Ye(s,t)}]}}case"borg_apply-template":{const e=r?.cube_id,t=r?.template_name;if(!e)throw new Error("cube_id is required");if(!t)throw new Error("template_name is required");const i=U(t);if(!i)throw new Error(`Unknown template "${t}". Available: ${S().join(", ")}`);const o=await W(e,i);let s="";const n=await _(e),a=xe(n.cube_directive,i);return a!==null&&(await T(e,{cube_directive:a}),s=" Template cube directive applied (cube directive was empty)."),{content:[{type:"text",text:`Applied template **${t}** to cube ${e} \u2014 ${o.created} role(s) created, ${o.updated} updated.${s}`}]}}default:throw new Error(`Unknown tool: ${g}`)}}catch(e){if(e instanceof Fe)return{content:[{type:"text",text:He(e.message)}],isError:!0};if(e instanceof We)return{content:[{type:"text",text:Ke(e.message)}],isError:!0};const t=Be(e??{});return t?{content:[{type:"text",text:t}],isError:!0}:{content:[{type:"text",text:`Error: ${e.message}`}],isError:!0}}}),p.setRequestHandler(G,async()=>({prompts:[{name:"borg_subscribe",description:"Set up Borg MCP Cube tier subscription ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial."},{name:"dashboard",description:"Open Borg MCP dashboard to manage cubes"}]})),p.setRequestHandler(Y,async m=>{const{name:g}=m.params;switch(g){case"borg_subscribe":return{description:"Set up Borg MCP Cube tier subscription ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",messages:[{role:"user",content:{type:"text",text:"Please help me set up a Borg MCP subscription using the subscribe tool."}}]};case"dashboard":return{description:"Open Borg MCP dashboard to manage cubes",messages:[{role:"user",content:{type:"text",text:"Please open the Borg MCP dashboard using the borg_open_dashboard tool."}}]};default:throw new Error(`Unknown prompt: ${g}`)}});const x=new V;await p.connect(x),await Je(),console.error(`${v()}\u25FC Borg MCP Client started`),console.error(`${v()}\u25FC Use borg_assimilate <cube-name> to join a cube as a drone`),console.error(`${v()}\u25FC Manage your cubes at https://borgmcp.ai/dashboard`)}st().catch(p=>{console.error(`${v()}Fatal error:`,p),process.exit(1)});
26
+ ${U().map(i=>{const o=S(i);return`- **${i}**: ${o.description}`}).join(`
27
+ `)}`}]};case"borg_sync-roles":{const e=r?.cube_id,t=r?.template_name||"software-dev",i=r?.apply===!0,o=r?.decisions&&typeof r.decisions=="object"?r.decisions:void 0;if(!e)throw new Error("cube_id is required");const s=await ge(e,t,i,o);return{content:[{type:"text",text:Ze(s,t)}]}}case"borg_apply-template":{const e=r?.cube_id,t=r?.template_name;if(!e)throw new Error("cube_id is required");if(!t)throw new Error("template_name is required");const i=S(t);if(!i)throw new Error(`Unknown template "${t}". Available: ${U().join(", ")}`);const o=await W(e,i);let s="";const n=await w(e),a=ke(n.cube_directive,i);return a!==null&&(await O(e,{cube_directive:a}),s=" Template cube directive applied (cube directive was empty)."),{content:[{type:"text",text:`Applied template **${t}** to cube ${e} \u2014 ${o.created} role(s) created, ${o.updated} updated.${s}`}]}}default:throw new Error(`Unknown tool: ${m}`)}}catch(e){if(e instanceof He)return{content:[{type:"text",text:Ve(e.message)}],isError:!0};if(e instanceof Qe)return{content:[{type:"text",text:Ke(e.message)}],isError:!0};const t=We(e??{});return t?{content:[{type:"text",text:t}],isError:!0}:{content:[{type:"text",text:`Error: ${e.message}`}],isError:!0}}}),p.setRequestHandler(G,async()=>({prompts:[{name:"borg_subscribe",description:"Set up Borg MCP Cube tier subscription ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial."},{name:"dashboard",description:"Open Borg MCP dashboard to manage cubes"}]})),p.setRequestHandler(J,async u=>{const{name:m}=u.params;switch(m){case"borg_subscribe":return{description:"Set up Borg MCP Cube tier subscription ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",messages:[{role:"user",content:{type:"text",text:"Please help me set up a Borg MCP subscription using the subscribe tool."}}]};case"dashboard":return{description:"Open Borg MCP dashboard to manage cubes",messages:[{role:"user",content:{type:"text",text:"Please open the Borg MCP dashboard using the borg_open_dashboard tool."}}]};default:throw new Error(`Unknown prompt: ${m}`)}});const H=new z;await p.connect(H),await et(),console.error(`${x()}\u25FC Borg MCP Client started`),console.error(`${x()}\u25FC Use borg_assimilate <cube-name> to join a cube as a drone`),console.error(`${x()}\u25FC Manage your cubes at https://borgmcp.ai/dashboard`)}ct().catch(p=>{console.error(`${x()}Fatal error:`,p),process.exit(1)});
@@ -1 +1 @@
1
- import{getIdToken as f,getRefreshToken as w,clearTokens as m}from"./config.js";import{refreshIdToken as S,RefreshTokenInvalidError as g,RefreshTransientError as T}from"./auth.js";import{consolePrefix as R}from"./console-prefix.js";import{debugLog as b}from"./debug.js";import{assertUuidShape as $}from"./evict-drone.js";import{DroneEvictedError as k,DroneFrozenError as C,DRONE_EVICTED_CODE as P,DRONE_FROZEN_CODE as O,errorCodeFromBody as I}from"./drone-lifecycle.js";const A=process.env.BORG_API_URL||"https://api.borgmcp.ai",D=3,L=6e4;let l=null;function x(e){return l||(l=S(e).finally(()=>{l=null}),l)}function J(e){if(e==null)return null;const n=e.trim();return/^\d+$/.test(n)?parseInt(n,10)*1e3:null}function v(e,n,t=L,o=()=>Math.random()*500){const s=e??1e3*(n+1);return Math.min(s,t)+o()}function G(e){const n=(t,o)=>`${t}${/[.:!?]$/.test(t)?"":":"} ${o}`;try{const t=JSON.parse(e);if(typeof t?.error=="string")return typeof t.details=="string"?n(t.error,t.details):t.error;if(t?.error&&typeof t.error=="object"){const o=t.error.message,s=t.error.details??t.details;if(typeof o=="string"&&typeof s=="string")return n(o,s);if(typeof o=="string")return o}if(typeof t?.message=="string"&&typeof t?.details=="string")return n(t.message,t.details);if(typeof t?.message=="string")return t.message}catch{}return e}async function M(e,n,t){const o=t.maxRetries??D;let s=e,a=0;for(;s.status===429&&a<o;){const d=v(J(s.headers.get("Retry-After")),a,t.capMs,t.jitter);t.log?.(`rate limited (429); retrying in ${Math.round(d)}ms (attempt ${a+1}/${o})`),await t.sleep(d),a++,s=await n()}return s}function U(e){return new Promise(n=>setTimeout(n,e))}async function H(){let e=await f();if(!e){const n=await w(),t=n!=null;if(n)try{await x(n),e=await f()}catch(o){if(o instanceof g)await m();else throw o instanceof T?o:new T(`Token refresh failed unexpectedly (your saved login was NOT cleared \u2014 retry; if it persists, restart the borg session): ${o?.message??"unknown"}`)}if(!e)throw new Error(t?"Authentication expired \u2014 your saved login has expired. Run: borg setup":"Authentication required \u2014 you are not signed in. Run: borg setup")}return e}async function N(){const e=await w();if(!e)return null;try{return await x(e),await f()}catch(n){if(n instanceof g&&await m(),n instanceof T)throw n;return null}}async function V(){if(await f())return"valid";const n=await w();if(!n)return"dead";try{return await x(n),await f()?"valid":"transient"}catch(t){return t instanceof g?(await m(),"dead"):"transient"}}async function r(e,n={}){let t=await H();const{droneSession:o,apiUrl:s,headers:a,...d}=n,E=s??A,y=(d.method??"GET").toUpperCase(),h=async c=>{const p={Authorization:`Bearer ${c}`,...a};o&&(p["X-Drone-Session"]=o),b(`\u2192 ${y} ${e}`);const u=await fetch(`${E}${e}`,{...d,headers:p});return b(`\u2190 ${u.status} ${y} ${e}`),u};let i=await h(t);if(i.status===401){const c=await N();c&&(t=c,i=await h(t))}if(i.status===401)throw new Error("Authentication required. Run: borg setup");if(i.status===429&&(i=await M(i,()=>h(t),{sleep:U,log:c=>console.error(`${R()}${c}`)})),!i.ok){const c=await i.text();b(`\u2717 ${i.status} ${y} ${e}: ${c}`);const p=G(c),u=I(c);if(i.status===410&&u===P)throw new k(p);if(i.status===423&&u===O)throw new C(p);if(i.status===429){const _=i.headers.get("Retry-After"),j=_?` (retry after ${_}s)`:"";throw new Error(`HTTP 429: rate limited${j}: ${p}`)}throw new Error(`HTTP ${i.status}: ${p}`)}return i}async function Z(e,n,t,o){const s={hostname:t??null};return(o==="claude"||o==="codex")&&(s.agent_kind=o),typeof e=="string"?s.cube_name=e:(e.cube_id&&(s.cube_id=e.cube_id),e.cube_name&&(s.cube_name=e.cube_name),e.role_id&&(s.role_id=e.role_id),e.role_name&&(s.role_name=e.role_name),e.prior_drone_id&&(s.prior_drone_id=e.prior_drone_id),e.model!=null&&(s.model=e.model)),await(await r("/api/assimilate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),apiUrl:n})).json()}async function Q(e,n){return await(await r("/api/drone/cube",{method:"GET",droneSession:e,apiUrl:n})).json()}async function Y(e,n){return await(await r("/api/drone/role",{method:"GET",droneSession:e,apiUrl:n})).json()}async function K(e,n){return await(await r("/api/drone/whoami",{method:"GET",droneSession:e,apiUrl:n})).json()}async function ee(e,n,t){const o=t?`?since=${encodeURIComponent(t)}`:"";return await(await r(`/api/drone/roster${o}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function te(e,n,t={}){const o=new URLSearchParams;t.since&&o.set("since",t.since),t.limit!==void 0&&o.set("limit",String(t.limit)),t.unreadOnly&&o.set("unread_only","true");const s=o.toString();return await(await r(`/api/drone/log${s?`?${s}`:""}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function ne(e,n,t){await r(`/api/drone/log/${t}/ack`,{method:"POST",body:JSON.stringify({kind:"ack"}),droneSession:e,apiUrl:n})}async function oe(e,n,t={}){const o=new URLSearchParams;t.since&&o.set("since",t.since);const s=o.toString();return await(await r(`/api/drone/regen${s?`?${s}`:""}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function se(e,n,t,o){const s=new URLSearchParams({role:t,section:o});return await(await r(`/api/drone/role-rationale?${s.toString()}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function re(e,n,t,o={}){const s={message:t,...o.visibility?{visibility:o.visibility}:{},...o.recipientDroneIds?{recipientDroneIds:o.recipientDroneIds}:{},...o.class?{class:o.class}:{},...o.to?{to:o.to}:{}};return await(await r("/api/drone/log",{method:"POST",headers:{"Content-Type":"application/json"},droneSession:e,apiUrl:n,body:JSON.stringify(s)})).json()}async function ae(e,n,t){const o={kind:t.kind??"friction",message:t.message,...t.metadata?{metadata:t.metadata}:{}};return await(await r("/api/drone/report",{method:"POST",headers:{"Content-Type":"application/json"},droneSession:e,apiUrl:n,body:JSON.stringify(o)})).json()}async function ie(){return await(await r("/api/cubes",{method:"GET"})).json()}async function ce(){return await(await r("/api/templates",{method:"GET"})).json()}async function pe(e,n,t){const o={cube_directive:n};e&&(o.name=e),t?.template&&(o.template=t.template),t&&Object.prototype.hasOwnProperty.call(t,"message_taxonomy")&&(o.message_taxonomy=t.message_taxonomy??null);const a=await(await r("/api/cubes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();return a.cube?{...a.cube,roles:a.roles??[],drones:a.drones??[]}:a}async function de(e,n){return await(await r(`/api/cubes/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function ue(e,n){return await(await r(`/api/cubes/${e}/taxonomy-patch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function fe(e){await r(`/api/cubes/${e}`,{method:"DELETE"})}async function le(e,n){return await(await r(`/api/cubes/${e}/roles`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function ye(e,n){return await(await r(`/api/roles/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function he(e,n){return await(await r(`/api/roles/${e}/section-patch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function we(e){await r(`/api/roles/${e}`,{method:"DELETE"})}async function me(e,n){return $(e,"drone_id"),await(await r(`/api/drones/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({role_id:n})})).json()}async function ge(e){$(e,"drone_id"),await r(`/api/drones/${e}`,{method:"DELETE"})}async function Te(e){const t=await(await r(`/api/cubes/${e}`,{method:"GET"})).json();return t.cube?{...t.cube,roles:t.roles??[],drones:t.drones??[]}:t}async function be(e,n){return await(await r(`/api/cubes/${e}/apply-template`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({template_name:n})})).json()}async function xe(){return await(await r("/api/subscription/status",{method:"GET"})).json()}async function _e(e,n="software-dev",t=!1,o){return await(await r(`/api/cubes/${e}/sync-roles`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({template_name:n,apply:t,...o?{decisions:o}:{}})})).json()}async function $e(){const n=await(await r("/api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"}})).json();if(!n.checkout_url)throw new Error("No checkout URL in response");return n.checkout_url}async function Ee(){const n=await(await r("/api/subscription/portal",{method:"POST",headers:{"Content-Type":"application/json"}})).json();if(!n.portal_url)throw new Error(n.message||"No portal URL in response");return n.portal_url}export{A as API_URL,ne as ackLogEntry,re as appendLog,be as applyTemplate,Z as assimilate,xe as checkSubscriptionStatus,Ee as createBillingPortalSession,pe as createCube,le as createRole,$e as createSubscription,fe as deleteCube,we as deleteRole,ge as evictDrone,G as extractHttpErrorMessage,Te as getCube,Q as getCubeInfo,Y as getRoleInfo,ee as getRoster,H as getValidToken,ie as listCubes,ce as listTemplates,J as parseRetryAfterMs,he as patchRoleSection,ue as patchTaxonomyClass,V as probeSession,v as rateLimitWaitMs,te as readLog,me as reassignDrone,oe as regen,M as retryOn429,se as roleRationale,ae as submitReport,_e as syncRoles,de as updateCube,ye as updateRole,K as whoami};
1
+ import{getIdToken as f,getRefreshToken as h,clearTokens as m}from"./config.js";import{refreshIdToken as R,RefreshTokenInvalidError as g,RefreshTransientError as T}from"./auth.js";import{consolePrefix as S}from"./console-prefix.js";import{debugLog as b}from"./debug.js";import{assertUuidShape as E}from"./evict-drone.js";import{DroneEvictedError as C,DroneFrozenError as k,DRONE_EVICTED_CODE as P,DRONE_FROZEN_CODE as O,errorCodeFromBody as I}from"./drone-lifecycle.js";import{MODEL_DESCRIPTOR_REGEX as D}from"./model-presets.js";const L=process.env.BORG_API_URL||"https://api.borgmcp.ai",A=3,v=6e4;let l=null;function x(e){return l||(l=R(e).finally(()=>{l=null}),l)}function G(e){if(e==null)return null;const n=e.trim();return/^\d+$/.test(n)?parseInt(n,10)*1e3:null}function J(e,n,t=v,o=()=>Math.random()*500){const s=e??1e3*(n+1);return Math.min(s,t)+o()}function M(e){const n=(t,o)=>`${t}${/[.:!?]$/.test(t)?"":":"} ${o}`;try{const t=JSON.parse(e);if(typeof t?.error=="string")return typeof t.details=="string"?n(t.error,t.details):t.error;if(t?.error&&typeof t.error=="object"){const o=t.error.message,s=t.error.details??t.details;if(typeof o=="string"&&typeof s=="string")return n(o,s);if(typeof o=="string")return o}if(typeof t?.message=="string"&&typeof t?.details=="string")return n(t.message,t.details);if(typeof t?.message=="string")return t.message}catch{}return e}async function U(e,n,t){const o=t.maxRetries??A;let s=e,a=0;for(;s.status===429&&a<o;){const d=J(G(s.headers.get("Retry-After")),a,t.capMs,t.jitter);t.log?.(`rate limited (429); retrying in ${Math.round(d)}ms (attempt ${a+1}/${o})`),await t.sleep(d),a++,s=await n()}return s}function H(e){return new Promise(n=>setTimeout(n,e))}async function q(){let e=await f();if(!e){const n=await h(),t=n!=null;if(n)try{await x(n),e=await f()}catch(o){if(o instanceof g)await m();else throw o instanceof T?o:new T(`Token refresh failed unexpectedly (your saved login was NOT cleared \u2014 retry; if it persists, restart the borg session): ${o?.message??"unknown"}`)}if(!e)throw new Error(t?"Authentication expired \u2014 your saved login has expired. Run: borg setup":"Authentication required \u2014 you are not signed in. Run: borg setup")}return e}async function B(){const e=await h();if(!e)return null;try{return await x(e),await f()}catch(n){if(n instanceof g&&await m(),n instanceof T)throw n;return null}}async function Q(){if(await f())return"valid";const n=await h();if(!n)return"dead";try{return await x(n),await f()?"valid":"transient"}catch(t){return t instanceof g?(await m(),"dead"):"transient"}}async function r(e,n={}){let t=await q();const{droneSession:o,apiUrl:s,headers:a,...d}=n,$=s??L,y=(d.method??"GET").toUpperCase(),w=async c=>{const p={Authorization:`Bearer ${c}`,...a};o&&(p["X-Drone-Session"]=o),b(`\u2192 ${y} ${e}`);const u=await fetch(`${$}${e}`,{...d,headers:p});return b(`\u2190 ${u.status} ${y} ${e}`),u};let i=await w(t);if(i.status===401){const c=await B();c&&(t=c,i=await w(t))}if(i.status===401)throw new Error("Authentication required. Run: borg setup");if(i.status===429&&(i=await U(i,()=>w(t),{sleep:H,log:c=>console.error(`${S()}${c}`)})),!i.ok){const c=await i.text();b(`\u2717 ${i.status} ${y} ${e}: ${c}`);const p=M(c),u=I(c);if(i.status===410&&u===P)throw new C(p);if(i.status===423&&u===O)throw new k(p);if(i.status===429){const _=i.headers.get("Retry-After"),j=_?` (retry after ${_}s)`:"";throw new Error(`HTTP 429: rate limited${j}: ${p}`)}throw new Error(`HTTP ${i.status}: ${p}`)}return i}async function Y(e,n,t,o){const s={hostname:t??null};if((o==="claude"||o==="codex")&&(s.agent_kind=o),typeof e=="string")s.cube_name=e;else if(e.cube_id&&(s.cube_id=e.cube_id),e.cube_name&&(s.cube_name=e.cube_name),e.role_id&&(s.role_id=e.role_id),e.role_name&&(s.role_name=e.role_name),e.prior_drone_id&&(s.prior_drone_id=e.prior_drone_id),e.model!=null){if(!D.test(e.model))throw new Error(`Invalid model descriptor: "${e.model}" (expected "<claude|ollama>:<model>").`);s.model=e.model}return await(await r("/api/assimilate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),apiUrl:n})).json()}async function K(e,n){return await(await r("/api/drone/cube",{method:"GET",droneSession:e,apiUrl:n})).json()}async function ee(e,n){return await(await r("/api/drone/role",{method:"GET",droneSession:e,apiUrl:n})).json()}async function te(e,n){return await(await r("/api/drone/whoami",{method:"GET",droneSession:e,apiUrl:n})).json()}async function ne(e,n,t){const o=t?`?since=${encodeURIComponent(t)}`:"";return await(await r(`/api/drone/roster${o}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function oe(e,n,t={}){const o=new URLSearchParams;t.since&&o.set("since",t.since),t.limit!==void 0&&o.set("limit",String(t.limit)),t.unreadOnly&&o.set("unread_only","true");const s=o.toString();return await(await r(`/api/drone/log${s?`?${s}`:""}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function se(e,n,t){await r(`/api/drone/log/${t}/ack`,{method:"POST",body:JSON.stringify({kind:"ack"}),droneSession:e,apiUrl:n})}async function re(e,n,t={}){const o=new URLSearchParams;t.since&&o.set("since",t.since);const s=o.toString();return await(await r(`/api/drone/regen${s?`?${s}`:""}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function ae(e,n,t,o){const s=new URLSearchParams({role:t,section:o});return await(await r(`/api/drone/role-rationale?${s.toString()}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function ie(e,n,t,o={}){const s={message:t,...o.visibility?{visibility:o.visibility}:{},...o.recipientDroneIds?{recipientDroneIds:o.recipientDroneIds}:{},...o.class?{class:o.class}:{},...o.to?{to:o.to}:{}};return await(await r("/api/drone/log",{method:"POST",headers:{"Content-Type":"application/json"},droneSession:e,apiUrl:n,body:JSON.stringify(s)})).json()}async function ce(e,n,t){const o={kind:t.kind??"friction",message:t.message,...t.metadata?{metadata:t.metadata}:{}};return await(await r("/api/drone/report",{method:"POST",headers:{"Content-Type":"application/json"},droneSession:e,apiUrl:n,body:JSON.stringify(o)})).json()}async function pe(){return await(await r("/api/cubes",{method:"GET"})).json()}async function de(){return await(await r("/api/templates",{method:"GET"})).json()}async function ue(e,n,t){const o={cube_directive:n};e&&(o.name=e),t?.template&&(o.template=t.template),t&&Object.prototype.hasOwnProperty.call(t,"message_taxonomy")&&(o.message_taxonomy=t.message_taxonomy??null);const a=await(await r("/api/cubes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();return a.cube?{...a.cube,roles:a.roles??[],drones:a.drones??[]}:a}async function fe(e,n){return await(await r(`/api/cubes/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function le(e,n){return await(await r(`/api/cubes/${e}/taxonomy-patch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function ye(e){await r(`/api/cubes/${e}`,{method:"DELETE"})}async function we(e,n){return await(await r(`/api/cubes/${e}/roles`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function he(e,n){return await(await r(`/api/roles/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function me(e,n){return await(await r(`/api/roles/${e}/section-patch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function ge(e){await r(`/api/roles/${e}`,{method:"DELETE"})}async function Te(e,n){return E(e,"drone_id"),await(await r(`/api/drones/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({role_id:n})})).json()}async function be(e){E(e,"drone_id"),await r(`/api/drones/${e}`,{method:"DELETE"})}async function xe(e){const t=await(await r(`/api/cubes/${e}`,{method:"GET"})).json();return t.cube?{...t.cube,roles:t.roles??[],drones:t.drones??[]}:t}async function _e(e,n){return await(await r(`/api/cubes/${e}/apply-template`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({template_name:n})})).json()}async function Ee(){return await(await r("/api/subscription/status",{method:"GET"})).json()}async function $e(e,n="software-dev",t=!1,o){return await(await r(`/api/cubes/${e}/sync-roles`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({template_name:n,apply:t,...o?{decisions:o}:{}})})).json()}async function je(){const n=await(await r("/api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"}})).json();if(!n.checkout_url)throw new Error("No checkout URL in response");return n.checkout_url}async function Re(){const n=await(await r("/api/subscription/portal",{method:"POST",headers:{"Content-Type":"application/json"}})).json();if(!n.portal_url)throw new Error(n.message||"No portal URL in response");return n.portal_url}export{L as API_URL,se as ackLogEntry,ie as appendLog,_e as applyTemplate,Y as assimilate,Ee as checkSubscriptionStatus,Re as createBillingPortalSession,ue as createCube,we as createRole,je as createSubscription,ye as deleteCube,ge as deleteRole,be as evictDrone,M as extractHttpErrorMessage,xe as getCube,K as getCubeInfo,ee as getRoleInfo,ne as getRoster,q as getValidToken,pe as listCubes,de as listTemplates,G as parseRetryAfterMs,me as patchRoleSection,le as patchTaxonomyClass,Q as probeSession,J as rateLimitWaitMs,oe as readLog,Te as reassignDrone,re as regen,U as retryOn429,ae as roleRationale,ce as submitReport,$e as syncRoles,fe as updateCube,he as updateRole,te as whoami};
@@ -3,6 +3,7 @@ export interface Role {
3
3
  name: string;
4
4
  is_default: boolean;
5
5
  is_human_seat: boolean;
6
+ role_class?: 'queen' | 'worker';
6
7
  default_model?: string | null;
7
8
  }
8
9
  /**
@@ -0,0 +1,57 @@
1
+ /**
2
+ * gh#899: role-scope the NATIVE MCP tool surface to cut the per-call tool tax
3
+ * for simpler models. This is a token-surface UX / context optimization ONLY —
4
+ * it carries ZERO authorization semantics. Server enforcement is USER/OWNER-
5
+ * level (RLS + cube ownership), independent of which tool SCHEMAS are pre-loaded
6
+ * at connect: a NON-OWNER is rejected regardless of role, and an OWNER's own
7
+ * drone is NOT — so reaching a "management" tool via the dispatcher is correct
8
+ * when the caller owns the cube, never a "worker is server-rejected" case. The
9
+ * dispatcher bypasses NO server check that exists (identical CallTool path).
10
+ * Never treat this filter as a security boundary.
11
+ *
12
+ * Deferred (filtered-out) tools are never lost — they remain reachable through
13
+ * the always-present dispatcher (`borg_tool` / `borg_describe-tool`), so a
14
+ * scoped role can never dead-end.
15
+ */
16
+ /** Always-present escape hatch — reaches any borg tool regardless of scope. */
17
+ export declare const DISPATCHER_TOOLS: readonly ["borg_tool", "borg_describe-tool"];
18
+ /** Every role needs these; pre-loaded natively for all roles. */
19
+ export declare const UNIVERSAL_TOOLS: readonly ["borg_regen", "borg_log", "borg_read-log", "borg_roster", "borg_stream-status", "borg_whoami", "borg_ack", "borg_version", "borg_cube", "borg_role", "borg_role-rationale", "borg_report-friction", "borg_assimilate", "borg_tool", "borg_describe-tool"];
20
+ /** Cube/role/drone management — native for management seats, deferred for workers. */
21
+ export declare const MANAGEMENT_TOOLS: readonly ["borg_create-cube", "borg_update-cube", "borg_delete-cube", "borg_create-role", "borg_update-role", "borg_delete-role", "borg_patch-role-section", "borg_patch-taxonomy-class", "borg_reassign-drone", "borg_evict-drone", "borg_sync-roles", "borg_apply-template", "borg_list-cubes", "borg_list-drones", "borg_list-roles", "borg_list-templates"];
22
+ /** Subscription/billing — native for management seats, deferred for workers. */
23
+ export declare const BILLING_TOOLS: readonly ["borg_subscribe", "borg_upgrade-subscription", "borg_subscription_status", "borg_open_dashboard"];
24
+ /**
25
+ * Highest-stakes subset of the management set — filtered from a worker's native
26
+ * surface for context economy only. NOT an auth list: server enforcement is
27
+ * owner-level (RLS + cube ownership) and independent of this client-side filter
28
+ * (a non-owner is rejected regardless of role; an owner's own drone is not).
29
+ * Named here only to focus reviewer attention.
30
+ */
31
+ export declare const AUTH_SENSITIVE_TOOLS: readonly ["borg_evict-drone", "borg_delete-cube", "borg_delete-role", "borg_reassign-drone"];
32
+ export interface RoleScope {
33
+ /** The drone's role name, as persisted at assimilate. Absent → role unknown. */
34
+ roleName?: string | null;
35
+ roleClass?: 'queen' | 'worker' | null;
36
+ isHumanSeat?: boolean | null;
37
+ }
38
+ /** Management seats (human-seat roles + queen-class) get the full surface. */
39
+ export declare function isManagementSeat(scope: RoleScope): boolean;
40
+ /**
41
+ * Names to HIDE from the native surface for this scope. Empty (hide nothing)
42
+ * when the role is unknown (no roleName — old cubes.json entry or pre-assimilate)
43
+ * or the caller is a management seat. Only a known worker role defers the
44
+ * management + billing sets. Fail-safe: anything not explicitly in a deferred
45
+ * set stays native.
46
+ */
47
+ export declare function deferredToolNames(scope: RoleScope | null): Set<string>;
48
+ /**
49
+ * Filter a tool-definition array down to the native surface for this scope.
50
+ * Tools whose name is in the deferred set are removed; everything else
51
+ * (universal, dispatcher, unmapped) stays. The deferred tools remain reachable
52
+ * via the dispatcher.
53
+ */
54
+ export declare function filterToolsForRole<T extends {
55
+ name: string;
56
+ }>(tools: T[], scope: RoleScope | null): T[];
57
+ //# sourceMappingURL=tool-scope.d.ts.map
@@ -0,0 +1 @@
1
+ const b=["borg_tool","borg_describe-tool"],a=["borg_regen","borg_log","borg_read-log","borg_roster","borg_stream-status","borg_whoami","borg_ack","borg_version","borg_cube","borg_role","borg_role-rationale","borg_report-friction","borg_assimilate",...b],_=["borg_create-cube","borg_update-cube","borg_delete-cube","borg_create-role","borg_update-role","borg_delete-role","borg_patch-role-section","borg_patch-taxonomy-class","borg_reassign-drone","borg_evict-drone","borg_sync-roles","borg_apply-template","borg_list-cubes","borg_list-drones","borg_list-roles","borg_list-templates"],g=["borg_subscribe","borg_upgrade-subscription","borg_subscription_status","borg_open_dashboard"],i=["borg_evict-drone","borg_delete-cube","borg_delete-role","borg_reassign-drone"];function n(r){return r.isHumanSeat===!0||r.roleClass==="queen"}function s(r){return!r||!r.roleName?new Set:n(r)?new Set:new Set([..._,...g])}function l(r,o){const e=s(o);return e.size===0?r:r.filter(t=>!e.has(t.name))}export{i as AUTH_SENSITIVE_TOOLS,g as BILLING_TOOLS,b as DISPATCHER_TOOLS,_ as MANAGEMENT_TOOLS,a as UNIVERSAL_TOOLS,s as deferredToolNames,l as filterToolsForRole,n as isManagementSeat};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "borgmcp",
3
- "version": "1.0.35",
3
+ "version": "1.0.36",
4
4
  "description": "Coordinate AI coding agents in shared cubes. Works with Claude Code and Codex. Create projects, assign roles, and share a live activity log.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",