borgmcp 1.0.16 → 1.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/claude.js +5 -5
- package/dist/cli-help.js +6 -4
- package/dist/console-prefix.d.ts +6 -1
- package/dist/console-prefix.js +1 -1
- package/dist/inbox-monitor.d.ts +44 -0
- package/dist/inbox-monitor.js +1 -1
- package/dist/index.js +13 -13
- package/dist/remote-client.d.ts +13 -0
- package/dist/remote-client.js +1 -1
- package/dist/setup-confirm.d.ts +73 -0
- package/dist/setup-confirm.js +2 -0
- package/dist/setup.js +20 -18
- package/dist/stream-status.d.ts +6 -0
- package/dist/stream-status.js +3 -3
- package/package.json +1 -1
package/dist/claude.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{spawn as S}from"child_process";import{randomUUID as y}from"node:crypto";import{basename as A}from"node:path";import{createInterface as P}from"node:readline/promises";import s from"chalk";import{findProjectRoot as T,getActiveCube as
|
|
2
|
+
import{spawn as S}from"child_process";import{randomUUID as y}from"node:crypto";import{basename as A}from"node:path";import{createInterface as P}from"node:readline/promises";import s from"chalk";import{findProjectRoot as T,getActiveCube as R,inboxPathForDrone as I,setCodexWakeTarget as E}from"./cubes.js";import{handleVersionFlag as D,getPackageVersion as g}from"./version.js";import{isHelpFlag as O,setupHelpText as F,topLevelHelpText as N}from"./cli-help.js";import{runSpawn as H}from"./spawn.js";import{parseSyncArgs as M,runSync as B}from"./sync.js";import{parseAssimilateArgs as G}from"./parse-assimilate-args.js";import{runAssimilate as L}from"./assimilate-cmd.js";import{buildDefaultAssimilateDeps as _}from"./assimilate-deps.js";import{setTerminalTitle as W}from"./terminal-title.js";import{initConsolePrefix as U,consolePrefix as r}from"./console-prefix.js";import{initDebugFromArgv as V}from"./debug.js";import{fetchLatestBorgmcpVersion as j,compareVersionsForStaleness as K}from"./stale-version-check.js";import{defaultCliChoiceDeps as Y,detectCliAvailability as v,installedCliNames as q,parseCliFlag as z,resolveCliChoice as X}from"./cli-platform.js";import{getRefreshToken as J,getIdToken as Q}from"./config.js";import{composeGetStarted as Z,shouldShowGetStarted as ee}from"./get-started.js";import{prepareCodexRemoteLaunch as re,withCodexCwdArg as oe,defaultCodexRemoteDeps as se}from"./codex-remote.js";import{findLoadedCodexThread as te}from"./codex-app-server.js";import{buildAgentKickoffPrompt as ie,recordCodexWakeTarget as ae,socketPathFromRemoteArgs as k}from"./codex-launch.js";import{codexBorgSessionConfigArgs as ne}from"./launch-gate.js";import{addCodexMcpServer as ce,addCodexSessionStartHook as le,addCodexUserPromptSubmitHook as de,addMcpServer as pe,addProjectSessionStartHook as me,addUserPromptSubmitHook as ue,isCodexMcpServerConfigured as fe,isMcpServerConfigured as ge,removeSessionStartHook as he}from"./config-utils.js";async function we(){V(process.argv),D(),await U();const n=(async()=>{if(!process.stderr.isTTY)return;const e=g(),a=await j();if(!a)return;const p=K(e,a);p.stale&&p.message&&process.stderr.write(`${r()}${p.message}
|
|
3
3
|
`)})();if((process.argv[2]==="--help"||process.argv[2]==="-h")&&(process.stdout.write(N(g())),process.exit(0)),process.argv[2]==="setup"){O(process.argv[3])&&(process.stdout.write(F(g())),process.exit(0)),await import("./setup.js");return}if(process.argv[2]==="assimilate"){const e=G(process.argv.slice(3));e.ok||(process.stderr.write(s.red(`${r()}\u25FC borg assimilate: ${e.error}
|
|
4
|
-
`)),process.exit(1));const a=_(),p=await L({role:e.role,flags:e.flags},a);process.exit(p)}if(process.argv[2]==="spawn"){const e=await H();process.exit(e)}if(process.argv[2]==="sync"){const e=M(process.argv.slice(3));e.ok||(process.stderr.write(s.red(`${r()}\u25FC borg sync: ${e.error}
|
|
5
|
-
`)),process.exit(1));const a=await B({},e.options);process.exit(a)}if(ee(await J()!==null,await Q()!==null)){const e=q(v()).length>0;process.stdout.write(Z(e)),process.exit(0)}const t=z(process.argv.slice(2));t.error&&(process.stderr.write(s.red(`${r()}\u25FC ${t.error}
|
|
6
|
-
`)),process.exit(1));const
|
|
4
|
+
`)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const a=_(),p=await L({role:e.role,flags:e.flags},a);process.exit(p)}if(process.argv[2]==="spawn"){const e=await H();process.exit(e)}if(process.argv[2]==="sync"){const e=M(process.argv.slice(3));e.ok||(process.stderr.write(s.red(`${r()}\u25FC borg sync: ${e.error}
|
|
5
|
+
`)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const a=await B({},e.options);process.exit(a)}if(ee(await J()!==null,await Q()!==null)){const e=q(v()).length>0;process.stdout.write(Z(e)),process.exit(0)}const t=z(process.argv.slice(2));t.error&&(process.stderr.write(s.red(`${r()}\u25FC ${t.error}
|
|
6
|
+
`)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const b=async e=>{const a=P({input:process.stdin,output:process.stdout});try{return await a.question(e)}finally{a.close()}},o=await X(t.cli,Y(b,()=>process.stdin.isTTY===!0));xe();const c=t.rest,i=await R();W(i?{label:i.droneLabel,cubeName:i.name}:null,A(process.cwd()));const $=i&&o==="claude"?`If you haven't yet, arm a persistent Monitor running the command \`borg-inbox-monitor ${I(i.cubeId,i.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([n,new Promise(e=>setTimeout(e,2e3))]);const h=o==="codex"?`borg-wake-${y()}`:null;let m,w=[],u={...process.env,BORG_SESSION:"1"},l=null,d=null;if(o==="codex"&&!c.includes("--remote")){console.error(`${r()}${s.gray("\u25FC Starting Codex remote-wake app-server\u2026")}`);const e=await re(se());e.warning?(console.error(`${r()}${s.yellow(`warning: ${e.warning}`)}`),m="\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."):m="Codex wake-path capability check passed: remote-control socket established for this session.",w=e.args,u={...process.env,...e.env,BORG_SESSION:"1"},l=k(e.args),d=e.server?.cleanup??null}else o==="codex"&&c.includes("--remote")&&(m="Codex wake-path capability check: using caller-provided --remote socket; if no wake arrives, run borg:regen manually when returning to the session.",l=k(c),l&&(u={...process.env,BORG_CODEX_REMOTE_WAKE:"1",BORG_SESSION:"1"}));const x=ie({cli:o,codexWakeNonce:h,monitorClause:$,codexWakePathClause:m});let f=[...c,x];o==="codex"&&(f=[...ne(),...w,...oe(f,process.cwd())]),console.error(`${r()}${s.blue(`\u25FC Launching ${o==="claude"?"Claude Code":"Codex"}\u2026`)}`);const C=S(o,f,{stdio:"inherit",shell:!1,env:u});o==="codex"&&i&&l&&ae({deps:{setCodexWakeTarget:E,findLoadedCodexThread:te},cubeId:i.cubeId,droneId:i.droneId,socketPath:l,passthroughArgs:c,previewNeedle:h??x.slice(0,120),cwd:process.cwd(),launchedAtSeconds:Math.floor(Date.now()/1e3)}),C.on("error",e=>{if(d)try{d()}catch{}e.code==="ENOENT"?(console.error(`${r()}${s.red(`
|
|
7
7
|
\u25FC Failed to launch ${o}`)}`),console.error(`${r()}${s.gray(`Make sure ${o} is installed.
|
|
8
8
|
`)}`)):console.error(`${r()}${s.red(`
|
|
9
9
|
\u25FC Failed to launch ${o}: ${e.message}
|
|
10
|
-
`)}`),process.exit(1)}),C.on("exit",e=>{if(d)try{d()}catch{}process.exit(e??0)})}function xe(){const n=v();if(n.claude)try{ge()||pe(),me(T(process.cwd())),he(),
|
|
10
|
+
`)}`),process.exit(1)}),C.on("exit",e=>{if(d)try{d()}catch{}process.exit(e??0)})}function xe(){const n=v();if(n.claude)try{ge()||pe(),me(T(process.cwd())),he(),ue()}catch(t){console.error(`${r()}${s.yellow(`warning: Claude Code integration check failed: ${t?.message??t}`)}`)}if(n.codex)try{fe()||ce(),le(),de()}catch(t){console.error(`${r()}${s.yellow(`warning: Codex integration check failed: ${t?.message??t}`)}`)}}we().catch(n=>{console.error(`${r()}${s.red(`
|
|
11
11
|
\u25FC Error: ${n.message}
|
|
12
12
|
`)}`),process.exit(1)});
|
package/dist/cli-help.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
function r(e){return e==="--help"||e==="-h"}function n(e){return`borgmcp ${e} \u2014
|
|
2
|
-
|
|
1
|
+
function r(e){return e==="--help"||e==="-h"}function n(e){return`borgmcp ${e} \u2014 run several AI coding agents on one project, together.
|
|
2
|
+
They coordinate through a shared log (a "cube"). For Claude Code & Codex.
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
Docs & quickstart: https://borgmcp.ai/get-started
|
|
5
|
+
|
|
6
|
+
Install Claude Code or Codex first. Type \`borg ...\` in your terminal;
|
|
7
|
+
type \`borg:...\` inside your agent session once you've joined a cube ("assimilate").
|
|
6
8
|
|
|
7
9
|
Usage:
|
|
8
10
|
borg Launch your agent CLI with cube context
|
package/dist/console-prefix.d.ts
CHANGED
|
@@ -16,7 +16,12 @@
|
|
|
16
16
|
* Format (matches the terminal-title.ts middle-dot convention so
|
|
17
17
|
* surfaces stay internally consistent):
|
|
18
18
|
* `[<drone-label> · <cube-name>]` (assimilated)
|
|
19
|
-
* `[
|
|
19
|
+
* `[borg · <repo-basename>]` (no cube cached)
|
|
20
|
+
*
|
|
21
|
+
* The not-yet-assimilated shape reads as neutral metadata ("this is
|
|
22
|
+
* borg, in project X"), NOT a fault the user must fix — and mirrors the
|
|
23
|
+
* unassimilated terminal-title shape (`borg · <repo-basename>`), so the
|
|
24
|
+
* title bar and the console prefix agree (gh#818 P1).
|
|
20
25
|
*/
|
|
21
26
|
/**
|
|
22
27
|
* Resolve the drone-self-identification prefix from cube state and
|
package/dist/console-prefix.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{basename as
|
|
1
|
+
import{basename as t}from"node:path";import i from"chalk";import{getActiveCube as c}from"./cubes.js";let r=null;function o(){return`[borg \xB7 ${t(process.cwd())}]`}async function a(){if(r!==null)return r;try{const e=await c();if(e?.droneLabel&&e?.name)return r=`[${e.droneLabel} \xB7 ${e.name}]`,r}catch{}return r=o(),r}function f(){return r!==null?r:o()}function n(){return i.gray(f())+" "}function x(...e){if(e.length===0){console.error(n());return}typeof e[0]=="string"?console.error(n()+e[0],...e.slice(1)):console.error(n(),...e)}function m(){r=null}export{m as _resetCachedPrefixForTests,x as cerr,n as consolePrefix,f as droneIdPrefix,a as initConsolePrefix};
|
package/dist/inbox-monitor.d.ts
CHANGED
|
@@ -49,6 +49,40 @@ export declare class RecentLineDeduper {
|
|
|
49
49
|
export declare function formatEventLine(inboxLine: string): string | null;
|
|
50
50
|
export declare function formatFreshEventLine(inboxLine: string, deduper: RecentLineDeduper): string | null;
|
|
51
51
|
export declare function seedDeduperFromInboxTail(inboxPath: string, deduper: RecentLineDeduper, maxLines?: number): void;
|
|
52
|
+
/** Holder-tracked stall state. `lastEmittedOffset` is stat-anchored. */
|
|
53
|
+
export interface TailStallState {
|
|
54
|
+
/** Inbox file size (bytes) as of the last tail delivery; seeded to EOF at arm. */
|
|
55
|
+
lastEmittedOffset: number;
|
|
56
|
+
/** Epoch ms when the CURRENT un-emitted-growth streak began; null = none. */
|
|
57
|
+
grewSince: number | null;
|
|
58
|
+
}
|
|
59
|
+
export type TailStallVerdict = {
|
|
60
|
+
kind: 'ok';
|
|
61
|
+
state: TailStallState;
|
|
62
|
+
} | {
|
|
63
|
+
kind: 'rotation';
|
|
64
|
+
state: TailStallState;
|
|
65
|
+
} | {
|
|
66
|
+
kind: 'respawn';
|
|
67
|
+
state: TailStallState;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* gh#822: PURE stall evaluator. Given the current inbox size + the holder's
|
|
71
|
+
* stat-anchored state, decide whether the tail is healthy, rotated, or stalled.
|
|
72
|
+
* False-reap-safe by construction (CR 131dcd78):
|
|
73
|
+
* - ROTATION (item 2): `inboxSize < lastEmittedOffset` ⇒ truncation/rotation —
|
|
74
|
+
* re-anchor offset to the NEW size + clear the streak; NEVER treated as
|
|
75
|
+
* negative growth, so the detector keeps working after the very rotation
|
|
76
|
+
* that triggers Subclass B.
|
|
77
|
+
* - QUIET cube: `inboxSize === lastEmittedOffset` ⇒ no un-emitted growth ⇒ ok
|
|
78
|
+
* (clears any streak). A silent cube can NEVER trip a respawn.
|
|
79
|
+
* - GREW-but-not-emitted: `inboxSize > lastEmittedOffset`. Only when that
|
|
80
|
+
* un-emitted growth PERSISTS continuously past `stallThresholdMs` ⇒ respawn.
|
|
81
|
+
* A brief/slow grow that the tail then delivers (a later tick re-anchors
|
|
82
|
+
* lastEmittedOffset → size==offset) clears the streak first. So "slow" never
|
|
83
|
+
* trips it; only SUSTAINED un-emitted growth does. Err toward not-respawning.
|
|
84
|
+
*/
|
|
85
|
+
export declare function evaluateInboxTailStall(inboxSize: number, state: TailStallState, nowMs: number, stallThresholdMs: number): TailStallVerdict;
|
|
52
86
|
export interface InboxLockDeps {
|
|
53
87
|
/**
|
|
54
88
|
* ATOMICALLY create the pidfile WITH `content` iff it does not exist. True =
|
|
@@ -70,6 +104,16 @@ export interface InboxLockDeps {
|
|
|
70
104
|
isAlive(pid: number): boolean;
|
|
71
105
|
}
|
|
72
106
|
export declare function pidfilePathFor(inboxPath: string): string;
|
|
107
|
+
/** gh#822: the holder-liveness heartbeat sidecar (mtime touched each tick). */
|
|
108
|
+
export declare function heartbeatPathFor(inboxPath: string): string;
|
|
109
|
+
export declare const HEARTBEAT_STALE_MS: number;
|
|
110
|
+
/**
|
|
111
|
+
* gh#822: `tail` args — ARM (`-n 0`, skip history, matches the prior shape) vs
|
|
112
|
+
* RECOVERY byte-seek (`-c +<N+1>`, re-read the un-emitted bytes from offset N
|
|
113
|
+
* FORWARD — CR build-gate item 3: NOT `-n 0`, which starts at the new EOF and
|
|
114
|
+
* skips exactly the bytes a stalled tail dropped).
|
|
115
|
+
*/
|
|
116
|
+
export declare function tailArgsFor(inboxPath: string, fromByteOffset: number | null): string[];
|
|
73
117
|
/**
|
|
74
118
|
* Try to become the SOLE monitor for this inbox. Returns true if we claimed the
|
|
75
119
|
* pidfile (caller proceeds to tail + must release it on exit); false if a LIVE
|
package/dist/inbox-monitor.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{spawn as
|
|
2
|
+
import{spawn as w}from"node:child_process";import{randomBytes as y}from"node:crypto";import{linkSync as T,readFileSync as p,realpathSync as v,statSync as k,unlinkSync as d,writeFileSync as I}from"node:fs";import{createInterface as O}from"node:readline";import{fileURLToPath as N}from"node:url";const L=/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\S*)\s+(\S+)\s+\(([^)]+)\):\s*(.*)$/,_=1024;class R{cap;seen=new Set;order=[];constructor(e=_){if(this.cap=e,!Number.isInteger(e)||e<1)throw new Error("cap must be a positive integer")}remember(e){if(this.seen.has(e))return!1;for(this.seen.add(e),this.order.push(e);this.order.length>this.cap;){const r=this.order.shift();r&&this.seen.delete(r)}return!0}}function b(t){const e=L.exec(t);if(!e)return null;const[,,r,o,i]=e,n=i.trim();return`${r} (${o}): ${n}`}function $(t,e){const r=b(t);return r===null?null:e.remember(t)?r:null}function D(t,e,r=512){if(!Number.isInteger(r)||r<1)throw new Error("maxLines must be a positive integer");let o;try{o=p(t,"utf-8")}catch(n){if(n?.code==="ENOENT")return;throw n}const i=o.split(/\r?\n/);i.at(-1)===""&&i.pop();for(const n of i.slice(-r))b(n)!==null&&e.remember(n)}function F(t,e,r,o){if(t<e.lastEmittedOffset)return{kind:"rotation",state:{lastEmittedOffset:t,grewSince:null}};if(t===e.lastEmittedOffset)return{kind:"ok",state:{lastEmittedOffset:e.lastEmittedOffset,grewSince:null}};const i=e.grewSince??r,n={lastEmittedOffset:e.lastEmittedOffset,grewSince:i};return r-i>=o?{kind:"respawn",state:n}:{kind:"ok",state:n}}function A(t){return`${t}.monitor.pid`}function C(t){return`${t}.monitor.heartbeat`}const h=3e4,M=5*h,J=5*h;function G(t,e){return e===null?["-F","-n","0",t]:["-F","-c",`+${e+1}`,t]}function E(t){try{return k(t).size}catch{return 0}}function P(t,e,r,o=3){const i=String(e);for(let n=0;n<o;n++){if(r.claim(t,i))return!0;const c=r.read(t);if(c===null)continue;const l=c.trim();if(l===""){r.removeIfContent(t,c);continue}const u=Number.parseInt(l,10);if(!Number.isNaN(u)&&r.isAlive(u))return!1;r.removeIfContent(t,c)}return!1}function H(){return{claim:(t,e)=>{const r=`${t}.tmp.${process.pid}.${y(6).toString("hex")}`;try{I(r,e,{mode:384});try{return T(r,t),!0}catch(o){if(o?.code==="EEXIST")return!1;throw o}}finally{try{d(r)}catch{}}},read:t=>{try{return p(t,"utf8")}catch{return null}},removeIfContent:(t,e)=>{try{p(t,"utf8")===e&&d(t)}catch{}},isAlive:t=>{try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}}}function K(){const t=process.argv[2];t||(console.error("borg-inbox-monitor: usage: borg-inbox-monitor <inbox-path>"),process.exit(2));const e=A(t),r=H();P(e,process.pid,r)||process.exit(0);const o=()=>r.removeIfContent(e,String(process.pid)),i=new R;D(t,i);let n={lastEmittedOffset:E(t),grewSince:null},c=!1,l=null;const u=a=>{const s=w("tail",G(t,a),{stdio:["ignore","pipe","inherit"]});l=s,s.stdout||(console.error("borg-inbox-monitor: tail subprocess has no stdout"),o(),process.exit(1)),O({input:s.stdout,crlfDelay:1/0}).on("line",f=>{const m=$(f,i);m!==null&&(console.log(m),n={lastEmittedOffset:E(t),grewSince:null})}),s.on("error",f=>{s===l&&(console.error(`borg-inbox-monitor: tail failed: ${f.message}`),o(),process.exit(1))}),s.on("exit",(f,m)=>{s===l&&(o(),c&&process.exit(0),m&&process.exit(0),process.exit(f??0))})};u(null);const S=C(t),x=setInterval(()=>{try{I(S,String(Date.now()),{mode:384})}catch{}const a=F(E(t),n,Date.now(),M);if(n=a.state,a.kind==="respawn"&&!c){const s=l;u(n.lastEmittedOffset);try{s?.kill("SIGKILL")}catch{}n={lastEmittedOffset:n.lastEmittedOffset,grewSince:null}}},h);x.unref();const g=a=>{if(c)return;c=!0,clearInterval(x);try{d(S)}catch{}o();const s=l;s&&!s.killed&&!s.kill(a)&&process.exit(0),setTimeout(()=>process.exit(0),1e3).unref()};process.once("SIGTERM",()=>g("SIGTERM")),process.once("SIGINT",()=>g("SIGINT"))}function q(t,e){try{return v(t)===N(e)}catch{return!1}}q(process.argv[1],import.meta.url)&&K();export{J as HEARTBEAT_STALE_MS,_ as RECENT_EMITTED_LINE_CAP,R as RecentLineDeduper,P as acquireInboxLock,F as evaluateInboxTailStall,b as formatEventLine,$ as formatFreshEventLine,C as heartbeatPathFor,q as isEntryInvocation,A as pidfilePathFor,D as seedDeduperFromInboxTail,G as tailArgsFor};
|
package/dist/index.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Server as V}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as K}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as z,ListToolsRequestSchema as G,ListPromptsRequestSchema as X,GetPromptRequestSchema as Y}from"@modelcontextprotocol/sdk/types.js";import{getCubeInfo as J,getRoleInfo as j,getRoster as Z,readLog as ee,appendLog as te,ackLogEntry as re,regen as O,listCubes as oe,createCube as ie,updateCube as T,deleteCube as ne,createRole as se,updateRole as ae,patchRoleSection as $,patchTaxonomyClass as P,deleteRole as ce,reassignDrone as le,evictDrone as de,getCube as w,checkSubscriptionStatus as pe,createBillingPortalSession as ue,createSubscription as me,syncRoles as he,applyTemplate as be,whoami as ge,roleRationale as ye,getValidToken as fe}from"./remote-client.js";import{startHealthBeatTick as we}from"./health-beat.js";import{getTemplate as S,listTemplateNames as U,resolveCubeDirectiveForCreate as _e,resolveCubeDirectiveForApply as ve,resolveMessageTaxonomyForCreate as xe}from"./templates.js";import{activeCubeWithFreshRegenIdentity as A,getActiveCube as f,setActiveCube as N,inboxPathForDrone as I}from"./cubes.js";import{addSessionStartHook as ke,addUserPromptSubmitHook as $e}from"./config-utils.js";import{humanAgo as L,formatLogEntryMarkdown as Se,formatRegenMarkdown as M,getDronePlaybook as Ue,nullTaxonomyTip as Ie,regenWakePathDroneLabel as qe}from"./regen-format.js";import{startLogStream as Ce,getStreamStatus as q}from"./log-stream.js";import{renderRoleList as Ee}from"./list-roles-render.js";import{getPackageVersion as _,getOnDiskVersion as Re,handleVersionFlag as De}from"./version.js";import{renderStreamStatus as je,checkInboxMonitorHealthy as C,formatWakePathPrefix as Oe,shouldShowWakePathWarning as Te}from"./stream-status.js";import{formatRoleAgentLabel as Pe,renderRoster as Ae}from"./roster-render.js";import{resolveDroneIdByLabel as Ne,isUuidShape as Le}from"./evict-drone.js";import{authRecoveryMessage as Me}from"./auth-recovery.js";import{classifyInSessionAssimilate as Be,reattachOnlyRefusal as Fe,reattachFailureMessage as He}from"./assimilate-guard.js";import{gateAllowsActivation as We,borgSessionToolNotice as Qe}from"./launch-gate.js";import{renderSyncRolesResult as Ve}from"./sync-roles-render.js";import{initConsolePrefix as Ke,consolePrefix as v}from"./console-prefix.js";import{isCodexRemoteWakeEnabled as E,resolveSessionAgentKind as ze,probeCodexBridgeArmed as Ge}from"./codex-app-wake.js";import{lifecycleSignalForMessage as Xe,recordLifecycleLog as B,shouldSuppressLifecycleLog as Ye}from"./lifecycle-log-guard.js";import{normalizeDirectLogRecipients as Je}from"./direct-log.js";import F from"open";import Ze from"os";function et(){try{const p=Ze.hostname();return p&&p.trim()?p.trim().slice(0,255):null}catch{return null}}async function H(p,x){return await be(p,x.name)}async function y(){const p=await f();if(!p)throw new Error("Not assimilated to a cube. Use borg:assimilate <cube-name> first.");return p}async function tt(){De();try{ke()}catch{}try{$e()}catch{}try{Ce()}catch{}try{we({getActiveCube:f,getStreamConnected:()=>q().connected,getInboxPath:m=>I(m.cubeId,m.droneId),checkMonitor:C,isCodexRemoteWake:E,probeBridgeArmed:m=>Ge({cubeId:m.cubeId,droneId:m.droneId}),resolveAgentKind:ze,resolveHostname:et,resolveVersion:_,getToken:fe,fetchImpl:globalThis.fetch.bind(globalThis)})}catch{}const p=new V({name:"borg-mcp-client",version:_()},{capabilities:{tools:{},prompts:{}}});p.setRequestHandler(G,async()=>({tools:[{name:"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:"subscription_status",description:"Check subscription status",inputSchema:{type:"object",properties:{},required:[]}},{name:"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: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."}},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."}},required:["role_id"]}},{name:"borg:patch-role-section",description:"Surgically patch ONE named section of a role's detailed_description, leaving the rest of the field byte-identical. Sections are delimited by plain-label lines (e.g. `Workflow:`, `Project conventions:`) \u2014 NOT markdown headings; text before the first label is the preamble. Use this instead of borg:update-role when changing a single section so you don't have to resend (and risk clobbering) the whole playbook. action=replace overwrites a section's body; action=insert adds a new section (optionally after a named one, else appended); action=delete removes a section.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to patch."},action:{type:"string",enum:["replace","insert","delete"],description:"replace / insert / delete a single section."},heading:{type:"string",description:'The section label WITHOUT the trailing colon (e.g. "Workflow"). Matched case-insensitively.'},body:{type:"string",description:"New text BELOW the heading (for replace/insert). Omit for delete."},after:{type:"string",description:"For insert only: place the new section after the section with this heading. Omit/null to append at the end."}},required:["role_id","action","heading"]}},{name:"borg:delete-role",description:"Delete a role. Refuses if any drone is still assigned \u2014 reassign or evict those drones from the dashboard first.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to delete."}},required:["role_id"]}},{name:"borg:reassign-drone",description:"Reassign a drone to a different role in the same cube. Coordinator-shaped: the cube's Coordinator drone is the one expected to call this when dispatching new drones to specific work. Server refuses if you try to assign to the Coordinator role when another drone already holds it (evict or reassign that drone first).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to reassign."},role_id:{type:"string",description:"UUID of the target role. Must belong to the same cube as the drone."}},required:["drone_id","role_id"]}},{name:"borg:evict-drone",description:"Evict (soft-delete) a drone from its cube. Coordinator-shaped: the cube's Coordinator/Queen seat calls this to remove a dead, stuck, or surplus drone \u2014 it drops out of the roster and frees its slot (incl. a held Coordinator/Queen-class seat), while its activity-log history is preserved with anonymized attribution. Owner-scoped: you can only evict drones in cubes you own. Identify the drone EITHER by drone_id (UUID) OR by label + cube_id (the label as it appears in the roster/regen).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to evict. Provide this OR (label + cube_id)."},label:{type:"string",description:'Drone label to evict, e.g. "two-of-seventeen-builder". Requires cube_id. Ignored when drone_id is given.'},cube_id:{type:"string",description:"UUID of the cube the labelled drone belongs to. Required when evicting by label."}}}},{name:"borg:list-drones",description:"List every drone in a cube (owner-scoped). Returns id, label, role_id, agent_kind, last_seen, and wake_path_alert_class for each \u2014 gives the Coordinator a roster they can act on with borg:reassign-drone.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose drones to list."}},required:["cube_id"]}},{name:"borg:list-roles",description:"List every role in a cube (owner-scoped). Returns id, name, short_description, is_default, is_human_seat, can_broadcast, receives_all_direct, and role_class for each \u2014 gives Coordinator-class drones the role UUIDs they need for borg:reassign-drone (e.g. to promote a drone to the Queen role). Closes the gh#153 Queen-role-promotion UX gap (Coordinator drones previously had no way to discover role IDs without operator help).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose roles to list."}},required:["cube_id"]}},{name:"borg:list-templates",description:"List available cube templates that can be applied via borg:apply-template or passed to borg:create-cube.",inputSchema:{type:"object",properties:{}}},{name:"borg:apply-template",description:"Apply a named template to an existing cube, NON-CLOBBERINGLY. Roles are merged by name: new roles are created; existing template-named roles get template sections/classes the cube LACKS auto-applied, but EVOLVED (conflicting) text is preserved, never overwritten. Use this to retrofit an existing cube with a richer role set (e.g. add Coordinator/Reviewer/UX Expert). To review + selectively accept conflicting fragments, use borg:sync-roles (which surfaces each conflict + takes per-fragment accept decisions).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to apply the template to."},template_name:{type:"string",description:"Template to apply (see borg:list-templates)."}},required:["cube_id","template_name"]}},{name:"borg:sync-roles",description:"Non-clobbering sync of an existing cube's roles + message_taxonomy against the current built-in template. The dry-run (default) classifies each FRAGMENT (role-text section, short_description, role flags, or taxonomy class) as ADD (the cube lacks it \u2014 safe auto-apply), UNCHANGED, or CONFLICT (the cube has EVOLVED text that differs from the template). On apply, ADDs auto-apply; CONFLICTs are applied ONLY when you explicitly accept them via `decisions` (keyed on the stable fragment key shown in the dry-run, e.g. `role:Builder:section:Workflow`). Unspecified conflicts default to KEEP (reject) \u2014 your cube's evolved coordination text is NEVER silently overwritten. Custom roles (names not in the template) are never touched.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to sync."},template_name:{type:"string",description:"Template to sync against (default: software-dev)."},apply:{type:"boolean",description:"If true, commit (auto-apply ADDs + accepted conflicts). If false (default), dry-run only \u2014 classify + surface conflicts."},decisions:{type:"object",description:'Per-conflict accept/reject map, keyed on the fragment key from the dry-run (e.g. {"role:Builder:section:Workflow":"accept"}). Unspecified conflicts default to "reject" (keep the cube version).',additionalProperties:{type:"string",enum:["accept","reject"]}}},required:["cube_id"]}}]})),p.setRequestHandler(z,async m=>{const{name:g,arguments:r}=m.params;if(!We(`tool ${g}`))return{content:[{type:"text",text:Qe(g)}],isError:!0};try{switch(g){case"borg:regen":{const e=await f();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=A(e,o);s!==e&&await N(s);const n=q(),a=I(s.cubeId,s.droneId),c=E()?!0:C(a),d=Te(n,c)?Oe({inboxPath:a,droneLabel:qe(o,s.droneLabel),cubeName:s.name}):"";let u="";try{const h=_(),l=Re();if(h!=="unknown"&&l!=="unknown"&&l!==h){const[b,R,W]=h.split(".").map(Number),[k,D,Q]=l.split(".").map(Number);(k>b||k===b&&D>R||k===b&&D===R&&Q>W)&&(u=`## \u{1F504} borgmcp ${l} installed \u2014 run /mcp and reconnect (or restart Claude Code) to apply. Currently running ${h}.
|
|
2
|
+
import{Server as V}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as K}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 w,checkSubscriptionStatus as ue,createBillingPortalSession as me,createSubscription as he,syncRoles as be,applyTemplate as ge,whoami as ye,roleRationale as fe,getValidToken as we}from"./remote-client.js";import{startHealthBeatTick as _e}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 P,getActiveCube as y,setActiveCube as N,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 _,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 Pe,renderRoster as Ne}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 Qe,borgSessionToolNotice as Ve}from"./launch-gate.js";import{renderSyncRolesResult as Ke}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{_e({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:_,getToken:we,fetchImpl:globalThis.fetch.bind(globalThis)})}catch{}const p=new V({name:"borg-mcp-client",version:_()},{capabilities:{tools:{},prompts:{}}});p.setRequestHandler(z,async()=>({tools:[{name:"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:"subscription_status",description:"Check subscription status",inputSchema:{type:"object",properties:{},required:[]}},{name:"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."}},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."}},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(!Qe(`tool ${g}`))return{content:[{type:"text",text:Ve(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=P(e,o);s!==e&&await N(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=_(),l=De();if(h!=="unknown"&&l!=="unknown"&&l!==h){const[b,R,H]=h.split(".").map(Number),[k,D,Q]=l.split(".").map(Number);(k>b||k===b&&D>R||k===b&&D===R&&Q>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"subscribe":return{content:[{type:"text",text:`Complete your subscription at: ${await
|
|
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 ${_()}`}]};case"borg:whoami":{const e=await
|
|
6
|
-
`)}]}}case"borg:role":{const e=await
|
|
7
|
-
`)}]}}case"borg:role-rationale":{const e=await
|
|
8
|
-
`)}]}}case"borg:roster":{const e=await
|
|
4
|
+
`)}}catch{}return{content:[{type:"text",text:u+d+M(o,{mode:i})}]}}case"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"subscription_status":{const e=await ue();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}case"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=P(t,o);return s!==t&&await N(s),{content:[{type:"text",text:[`# Re-attached to cube: ${s.name}`,"",`**Drone label:** ${s.droneLabel}`,"**Seat:** existing identity reused \u2014 no new drone minted (gh#780)","",""].join(`
|
|
5
|
+
`)+M(o,{mode:"full"})}]}}catch(o){const s=He(o??{});if(!s)throw o;return{content:[{type:"text",text:s}],isError:!0}}}case"borg:version":return{content:[{type:"text",text:`borgmcp ${_()}`}]};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
|
+
`)}]}}case"borg:role":{const e=await f(),{role:t}=await j(e.sessionToken,e.apiUrl);return{content:[{type:"text",text:[`# Your role: ${t.name}`,"",t.detailed_description||"_(no detailed description set)_"].join(`
|
|
7
|
+
`)}]}}case"borg:role-rationale":{const e=await f(),t=typeof r?.role=="string"?r.role:"",i=typeof r?.section=="string"?r.section:"",o=await fe(e.sessionToken,e.apiUrl,t,i);return{content:[{type:"text",text:[`# Role rationale: ${o.role} \u2014 ${o.section}`,"",o.body||"_(empty)_"].join(`
|
|
8
|
+
`)}]}}case"borg:roster":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,{drones:i,roles:o,since:s}=await Z(e.sessionToken,e.apiUrl,t);return{content:[{type:"text",text:Ne({cubeName:e.name,drones:i,roles:o,resolvedSince:s??null,humanAgo:L})}]}}case"borg:stream-status":{const e=q(),t=await y(),i=t?I(t.cubeId,t.droneId):null,o=t?C()?!0:E(i):null;let s="";e.runLoopHealth==="silent-inert"&&(s=`## \u26A0 SSE stream loop silent-inert \u2014 run /mcp and reconnect to restart
|
|
9
9
|
|
|
10
10
|
The log-stream consumer started but never connected. This drone will not receive real-time cube events.
|
|
11
11
|
|
|
12
|
-
`);const n=
|
|
13
|
-
`)}]}}case"borg:log":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await
|
|
12
|
+
`);const n=Oe({status:e,inboxMonitorHealthy:o,inboxPath:i,droneLabel:t?.droneLabel??null,cubeName:t?.name??null,humanAgo:L});return{content:[{type:"text",text:s+n}]}}case"borg:read-log":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,i=typeof r?.limit=="number"?r.limit:void 0,o=r?.unread_only===!0||r?.unread_only==="true",{entries:s,drones:n,roles:a,behind_by:c,has_more:d}=await ee(e.sessionToken,e.apiUrl,{since:t,limit:i,unreadOnly:o}),u=new Map;for(const b of n)u.set(b.id,b);const h=new Map;for(const b of a)h.set(b.id,b);const l=[];if(l.push(`# Activity log: ${e.name}`),l.push(""),!s.length)l.push("_(no entries)_");else for(const b of s)l.push(Se(b,u,h));return d===!0?(l.push(""),l.push("\u26A0 has_more: true \u2014 call `borg:read-log unread_only=true` again until has_more=false so you finish draining unread entries.")):typeof c=="number"&&c>0&&(l.push(""),l.push(`\u26A0 behind_by: ${c} more unread ${c===1?"entry":"entries"} addressed to you \u2014 call \`borg:read-log unread_only=true\` again until behind_by=0 so you don't skip messages.`)),{content:[{type:"text",text:l.join(`
|
|
13
|
+
`)}]}}case"borg:log":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg:assimilate <cube-name> first.");if(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
|
-
\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:ack":{const e=r?.entry_id;if(!e||typeof e!="string")throw new Error("entry_id is required");const t=await
|
|
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})
|
|
16
16
|
${(i.cube_directive||"_(no directive set)_").split(`
|
|
17
17
|
`)[0].slice(0,120)}`);return{content:[{type:"text",text:`Your cubes (${e.length}):
|
|
18
18
|
|
|
19
19
|
${t.join(`
|
|
20
20
|
|
|
21
|
-
`)}`}]}}case"borg:create-cube":{const e=r?.name,t=r?.cube_directive,i=r?.template;if(!e)throw new Error("name is required");if(t===void 0)throw new Error("cube_directive is required (pass empty string if none)");let o=null;if(i&&(o=
|
|
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}),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),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.");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 w(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 w(e);if(!t.length)return{content:[{type:"text",text:"No drones in this cube yet."}]};const o=new Map(i.map(n=>[n.id,n])),s=t.map(n=>{const a=o.get(n.role_id),c=Pe(a?.name??"?",n.agent_kind),d=n.wake_path_alert_class&&n.wake_path_alert_class!=="independent"?` \u2014 wake-path-class: ${n.wake_path_alert_class}`:"";return`- **${n.label}** (id: ${n.id}) \u2014 role: ${c} (${n.role_id}) \u2014 last seen ${n.last_seen}${d}`});return{content:[{type:"text",text:`Drones in cube ${e} (${t.length}):
|
|
22
22
|
|
|
23
23
|
${s.join(`
|
|
24
|
-
`)}`}]}}case"borg:list-roles":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{roles:t}=await w(e);return{content:[{type:"text",text:
|
|
24
|
+
`)}`}]}}case"borg:list-roles":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{roles:t}=await w(e);return{content:[{type:"text",text:Re(t,e)}]}}case"borg:list-templates":return{content:[{type:"text",text:`Available templates:
|
|
25
25
|
|
|
26
|
-
${
|
|
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
|
|
26
|
+
${S().map(i=>{const o=U(i);return`- **${i}**: ${o.description}`}).join(`
|
|
27
|
+
`)}`}]};case"borg:sync-roles":{const e=r?.cube_id,t=r?.template_name||"software-dev",i=r?.apply===!0,o=r?.decisions&&typeof r.decisions=="object"?r.decisions:void 0;if(!e)throw new Error("cube_id is required");const s=await be(e,t,i,o);return{content:[{type:"text",text:Ke(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 w(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:"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"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 open_dashboard tool."}}]};default:throw new Error(`Unknown prompt: ${g}`)}});const x=new K;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)});
|
package/dist/remote-client.d.ts
CHANGED
|
@@ -235,6 +235,19 @@ export declare function appendLog(sessionToken: string, apiUrl: string, message:
|
|
|
235
235
|
label: string;
|
|
236
236
|
}[];
|
|
237
237
|
}>;
|
|
238
|
+
/**
|
|
239
|
+
* gh#716 — submit a friction/bug report to the borgmcp dev team (borg:report-friction).
|
|
240
|
+
* WRITE-ONLY: the caller never reads reports back. The server scrubs secrets before
|
|
241
|
+
* persist and stamps reporter_user_id from the authenticated session (never client input).
|
|
242
|
+
* Drone-session authed (POST /api/drone/report). Opaque `{ ok: true }` response.
|
|
243
|
+
*/
|
|
244
|
+
export declare function submitReport(sessionToken: string, apiUrl: string, input: {
|
|
245
|
+
kind?: 'friction' | 'bug';
|
|
246
|
+
message: string;
|
|
247
|
+
metadata?: Record<string, string>;
|
|
248
|
+
}): Promise<{
|
|
249
|
+
ok: boolean;
|
|
250
|
+
}>;
|
|
238
251
|
/**
|
|
239
252
|
* List all cubes owned by the authenticated user. Owner-scoped via the
|
|
240
253
|
* Bearer token alone; no drone session needed.
|
package/dist/remote-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getIdToken as f,getRefreshToken as w,clearTokens as m}from"./config.js";import{refreshIdToken as
|
|
1
|
+
import{getIdToken as f,getRefreshToken as w,clearTokens as m}from"./config.js";import{refreshIdToken as j,RefreshTokenInvalidError as g,RefreshTransientError as x}from"./auth.js";import{consolePrefix as R}from"./console-prefix.js";import{debugLog as T}from"./debug.js";import{assertUuidShape as $}from"./evict-drone.js";const E=process.env.BORG_API_URL||"https://api.borgmcp.ai",k=3,C=6e4;let l=null;function b(e){return l||(l=j(e).finally(()=>{l=null}),l)}function P(e){if(e==null)return null;const n=e.trim();return/^\d+$/.test(n)?parseInt(n,10)*1e3:null}function O(e,n,t=C,o=()=>Math.random()*500){const s=e??1e3*(n+1);return Math.min(s,t)+o()}function I(e){const n=(t,o)=>`${t}${/[.:!?]$/.test(t)?"":":"} ${o}`;try{const t=JSON.parse(e);if(typeof t?.error=="string")return typeof t.details=="string"?n(t.error,t.details):t.error;if(t?.error&&typeof t.error=="object"){const o=t.error.message,s=t.error.details??t.details;if(typeof o=="string"&&typeof s=="string")return n(o,s);if(typeof o=="string")return o}if(typeof t?.message=="string"&&typeof t?.details=="string")return n(t.message,t.details);if(typeof t?.message=="string")return t.message}catch{}return e}async function A(e,n,t){const o=t.maxRetries??k;let s=e,a=0;for(;s.status===429&&a<o;){const p=O(P(s.headers.get("Retry-After")),a,t.capMs,t.jitter);t.log?.(`rate limited (429); retrying in ${Math.round(p)}ms (attempt ${a+1}/${o})`),await t.sleep(p),a++,s=await n()}return s}function L(e){return new Promise(n=>setTimeout(n,e))}async function J(){let e=await f();if(!e){const n=await w(),t=n!=null;if(n)try{await b(n),e=await f()}catch(o){if(o instanceof g&&await m(),o instanceof x)throw o}if(!e)throw new Error(t?"Authentication expired \u2014 your saved login has expired. Run: borg setup":"Authentication required \u2014 you are not signed in. Run: borg setup")}return e}async function G(){const e=await w();if(!e)return null;try{return await b(e),await f()}catch(n){if(n instanceof g&&await m(),n instanceof x)throw n;return null}}async function q(){if(await f())return"valid";const n=await w();if(!n)return"dead";try{return await b(n),await f()?"valid":"transient"}catch(t){return t instanceof g?(await m(),"dead"):"transient"}}async function r(e,n={}){let t=await J();const{droneSession:o,apiUrl:s,headers:a,...p}=n,_=s??E,y=(p.method??"GET").toUpperCase(),h=async c=>{const d={Authorization:`Bearer ${c}`,...a};o&&(d["X-Drone-Session"]=o),T(`\u2192 ${y} ${e}`);const u=await fetch(`${_}${e}`,{...p,headers:d});return T(`\u2190 ${u.status} ${y} ${e}`),u};let i=await h(t);if(i.status===401){const c=await G();c&&(t=c,i=await h(t))}if(i.status===401)throw new Error("Authentication required. Run: borg setup");if(i.status===429&&(i=await A(i,()=>h(t),{sleep:L,log:c=>console.error(`${R()}${c}`)})),!i.ok){const c=await i.text();T(`\u2717 ${i.status} ${y} ${e}: ${c}`);const d=I(c);if(i.status===429){const u=i.headers.get("Retry-After"),S=u?` (retry after ${u}s)`:"";throw new Error(`HTTP 429: rate limited${S}: ${d}`)}throw new Error(`HTTP ${i.status}: ${d}`)}return i}async function B(e,n,t,o){const s={hostname:t??null};return(o==="claude"||o==="codex")&&(s.agent_kind=o),typeof e=="string"?s.cube_name=e:(e.cube_id&&(s.cube_id=e.cube_id),e.cube_name&&(s.cube_name=e.cube_name),e.role_id&&(s.role_id=e.role_id),e.role_name&&(s.role_name=e.role_name),e.prior_drone_id&&(s.prior_drone_id=e.prior_drone_id)),await(await r("/api/assimilate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),apiUrl:n})).json()}async function N(e,n){return await(await r("/api/drone/cube",{method:"GET",droneSession:e,apiUrl:n})).json()}async function F(e,n){return await(await r("/api/drone/role",{method:"GET",droneSession:e,apiUrl:n})).json()}async function X(e,n){return await(await r("/api/drone/whoami",{method:"GET",droneSession:e,apiUrl:n})).json()}async function W(e,n,t){const o=t?`?since=${encodeURIComponent(t)}`:"";return await(await r(`/api/drone/roster${o}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function z(e,n,t={}){const o=new URLSearchParams;t.since&&o.set("since",t.since),t.limit!==void 0&&o.set("limit",String(t.limit)),t.unreadOnly&&o.set("unread_only","true");const s=o.toString();return await(await r(`/api/drone/log${s?`?${s}`:""}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function Q(e,n,t){await r(`/api/drone/log/${t}/ack`,{method:"POST",body:JSON.stringify({kind:"ack"}),droneSession:e,apiUrl:n})}async function V(e,n,t={}){const o=new URLSearchParams;t.since&&o.set("since",t.since);const s=o.toString();return await(await r(`/api/drone/regen${s?`?${s}`:""}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function Y(e,n,t,o){const s=new URLSearchParams({role:t,section:o});return await(await r(`/api/drone/role-rationale?${s.toString()}`,{method:"GET",droneSession:e,apiUrl:n})).json()}async function Z(e,n,t,o={}){const s={message:t,...o.visibility?{visibility:o.visibility}:{},...o.recipientDroneIds?{recipientDroneIds:o.recipientDroneIds}:{},...o.class?{class:o.class}:{},...o.to?{to:o.to}:{}};return await(await r("/api/drone/log",{method:"POST",headers:{"Content-Type":"application/json"},droneSession:e,apiUrl:n,body:JSON.stringify(s)})).json()}async function K(e,n,t){const o={kind:t.kind??"friction",message:t.message,...t.metadata?{metadata:t.metadata}:{}};return await(await r("/api/drone/report",{method:"POST",headers:{"Content-Type":"application/json"},droneSession:e,apiUrl:n,body:JSON.stringify(o)})).json()}async function ee(){return await(await r("/api/cubes",{method:"GET"})).json()}async function te(){return await(await r("/api/templates",{method:"GET"})).json()}async function ne(e,n,t){const o={cube_directive:n};e&&(o.name=e),t?.template&&(o.template=t.template),t&&Object.prototype.hasOwnProperty.call(t,"message_taxonomy")&&(o.message_taxonomy=t.message_taxonomy??null);const a=await(await r("/api/cubes",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();return a.cube?{...a.cube,roles:a.roles??[],drones:a.drones??[]}:a}async function oe(e,n){return await(await r(`/api/cubes/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function se(e,n){return await(await r(`/api/cubes/${e}/taxonomy-patch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function re(e){await r(`/api/cubes/${e}`,{method:"DELETE"})}async function ae(e,n){return await(await r(`/api/cubes/${e}/roles`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function ie(e,n){return await(await r(`/api/roles/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function ce(e,n){return await(await r(`/api/roles/${e}/section-patch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json()}async function pe(e){await r(`/api/roles/${e}`,{method:"DELETE"})}async function de(e,n){return $(e,"drone_id"),await(await r(`/api/drones/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({role_id:n})})).json()}async function ue(e){$(e,"drone_id"),await r(`/api/drones/${e}`,{method:"DELETE"})}async function fe(e){const t=await(await r(`/api/cubes/${e}`,{method:"GET"})).json();return t.cube?{...t.cube,roles:t.roles??[],drones:t.drones??[]}:t}async function le(e,n){return await(await r(`/api/cubes/${e}/apply-template`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({template_name:n})})).json()}async function ye(){return await(await r("/api/subscription/status",{method:"GET"})).json()}async function he(e,n="software-dev",t=!1,o){return await(await r(`/api/cubes/${e}/sync-roles`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({template_name:n,apply:t,...o?{decisions:o}:{}})})).json()}async function we(){const n=await(await r("/api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"}})).json();if(!n.checkout_url)throw new Error("No checkout URL in response");return n.checkout_url}async function me(){const n=await(await r("/api/subscription/portal",{method:"POST",headers:{"Content-Type":"application/json"}})).json();if(!n.portal_url)throw new Error(n.message||"No portal URL in response");return n.portal_url}export{E as API_URL,Q as ackLogEntry,Z as appendLog,le as applyTemplate,B as assimilate,ye as checkSubscriptionStatus,me as createBillingPortalSession,ne as createCube,ae as createRole,we as createSubscription,re as deleteCube,pe as deleteRole,ue as evictDrone,I as extractHttpErrorMessage,fe as getCube,N as getCubeInfo,F as getRoleInfo,W as getRoster,J as getValidToken,ee as listCubes,te as listTemplates,P as parseRetryAfterMs,ce as patchRoleSection,se as patchTaxonomyClass,q as probeSession,O as rateLimitWaitMs,z as readLog,de as reassignDrone,V as regen,A as retryOn429,Y as roleRationale,K as submitReport,he as syncRoles,oe as updateCube,ie as updateRole,X as whoami};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* gh#818 P3 — disclose + confirm the `borg setup` global-config mutation.
|
|
3
|
+
*
|
|
4
|
+
* Step-1 of the setup wizard writes the user's GLOBAL agent config
|
|
5
|
+
* (registers the borg MCP server + hooks). Before gh#818 this happened
|
|
6
|
+
* silently on first run. This module adds informed-consent disclosure:
|
|
7
|
+
* it lists WHICH files will be written (well-known `os.homedir()` paths)
|
|
8
|
+
* and asks to continue before the first mutation.
|
|
9
|
+
*
|
|
10
|
+
* Pure / dep-injected (mirrors `resolveCliChoice` + `setup-action.ts`) so
|
|
11
|
+
* the decision is unit-testable without spawning a prompt or touching argv.
|
|
12
|
+
*
|
|
13
|
+
* SECURITY (SR-light, gh#818 221c43df): the disclosure lists file PATHS +
|
|
14
|
+
* at most the PUBLIC `BORG_API_URL` — there is NO token/secret in the
|
|
15
|
+
* written config to echo. Tokens live in the AES-256-GCM keychain, and
|
|
16
|
+
* Step-1 runs BEFORE OAuth, so at mutation time no token even exists.
|
|
17
|
+
*/
|
|
18
|
+
export interface ConfigMutationTarget {
|
|
19
|
+
/** Human-readable config file path (tilde form). */
|
|
20
|
+
file: string;
|
|
21
|
+
/** What is added to it. */
|
|
22
|
+
change: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The set of global config files Step-1 writes, scoped to the detected
|
|
26
|
+
* agent CLIs. Paths mirror `config-utils.ts`:
|
|
27
|
+
* Claude Code: ~/.claude.json (MCP server) + ~/.claude/settings.json (hook)
|
|
28
|
+
* Codex: ~/.codex/config.toml (MCP server) + ~/.codex/hooks.json (hooks)
|
|
29
|
+
*/
|
|
30
|
+
export declare function configMutationTargets(deps: {
|
|
31
|
+
claude: boolean;
|
|
32
|
+
codex: boolean;
|
|
33
|
+
}): ConfigMutationTarget[];
|
|
34
|
+
/**
|
|
35
|
+
* Disclosure text: the files Step-1 will write + an undo note. Pure so SR
|
|
36
|
+
* can pin "lists paths only, no secret". Lists the public `BORG_API_URL`
|
|
37
|
+
* only by reference (the MCP-server registration env), never a credential.
|
|
38
|
+
*/
|
|
39
|
+
export declare function formatConfigMutationDisclosure(targets: ConfigMutationTarget[]): string;
|
|
40
|
+
export type ConfirmDecision = 'proceed' | 'abort';
|
|
41
|
+
export interface ConfirmConfigMutationDeps {
|
|
42
|
+
/** `process.stdin.isTTY === true`. */
|
|
43
|
+
isTTY: boolean;
|
|
44
|
+
/** `--yes` / `-y` present in argv. */
|
|
45
|
+
yes: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Injected interactive confirm — returns the user's yes(true)/no(false).
|
|
48
|
+
* Only invoked in the TTY-and-not-`--yes` path; NEVER called otherwise
|
|
49
|
+
* (so a non-TTY never reads stdin — see item 1 below).
|
|
50
|
+
*/
|
|
51
|
+
confirm: () => Promise<boolean>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Decide whether to proceed with the Step-1 config mutation.
|
|
55
|
+
*
|
|
56
|
+
* The six CR-binding build-gate items (gh#818, 3b3e85a5) live here:
|
|
57
|
+
* 1. (THE load-bearing headless no-regress) non-TTY → 'proceed' WITHOUT
|
|
58
|
+
* prompting. We return before touching `confirm`, so a non-TTY run
|
|
59
|
+
* (CI / pipe / headless) never reads stdin → no hang.
|
|
60
|
+
* 2. `--yes`/`-y` → 'proceed' without prompting (scripted-but-TTY +
|
|
61
|
+
* explicit non-interactive). No collision with --no-browser/--device.
|
|
62
|
+
* 3. TTY + interactive → ask; decline → 'abort' (the caller exits BEFORE
|
|
63
|
+
* any write).
|
|
64
|
+
* 6. This dep-injected shape IS the testable seam.
|
|
65
|
+
*/
|
|
66
|
+
export declare function confirmConfigMutation(deps: ConfirmConfigMutationDeps): Promise<ConfirmDecision>;
|
|
67
|
+
/**
|
|
68
|
+
* Scan argv for the `--yes` / `-y` bypass. Kept separate so the flag set
|
|
69
|
+
* is pinned in tests (item 2 — no collision with the existing
|
|
70
|
+
* --no-browser/--device scan in setup.ts).
|
|
71
|
+
*/
|
|
72
|
+
export declare function parseYesFlag(argv: string[]): boolean;
|
|
73
|
+
//# sourceMappingURL=setup-confirm.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function t(e){const o=[];return e.claude&&(o.push({file:"~/.claude.json",change:"registers the borg MCP server"}),o.push({file:"~/.claude/settings.json",change:"adds a UserPromptSubmit hook"})),e.codex&&(o.push({file:"~/.codex/config.toml",change:"registers the borg MCP server"}),o.push({file:"~/.codex/hooks.json",change:"adds SessionStart + UserPromptSubmit hooks"})),o}function n(e){const o=[];o.push("borg setup will register the borg MCP server in your agent config:");for(const r of e)o.push(` \u2022 ${r.file} (${r.change})`);return o.push('These changes are additive and reversible \u2014 remove the "borg" entries to undo.'),o.join(`
|
|
2
|
+
`)}async function s(e){return!e.isTTY||e.yes||await e.confirm()?"proceed":"abort"}function i(e){return e.includes("--yes")||e.includes("-y")}export{t as configMutationTargets,s as confirmConfigMutation,n as formatConfigMutationDisclosure,i as parseYesFlag};
|
package/dist/setup.js
CHANGED
|
@@ -1,31 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
\u25FC Borg MCP Setup Wizard \u25FC`));const
|
|
2
|
+
import u from"prompts";import e from"chalk";import p from"open";import d from"which";import{authenticateWithGoogle as f}from"./auth.js";import{checkSubscriptionStatus as i,createSubscription as y,probeSession as w}from"./remote-client.js";import{setupActionForSession as C}from"./setup-action.js";import{confirmConfigMutation as k,configMutationTargets as S,formatConfigMutationDisclosure as x,parseYesFlag as v}from"./setup-confirm.js";import{retrySubscriptionCheck as h}from"./subscription-retry.js";import{addMcpServer as F,addUserPromptSubmitHook as $,addCodexMcpServer as A,addCodexSessionStartHook as M,addCodexUserPromptSubmitHook as P,isMcpServerConfigured as R,isCodexMcpServerConfigured as T,removeSessionStartHook as U}from"./config-utils.js";import{handleVersionFlag as q}from"./version.js";import{initDebugFromArgv as D}from"./debug.js";async function I(){D(process.argv),q(),console.log(e.blue.bold(`
|
|
3
|
+
\u25FC Borg MCP Setup Wizard \u25FC`));const c=process.argv.includes("--no-browser")||process.argv.includes("--device");let t=null,n=null;try{t=d.sync("claude")}catch{}try{n=d.sync("codex")}catch{}t&&console.log(e.gray(`Found Claude CLI: ${t}`)),n&&console.log(e.gray(`Found Codex CLI: ${n}`)),(t||n)&&console.log(""),!t&&!n&&(console.error(e.red(`\u25FC No supported agent CLI found
|
|
4
4
|
`)),console.error(e.yellow("Please install Claude Code or Codex first:")),console.error(e.gray(" Claude Code: https://claude.ai/download")),console.error(e.gray(` Codex: https://developers.openai.com/codex
|
|
5
|
-
`)),process.exit(1)),console.log(e.blue("\u25FC Agent CLI Integration")),n)
|
|
5
|
+
`)),process.exit(1)),console.log(e.blue("\u25FC Agent CLI Integration"));const b=v(process.argv);if(console.log(x(S({claude:t!==null,codex:n!==null}))),await k({isTTY:process.stdin.isTTY===!0,yes:b,confirm:async()=>{const{proceed:o}=await u({type:"confirm",name:"proceed",message:"Continue with these changes?",initial:!0});return o===!0}})==="abort"&&(console.log(e.yellow(`
|
|
6
|
+
\u25FC Setup cancelled \u2014 no changes made.
|
|
7
|
+
`)),process.exit(0)),console.log(""),t)try{R()||F(),U(),$(),console.log(e.green("\u25FC borg configured for Claude Code"))}catch(o){console.error(e.red(`
|
|
6
8
|
\u25FC Failed to configure Claude Code: ${o.message}
|
|
7
|
-
`)),process.exit(1)}if(
|
|
9
|
+
`)),process.exit(1)}if(n)try{T()||A(),M(),P(),console.log(e.green("\u25FC borg configured for Codex"))}catch(o){console.error(e.red(`
|
|
8
10
|
\u25FC Failed to configure Codex: ${o.message}
|
|
9
|
-
`)),process.exit(1)}console.log(""),console.log(e.blue("\u25FC Google Authentication"));const g=
|
|
11
|
+
`)),process.exit(1)}console.log(""),console.log(e.blue("\u25FC Google Authentication"));const g=C(await w());if(g==="skip")console.log(e.green(`\u25FC Already signed in
|
|
10
12
|
`));else if(g==="retry")console.error(e.yellow(`
|
|
11
|
-
\u25FC Could not reach Google to verify your session (network issue).`)),console.error(e.yellow("Re-run `borg setup` when your connection is back.\n")),process.exit(1);else try{await
|
|
13
|
+
\u25FC Could not reach Google to verify your session (network issue).`)),console.error(e.yellow("Re-run `borg setup` when your connection is back.\n")),process.exit(1);else try{await f(c?{noBrowser:!0}:void 0)}catch(o){console.error(e.red(`
|
|
12
14
|
\u25FC Authentication failed: ${o.message}
|
|
13
|
-
`)),console.error(e.yellow("Re-run `borg setup` to try again.\n")),process.exit(1)}console.log(e.blue("\u25FC Subscription Check"));let s;try{s=await
|
|
15
|
+
`)),console.error(e.yellow("Re-run `borg setup` to try again.\n")),process.exit(1)}console.log(e.blue("\u25FC Subscription Check"));let s;try{s=await i()}catch(o){console.error(e.yellow(`
|
|
14
16
|
\u25FC Subscription check failed: ${o.message}`)),console.error(e.gray(`\u25FC Retrying before falling back to the Free tier...
|
|
15
|
-
`)),s={hasAccess:!1}}if(s=await
|
|
17
|
+
`)),s={hasAccess:!1}}if(s=await h(s,{check:i,sleep:o=>new Promise(r=>setTimeout(r,o)),onRetry:(o,r)=>console.log(e.gray(`\u25FC Checking subscription... (attempt ${o}/${r})`))}),s.hasAccess)if(console.log(e.green("\u25FC Active subscription found")),s.expiresAt){const o=new Date(s.expiresAt);console.log(e.gray(` Expires: ${o.toLocaleDateString()}
|
|
16
18
|
`))}else console.log("");else{console.log(e.green("\u25FC You're on the Free tier \u2014 permanent, no card needed: 1 cube + 3 agent sessions + 100 req/hr.")),console.log(e.gray(`\u25FC Start using borgmcp right now. Upgrade any time: $1/month per cube, each cube adds 8 pooled agent sessions + 1000 req/hr.
|
|
17
|
-
`));const{subscribeMethod:o}=await
|
|
19
|
+
`));const{subscribeMethod:o}=await u({type:"select",name:"subscribeMethod",message:"You're ready on the Free tier. Want to do more?",choices:[{title:"\u25FC Continue on the Free tier (recommended)",value:"skip",description:"Start now \u2014 1 cube, 3 agent sessions, 100 req/hr. No payment required."},{title:"\u25FC Upgrade to Cube tier \u2014 $1/month per cube",value:"web",description:"Each cube adds 8 pooled agent sessions + 1000 req/hr. Opens the subscribe page in your browser."},{title:"\u25FC Quick Stripe checkout",value:"stripe",description:"Fast upgrade checkout in the browser"},{title:"\u25FC I already subscribed \u2014 re-check",value:"recheck",description:"Re-check now \u2014 a just-completed subscription can take a moment to activate"}]});switch(o===void 0&&console.log(e.yellow(`
|
|
18
20
|
\u25FC No subscription option selected \u2014 continuing on the Free tier.
|
|
19
21
|
`)),o){case"web":console.log(e.blue(`
|
|
20
|
-
\u25FC Opening: https://borgmcp.ai/subscribe`));try{await
|
|
21
|
-
`)),await
|
|
22
|
+
\u25FC Opening: https://borgmcp.ai/subscribe`));try{await p("https://borgmcp.ai/subscribe"),console.log(e.gray(`\u25FC Waiting for subscription (checking every 5s for 2 min)...
|
|
23
|
+
`)),await m()}catch(r){console.error(e.yellow(`
|
|
22
24
|
\u25FC ${r.message}`)),console.log(e.green(`\u25FC Continuing on the Free tier. Upgrade any time from https://borgmcp.ai/subscribe.
|
|
23
|
-
`))}break;case"stripe":try{const r=await
|
|
24
|
-
\u25FC Opening Stripe: ${r}`)),await
|
|
25
|
-
`)),await
|
|
25
|
+
`))}break;case"stripe":try{const r=await y();console.log(e.blue(`
|
|
26
|
+
\u25FC Opening Stripe: ${r}`)),await p(r),console.log(e.gray(`\u25FC Waiting for subscription...
|
|
27
|
+
`)),await m()}catch(r){console.error(e.red(`
|
|
26
28
|
\u25FC Failed to create checkout: ${r.message}
|
|
27
29
|
`)),console.log(e.green(`\u25FC Continuing on the Free tier. Upgrade any time from https://borgmcp.ai/subscribe.
|
|
28
|
-
`))}break;case"recheck":try{let r;try{r=await
|
|
30
|
+
`))}break;case"recheck":try{let r;try{r=await i()}catch{r={hasAccess:!1}}r=await h(r,{check:i,sleep:a=>new Promise(l=>setTimeout(l,a)),onRetry:(a,l)=>console.log(e.gray(`\u25FC Re-checking subscription... (attempt ${a}/${l})`))}),r.hasAccess?console.log(e.green(`
|
|
29
31
|
\u25FC Subscription found!
|
|
30
32
|
`)):console.log(e.yellow(`
|
|
31
33
|
\u25FC No subscription found \u2014 continuing on the Free tier.
|
|
@@ -37,7 +39,7 @@ import b from"prompts";import e from"chalk";import u from"open";import d from"wh
|
|
|
37
39
|
`));break}}console.log(e.green.bold(`Setup complete!
|
|
38
40
|
`)),console.log(e.yellow(`\u{1F504} Restart Claude Code/Codex (or open a new session) for the changes to take effect.
|
|
39
41
|
`)),console.log(e.gray("\u25FC Next steps:")),console.log(e.gray('1. cd into your project, then run "borg assimilate" to join a cube')),console.log(e.gray(" (this creates/joins the cube and launches your agent)")),console.log(e.gray(`2. Manage cubes and subscription at https://borgmcp.ai/dashboard
|
|
40
|
-
`))}async function
|
|
41
|
-
`));return}}catch{}}throw new Error("Timeout - Run setup again after subscribing")}
|
|
42
|
-
\u25FC Setup failed: ${
|
|
42
|
+
`))}async function m(){for(let t=0;t<24;t++){await new Promise(n=>setTimeout(n,5e3));try{if((await i()).hasAccess){console.log(e.green(`\u25FC Subscription activated!
|
|
43
|
+
`));return}}catch{}}throw new Error("Timeout - Run setup again after subscribing")}I().catch(c=>{console.error(e.red(`
|
|
44
|
+
\u25FC Setup failed: ${c.message}
|
|
43
45
|
`)),process.exit(1)});
|
package/dist/stream-status.d.ts
CHANGED
|
@@ -43,6 +43,12 @@ import type { StreamStatus } from './log-stream.js';
|
|
|
43
43
|
* platforms gracefully).
|
|
44
44
|
*/
|
|
45
45
|
export declare function checkInboxMonitorHealthy(inboxPath: string | null): boolean | null;
|
|
46
|
+
/**
|
|
47
|
+
* gh#822: is the holder heartbeat sidecar present AND stale past the threshold?
|
|
48
|
+
* Absent (old monitor / just-armed) or fresh → NOT stale (false). Only a
|
|
49
|
+
* present-but-stale sidecar → true (the wedged-holder signal).
|
|
50
|
+
*/
|
|
51
|
+
export declare function isHeartbeatStale(inboxPath: string): boolean;
|
|
46
52
|
export interface RenderInputs {
|
|
47
53
|
status: StreamStatus;
|
|
48
54
|
/**
|
package/dist/stream-status.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{spawnSync as p}from"node:child_process";function
|
|
2
|
-
`)}function
|
|
3
|
-
`)}export{
|
|
1
|
+
import{spawnSync as p}from"node:child_process";import{statSync as m}from"node:fs";import{heartbeatPathFor as d,HEARTBEAT_STALE_MS as f}from"./inbox-monitor.js";function y(n){if(!n)return null;try{const t=p("pgrep",["-f",n],{encoding:"utf-8",timeout:2e3});return t.error?null:t.status===0&&t.stdout.trim().length>0?!b(n):t.status===1?!1:null}catch{return null}}function b(n){try{const t=m(d(n)).mtimeMs;return Date.now()-t>f}catch{return!1}}function _(n){const{status:t,inboxMonitorHealthy:s,inboxPath:r,droneLabel:l,cubeName:u,humanAgo:i}=n,h=t.reconnectAttempts===0&&t.lastWireActivityAt===null&&!t.connected,c=t.ownership?.state==="owned-by-other-process";let o;c?o="**Stream owned by another Borg MCP process.**":h?o="**Stream not started.**":t.connected?s===!1?o="**Stream connected (no inbox-Monitor \u2014 wake path broken).**":t.lastContentEventAt===null?o="**Stream connected, awaiting first content event.**":o=`**Stream connected, last content ${i(new Date(t.lastContentEventAt))}.**`:o=`**Stream disconnected (reconnect attempt ${t.reconnectAttempts}).**`;const e=[];if(e.push(o),e.push(""),e.push("# Log-stream status"),e.push(""),c?e.push("- **state**: _(stream owner is another local process)_"):h?e.push("- **state**: _(stream not started)_"):e.push(`- **connected**: ${t.connected}`),e.push(`- **last content event**: ${t.lastContentEventAt?`${t.lastContentEventAt} (${i(new Date(t.lastContentEventAt))})`:"_(none yet)_"}`),e.push(`- **last heartbeat at**: ${t.lastHeartbeatAt?`${t.lastHeartbeatAt} (${i(new Date(t.lastHeartbeatAt))})`:"_(none)_"}`),e.push(`- **last wire activity**: ${t.lastWireActivityAt?`${t.lastWireActivityAt} (${i(new Date(t.lastWireActivityAt))})`:"_(none)_"}`),e.push(`- **last persisted event id**: ${t.lastPersistedEventId??"_(none)_"}`),e.push(`- **reconnect attempts**: ${t.reconnectAttempts}`),c){const a=t.ownership;e.push(`- **stream owner pid**: ${a.pid??"_(unknown)_"}`),e.push(`- **stream owner cwd**: ${a.cwd??"_(unknown)_"}`),e.push(`- **stream owner heartbeat age**: ${typeof a.ageMs=="number"&&Number.isFinite(a.ageMs)?`${Math.max(0,Math.round(a.ageMs/1e3))}s`:"_(unknown)_"}`)}return t.connected&&s===!1&&(e.push("- **inbox-monitor**: _(no watcher detected \u2014 wake path broken)_"),r&&l&&u&&(e.push(""),e.push("## Real-time wake-up (do this now)"),e.push("No process is tailing this drone's inbox file \u2014 this session won't wake on real-time cube activity, only on its fallback timer, and will miss live coordination from other drones. Arm an inbox Monitor:"),e.push(""),e.push(`> Monitor command: \`tail -n 0 -F ${r}\` \u2014 persistent, 1h timeout, description "borg inbox for ${l} on cube ${u}".`))),e.join(`
|
|
2
|
+
`)}function k(n,t){return n.connected&&t===!1}function v(n){const{inboxPath:t,droneLabel:s,cubeName:r}=n;return!t||!s||!r?"":["## \u26A0 Wake path broken \u2014 arm Monitor NOW","","No process is tailing this drone's inbox file. SSE delivery is healthy (entries reach disk), but Claude Code has no event source to wake on. Until you arm a Monitor, this session only wakes on the /loop fallback heartbeat and will miss live coordination from other drones:","",`> Monitor command: \`tail -n 0 -F ${t}\` \u2014 persistent, 1h timeout, description "borg inbox for ${s} on cube ${r}".`,"","---",""].join(`
|
|
3
|
+
`)}export{y as checkInboxMonitorHealthy,v as formatWakePathPrefix,b as isHeartbeatStale,_ as renderStreamStatus,k as shouldShowWakePathWarning};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "borgmcp",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.18",
|
|
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",
|