borgmcp 1.0.29 → 1.0.30

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.
@@ -9,7 +9,7 @@ export interface AssimilateFlags {
9
9
  here?: boolean;
10
10
  yes?: boolean;
11
11
  cli?: BorgCli;
12
- backend?: string;
12
+ model?: string;
13
13
  }
14
14
  export interface AssimilateArgs {
15
15
  role: string | undefined;
@@ -81,7 +81,8 @@ export interface AssimilateDeps {
81
81
  role_id: string;
82
82
  hostname?: string | null;
83
83
  prior_drone_id?: string;
84
- backend?: string | null;
84
+ model?: string | null;
85
+ agent_kind?: 'claude' | 'codex' | null;
85
86
  }) => Promise<AssimilateResult>;
86
87
  listTemplates: (apiUrl: string, token: string) => Promise<Array<{
87
88
  name: string;
@@ -102,19 +103,19 @@ export interface AssimilateDeps {
102
103
  updatedAfter: number;
103
104
  }) => Promise<string | null>;
104
105
  fetch: typeof fetch;
105
- checkBackendReachable: (descriptor: string | null, fetchImpl: typeof fetch, ollamaBaseUrl?: string) => Promise<{
106
+ checkModelReachable: (descriptor: string | null, fetchImpl: typeof fetch, ollamaBaseUrl?: string) => Promise<{
106
107
  ok: boolean;
107
108
  message?: string;
108
109
  }>;
109
- getLaunchBackend: (cubeId: string, droneId: string) => Promise<{
110
- backend: string;
110
+ getLaunchModel: (cubeId: string, droneId: string) => Promise<{
111
+ model: string;
111
112
  ollamaBaseUrl: string | null;
112
113
  } | null>;
113
- setLaunchBackend: (cubeId: string, droneId: string, record: {
114
- backend: string;
114
+ setLaunchModel: (cubeId: string, droneId: string, record: {
115
+ model: string;
115
116
  ollamaBaseUrl: string | null;
116
117
  }) => Promise<void>;
117
- clearLaunchBackend: (cubeId: string, droneId: string) => Promise<void>;
118
+ clearLaunchModel: (cubeId: string, droneId: string) => Promise<void>;
118
119
  }
119
120
  export declare function runAssimilate(args: AssimilateArgs, deps: AssimilateDeps): Promise<number>;
120
121
  /**
@@ -1,47 +1,47 @@
1
- import{dirname as Z,basename as E}from"node:path";import{randomUUID as ee}from"node:crypto";import{roleSlug as te,matchRoleByName as re,pickDefaultRole as ne}from"./role-resolver.js";import{deriveCubeName as oe,parseGitRemote as ie,sanitizeRemoteUrl as ae}from"./cube-name.js";import{validateName as M}from"./name-validator.js";import{renderAssimilationWelcome as se}from"./assimilate-welcome.js";import{shellEscape as le}from"./shell-escape.js";import{withCodexCwdArg as ce}from"./codex-remote.js";import{buildAgentKickoffPrompt as ue,recordCodexWakeTarget as me,socketPathFromRemoteArgs as de}from"./codex-launch.js";import{perWorktreeBranchName as Y,adoptWorktree as fe,computeWorktreePath as G}from"./worktree-lifecycle.js";import{codexBorgSessionConfigArgs as he}from"./launch-gate.js";import{resolveLaunchEnv as ge,resolveOllamaBaseUrl as be,parseBackend as we}from"./backend-presets.js";async function De(r,e){if(r.role!==void 0){const t=M(r.role);if(!t.ok)return e.stderr(t.error+`
2
- `),1}if(r.flags.worktree!==void 0){const t=M(r.flags.worktree);if(!t.ok)return e.stderr(t.error+`
1
+ import{dirname as Z,basename as E}from"node:path";import{randomUUID as ee}from"node:crypto";import{roleSlug as te,matchRoleByName as re,pickDefaultRole as ne}from"./role-resolver.js";import{deriveCubeName as oe,parseGitRemote as ie,sanitizeRemoteUrl as ae}from"./cube-name.js";import{validateName as F}from"./name-validator.js";import{renderAssimilationWelcome as le}from"./assimilate-welcome.js";import{shellEscape as se}from"./shell-escape.js";import{withCodexCwdArg as ce}from"./codex-remote.js";import{buildAgentKickoffPrompt as ue,recordCodexWakeTarget as me,socketPathFromRemoteArgs as de}from"./codex-launch.js";import{perWorktreeBranchName as Y,adoptWorktree as fe,computeWorktreePath as G}from"./worktree-lifecycle.js";import{codexBorgSessionConfigArgs as he}from"./launch-gate.js";import{resolveLaunchEnv as ge,resolveOllamaBaseUrl as we,parseModel as be}from"./model-presets.js";async function Oe(r,e){if(r.role!==void 0){const t=F(r.role);if(!t.ok)return e.stderr(t.error+`
2
+ `),1}if(r.flags.worktree!==void 0){const t=F(r.flags.worktree);if(!t.ok)return e.stderr(t.error+`
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=oe(a,o),o){const u=ae(o),m=u?ie(u):null;u&&!m&&n&&e.stderr(`couldn't parse git remote '${u}' \u2014 using directory name '${n}' as cube name
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 x=e.cwd();e.stderr(`Checking your cubes\u2026
4
+ `)}}let l=null;if(n&&n.includes("@")&&n.includes(":")){const t=n.lastIndexOf(":");l={ownerEmail:n.substring(0,t),cubeName:n.substring(t+1)},n=l.cubeName}const x=e.cwd();e.stderr(`Checking your cubes\u2026
5
5
  `);let A;try{A=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(),A=await e.listCubes(i.apiUrl,i.token);else throw t}const N=A.find(t=>t.name===n);if(!N&&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 c,_;if(N)c=await e.getCube(i.apiUrl,i.token,N.id),_=!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 S=v===0?" (default)":"";u.push(` ${v+1}) ${y.name}${S} \u2014 ${y.description}`)}),u.push(` ${o.length+1}) skip \u2014 no template`);const m=(await e.prompt(u.join(`
6
+ `),i=await e.runSetup(),A=await e.listCubes(i.apiUrl,i.token);else throw t}const _=A.find(t=>t.name===n);if(!_&&l)return e.stderr(`No cube named '${l.cubeName}' accessible to you owned by '${l.ownerEmail}'. Did you accept their invite? See borgmcp.ai/dashboard.
7
+ `),1;let c,N;if(_)c=await e.getCube(i.apiUrl,i.token,_.id),N=!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 S=v===0?" (default)":"";u.push(` ${v+1}) ${y.name}${S} \u2014 ${y.description}`)}),u.push(` ${o.length+1}) skip \u2014 no template`);const m=(await e.prompt(u.join(`
8
8
  `)+`
9
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
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.
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
- `),c=await e.createCube(i.apiUrl,i.token,t?{name:n??void 0,template:t}:{name:n??void 0}),_=!0}let d;if(r.role!==void 0){if(d=re(c.roles,r.role),!d){const t=c.roles.map(m=>m.name).join(", "),o=$e(r.role,c.roles.map(m=>m.name)),u=o?` Did you mean "${o}"?`:"";return e.stderr(`no role matching "${r.role}" in cube "${c.name}". Available: ${t}.${u}
14
+ `),c=await e.createCube(i.apiUrl,i.token,t?{name:n??void 0,template:t}:{name:n??void 0}),N=!0}let d;if(r.role!==void 0){if(d=re(c.roles,r.role),!d){const t=c.roles.map(m=>m.name).join(", "),o=$e(r.role,c.roles.map(m=>m.name)),u=o?` Did you mean "${o}"?`:"";return e.stderr(`no role matching "${r.role}" in cube "${c.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=ne(c.roles,{isFirstDrone:_}),!d)return e.stderr(`cube "${c.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.
16
+ `),1}}else if(d=ne(c.roles,{isFirstDrone:N}),!d)return e.stderr(`cube "${c.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
17
  `),1;const C=await e.getActiveCube();let $;if(C&&r.flags.here)if(C.cubeId===c.id)$=C.droneId;else return e.stderr(`this directory already hosts an active drone; remove --here or run from a fresh worktree
18
- `),1;const T=$!=null?await e.getLaunchBackend(c.id,$):null,h=r.flags.backend??T?.backend??d.default_backend??null,P=be(process.env,h!=null&&h===T?.backend?T?.ollamaBaseUrl:void 0);if(h){const t=await e.checkBackendReachable(h,e.fetch,P);if(!t.ok)return e.stderr(`${t.message}
19
- `),1}e.stderr(`Joining cube '${c.name}' as ${d.name}\u2026
20
- `);let l;try{l=await e.assimilate(i.apiUrl,i.token,{cube_id:c.id,role_id:d.id,hostname:e.getHostname(),backend:h,...$?{prior_drone_id:$}:{}})}catch(t){const o=t instanceof Error?t.message:String(t);return e.stderr(`assimilate failed: ${o}
21
- `),1}const p=c.roles.find(t=>t.id===l.role_id)??d;l.reattached?e.stderr(`re-attached to existing seat ${l.drone_label} (session token rotated, no new drone minted)
18
+ `),1;const T=$!=null?await e.getLaunchModel(c.id,$):null,h=r.flags.model??T?.model??d.default_model??null,P=we(process.env,h!=null&&h===T?.model?T?.ollamaBaseUrl:void 0);if(h){const t=await e.checkModelReachable(h,e.fetch,P);if(!t.ok)return e.stderr(`${t.message}
19
+ `),1}const g=await e.resolveCli(r.flags.cli);e.stderr(`Joining cube '${c.name}' as ${d.name}\u2026
20
+ `);let s;try{s=await e.assimilate(i.apiUrl,i.token,{cube_id:c.id,role_id:d.id,hostname:e.getHostname(),agent_kind:g,model:h,...$?{prior_drone_id:$}:{}})}catch(t){const o=t instanceof Error?t.message:String(t);return e.stderr(`assimilate failed: ${o}
21
+ `),1}const p=c.roles.find(t=>t.id===s.role_id)??d;s.reattached?e.stderr(`re-attached to existing seat ${s.drone_label} (session token rotated, no new drone minted)
22
22
  `):p.id!==d.id&&e.stderr(`Note: your invite didn't grant the "${d.name}" role \u2014 assimilated as "${p.name}" instead.
23
23
  `);const z=r.flags.worktree!==void 0||C!==null&&!r.flags.here;let f=null;if(z){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.
24
24
  Fix: create at least one commit (\`git commit --allow-empty -m "initial"\`)
25
25
  OR: pass --here to skip the sibling spawn and use the current directory
26
26
  `),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}
27
27
  `);const y=E(a),v=r.flags.worktree??te(p.name);if(v.length===0)return e.stderr(`cannot derive a worktree name from role "${p.name}"; pass an explicit --worktree <name>
28
- `),1;const S=e.homedir();let b=G(S,y,v),H=2;for(;e.pathExists(b)||ve(e,a,b);)b=G(S,y,v,H),H++;e.mkdirp(Z(b));const D=Y(E(b),y),F=e.runSync("git",["worktree","add","-b",D,b,o],a);if(F.status!==0)return e.stderr(`git worktree add failed: ${q(F.stderr)}
29
- `),1;e.stderr(`spawned sibling worktree at ${b} on branch ${D} (${o}); original dir is registered as active (edit ~/.config/borgmcp/cubes.json if stale).
30
- `),e.chdir(b),e.stderr(ke(b,D,a)),f=e.cwd()}try{await e.setActiveCube({cubeId:l.cube_id,droneId:l.drone_id,name:c.name,sessionToken:l.session_token,droneLabel:l.drone_label,apiUrl:i.apiUrl})}catch(t){const o=t instanceof Error?t.message:String(t);if(e.stderr(`setActiveCube failed: ${o}
28
+ `),1;const S=e.homedir();let b=G(S,y,v),H=2;for(;e.pathExists(b)||ve(e,a,b);)b=G(S,y,v,H),H++;e.mkdirp(Z(b));const O=Y(E(b),y),B=e.runSync("git",["worktree","add","-b",O,b,o],a);if(B.status!==0)return e.stderr(`git worktree add failed: ${q(B.stderr)}
29
+ `),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).
30
+ `),e.chdir(b),e.stderr(ke(b,O,a)),f=e.cwd()}try{await e.setActiveCube({cubeId:s.cube_id,droneId:s.drone_id,name:c.name,sessionToken:s.session_token,droneLabel:s.drone_label,apiUrl:i.apiUrl})}catch(t){const o=t instanceof Error?t.message:String(t);if(e.stderr(`setActiveCube failed: ${o}
31
31
  `),f){const u=e.runSync("git",["worktree","remove","--force",f],a);u.status===0?e.stderr(`rolled back spawned worktree at ${f}
32
32
  `):e.stderr(`manual cleanup needed: \`git worktree remove --force ${f}\` (rollback attempt failed: ${q(u.stderr).trim()||"unknown"})
33
- `)}return 1}e.setTerminalTitle(l.drone_label,c.name);const K=e.isTTY()&&!process.env.NO_COLOR&&!process.env.CI;e.stdout(se(p.name,c.name,K));const w=await e.resolveCli(r.flags.cli),g=e.cwd();try{e.installProjectSessionHook(g)}catch{e.stderr(`warning: could not install the project-local SessionStart hook in ${g}; it will be re-attempted on the next borg launch
34
- `)}if(!f){e.runSync("git",["fetch","origin","--prune"],g);const t=Y(E(g),E(a)),o=fe(e.runSync,g,t,"origin/main");o.action==="adopted"?(e.stderr(`worktree: adopted branch ${t} at origin/main
35
- `),e.stderr(ye(g,t))):o.message&&e.stderr(`worktree sync: ${o.message}
36
- `)}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.
37
- `);const J=e.getInboxPath(l.cube_id,l.drone_id),I=w==="codex"?`borg-wake-${ee()}`:null,V=w==="claude"?`If you haven't yet, arm a persistent Monitor running the command \`borg-inbox-monitor ${J}\` so each event's task-notification title summarizes the new cube log entry (drone label, role, and first ~80 chars of the message body) \u2014 letting you triage events without reading the full body. `:"";let U,O=[],R,B=null,L=null;h?await e.setLaunchBackend(l.cube_id,l.drone_id,{backend:h,ollamaBaseUrl:we(h).kind==="ollama"?P:null}):await e.clearLaunchBackend(l.cube_id,l.drone_id);const W=ge(h,P),j={...process.env,...W.set,BORG_SESSION:"1"};for(const t of W.unset)delete j[t];if(w==="codex"){const t=await e.prepareCodexRemoteLaunch();t.warning?(e.stderr(`warning: ${t.warning}
38
- `),U="\u26A0 Codex wake-path capability check failed: remote-control is unavailable for this session. Run borg_regen manually whenever you return, and expect only fallback wakeups until relaunch."):U="Codex wake-path capability check passed: remote-control socket established for this session.",O=t.args,Object.keys(t.env).length>0&&Object.assign(j,t.env),B=de(t.args),L=t.server?.cleanup??null}R=[ue({cli:w,codexWakeNonce:I,monitorClause:V,codexWakePathClause:U})],w==="codex"&&(R=[...he(),...O,...ce(R,g)]);const Q=e.exec(w,R,g,j);w==="codex"&&B&&I&&me({deps:e,cubeId:l.cube_id,droneId:l.drone_id,socketPath:B,cwd:g,previewNeedle:I,launchedAtSeconds:Math.floor(Date.now()/1e3)});const X=await Q;if(L)try{L()}catch{}return f&&x!==f&&e.stderr(`
33
+ `)}return 1}e.setTerminalTitle(s.drone_label,c.name);const K=e.isTTY()&&!process.env.NO_COLOR&&!process.env.CI;e.stdout(le(p.name,c.name,K));const w=e.cwd();try{e.installProjectSessionHook(w)}catch{e.stderr(`warning: could not install the project-local SessionStart hook in ${w}; it will be re-attempted on the next borg launch
34
+ `)}if(!f){e.runSync("git",["fetch","origin","--prune"],w);const t=Y(E(w),E(a)),o=fe(e.runSync,w,t,"origin/main");o.action==="adopted"?(e.stderr(`worktree: adopted branch ${t} at origin/main
35
+ `),e.stderr(ye(w,t))):o.message&&e.stderr(`worktree sync: ${o.message}
36
+ `)}await e.probeMcpReady()||e.stderr(`warning: borg-mcp readiness probe did not complete within the timeout; launching ${g} anyway \u2014 the kickoff prompt's ToolSearch fallback will recover if the MCP server takes longer to start.
37
+ `);const J=e.getInboxPath(s.cube_id,s.drone_id),I=g==="codex"?`borg-wake-${ee()}`:null,V=g==="claude"?`If you haven't yet, arm a persistent Monitor running the command \`borg-inbox-monitor ${J}\` so each event's task-notification title summarizes the new cube log entry (drone label, role, and first ~80 chars of the message body) \u2014 letting you triage events without reading the full body. `:"";let U,W=[],R,L=null,j=null;h?await e.setLaunchModel(s.cube_id,s.drone_id,{model:h,ollamaBaseUrl:be(h).kind==="ollama"?P:null}):await e.clearLaunchModel(s.cube_id,s.drone_id);const M=ge(h,P),D={...process.env,...M.set,BORG_SESSION:"1"};for(const t of M.unset)delete D[t];if(g==="codex"){const t=await e.prepareCodexRemoteLaunch();t.warning?(e.stderr(`warning: ${t.warning}
38
+ `),U="\u26A0 Codex wake-path capability check failed: remote-control is unavailable for this session. Run borg_regen manually whenever you return, and expect only fallback wakeups until relaunch."):U="Codex wake-path capability check passed: remote-control socket established for this session.",W=t.args,Object.keys(t.env).length>0&&Object.assign(D,t.env),L=de(t.args),j=t.server?.cleanup??null}R=[ue({cli:g,codexWakeNonce:I,monitorClause:V,codexWakePathClause:U})],g==="codex"&&(R=[...he(),...W,...ce(R,w)]);const Q=e.exec(g,R,w,D);g==="codex"&&L&&I&&me({deps:e,cubeId:s.cube_id,droneId:s.drone_id,socketPath:L,cwd:w,previewNeedle:I,launchedAtSeconds:Math.floor(Date.now()/1e3)});const X=await Q;if(j)try{j()}catch{}return f&&x!==f&&e.stderr(`
39
39
  Agent exited. You were working in ${f}; your shell is back in ${x}.
40
40
  To return:
41
- cd ${le(f)}
41
+ cd ${se(f)}
42
42
  `),X}function ke(r,e,i){return`
43
43
  WORKTREE STEERING: You are in worktree ${r} on branch ${e}. Do ALL work HERE \u2014 cut your feature branch (fix/.../feat/...) off ${e} in THIS worktree, use relative paths / your cwd. NEVER \`git -C ${i}\` or operate on the primary checkout ${i}: the same branch can't be checked out in two worktrees, so work created in the primary won't reach your wt-branch without manual surgery (cherry-pick/merge).
44
44
  `}function ye(r,e){return`
45
45
  WORKTREE STEERING: This checkout is now on branch ${e}. Do ALL work HERE in ${r} \u2014 cut your feature branch (fix/.../feat/...) off ${e}, use relative paths / your cwd.
46
46
  `}function q(r){return r.replace(/[\x00-\x1F\x7F]/g,"")}function ve(r,e,i){const a=r.runSync("git",["worktree","list","--porcelain"],e);return a.status!==0?!1:a.stdout.split(`
47
- `).some(n=>n===`worktree ${i}`)}function $e(r,e){if(e.length===0)return null;const i=r.toLowerCase();let a=null;for(const n of e){const s=pe(i,n.toLowerCase());s<=2&&(a===null||s<a.distance)&&(a={name:n,distance:s})}return a?a.name:null}function pe(r,e){if(r===e)return 0;if(r.length===0)return e.length;if(e.length===0)return r.length;const i=new Array(e.length+1),a=new Array(e.length+1);for(let n=0;n<=e.length;n++)i[n]=n;for(let n=1;n<=r.length;n++){a[0]=n;for(let s=1;s<=e.length;s++){const x=r[n-1]===e[s-1]?0:1;a[s]=Math.min(a[s-1]+1,i[s]+1,i[s-1]+x)}for(let s=0;s<=e.length;s++)i[s]=a[s]}return i[e.length]}export{De as runAssimilate,q as safeStderr,$e as suggestRoleName};
47
+ `).some(n=>n===`worktree ${i}`)}function $e(r,e){if(e.length===0)return null;const i=r.toLowerCase();let a=null;for(const n of e){const l=pe(i,n.toLowerCase());l<=2&&(a===null||l<a.distance)&&(a={name:n,distance:l})}return a?a.name:null}function pe(r,e){if(r===e)return 0;if(r.length===0)return e.length;if(e.length===0)return r.length;const i=new Array(e.length+1),a=new Array(e.length+1);for(let n=0;n<=e.length;n++)i[n]=n;for(let n=1;n<=r.length;n++){a[0]=n;for(let l=1;l<=e.length;l++){const x=r[n-1]===e[l-1]?0:1;a[l]=Math.min(a[l-1]+1,i[l]+1,i[l-1]+x)}for(let l=0;l<=e.length;l++)i[l]=a[l]}return i[e.length]}export{Oe as runAssimilate,q as safeStderr,$e as suggestRoleName};
@@ -1,3 +1,3 @@
1
- import{spawnSync as m,spawn as l}from"node:child_process";import{existsSync as h,mkdirSync as f}from"node:fs";import{hostname as b,homedir as k}from"node:os";import{createInterface as d}from"node:readline/promises";import{API_URL as u,getValidToken as p,listCubes as C,getCube as _,createCube as T,assimilate as y,listTemplates as w}from"./remote-client.js";import{findProjectRoot as g,getActiveCube as L,setActiveCube as x,inboxPathForDrone as S,setCodexWakeTarget as v,getLaunchBackend as R,setLaunchBackend as B,clearLaunchBackend as A}from"./cubes.js";import{authenticateWithGoogle as P}from"./auth.js";import{addProjectSessionStartHook as U}from"./config-utils.js";import{setTerminalTitle as j}from"./terminal-title.js";import{defaultCliChoiceDeps as D,resolveCliChoice as G}from"./cli-platform.js";import{prepareCodexRemoteLaunch as H,defaultCodexRemoteDeps as I}from"./codex-remote.js";import{findLoadedCodexThread as q}from"./codex-app-server.js";import{checkBackendReachable as V}from"./backend-presets.js";function $(){return{runSync:(e,t,r)=>{const o=m(e,t,{cwd:r,encoding:"utf-8"});return{status:o.status,stdout:o.stdout??"",stderr:o.stderr??""}},pathExists:e=>h(e),cwd:()=>process.cwd(),chdir:e=>process.chdir(e),homedir:()=>k(),mkdirp:e=>f(e,{recursive:!0}),exec:(e,t,r,o)=>new Promise((s,i)=>{const a=l(e,t,{cwd:r,stdio:"inherit",shell:!1,env:o??process.env});a.on("error",i),a.on("exit",n=>s(n??0))}),stderr:e=>process.stderr.write(e),stdout:e=>process.stdout.write(e),prompt:async e=>{const t=d({input:process.stdin,output:process.stdout});try{return await t.question(e)}finally{t.close()}},isTTY:()=>process.stdin.isTTY===!0,getHostname:()=>b(),setTerminalTitle:(e,t)=>{j({label:e,cubeName:t},t)},getActiveCube:()=>L(),setActiveCube:e=>x(e),findProjectRoot:e=>g(e),installProjectSessionHook:e=>{U(e)},getCachedAuth:async()=>{try{return{token:await p(),apiUrl:u}}catch{return null}},runSetup:async()=>(await P(),{token:await p(),apiUrl:u}),listCubes:async(e,t)=>{const{cubes:r}=await C();return r.map(o=>({id:o.id,name:o.name}))},getCube:async(e,t,r)=>{const o=await _(r);return{id:o.id,name:o.name,roles:o.roles}},createCube:async(e,t,r)=>{const o=await T(r.name,"",r.template?{template:r.template}:void 0);return{id:o.id,name:o.name,roles:o.roles}},assimilate:async(e,t,r)=>{const o=await y({cube_id:r.cube_id,role_id:r.role_id,...r.prior_drone_id?{prior_drone_id:r.prior_drone_id}:{},...r.backend!=null?{backend:r.backend}:{}},void 0,r.hostname??null);return{cube_id:o.cube.id,drone_id:o.drone.id,drone_label:o.drone.label,session_token:o.sessionToken,role_id:o.role.id,reattached:o.reattached===!0}},listTemplates:async(e,t)=>{const{templates:r}=await w();return r.map(o=>({name:o.name,description:o.description}))},getInboxPath:(e,t)=>S(e,t),probeMcpReady:()=>new Promise(e=>{const t=l("borg-mcp",[],{stdio:["pipe","pipe","pipe"],shell:!1});let r="",o=!1;const s=n=>{if(!o){o=!0;try{t.kill("SIGTERM")}catch{}e(n)}},i=setTimeout(()=>s(!1),2e3);t.on("error",()=>{clearTimeout(i),s(!1)}),t.on("exit",()=>{clearTimeout(i),s(o)}),t.stdout?.on("data",n=>{r+=n.toString("utf-8");for(const c of r.split(`
1
+ import{spawnSync as p,spawn as l}from"node:child_process";import{existsSync as h,mkdirSync as f}from"node:fs";import{hostname as b,homedir as C}from"node:os";import{createInterface as d}from"node:readline/promises";import{API_URL as u,getValidToken as m,listCubes as _,getCube as T,createCube as y,assimilate as k,listTemplates as w}from"./remote-client.js";import{findProjectRoot as g,getActiveCube as L,setActiveCube as x,inboxPathForDrone as M,setCodexWakeTarget as S,getLaunchModel as v,setLaunchModel as R,clearLaunchModel as A}from"./cubes.js";import{authenticateWithGoogle as P}from"./auth.js";import{addProjectSessionStartHook as U}from"./config-utils.js";import{setTerminalTitle as j}from"./terminal-title.js";import{defaultCliChoiceDeps as D,resolveCliChoice as G}from"./cli-platform.js";import{prepareCodexRemoteLaunch as H,defaultCodexRemoteDeps as I}from"./codex-remote.js";import{findLoadedCodexThread as q}from"./codex-app-server.js";import{checkModelReachable as V}from"./model-presets.js";function $(){return{runSync:(e,t,o)=>{const r=p(e,t,{cwd:o,encoding:"utf-8"});return{status:r.status,stdout:r.stdout??"",stderr:r.stderr??""}},pathExists:e=>h(e),cwd:()=>process.cwd(),chdir:e=>process.chdir(e),homedir:()=>C(),mkdirp:e=>f(e,{recursive:!0}),exec:(e,t,o,r)=>new Promise((s,i)=>{const a=l(e,t,{cwd:o,stdio:"inherit",shell:!1,env:r??process.env});a.on("error",i),a.on("exit",n=>s(n??0))}),stderr:e=>process.stderr.write(e),stdout:e=>process.stdout.write(e),prompt:async e=>{const t=d({input:process.stdin,output:process.stdout});try{return await t.question(e)}finally{t.close()}},isTTY:()=>process.stdin.isTTY===!0,getHostname:()=>b(),setTerminalTitle:(e,t)=>{j({label:e,cubeName:t},t)},getActiveCube:()=>L(),setActiveCube:e=>x(e),findProjectRoot:e=>g(e),installProjectSessionHook:e=>{U(e)},getCachedAuth:async()=>{try{return{token:await m(),apiUrl:u}}catch{return null}},runSetup:async()=>(await P(),{token:await m(),apiUrl:u}),listCubes:async(e,t)=>{const{cubes:o}=await _();return o.map(r=>({id:r.id,name:r.name}))},getCube:async(e,t,o)=>{const r=await T(o);return{id:r.id,name:r.name,roles:r.roles}},createCube:async(e,t,o)=>{const r=await y(o.name,"",o.template?{template:o.template}:void 0);return{id:r.id,name:r.name,roles:r.roles}},assimilate:async(e,t,o)=>{const r=await k({cube_id:o.cube_id,role_id:o.role_id,...o.prior_drone_id?{prior_drone_id:o.prior_drone_id}:{},...o.model!=null?{model:o.model}:{}},void 0,o.hostname??null,o.agent_kind??null);return{cube_id:r.cube.id,drone_id:r.drone.id,drone_label:r.drone.label,session_token:r.sessionToken,role_id:r.role.id,reattached:r.reattached===!0}},listTemplates:async(e,t)=>{const{templates:o}=await w();return o.map(r=>({name:r.name,description:r.description}))},getInboxPath:(e,t)=>M(e,t),probeMcpReady:()=>new Promise(e=>{const t=l("borg-mcp",[],{stdio:["pipe","pipe","pipe"],shell:!1});let o="",r=!1;const s=n=>{if(!r){r=!0;try{t.kill("SIGTERM")}catch{}e(n)}},i=setTimeout(()=>s(!1),2e3);t.on("error",()=>{clearTimeout(i),s(!1)}),t.on("exit",()=>{clearTimeout(i),s(r)}),t.stdout?.on("data",n=>{o+=n.toString("utf-8");for(const c of o.split(`
2
2
  `))if(c.includes('"protocolVersion"')&&c.includes('"result"')){clearTimeout(i),s(!0);return}});const a=JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"borg-assimilate-probe",version:"0.9.3"}}});try{t.stdin?.write(a+`
3
- `)}catch{clearTimeout(i),s(!1)}}),resolveCli:e=>G(e,D(async t=>{const r=d({input:process.stdin,output:process.stdout});try{return await r.question(t)}finally{r.close()}},()=>process.stdin.isTTY===!0)),prepareCodexRemoteLaunch:()=>H(I()),setCodexWakeTarget:v,findLoadedCodexThread:q,fetch,checkBackendReachable:V,getLaunchBackend:(e,t)=>R(e,t),setLaunchBackend:(e,t,r)=>B(e,t,r),clearLaunchBackend:(e,t)=>A(e,t)}}export{$ as buildDefaultAssimilateDeps};
3
+ `)}catch{clearTimeout(i),s(!1)}}),resolveCli:e=>G(e,D(async t=>{const o=d({input:process.stdin,output:process.stdout});try{return await o.question(t)}finally{o.close()}},()=>process.stdin.isTTY===!0)),prepareCodexRemoteLaunch:()=>H(I()),setCodexWakeTarget:S,findLoadedCodexThread:q,fetch,checkModelReachable:V,getLaunchModel:(e,t)=>v(e,t),setLaunchModel:(e,t,o)=>R(e,t,o),clearLaunchModel:(e,t)=>A(e,t)}}export{$ as buildDefaultAssimilateDeps};
package/dist/claude.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as D}from"child_process";import{randomUUID as L}from"node:crypto";import{basename as E}from"node:path";import{createInterface as B}from"node:readline/promises";import a from"chalk";import{findProjectRoot as O,getActiveCube as H,getLaunchBackend as M,inboxPathForDrone as F,setCodexWakeTarget as N,pruneDeadCodexWakeTargets as _}from"./cubes.js";import{applyOllamaLaunchEnv as G,checkBackendReachable as W}from"./backend-presets.js";import{handleVersionFlag as Y,getPackageVersion as g}from"./version.js";import{isHelpFlag as y,setupHelpText as U,topLevelHelpText as V,assimilateHelpText as j}from"./cli-help.js";import{runSpawn as K}from"./spawn.js";import{parseSyncArgs as q,runSync as z}from"./sync.js";import{parseAssimilateArgs as X}from"./parse-assimilate-args.js";import{runAssimilate as J}from"./assimilate-cmd.js";import{buildDefaultAssimilateDeps as Q}from"./assimilate-deps.js";import{parseLaunchAllArgs as S}from"./parse-launch-all-args.js";import{runLaunchAll as T}from"./launch-all-cmd.js";import{buildDefaultLaunchAllDeps as w}from"./launch-all-deps.js";import{discoverDroneCandidates as Z}from"./launch-all-discovery.js";import{runBareLaunchMenu as ee,shouldShowLaunchMenu as re}from"./bare-launch-menu.js";import{setTerminalTitle as oe}from"./terminal-title.js";import{initConsolePrefix as se,consolePrefix as s}from"./console-prefix.js";import{initDebugFromArgv as te}from"./debug.js";import{fetchLatestBorgmcpVersion as ae,compareVersionsForStaleness as ie}from"./stale-version-check.js";import{defaultCliChoiceDeps as ne,detectCliAvailability as x,installedCliNames as A,parseCliFlag as ce,resolveCliChoice as le}from"./cli-platform.js";import{getRefreshToken as de,getIdToken as pe}from"./config.js";import{composeGetStarted as ue,shouldShowGetStarted as me}from"./get-started.js";import{prepareCodexRemoteLaunch as fe,withCodexCwdArg as ge,defaultCodexRemoteDeps as he,checkCodexBridgeHealthy as we}from"./codex-remote.js";import{findLoadedCodexThread as xe}from"./codex-app-server.js";import{buildAgentKickoffPrompt as ve,recordCodexWakeTarget as ke,socketPathFromRemoteArgs as I}from"./codex-launch.js";import{codexBorgSessionConfigArgs as be}from"./launch-gate.js";import{addCodexMcpServer as Ce,addCodexSessionStartHook as $e,addCodexUserPromptSubmitHook as ye,addMcpServer as Se,addProjectSessionStartHook as Te,addUserPromptSubmitHook as Ae,isCodexMcpServerConfigured as Ie,isMcpServerConfigured as Pe,removeSessionStartHook as Re}from"./config-utils.js";async function De(){te(process.argv),Y(),await se();const c=(async()=>{if(!process.stderr.isTTY)return;const e=g(),r=await ae();if(!r)return;const i=ie(e,r);i.stale&&i.message&&process.stderr.write(`${s()}${i.message}
2
+ import{spawn as D}from"child_process";import{randomUUID as L}from"node:crypto";import{basename as M}from"node:path";import{createInterface as E}from"node:readline/promises";import a from"chalk";import{findProjectRoot as O,getActiveCube as H,getLaunchModel as F,inboxPathForDrone as N,setCodexWakeTarget as B,pruneDeadCodexWakeTargets as _}from"./cubes.js";import{applyOllamaLaunchEnv as G,checkModelReachable as W}from"./model-presets.js";import{handleVersionFlag as Y,getPackageVersion as g}from"./version.js";import{isHelpFlag as y,setupHelpText as U,topLevelHelpText as V,assimilateHelpText as j}from"./cli-help.js";import{runSpawn as K}from"./spawn.js";import{parseSyncArgs as q,runSync as z}from"./sync.js";import{parseAssimilateArgs as X}from"./parse-assimilate-args.js";import{runAssimilate as J}from"./assimilate-cmd.js";import{buildDefaultAssimilateDeps as Q}from"./assimilate-deps.js";import{parseLaunchAllArgs as S}from"./parse-launch-all-args.js";import{runLaunchAll as T}from"./launch-all-cmd.js";import{buildDefaultLaunchAllDeps as w}from"./launch-all-deps.js";import{discoverDroneCandidates as Z}from"./launch-all-discovery.js";import{runBareLaunchMenu as ee,shouldShowLaunchMenu as re}from"./bare-launch-menu.js";import{setTerminalTitle as oe}from"./terminal-title.js";import{initConsolePrefix as se,consolePrefix as s}from"./console-prefix.js";import{initDebugFromArgv as te}from"./debug.js";import{fetchLatestBorgmcpVersion as ae,compareVersionsForStaleness as ie}from"./stale-version-check.js";import{defaultCliChoiceDeps as ne,detectCliAvailability as x,installedCliNames as A,parseCliFlag as ce,resolveCliChoice as le}from"./cli-platform.js";import{getRefreshToken as de,getIdToken as pe}from"./config.js";import{composeGetStarted as ue,shouldShowGetStarted as me}from"./get-started.js";import{prepareCodexRemoteLaunch as fe,withCodexCwdArg as ge,defaultCodexRemoteDeps as he,checkCodexBridgeHealthy as we}from"./codex-remote.js";import{findLoadedCodexThread as xe}from"./codex-app-server.js";import{buildAgentKickoffPrompt as ve,recordCodexWakeTarget as be,socketPathFromRemoteArgs as I}from"./codex-launch.js";import{codexBorgSessionConfigArgs as Ce}from"./launch-gate.js";import{addCodexMcpServer as ke,addCodexSessionStartHook as $e,addCodexUserPromptSubmitHook as ye,addMcpServer as Se,addProjectSessionStartHook as Te,addUserPromptSubmitHook as Ae,isCodexMcpServerConfigured as Ie,isMcpServerConfigured as Pe,removeSessionStartHook as Re}from"./config-utils.js";async function De(){te(process.argv),Y(),await se();const c=(async()=>{if(!process.stderr.isTTY)return;const e=g(),r=await ae();if(!r)return;const i=ie(e,r);i.stale&&i.message&&process.stderr.write(`${s()}${i.message}
3
3
  `)})();if((process.argv[2]==="--help"||process.argv[2]==="-h")&&(process.stdout.write(V(g())),process.exit(0)),process.argv[2]==="setup"){y(process.argv[3])&&(process.stdout.write(U(g())),process.exit(0)),await import("./setup.js");return}if(process.argv[2]==="assimilate"){process.argv.slice(3).some(y)&&(process.stdout.write(j(g())),process.exit(0));const e=X(process.argv.slice(3));e.ok||(process.stderr.write(a.red(`${s()}\u25FC borg assimilate: ${e.error}
4
4
  `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const r=Q(),i=await J({role:e.role,flags:e.flags},r);process.exit(i)}if(process.argv[2]==="spawn"){const e=await K();process.exit(e)}if(process.argv[2]==="sync"){const e=q(process.argv.slice(3));e.ok||(process.stderr.write(a.red(`${s()}\u25FC borg sync: ${e.error}
5
5
  `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const r=await z({},e.options);process.exit(r)}if(process.argv[2]==="launch-all"){const e=S(process.argv.slice(3));e.ok||(process.stderr.write(a.red(`${s()}\u25FC borg launch-all: ${e.error}
6
6
  `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const r=w(),i=await T(e.args,r);process.exit(i)}if(me(await de()!==null,await pe()!==null)){const e=A(x()).length>0;process.stdout.write(ue(e)),process.exit(0)}const n=ce(process.argv.slice(2));n.error&&(process.stderr.write(a.red(`${s()}\u25FC ${n.error}
7
- `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const v=async e=>{const r=B({input:process.stdin,output:process.stdout});try{return await r.question(e)}finally{r.close()}};let o=await le(n.cli,ne(v,()=>process.stdin.isTTY===!0));Le();const t=await H();if(re({extraArgs:process.argv.slice(2),stdinIsTTY:process.stdin.isTTY===!0,stdoutIsTTY:process.stdout.isTTY===!0})){const e=A(x()).find(m=>m!==o)??null;let r=!1;t&&(r=(await Z({targetCubeId:t.cubeId},w())).length>0);const i=await ee({defaultCli:o,otherInstalledCli:e,hasLaunchAllTargets:r},v);if(i.kind==="launch-all"){const m=S([]),R=m.ok?await T(m.args,w()):1;process.exit(R)}o=i.cli}const l=n.rest;oe(t?{label:t.droneLabel,cubeName:t.name}:null,E(process.cwd()));const P=t&&o==="claude"?`If you haven't yet, arm a persistent Monitor running the command \`borg-inbox-monitor ${F(t.cubeId,t.droneId)}\` so each event's task-notification title summarizes the new cube log entry (drone label, role, and first ~80 chars of the message body) \u2014 letting you triage events without reading the full body. `:"";await Promise.race([c,new Promise(e=>setTimeout(e,2e3))]);const k=o==="codex"?`borg-wake-${L()}`:null;let f,b=[],d={...process.env,BORG_SESSION:"1"},p=null,u=null;if(o==="codex"&&!l.includes("--remote")){console.error(`${s()}${a.gray("\u25FC Starting Codex remote-wake app-server\u2026")}`);const e=await fe(he());e.warning?(console.error(`${s()}${a.yellow(`warning: ${e.warning}`)}`),f="\u26A0 Codex wake-path capability check failed: remote-control is unavailable for this session. Run borg_regen manually whenever you return, and expect only fallback wakeups until relaunch."):f="Codex wake-path capability check passed: remote-control socket established for this session.",b=e.args,d={...process.env,...e.env,BORG_SESSION:"1"},p=I(e.args),u=e.server?.cleanup??null}else o==="codex"&&l.includes("--remote")&&(f="Codex wake-path capability check: using caller-provided --remote socket; if no wake arrives, run borg_regen manually when returning to the session.",p=I(l),p&&(d={...process.env,BORG_CODEX_REMOTE_WAKE:"1",BORG_SESSION:"1"}));if(t){const e=await M(t.cubeId,t.droneId),r=G(d,e,process.env);if(d=r.env,r.probe){const i=await W(r.probe.descriptor,fetch,r.probe.baseUrl);i.ok||console.error(`${s()}${a.yellow(`warning: ${i.message}`)}`)}}const C=ve({cli:o,codexWakeNonce:k,monitorClause:P,codexWakePathClause:f});let h=[...l,C];o==="codex"&&(h=[...be(),...b,...ge(h,process.cwd())]),console.error(`${s()}${a.blue(`\u25FC Launching ${o==="claude"?"Claude Code":"Codex"}\u2026`)}`);const $=D(o,h,{stdio:"inherit",shell:!1,env:d});o==="codex"&&t&&p&&(ke({deps:{setCodexWakeTarget:N,findLoadedCodexThread:xe},cubeId:t.cubeId,droneId:t.droneId,socketPath:p,passthroughArgs:l,previewNeedle:k??C.slice(0,120),cwd:process.cwd(),launchedAtSeconds:Math.floor(Date.now()/1e3)}),_(e=>we(e))),$.on("error",e=>{if(u)try{u()}catch{}e.code==="ENOENT"?(console.error(`${s()}${a.red(`
7
+ `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const v=async e=>{const r=E({input:process.stdin,output:process.stdout});try{return await r.question(e)}finally{r.close()}};let o=await le(n.cli,ne(v,()=>process.stdin.isTTY===!0));Le();const t=await H();if(re({extraArgs:process.argv.slice(2),stdinIsTTY:process.stdin.isTTY===!0,stdoutIsTTY:process.stdout.isTTY===!0})){const e=A(x()).find(m=>m!==o)??null;let r=!1;t&&(r=(await Z({targetCubeId:t.cubeId},w())).length>0);const i=await ee({defaultCli:o,otherInstalledCli:e,hasLaunchAllTargets:r},v);if(i.kind==="launch-all"){const m=S([]),R=m.ok?await T(m.args,w()):1;process.exit(R)}o=i.cli}const l=n.rest;oe(t?{label:t.droneLabel,cubeName:t.name}:null,M(process.cwd()));const P=t&&o==="claude"?`If you haven't yet, arm a persistent Monitor running the command \`borg-inbox-monitor ${N(t.cubeId,t.droneId)}\` so each event's task-notification title summarizes the new cube log entry (drone label, role, and first ~80 chars of the message body) \u2014 letting you triage events without reading the full body. `:"";await Promise.race([c,new Promise(e=>setTimeout(e,2e3))]);const b=o==="codex"?`borg-wake-${L()}`:null;let f,C=[],d={...process.env,BORG_SESSION:"1"},p=null,u=null;if(o==="codex"&&!l.includes("--remote")){console.error(`${s()}${a.gray("\u25FC Starting Codex remote-wake app-server\u2026")}`);const e=await fe(he());e.warning?(console.error(`${s()}${a.yellow(`warning: ${e.warning}`)}`),f="\u26A0 Codex wake-path capability check failed: remote-control is unavailable for this session. Run borg_regen manually whenever you return, and expect only fallback wakeups until relaunch."):f="Codex wake-path capability check passed: remote-control socket established for this session.",C=e.args,d={...process.env,...e.env,BORG_SESSION:"1"},p=I(e.args),u=e.server?.cleanup??null}else o==="codex"&&l.includes("--remote")&&(f="Codex wake-path capability check: using caller-provided --remote socket; if no wake arrives, run borg_regen manually when returning to the session.",p=I(l),p&&(d={...process.env,BORG_CODEX_REMOTE_WAKE:"1",BORG_SESSION:"1"}));if(t){const e=await F(t.cubeId,t.droneId),r=G(d,e,process.env);if(d=r.env,r.probe){const i=await W(r.probe.descriptor,fetch,r.probe.baseUrl);i.ok||console.error(`${s()}${a.yellow(`warning: ${i.message}`)}`)}}const k=ve({cli:o,codexWakeNonce:b,monitorClause:P,codexWakePathClause:f});let h=[...l,k];o==="codex"&&(h=[...Ce(),...C,...ge(h,process.cwd())]),console.error(`${s()}${a.blue(`\u25FC Launching ${o==="claude"?"Claude Code":"Codex"}\u2026`)}`);const $=D(o,h,{stdio:"inherit",shell:!1,env:d});o==="codex"&&t&&p&&(be({deps:{setCodexWakeTarget:B,findLoadedCodexThread:xe},cubeId:t.cubeId,droneId:t.droneId,socketPath:p,passthroughArgs:l,previewNeedle:b??k.slice(0,120),cwd:process.cwd(),launchedAtSeconds:Math.floor(Date.now()/1e3)}),_(e=>we(e))),$.on("error",e=>{if(u)try{u()}catch{}e.code==="ENOENT"?(console.error(`${s()}${a.red(`
8
8
  \u25FC Failed to launch ${o}`)}`),console.error(`${s()}${a.gray(`Make sure ${o} is installed.
9
9
  `)}`)):console.error(`${s()}${a.red(`
10
10
  \u25FC Failed to launch ${o}: ${e.message}
11
- `)}`),process.exit(1)}),$.on("exit",e=>{if(u)try{u()}catch{}process.exit(e??0)})}function Le(){const c=x();if(c.claude)try{Pe()||Se(),Te(O(process.cwd())),Re(),Ae()}catch(n){console.error(`${s()}${a.yellow(`warning: Claude Code integration check failed: ${n?.message??n}`)}`)}if(c.codex)try{Ie()||Ce(),$e(),ye()}catch(n){console.error(`${s()}${a.yellow(`warning: Codex integration check failed: ${n?.message??n}`)}`)}}De().catch(c=>{console.error(`${s()}${a.red(`
11
+ `)}`),process.exit(1)}),$.on("exit",e=>{if(u)try{u()}catch{}process.exit(e??0)})}function Le(){const c=x();if(c.claude)try{Pe()||Se(),Te(O(process.cwd())),Re(),Ae()}catch(n){console.error(`${s()}${a.yellow(`warning: Claude Code integration check failed: ${n?.message??n}`)}`)}if(c.codex)try{Ie()||ke(),$e(),ye()}catch(n){console.error(`${s()}${a.yellow(`warning: Codex integration check failed: ${n?.message??n}`)}`)}}De().catch(c=>{console.error(`${s()}${a.red(`
12
12
  \u25FC Error: ${c.message}
13
13
  `)}`),process.exit(1)});
@@ -16,7 +16,7 @@ export declare function isHelpFlag(arg: string | undefined): boolean;
16
16
  export declare function topLevelHelpText(version: string): string;
17
17
  /**
18
18
  * Help text for `borg assimilate --help` — the home for the full assimilate flag
19
- * set, including `--backend` and remote-Ollama config, which the concise
19
+ * set, including `--model` and remote-Ollama config, which the concise
20
20
  * top-level help only hints at.
21
21
  */
22
22
  export declare function assimilateHelpText(version: string): string;
package/dist/cli-help.js CHANGED
@@ -1,4 +1,4 @@
1
- function n(e){return e==="--help"||e==="-h"}function o(e){return`borgmcp ${e} \u2014 run several AI coding agents on one project, together.
1
+ function o(e){return e==="--help"||e==="-h"}function n(e){return`borgmcp ${e} \u2014 run several AI coding agents on one project, together.
2
2
  They coordinate through a shared log (a "cube"). For Claude Code & Codex.
3
3
 
4
4
  Docs & quickstart: https://borgmcp.ai/get-started
@@ -12,7 +12,7 @@ Usage:
12
12
  borg setup --no-browser Set up from SSH/headless terminals
13
13
  borg assimilate [role] Join a cube (creates one if needed)
14
14
  borg assimilate --worktree <name> Spawn a worktree drone (in ~/.borg/worktrees/<repo>/<name>)
15
- borg assimilate --backend ollama:<model> Run the drone on an Ollama model (see \`borg assimilate --help\`)
15
+ borg assimilate --model ollama:<model> Run the drone on an Ollama model (see \`borg assimilate --help\`)
16
16
  borg sync [--prune] Sync this worktree's branch to origin/main
17
17
  borg launch-all [cube] Launch all drone worktrees of a cube (default: active cube)
18
18
  borg --cli claude|codex Choose agent CLI for this project
@@ -35,18 +35,18 @@ Flags:
35
35
  --template <name> Bootstrap a new cube from a bundled role template
36
36
  --no-template Create the cube with no template roles
37
37
  --cli claude|codex Agent CLI to launch (default: claude)
38
- --backend <kind>:<model> Model backend for this drone (default: your Claude config)
38
+ --model <kind>:<model> Model for this drone (default: your Claude config)
39
39
  --yes, -y Skip confirmation prompts
40
40
 
41
- Backends (--backend <kind>:<model>):
42
- claude:<model> e.g. --backend claude:claude-opus-4-8
43
- ollama:<model> Run on an Ollama model, e.g. --backend ollama:qwen3-coder-next
41
+ Models (--model <kind>:<model>):
42
+ claude:<model> e.g. --model claude:claude-opus-4-8
43
+ ollama:<model> Run on an Ollama model, e.g. --model ollama:qwen3-coder-next
44
44
  The model must be pulled (ollama pull <model>); borg verifies it
45
45
  against the Ollama server before assimilating.
46
46
 
47
47
  Remote Ollama: set BORG_OLLAMA_BASE_URL (default http://localhost:11434), e.g.
48
48
  BORG_OLLAMA_BASE_URL=http://Mac-Studio.local:11434 \\
49
- borg assimilate build --backend ollama:qwen3-coder-next
49
+ borg assimilate build --model ollama:qwen3-coder-next
50
50
  `}function r(e){return`borg setup (borgmcp ${e}) \u2014 set up OAuth + register the borg MCP server
51
51
 
52
52
  Borg MCP needs Claude Code or Codex installed first.
@@ -58,4 +58,4 @@ Usage:
58
58
  for SSH / headless / container terminals. Alias: --device.
59
59
  Auto-detected on SSH/headless; this forces it.
60
60
  borg setup --help Show this help
61
- `}export{t as assimilateHelpText,n as isHelpFlag,r as setupHelpText,o as topLevelHelpText};
61
+ `}export{t as assimilateHelpText,o as isHelpFlag,r as setupHelpText,n as topLevelHelpText};
package/dist/cubes.d.ts CHANGED
@@ -92,13 +92,13 @@ export declare function getCodexWakeTarget(cubeId: string, droneId: string): Pro
92
92
  * cubes.ts stays free of the codex-remote dependency.
93
93
  */
94
94
  export declare function pruneDeadCodexWakeTargets(socketLiveness: (socketPath: string) => boolean | null): Promise<void>;
95
- export interface LaunchBackendRecord {
96
- /** Backend descriptor, e.g. `ollama:qwen3-coder-next` or `claude:claude-opus-4-8`. */
97
- backend: string;
98
- /** Resolved Ollama host for an ollama backend; null for claude. */
95
+ export interface LaunchModelRecord {
96
+ /** Model descriptor, e.g. `ollama:qwen3-coder-next` or `claude:claude-opus-4-8`. */
97
+ model: string;
98
+ /** Resolved Ollama host for an ollama model; null for claude. */
99
99
  ollamaBaseUrl: string | null;
100
100
  }
101
- export declare function setLaunchBackend(cubeId: string, droneId: string, record: LaunchBackendRecord, file?: string): Promise<void>;
102
- export declare function getLaunchBackend(cubeId: string, droneId: string, file?: string): Promise<LaunchBackendRecord | null>;
103
- export declare function clearLaunchBackend(cubeId: string, droneId: string, file?: string): Promise<void>;
101
+ export declare function setLaunchModel(cubeId: string, droneId: string, record: LaunchModelRecord, file?: string): Promise<void>;
102
+ export declare function getLaunchModel(cubeId: string, droneId: string, file?: string): Promise<LaunchModelRecord | null>;
103
+ export declare function clearLaunchModel(cubeId: string, droneId: string, file?: string): Promise<void>;
104
104
  //# sourceMappingURL=cubes.d.ts.map
package/dist/cubes.js CHANGED
@@ -1,5 +1,5 @@
1
- import{existsSync as A}from"node:fs";import{mkdir as l,readFile as f,writeFile as d,unlink as m}from"node:fs/promises";import{homedir as L}from"node:os";import{dirname as s,join as c,resolve as N}from"node:path";import{pruneDeadWakeTargets as S}from"./codex-wake-resolve.js";import{BACKEND_DESCRIPTOR_REGEX as T}from"./backend-presets.js";const u=c(L(),".config","borgmcp"),p=c(u,"cubes.json"),w=c(u,"launch.json"),g=c(u,"codex-wake-targets.json"),b=c(u,"launch-backends.json"),B=c(u,"inboxes");function a(e=process.cwd()){let t=N(e);for(;;){if(A(c(t,".git")))return t;const r=s(t);if(r===t)return N(e);t=r}}const i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function G(e,t){if(!i.test(e))throw new Error(`Invalid cubeId: ${e}`);if(!i.test(t))throw new Error(`Invalid droneId: ${t}`);return c(B,e,`${t}.log`)}function P(e){return e!==null&&typeof e=="object"&&typeof e.projects=="object"&&e.projects!==null&&!Array.isArray(e.projects)}async function y(){let e;try{e=await f(p,"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}let t;try{t=JSON.parse(e)}catch{return null}return P(t)?t:null}async function C(e){await l(s(p),{recursive:!0}),await d(p,JSON.stringify(e,null,2)+`
2
- `,{mode:384})}function _(e){return e!==null&&typeof e=="object"&&typeof e.projects=="object"&&e.projects!==null&&!Array.isArray(e.projects)}async function h(){let e;try{e=await f(w,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}try{const t=JSON.parse(e);return _(t)?t:null}catch{return null}}async function $(e){await l(s(w),{recursive:!0}),await d(w,JSON.stringify(e,null,2)+`
3
- `,{mode:384})}function F(e,t){if(!i.test(e))throw new Error(`Invalid cubeId: ${e}`);if(!i.test(t))throw new Error(`Invalid droneId: ${t}`);return`${e}:${t}`}function D(e){return e!==null&&typeof e=="object"&&typeof e.targets=="object"&&e.targets!==null&&!Array.isArray(e.targets)}async function j(){let e;try{e=await f(g,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}try{const t=JSON.parse(e);return D(t)?t:null}catch{return null}}async function I(e){await l(s(g),{recursive:!0}),await d(g,JSON.stringify(e,null,2)+`
4
- `,{mode:384})}async function H(){const e=await y();if(!e)return null;const t=a(),r=e.projects[t];return!r||typeof r.cubeId!="string"||!r.cubeId||typeof r.droneId!="string"||!r.droneId?null:r}async function q(e){const t=await y()??{projects:{}};t.projects[a()]=e,await C(t)}function z(e,t){const r=t.cube?.name??e.name,n=t.drone?.label??e.droneLabel;return r===e.name&&n===e.droneLabel?e:{...e,name:r,droneLabel:n}}async function M(){const e=await y();if(!e)return;const t=a();if(t in e.projects){if(delete e.projects[t],Object.keys(e.projects).length===0){try{await m(p)}catch(r){if(r?.code!=="ENOENT")throw r}return}await C(e)}}async function Q(){const e=await h();if(!e)return null;const t=e.projects[a()];return t?.cli==="claude"||t?.cli==="codex"?t.cli:null}async function V(e){const t=await h();if(!t)return null;const r=t.projects[a(e)];return r?.cli==="claude"||r?.cli==="codex"?r.cli:null}async function Y(){const e=await y();return e?Object.entries(e.projects).filter(([,t])=>t!==null&&typeof t=="object"&&typeof t.cubeId=="string"&&t.cubeId.length>0&&typeof t.droneId=="string"&&t.droneId.length>0).map(([t,r])=>({projectPath:t,cube:r})):[]}async function Z(e){const t=await h()??{projects:{}};t.projects[a()]={cli:e},await $(t)}async function ee(e,t,r){const n=await j()??{targets:{}};n.targets[F(e,t)]={...r,updatedAt:new Date().toISOString()},await I(n)}async function te(e,t){const r=await j();if(!r)return null;const n=r.targets[F(e,t)];return!n||typeof n.threadId!="string"||typeof n.socketPath!="string"?null:n}async function re(e){const t=await j();if(!t)return;const{targets:r,changed:n}=S(t.targets,e);n&&await I({...t,targets:r})}function k(e,t){if(!i.test(e))throw new Error(`Invalid cubeId: ${e}`);if(!i.test(t))throw new Error(`Invalid droneId: ${t}`);return`${e}:${t}`}function U(e){return e!==null&&typeof e=="object"&&typeof e.backends=="object"&&e.backends!==null&&!Array.isArray(e.backends)}async function x(e){let t;try{t=await f(e,"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}try{const r=JSON.parse(t);return U(r)?r:null}catch{return null}}async function O(e,t){await l(s(e),{recursive:!0}),await d(e,JSON.stringify(t,null,2)+`
5
- `,{mode:384})}async function ne(e,t,r,n=b){const o=await x(n)??{backends:{}};o.backends[k(e,t)]={backend:r.backend,ollamaBaseUrl:r.ollamaBaseUrl},await O(n,o)}async function oe(e,t,r=b){const n=await x(r);if(!n)return null;const o=n.backends[k(e,t)];return!o||typeof o.backend!="string"||!T.test(o.backend)?null:{backend:o.backend,ollamaBaseUrl:typeof o.ollamaBaseUrl=="string"?o.ollamaBaseUrl:null}}async function ce(e,t,r=b){const n=await x(r);if(!n)return;const o=k(e,t);if(o in n.backends){if(delete n.backends[o],Object.keys(n.backends).length===0){try{await m(r)}catch(E){if(E?.code!=="ENOENT")throw E}return}await O(r,n)}}export{z as activeCubeWithFreshRegenIdentity,M as clearActiveCube,ce as clearLaunchBackend,a as findProjectRoot,H as getActiveCube,te as getCodexWakeTarget,oe as getLaunchBackend,Q as getProjectCliPreference,V as getProjectCliPreferenceForPath,G as inboxPathForDrone,re as pruneDeadCodexWakeTargets,Y as readAllProjectIdentities,q as setActiveCube,ee as setCodexWakeTarget,ne as setLaunchBackend,Z as setProjectCliPreference};
1
+ import{existsSync as k}from"node:fs";import{mkdir as u,readFile as f,writeFile as d,unlink as N}from"node:fs/promises";import{homedir as A}from"node:os";import{dirname as s,join as i,resolve as O}from"node:path";import{pruneDeadWakeTargets as S}from"./codex-wake-resolve.js";import{MODEL_DESCRIPTOR_REGEX as T}from"./model-presets.js";const l=i(A(),".config","borgmcp"),p=i(l,"cubes.json"),w=i(l,"launch.json"),g=i(l,"codex-wake-targets.json"),h=i(l,"launch-models.json"),P=i(l,"inboxes");function c(e=process.cwd()){let t=O(e);for(;;){if(k(i(t,".git")))return t;const r=s(t);if(r===t)return O(e);t=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 X(e,t){if(!a.test(e))throw new Error(`Invalid cubeId: ${e}`);if(!a.test(t))throw new Error(`Invalid droneId: ${t}`);return i(P,e,`${t}.log`)}function _(e){return e!==null&&typeof e=="object"&&typeof e.projects=="object"&&e.projects!==null&&!Array.isArray(e.projects)}async function y(){let e;try{e=await f(p,"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}let t;try{t=JSON.parse(e)}catch{return null}return _(t)?t:null}async function C(e){await u(s(p),{recursive:!0}),await d(p,JSON.stringify(e,null,2)+`
2
+ `,{mode:384})}function $(e){return e!==null&&typeof e=="object"&&typeof e.projects=="object"&&e.projects!==null&&!Array.isArray(e.projects)}async function m(){let e;try{e=await f(w,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}try{const t=JSON.parse(e);return $(t)?t:null}catch{return null}}async function D(e){await u(s(w),{recursive:!0}),await d(w,JSON.stringify(e,null,2)+`
3
+ `,{mode:384})}function F(e,t){if(!a.test(e))throw new Error(`Invalid cubeId: ${e}`);if(!a.test(t))throw new Error(`Invalid droneId: ${t}`);return`${e}:${t}`}function U(e){return e!==null&&typeof e=="object"&&typeof e.targets=="object"&&e.targets!==null&&!Array.isArray(e.targets)}async function j(){let e;try{e=await f(g,"utf8")}catch(t){if(t?.code==="ENOENT")return null;throw t}try{const t=JSON.parse(e);return U(t)?t:null}catch{return null}}async function I(e){await u(s(g),{recursive:!0}),await d(g,JSON.stringify(e,null,2)+`
4
+ `,{mode:384})}async function G(){const e=await y();if(!e)return null;const t=c(),r=e.projects[t];return!r||typeof r.cubeId!="string"||!r.cubeId||typeof r.droneId!="string"||!r.droneId?null:r}async function H(e){const t=await y()??{projects:{}};t.projects[c()]=e,await C(t)}function q(e,t){const r=t.cube?.name??e.name,n=t.drone?.label??e.droneLabel;return r===e.name&&n===e.droneLabel?e:{...e,name:r,droneLabel:n}}async function z(){const e=await y();if(!e)return;const t=c();if(t in e.projects){if(delete e.projects[t],Object.keys(e.projects).length===0){try{await N(p)}catch(r){if(r?.code!=="ENOENT")throw r}return}await C(e)}}async function Q(){const e=await m();if(!e)return null;const t=e.projects[c()];return t?.cli==="claude"||t?.cli==="codex"?t.cli:null}async function V(e){const t=await m();if(!t)return null;const r=t.projects[c(e)];return r?.cli==="claude"||r?.cli==="codex"?r.cli:null}async function Y(){const e=await y();return e?Object.entries(e.projects).filter(([,t])=>t!==null&&typeof t=="object"&&typeof t.cubeId=="string"&&t.cubeId.length>0&&typeof t.droneId=="string"&&t.droneId.length>0).map(([t,r])=>({projectPath:t,cube:r})):[]}async function Z(e){const t=await m()??{projects:{}};t.projects[c()]={cli:e},await D(t)}async function ee(e,t,r){const n=await j()??{targets:{}};n.targets[F(e,t)]={...r,updatedAt:new Date().toISOString()},await I(n)}async function te(e,t){const r=await j();if(!r)return null;const n=r.targets[F(e,t)];return!n||typeof n.threadId!="string"||typeof n.socketPath!="string"?null:n}async function re(e){const t=await j();if(!t)return;const{targets:r,changed:n}=S(t.targets,e);n&&await I({...t,targets:r})}function x(e,t){if(!a.test(e))throw new Error(`Invalid cubeId: ${e}`);if(!a.test(t))throw new Error(`Invalid droneId: ${t}`);return`${e}:${t}`}function v(e){return e!==null&&typeof e=="object"&&typeof e.models=="object"&&e.models!==null&&!Array.isArray(e.models)}async function E(e){let t;try{t=await f(e,"utf8")}catch(r){if(r?.code==="ENOENT")return null;throw r}try{const r=JSON.parse(t);return v(r)?r:null}catch{return null}}async function L(e,t){await u(s(e),{recursive:!0}),await d(e,JSON.stringify(t,null,2)+`
5
+ `,{mode:384})}async function ne(e,t,r,n=h){const o=await E(n)??{models:{}};o.models[x(e,t)]={model:r.model,ollamaBaseUrl:r.ollamaBaseUrl},await L(n,o)}async function oe(e,t,r=h){const n=await E(r);if(!n)return null;const o=n.models[x(e,t)];return!o||typeof o.model!="string"||!T.test(o.model)?null:{model:o.model,ollamaBaseUrl:typeof o.ollamaBaseUrl=="string"?o.ollamaBaseUrl:null}}async function ie(e,t,r=h){const n=await E(r);if(!n)return;const o=x(e,t);if(o in n.models){if(delete n.models[o],Object.keys(n.models).length===0){try{await N(r)}catch(b){if(b?.code!=="ENOENT")throw b}return}await L(r,n)}}export{q as activeCubeWithFreshRegenIdentity,z as clearActiveCube,ie as clearLaunchModel,c as findProjectRoot,G as getActiveCube,te as getCodexWakeTarget,oe as getLaunchModel,Q as getProjectCliPreference,V as getProjectCliPreferenceForPath,X as inboxPathForDrone,re as pruneDeadCodexWakeTargets,Y as readAllProjectIdentities,H as setActiveCube,ee as setCodexWakeTarget,ne as setLaunchModel,Z as setProjectCliPreference};
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
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 X,ListToolsRequestSchema as z,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 be,syncRoles as he,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 I}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 Ie,nullTaxonomyTip as qe,regenWakePathDroneLabel as Ee}from"./regen-format.js";import{startLogStream as Ce,getStreamStatus as q}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 E,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{classifyInSessionAssimilate as We,reattachOnlyRefusal as Fe,reattachFailureMessage as He}from"./assimilate-guard.js";import{gateAllowsActivation as Ke,borgSessionToolNotice as Qe}from"./launch-gate.js";import{renderSyncRolesResult as Ve}from"./sync-roles-render.js";import{initConsolePrefix as Xe,consolePrefix as v}from"./console-prefix.js";import{isCodexRemoteWakeEnabled as C,resolveSessionAgentKind as ze,probeCodexBridgeArmed as Ge}from"./codex-app-wake.js";import{lifecycleSignalForMessage as Ye,recordLifecycleLog as B,shouldSuppressLifecycleLog as Je}from"./lifecycle-log-guard.js";import{normalizeDirectLogRecipients as Ze}from"./direct-log.js";import W from"open";import et from"os";function tt(){try{const p=et.hostname();return p&&p.trim()?p.trim().slice(0,255):null}catch{return null}}async function F(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 rt(){je();try{$e()}catch{}try{Ue()}catch{}try{Ce()}catch{}try{we({getActiveCube:y,getStreamConnected:()=>q().connected,getInboxPath:m=>I(m.cubeId,m.droneId),checkMonitor:E,isCodexRemoteWake:C,probeBridgeArmed:m=>Ge({cubeId:m.cubeId,droneId:m.droneId}),resolveAgentKind:ze,resolveHostname:tt,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(z,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_backend:{type:"string",description:'Default backend 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_backend:{type:"string",description:'Default backend 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(X,async m=>{const{name:g,arguments:r}=m.params;if(!Ke(`tool ${g}`))return{content:[{type:"text",text:Qe(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=q(),a=I(s.cubeId,s.droneId),c=C()?!0:E(a),d=Ae(n,c)?Te({inboxPath:a,droneLabel:Ee(o,s.droneLabel),cubeName:s.name}):"";let u="";try{const b=w(),l=De();if(b!=="unknown"&&l!=="unknown"&&l!==b){const[h,R,H]=b.split(".").map(Number),[k,D,K]=l.split(".").map(Number);(k>h||k===h&&D>R||k===h&&D===R&&K>H)&&(u=`## \u{1F504} borgmcp ${l} installed \u2014 run /mcp and reconnect (or restart Claude Code) to apply. Currently running ${b}.
2
+ import{Server as Q}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as V}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as X,ListToolsRequestSchema as z,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 I}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 Ie,nullTaxonomyTip as qe,regenWakePathDroneLabel as Ee}from"./regen-format.js";import{startLogStream as Ce,getStreamStatus as q}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 E,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{classifyInSessionAssimilate as We,reattachOnlyRefusal as Fe,reattachFailureMessage as He}from"./assimilate-guard.js";import{gateAllowsActivation as Ke,borgSessionToolNotice as Qe}from"./launch-gate.js";import{renderSyncRolesResult as Ve}from"./sync-roles-render.js";import{initConsolePrefix as Xe,consolePrefix as v}from"./console-prefix.js";import{isCodexRemoteWakeEnabled as C,resolveSessionAgentKind as ze,probeCodexBridgeArmed as Ge}from"./codex-app-wake.js";import{lifecycleSignalForMessage as Ye,recordLifecycleLog as B,shouldSuppressLifecycleLog as Je}from"./lifecycle-log-guard.js";import{normalizeDirectLogRecipients as Ze}from"./direct-log.js";import W from"open";import et from"os";function tt(){try{const p=et.hostname();return p&&p.trim()?p.trim().slice(0,255):null}catch{return null}}async function F(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 rt(){je();try{$e()}catch{}try{Ue()}catch{}try{Ce()}catch{}try{we({getActiveCube:y,getStreamConnected:()=>q().connected,getInboxPath:m=>I(m.cubeId,m.droneId),checkMonitor:E,isCodexRemoteWake:C,probeBridgeArmed:m=>Ge({cubeId:m.cubeId,droneId:m.droneId}),resolveAgentKind:ze,resolveHostname:tt,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(z,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(X,async m=>{const{name:g,arguments:r}=m.params;if(!Ke(`tool ${g}`))return{content:[{type:"text",text:Qe(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=q(),a=I(s.cubeId,s.droneId),c=C()?!0:E(a),d=Ae(n,c)?Te({inboxPath:a,droneLabel:Ee(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}.
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 be()}`}]};case"borg_upgrade-subscription":{const e=await me();try{await W(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 W(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=We(t,e);if(i.kind!=="reattach")return{content:[{type:"text",text:Fe(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(`
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 W(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 W(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=We(t,e);if(i.kind!=="reattach")return{content:[{type:"text",text:Fe(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
5
  `)+M(o,{mode:"full"})}]}}catch(o){const s=He(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=qe(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
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(`
@@ -9,7 +9,7 @@ import{Server as Q}from"@modelcontextprotocol/sdk/server/index.js";import{StdioS
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 h of n)u.set(h.id,h);const b=new Map;for(const h of a)b.set(h.id,h);const l=[];if(l.push(`# Activity log: ${e.name}`),l.push(""),!s.length)l.push("_(no entries)_");else for(const h of s)l.push(Se(h,u,b));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(`
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
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(Ye(e)){const l=await Je(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?Ze(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
14
  ${c.routing.message}`:"",u=c.unreachableRecipients?.length?`
15
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})
@@ -18,10 +18,10 @@ ${c.routing.message}`:"",u=c.unreachableRecipients?.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 F(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_backend=="string"?{default_backend:r.default_backend}:{}}),u=[d.role_class==="queen"?"Queen":null,d.is_human_seat?"human-seat":null,d.is_default?"default":null].filter(Boolean).join(", "),b=u?` (${u})`:"";return{content:[{type:"text",text:`Created role **${d.name}**${b} (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_backend=="string"&&(t.default_backend=r.default_backend),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_backend.");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=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 F(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}):
22
22
 
23
23
  ${s.join(`
24
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:
25
25
 
26
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 he(e,t,i,o);return{content:[{type:"text",text:Ve(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 F(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){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 Xe(),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`)}rt().catch(p=>{console.error(`${v()}Fatal error:`,p),process.exit(1)});
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:Ve(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 F(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){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 Xe(),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`)}rt().catch(p=>{console.error(`${v()}Fatal error:`,p),process.exit(1)});
@@ -1,11 +1,11 @@
1
1
  /**
2
- * Backend preset registry: parse descriptors and resolve launch env.
2
+ * Model preset registry: parse descriptors and resolve launch env.
3
3
  * Descriptor format: <kind>:<model> where kind ∈ {claude, ollama}.
4
4
  * Parse on first colon only (model tags contain colons).
5
5
  *
6
6
  * CLIENT copy of the descriptor regex — byte-identical to the worker.
7
7
  */
8
- export declare const BACKEND_DESCRIPTOR_REGEX: RegExp;
8
+ export declare const MODEL_DESCRIPTOR_REGEX: RegExp;
9
9
  /** Default Ollama endpoint when BORG_OLLAMA_BASE_URL is unset. */
10
10
  export declare const OLLAMA_DEFAULT_BASE_URL = "http://localhost:11434";
11
11
  /**
@@ -17,16 +17,16 @@ export declare const OLLAMA_DEFAULT_BASE_URL = "http://localhost:11434";
17
17
  */
18
18
  export declare function resolveOllamaBaseUrl(env?: Record<string, string | undefined>, storedUrl?: string | null): string;
19
19
  /**
20
- * Restore a drone's persisted launch backend onto a base environment — the
20
+ * Restore a drone's persisted launch model onto a base environment — the
21
21
  * bare-`borg` relaunch path. Returns the merged child env plus, for ollama
22
- * backends, a `{ descriptor, baseUrl }` the caller can use for a best-effort
23
- * reachability warning. A null/absent stored backend leaves the env untouched
22
+ * models, a `{ descriptor, baseUrl }` the caller can use for a best-effort
23
+ * reachability warning. A null/absent stored model leaves the env untouched
24
24
  * (backward compatible — no stored entry ⇒ today's behavior). Base-URL
25
25
  * precedence is BORG_OLLAMA_BASE_URL ▸ stored ▸ default (the pairing rule: the
26
26
  * stored host travels with the stored descriptor).
27
27
  */
28
28
  export declare function applyOllamaLaunchEnv(baseEnv: Record<string, string | undefined>, stored: {
29
- backend: string;
29
+ model: string;
30
30
  ollamaBaseUrl?: string | null;
31
31
  } | null, processEnv?: Record<string, string | undefined>): {
32
32
  env: Record<string, string | undefined>;
@@ -35,7 +35,7 @@ export declare function applyOllamaLaunchEnv(baseEnv: Record<string, string | un
35
35
  baseUrl: string;
36
36
  } | null;
37
37
  };
38
- export declare function parseBackend(descriptor: string): {
38
+ export declare function parseModel(descriptor: string): {
39
39
  kind: 'claude' | 'ollama';
40
40
  model: string;
41
41
  };
@@ -50,12 +50,12 @@ export declare function resolveLaunchEnv(descriptor: string | null, ollamaBaseUr
50
50
  * model names). Tag presence is judged on the LAST path segment so a
51
51
  * registry-host:port prefix colon (e.g. `localhost:5000/llama3`) is not mistaken
52
52
  * for a tag. NOTE: digest refs (`name@sha256:…`) can't reach here — they're
53
- * fenced out by BACKEND_DESCRIPTOR_REGEX (no `@`); widening that regex would
53
+ * fenced out by MODEL_DESCRIPTOR_REGEX (no `@`); widening that regex would
54
54
  * require updating this matcher in lockstep.
55
55
  */
56
56
  export declare function ollamaModelMatches(requested: string, available: string[]): boolean;
57
- export declare function checkBackendReachable(descriptor: string | null, fetchImpl: typeof fetch, ollamaBaseUrl?: string): Promise<{
57
+ export declare function checkModelReachable(descriptor: string | null, fetchImpl: typeof fetch, ollamaBaseUrl?: string): Promise<{
58
58
  ok: boolean;
59
59
  message?: string;
60
60
  }>;
61
- //# sourceMappingURL=backend-presets.d.ts.map
61
+ //# sourceMappingURL=model-presets.d.ts.map
@@ -0,0 +1 @@
1
+ const _=/^(claude|ollama):[A-Za-z0-9._:\/-]+$/,O="http://localhost:11434";function h(n=process.env,t){const e=n.BORG_OLLAMA_BASE_URL?.trim()||t?.trim()||"";return e?(/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`).replace(/\/+$/,""):O}function $(n,t,e=process.env){if(!t||!t.model)return{env:n,probe:null};const{kind:l}=f(t.model),o=h(e,t.ollamaBaseUrl??void 0),{set:u,unset:s}=A(t.model,o),c={...n,...u};for(const d of s)delete c[d];return{env:c,probe:l==="ollama"?{descriptor:t.model,baseUrl:o}:null}}function f(n){const t=n.indexOf(":");if(t<0)throw new Error(`invalid model descriptor: ${n} (expected <kind>:<model>)`);const e=n.substring(0,t),l=n.substring(t+1);if(e!=="claude"&&e!=="ollama")throw new Error(`invalid model kind: ${e} (expected claude or ollama)`);return{kind:e,model:l}}function A(n,t=h()){if(!n)return{set:{},unset:[]};const{kind:e,model:l}=f(n);return e==="claude"?{set:{ANTHROPIC_MODEL:l},unset:[]}:{set:{ANTHROPIC_BASE_URL:t,ANTHROPIC_MODEL:l,ANTHROPIC_AUTH_TOKEN:"ollama"},unset:["ANTHROPIC_API_KEY"]}}function L(n,t){const e=n.toLowerCase(),o=e.slice(e.lastIndexOf("/")+1).includes(":")?e:`${e}:latest`;return t.some(u=>{const s=u.toLowerCase();return s===o||s===e})}async function g(n,t,e=h()){if(!n)return{ok:!0};const{kind:l,model:o}=f(n);if(l==="claude")return{ok:!0};const s=e.includes("localhost")||e.includes("127.0.0.1")||e.includes("[::1]")?"start it (ollama serve)":"check the host is up and Ollama is listening there (OLLAMA_HOST=0.0.0.0)",c={ok:!1,message:`Ollama not reachable at ${e} \u2014 ${s}, or assimilate with a Claude model.`},d=new AbortController,p=setTimeout(()=>d.abort(),3e3);try{const m=await t(`${e}/api/tags`,{signal:d.signal});if(!m.ok)return c;let r=null;try{const i=await m.json();i&&Array.isArray(i.models)&&(r=i.models.map(a=>(a?.name??a?.model??"").replace(/[\x00-\x1F\x7F]/g,"")).filter(a=>a.length>0))}catch{}if(r&&!L(o,r)){const i=r.length===0?"no models are pulled there":`available: ${r.slice(0,12).map(a=>a.length>64?`${a.slice(0,64)}\u2026`:a).join(", ")}${r.length>12?`, \u2026 (${r.length} total)`:""}`;return{ok:!1,message:`Ollama model '${o}' not found at ${e} (${i}) \u2014 pull it with: ollama pull ${o}`}}return{ok:!0}}catch{return c}finally{clearTimeout(p)}}export{_ as MODEL_DESCRIPTOR_REGEX,O as OLLAMA_DEFAULT_BASE_URL,$ as applyOllamaLaunchEnv,g as checkModelReachable,L as ollamaModelMatches,f as parseModel,A as resolveLaunchEnv,h as resolveOllamaBaseUrl};
@@ -1 +1 @@
1
- function c(l){let n;const t={};for(let a=0;a<l.length;a+=1){const r=l[a];if(r==="--worktree"){const e=l[a+1];if(typeof e!="string"||e.length===0)return{ok:!1,error:"--worktree requires a name argument (e.g. `--worktree drone-2`)"};t.worktree=e,a+=1}else if(r==="--template"){const e=l[a+1];if(typeof e!="string"||e.length===0)return{ok:!1,error:"--template requires a name argument (e.g. `--template software-dev`)"};t.template=e,a+=1}else if(r==="--no-template")t.noTemplate=!0;else if(r==="--cube-name"){const e=l[a+1];if(typeof e!="string"||e.length===0)return{ok:!1,error:"--cube-name requires a name argument (e.g. `--cube-name my-cube`)"};t.cubeName=e,a+=1}else if(r==="--here")t.here=!0;else if(r==="--yes"||r==="-y")t.yes=!0;else if(r==="--cli"){const e=l[a+1];if(e!=="claude"&&e!=="codex")return{ok:!1,error:"--cli requires claude or codex"};t.cli=e,a+=1}else if(r.startsWith("--cli=")){const e=r.slice(6);if(e!=="claude"&&e!=="codex")return{ok:!1,error:"--cli requires claude or codex"};t.cli=e}else if(r==="--backend"){const e=l[a+1];if(typeof e!="string"||e.length===0)return{ok:!1,error:"--backend requires a descriptor (e.g. `--backend claude:claude-opus-4-8` or `--backend ollama:qwen3-coder-next:q4_K_M`)"};if(!e.match(/^(claude|ollama):[A-Za-z0-9._:\/-]+$/))return{ok:!1,error:`invalid backend descriptor '${e}' \u2014 expected <kind>:<model> where kind is claude or ollama`};t.backend=e,a+=1}else if(r.startsWith("--backend=")){const e=r.slice(10);if(!e.match(/^(claude|ollama):[A-Za-z0-9._:\/-]+$/))return{ok:!1,error:`invalid backend descriptor '${e}' \u2014 expected <kind>:<model> where kind is claude or ollama`};t.backend=e}else{if(r.startsWith("--"))return{ok:!1,error:`unknown flag: ${r}. Supported: --worktree, --template, --no-template, --cube-name, --here, --yes, --cli, --backend`};if(n!==void 0)return{ok:!1,error:`unexpected extra argument: ${r} (already have role "${n}")`};n=r}}return t.template!==void 0&&t.noTemplate?{ok:!1,error:"--template and --no-template are mutually exclusive"}:{ok:!0,role:n,flags:t}}export{c as parseAssimilateArgs};
1
+ function i(o){let a;const t={};for(let l=0;l<o.length;l+=1){const r=o[l];if(r==="--worktree"){const e=o[l+1];if(typeof e!="string"||e.length===0)return{ok:!1,error:"--worktree requires a name argument (e.g. `--worktree drone-2`)"};t.worktree=e,l+=1}else if(r==="--template"){const e=o[l+1];if(typeof e!="string"||e.length===0)return{ok:!1,error:"--template requires a name argument (e.g. `--template software-dev`)"};t.template=e,l+=1}else if(r==="--no-template")t.noTemplate=!0;else if(r==="--cube-name"){const e=o[l+1];if(typeof e!="string"||e.length===0)return{ok:!1,error:"--cube-name requires a name argument (e.g. `--cube-name my-cube`)"};t.cubeName=e,l+=1}else if(r==="--here")t.here=!0;else if(r==="--yes"||r==="-y")t.yes=!0;else if(r==="--cli"){const e=o[l+1];if(e!=="claude"&&e!=="codex")return{ok:!1,error:"--cli requires claude or codex"};t.cli=e,l+=1}else if(r.startsWith("--cli=")){const e=r.slice(6);if(e!=="claude"&&e!=="codex")return{ok:!1,error:"--cli requires claude or codex"};t.cli=e}else if(r==="--model"||r==="--backend"){const e=o[l+1];if(typeof e!="string"||e.length===0)return{ok:!1,error:"--model requires a descriptor (e.g. `--model claude:claude-opus-4-8` or `--model ollama:qwen3-coder-next:q4_K_M`)"};if(!e.match(/^(claude|ollama):[A-Za-z0-9._:\/-]+$/))return{ok:!1,error:`invalid model descriptor '${e}' \u2014 expected <kind>:<model> where kind is claude or ollama`};t.model=e,l+=1}else if(r.startsWith("--model=")||r.startsWith("--backend=")){const e=r.slice(r.indexOf("=")+1);if(!e.match(/^(claude|ollama):[A-Za-z0-9._:\/-]+$/))return{ok:!1,error:`invalid model descriptor '${e}' \u2014 expected <kind>:<model> where kind is claude or ollama`};t.model=e}else{if(r.startsWith("--"))return{ok:!1,error:`unknown flag: ${r}. Supported: --worktree, --template, --no-template, --cube-name, --here, --yes, --cli, --model`};if(a!==void 0)return{ok:!1,error:`unexpected extra argument: ${r} (already have role "${a}")`};a=r}}return t.template!==void 0&&t.noTemplate?{ok:!1,error:"--template and --no-template are mutually exclusive"}:{ok:!0,role:a,flags:t}}export{i as parseAssimilateArgs};
@@ -334,7 +334,7 @@ export declare function createRole(cubeId: string, data: {
334
334
  is_human_seat?: boolean;
335
335
  can_broadcast?: boolean;
336
336
  receives_all_direct?: boolean;
337
- default_backend?: string;
337
+ default_model?: string;
338
338
  role_class?: 'queen' | 'worker';
339
339
  }): Promise<{
340
340
  role: any;
@@ -350,7 +350,7 @@ export declare function updateRole(roleId: string, updates: {
350
350
  is_human_seat?: boolean;
351
351
  can_broadcast?: boolean;
352
352
  receives_all_direct?: boolean;
353
- default_backend?: string;
353
+ default_model?: string;
354
354
  role_class?: 'queen' | 'worker';
355
355
  }): Promise<{
356
356
  role: any;
@@ -3,7 +3,7 @@ export interface Role {
3
3
  name: string;
4
4
  is_default: boolean;
5
5
  is_human_seat: boolean;
6
- default_backend?: string | null;
6
+ default_model?: string | null;
7
7
  }
8
8
  /**
9
9
  * Normalize a role-name argument or stored name into a slug used for
@@ -31,19 +31,19 @@ export interface RosterDrone {
31
31
  wake_path?: 'live' | 'degraded' | 'deaf' | null;
32
32
  wake_path_alert_class?: 'dead' | 'post-blocked' | 'presumed-dead' | 'systemic-post-block' | 'wake-path-deaf' | 'independent' | null;
33
33
  /**
34
- * Backend descriptor (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M").
35
- * Null for drones with no explicit backend (use cube/role default).
34
+ * Model descriptor (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M").
35
+ * Null for drones with no explicit model (use cube/role default).
36
36
  */
37
- backend?: string | null;
37
+ model?: string | null;
38
38
  }
39
39
  export interface RosterRole {
40
40
  id: string;
41
41
  name: string;
42
42
  /**
43
- * Default backend descriptor for drones assigned to this role.
43
+ * Default model descriptor for drones assigned to this role.
44
44
  * Null = no role default (use cube default or null for Claude).
45
45
  */
46
- default_backend?: string | null;
46
+ default_model?: string | null;
47
47
  }
48
48
  export declare function formatRoleAgentLabel(roleName: string, agentKind: RosterDrone['agent_kind']): string;
49
49
  export interface RenderRosterInputs {
@@ -1,3 +1,3 @@
1
- const w={degraded:"unverified",deaf:"unresponsive"};function f(t,a){return a?`${t}, ${a}`:t}function A(t){const{cubeName:a,drones:o,roles:i,resolvedSince:s,humanAgo:r}=t,c=new Map;for(const e of i)c.set(e.id,e);const n=[];if(n.push(`# Drones in cube: ${a}`),n.push(""),s&&(n.push(`_Liveness probe since ${s} (${r(s)}). \`awake\` = drone posted to the cube log after that point._`),n.push("")),!o.length)return n.push("_(no drones connected)_"),n.join(`
2
- `);for(const e of o){const h=c.get(e.role_id)?.name??"unknown",l=f(h,e.agent_kind),k=r(e.last_seen),p=e.backend?` \xB7 \`${e.backend}\``:"",u=e.wake_path&&e.wake_path!=="live"?` \xB7 \`wake-path:${w[e.wake_path]??e.wake_path}\``:"",_=e.wake_path_alert_class&&e.wake_path_alert_class!=="independent"?` \xB7 \`wake-path-class:${e.wake_path_alert_class}\``:"",$=typeof e.regen_count=="number"?` \xB7 \`regen-count:${e.regen_count}\``:"";if(s){const d=e.seen_since===!0?"`awake`":"`stale`";n.push(`- **${e.label}** (${l}) \u2014 last seen ${k} \xB7 ${d}${$}${u}${_}${p}`)}else n.push(`- **${e.label}** (${l}) \u2014 last seen ${k}${$}${u}${_}${p}`)}return n.join(`
3
- `)}export{f as formatRoleAgentLabel,A as renderRoster};
1
+ const w={degraded:"unverified",deaf:"unresponsive"};function f(t,s){return s?`${t}, ${s}`:t}function m(t){const{cubeName:s,drones:o,roles:h,resolvedSince:a,humanAgo:r}=t,l=new Map;for(const e of h)l.set(e.id,e);const n=[];if(n.push(`# Drones in cube: ${s}`),n.push(""),a&&(n.push(`_Liveness probe since ${a} (${r(a)}). \`awake\` = drone posted to the cube log after that point._`),n.push("")),!o.length)return n.push("_(no drones connected)_"),n.join(`
2
+ `);for(const e of o){const k=l.get(e.role_id)?.name??"unknown",c=f(k,e.agent_kind),p=r(e.last_seen),u=e.model?` \xB7 \`${e.model}\``:"",_=e.wake_path&&e.wake_path!=="live"?` \xB7 \`wake-path:${w[e.wake_path]??e.wake_path}\``:"",$=e.wake_path_alert_class&&e.wake_path_alert_class!=="independent"?` \xB7 \`wake-path-class:${e.wake_path_alert_class}\``:"",i=typeof e.regen_count=="number"?` \xB7 \`regen-count:${e.regen_count}\``:"";if(a){const d=e.seen_since===!0?"`awake`":"`stale`";n.push(`- **${e.label}** (${c}) \u2014 last seen ${p} \xB7 ${d}${i}${_}${$}${u}`)}else n.push(`- **${e.label}** (${c}) \u2014 last seen ${p}${i}${_}${$}${u}`)}return n.join(`
3
+ `)}export{f as formatRoleAgentLabel,m as renderRoster};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "borgmcp",
3
- "version": "1.0.29",
3
+ "version": "1.0.30",
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",
@@ -1 +0,0 @@
1
- const b=/^(claude|ollama):[A-Za-z0-9._:\/-]+$/,k="http://localhost:11434";function h(n=process.env,t){const e=n.BORG_OLLAMA_BASE_URL?.trim()||t?.trim()||"";return e?(/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`).replace(/\/+$/,""):k}function _(n,t,e=process.env){if(!t||!t.backend)return{env:n,probe:null};const{kind:a}=f(t.backend),l=h(e,t.ollamaBaseUrl??void 0),{set:u,unset:c}=A(t.backend,l),s={...n,...u};for(const d of c)delete s[d];return{env:s,probe:a==="ollama"?{descriptor:t.backend,baseUrl:l}:null}}function f(n){const t=n.indexOf(":");if(t<0)throw new Error(`invalid backend descriptor: ${n} (expected <kind>:<model>)`);const e=n.substring(0,t),a=n.substring(t+1);if(e!=="claude"&&e!=="ollama")throw new Error(`invalid backend kind: ${e} (expected claude or ollama)`);return{kind:e,model:a}}function A(n,t=h()){if(!n)return{set:{},unset:[]};const{kind:e,model:a}=f(n);return e==="claude"?{set:{ANTHROPIC_MODEL:a},unset:[]}:{set:{ANTHROPIC_BASE_URL:t,ANTHROPIC_MODEL:a,ANTHROPIC_AUTH_TOKEN:"ollama"},unset:["ANTHROPIC_API_KEY"]}}function O(n,t){const e=n.toLowerCase(),l=e.slice(e.lastIndexOf("/")+1).includes(":")?e:`${e}:latest`;return t.some(u=>{const c=u.toLowerCase();return c===l||c===e})}async function L(n,t,e=h()){if(!n)return{ok:!0};const{kind:a,model:l}=f(n);if(a==="claude")return{ok:!0};const c=e.includes("localhost")||e.includes("127.0.0.1")||e.includes("[::1]")?"start it (ollama serve)":"check the host is up and Ollama is listening there (OLLAMA_HOST=0.0.0.0)",s={ok:!1,message:`Ollama not reachable at ${e} \u2014 ${c}, or assimilate with a Claude backend.`},d=new AbortController,p=setTimeout(()=>d.abort(),3e3);try{const m=await t(`${e}/api/tags`,{signal:d.signal});if(!m.ok)return s;let r=null;try{const i=await m.json();i&&Array.isArray(i.models)&&(r=i.models.map(o=>(o?.name??o?.model??"").replace(/[\x00-\x1F\x7F]/g,"")).filter(o=>o.length>0))}catch{}if(r&&!O(l,r)){const i=r.length===0?"no models are pulled there":`available: ${r.slice(0,12).map(o=>o.length>64?`${o.slice(0,64)}\u2026`:o).join(", ")}${r.length>12?`, \u2026 (${r.length} total)`:""}`;return{ok:!1,message:`Ollama model '${l}' not found at ${e} (${i}) \u2014 pull it with: ollama pull ${l}`}}return{ok:!0}}catch{return s}finally{clearTimeout(p)}}export{b as BACKEND_DESCRIPTOR_REGEX,k as OLLAMA_DEFAULT_BASE_URL,_ as applyOllamaLaunchEnv,L as checkBackendReachable,O as ollamaModelMatches,f as parseBackend,A as resolveLaunchEnv,h as resolveOllamaBaseUrl};