borgmcp 1.0.26 → 1.0.28

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/README.md CHANGED
@@ -45,7 +45,7 @@ borg setup
45
45
 
46
46
  The wizard signs you in with Google, checks your subscription access, and registers Borg MCP with the supported agent CLIs installed on your machine.
47
47
 
48
- `borg ...` commands are terminal commands. `borg:...` commands are MCP tools
48
+ `borg ...` commands are terminal commands. `borg_...` commands are MCP tools
49
49
  you ask your agent to run inside Claude Code or Codex.
50
50
 
51
51
  If both Claude Code and Codex are installed, use `--cli` when launching or assimilating if you want to choose explicitly:
@@ -80,18 +80,18 @@ borg assimilate code-reviewer --cli codex
80
80
 
81
81
  ## Core MCP tools
82
82
 
83
- After assimilation, the agent session has `borg:` tools available:
83
+ After assimilation, the agent session has `borg_` tools available:
84
84
 
85
- - `borg:regen` - Refresh cube context, role instructions, roster, and recent log.
86
- - `borg:log` - Append to the shared activity log. Can broadcast or direct messages to drones/roles.
87
- - `borg:read-log` - Read recent log entries, optionally since an entry id or timestamp.
88
- - `borg:ack` - Acknowledge a routed log entry without adding noise to the activity log.
89
- - `borg:roster` - List drones and liveness markers in the cube.
90
- - `borg:stream-status` - Diagnose the SSE/inbox wake path.
91
- - `borg:cube`, `borg:role`, `borg:whoami` - Inspect current cube, role, and identity.
92
- - `borg:create-cube`, `borg:update-cube`, `borg:delete-cube` - Manage cubes.
93
- - `borg:create-role`, `borg:update-role`, `borg:reassign-drone` - Manage roles and drone assignments.
94
- - `borg:apply-template`, `borg:sync-roles`, `borg:patch-taxonomy-class` - Bootstrap and maintain role/message-taxonomy templates.
85
+ - `borg_regen` - Refresh cube context, role instructions, roster, and recent log.
86
+ - `borg_log` - Append to the shared activity log. Can broadcast or direct messages to drones/roles.
87
+ - `borg_read-log` - Read recent log entries, optionally since an entry id or timestamp.
88
+ - `borg_ack` - Acknowledge a routed log entry without adding noise to the activity log.
89
+ - `borg_roster` - List drones and liveness markers in the cube.
90
+ - `borg_stream-status` - Diagnose the SSE/inbox wake path.
91
+ - `borg_cube`, `borg_role`, `borg_whoami` - Inspect current cube, role, and identity.
92
+ - `borg_create-cube`, `borg_update-cube`, `borg_delete-cube` - Manage cubes.
93
+ - `borg_create-role`, `borg_update-role`, `borg_reassign-drone` - Manage roles and drone assignments.
94
+ - `borg_apply-template`, `borg_sync-roles`, `borg_patch-taxonomy-class` - Bootstrap and maintain role/message-taxonomy templates.
95
95
 
96
96
  ## Typical two-agent flow
97
97
 
@@ -122,9 +122,9 @@ After assimilation, the agent session has `borg:` tools available:
122
122
  4. In the agent session, verify the connection and coordinate through the log.
123
123
 
124
124
  ```text
125
- borg:whoami
126
- borg:roster
127
- borg:log "STARTING: review feat/login"
125
+ borg_whoami
126
+ borg_roster
127
+ borg_log "STARTING: review feat/login"
128
128
  ```
129
129
 
130
130
  ## Troubleshooting
@@ -160,17 +160,17 @@ Run assimilation from your project repo:
160
160
  borg assimilate
161
161
  ```
162
162
 
163
- Then ask the agent for `borg:whoami` and `borg:roster` to verify the connection.
163
+ Then ask the agent for `borg_whoami` and `borg_roster` to verify the connection.
164
164
 
165
165
  ### Wake path warning
166
166
 
167
- If `borg:regen` or `borg:stream-status` reports a broken wake path, follow the
167
+ If `borg_regen` or `borg_stream-status` reports a broken wake path, follow the
168
168
  CLI-specific recovery it prints:
169
169
 
170
170
  - Claude Code: arm the inbox monitor command. The monitor wakes the agent
171
171
  session when another drone posts to the cube.
172
172
  - Codex: check the remote-control socket status, relaunch with `borg --cli codex`
173
- or `borg assimilate --cli codex` if needed, and run `borg:regen` manually when
173
+ or `borg assimilate --cli codex` if needed, and run `borg_regen` manually when
174
174
  returning to the session if no wake arrived.
175
175
 
176
176
  ## Development
@@ -12,8 +12,8 @@ Pass --template <name>, --no-template, or --yes (defaults to starter).
12
12
  `),1;t="starter"}e.stderr(n?`Creating cube '${n}'\u2026
13
13
  `:`Creating your cube\u2026
14
14
  `),l=await e.createCube(i.apiUrl,i.token,t?{name:n??void 0,template:t}:{name:n??void 0}),N=!0}let f;if(r.role!==void 0){if(f=ee(l.roles,r.role),!f){const t=l.roles.map(m=>m.name).join(", "),o=be(r.role,l.roles.map(m=>m.name)),c=o?` Did you mean "${o}"?`:"";return e.stderr(`no role matching "${r.role}" in cube "${l.name}". Available: ${t}.${c}
15
- (Use --template <name> on first-drone setup or run \`borg:create-role\` from inside Claude.)
16
- `),1}}else if(f=te(l.roles,{isFirstDrone:N}),!f)return e.stderr(`cube "${l.name}" has no default or human-seat role; cannot infer a role. Either pass a role argument explicitly (e.g. \`borg assimilate builder\`) or run \`borg:create-role\` from inside Claude to set up roles.
15
+ (Use --template <name> on first-drone setup or run \`borg_create-role\` from inside Claude.)
16
+ `),1}}else if(f=te(l.roles,{isFirstDrone:N}),!f)return e.stderr(`cube "${l.name}" has no default or human-seat role; cannot infer a role. Either pass a role argument explicitly (e.g. \`borg assimilate builder\`) or run \`borg_create-role\` from inside Claude to set up roles.
17
17
  `),1;const p=await e.getActiveCube();let T;if(p&&r.flags.here)if(p.cubeId===l.id)T=p.droneId;else return e.stderr(`this directory already hosts an active drone; remove --here or run from a fresh worktree
18
18
  `),1;const x=r.flags.backend??f.default_backend??null;if(x){const t=await e.checkBackendReachable(x,e.fetch);if(!t.ok)return e.stderr(`${t.message}
19
19
  `),1}e.stderr(`Joining cube '${l.name}' as ${f.name}\u2026
@@ -34,8 +34,8 @@ Pass --template <name>, --no-template, or --yes (defaults to starter).
34
34
  `)}if(!d){e.runSync("git",["fetch","origin","--prune"],h);const t=F(S(h),S(a)),o=me(e.runSync,h,t,"origin/main");o.action==="adopted"?(e.stderr(`worktree: adopted branch ${t} at origin/main
35
35
  `),e.stderr(ge(h,t))):o.message&&e.stderr(`worktree sync: ${o.message}
36
36
  `)}await e.probeMcpReady()||e.stderr(`warning: borg-mcp readiness probe did not complete within the timeout; launching ${w} anyway \u2014 the kickoff prompt's ToolSearch fallback will recover if the MCP server takes longer to start.
37
- `);const z=e.getInboxPath(u.cube_id,u.drone_id),P=w==="codex"?`borg-wake-${X()}`:null,K=w==="claude"?`If you haven't yet, arm a persistent Monitor running the command \`borg-inbox-monitor ${z}\` so each event's task-notification title summarizes the new cube log entry (drone label, role, and first ~80 chars of the message body) \u2014 letting you triage events without reading the full body. `:"";let I,L=[],C,_=null,j=null;const W=de(x),D={...process.env,...W.set,BORG_SESSION:"1"};for(const t of W.unset)delete D[t];if(w==="codex"){const t=await e.prepareCodexRemoteLaunch();t.warning?(e.stderr(`warning: ${t.warning}
38
- `),I="\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."):I="Codex wake-path capability check passed: remote-control socket established for this session.",L=t.args,Object.keys(t.env).length>0&&Object.assign(D,t.env),_=ue(t.args),j=t.server?.cleanup??null}C=[le({cli:w,codexWakeNonce:P,monitorClause:K,codexWakePathClause:I})],w==="codex"&&(C=[...fe(),...L,...se(C,h)]);const J=e.exec(w,C,h,D);w==="codex"&&_&&P&&ce({deps:e,cubeId:u.cube_id,droneId:u.drone_id,socketPath:_,cwd:h,previewNeedle:P,launchedAtSeconds:Math.floor(Date.now()/1e3)});const V=await J;if(j)try{j()}catch{}return d&&v!==d&&e.stderr(`
37
+ `);const z=e.getInboxPath(u.cube_id,u.drone_id),_=w==="codex"?`borg-wake-${X()}`:null,K=w==="claude"?`If you haven't yet, arm a persistent Monitor running the command \`borg-inbox-monitor ${z}\` so each event's task-notification title summarizes the new cube log entry (drone label, role, and first ~80 chars of the message body) \u2014 letting you triage events without reading the full body. `:"";let P,L=[],C,I=null,j=null;const W=de(x),D={...process.env,...W.set,BORG_SESSION:"1"};for(const t of W.unset)delete D[t];if(w==="codex"){const t=await e.prepareCodexRemoteLaunch();t.warning?(e.stderr(`warning: ${t.warning}
38
+ `),P="\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."):P="Codex wake-path capability check passed: remote-control socket established for this session.",L=t.args,Object.keys(t.env).length>0&&Object.assign(D,t.env),I=ue(t.args),j=t.server?.cleanup??null}C=[le({cli:w,codexWakeNonce:_,monitorClause:K,codexWakePathClause:P})],w==="codex"&&(C=[...fe(),...L,...se(C,h)]);const J=e.exec(w,C,h,D);w==="codex"&&I&&_&&ce({deps:e,cubeId:u.cube_id,droneId:u.drone_id,socketPath:I,cwd:h,previewNeedle:_,launchedAtSeconds:Math.floor(Date.now()/1e3)});const V=await J;if(j)try{j()}catch{}return d&&v!==d&&e.stderr(`
39
39
  Agent exited. You were working in ${d}; your shell is back in ${v}.
40
40
  To return:
41
41
  cd ${ae(d)}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * gh#780 option (ii): in-session borg:assimilate is RE-ATTACH-ONLY
2
+ * gh#780 option (ii): in-session borg_assimilate is RE-ATTACH-ONLY
3
3
  * (Queen ruling 33a62d94).
4
4
  *
5
5
  * Root-cause context: the tool used to POST /api/assimilate, which ALWAYS
@@ -1,2 +1,2 @@
1
- import{authRecoveryMessage as a}from"./auth-recovery.js";function i(e){return e.trim().toLowerCase()}function s(e,t){return e?i(e.name)===i(t)?{kind:"reattach"}:{kind:"different-cube",activeCubeName:e.name}:{kind:"no-identity"}}function r(e,t){return e.kind==="no-identity"?`\u25FC This session has no drone seat for this worktree, and in-session borg:assimilate is re-attach-only (it never creates seats \u2014 gh#780). To create a seat for cube "${t}", run \`borg assimilate\` in a terminal \u2014 it spawns the worktree, persists the identity, and launches the agent in one step.`:`\u25FC This worktree is attached to cube "${e.activeCubeName}"; in-session borg:assimilate is re-attach-only and cannot switch to "${t}" (gh#780). To work in "${t}", run \`borg assimilate\` in a terminal from that project (or spawn a fresh worktree for it).`}function o(e){return a(e)?null:`\u25FC Re-attach failed \u2014 this worktree's saved seat is unreachable (likely evicted or its session was revoked). Server said: ${e.message??String(e)}
2
- Recover by running \`borg assimilate\` in a terminal to create a fresh seat; in-session borg:assimilate never re-mints (gh#780).`}export{s as classifyInSessionAssimilate,o as reattachFailureMessage,r as reattachOnlyRefusal};
1
+ import{authRecoveryMessage as a}from"./auth-recovery.js";function i(e){return e.trim().toLowerCase()}function s(e,t){return e?i(e.name)===i(t)?{kind:"reattach"}:{kind:"different-cube",activeCubeName:e.name}:{kind:"no-identity"}}function r(e,t){return e.kind==="no-identity"?`\u25FC This session has no drone seat for this worktree, and in-session borg_assimilate is re-attach-only (it never creates seats \u2014 gh#780). To create a seat for cube "${t}", run \`borg assimilate\` in a terminal \u2014 it spawns the worktree, persists the identity, and launches the agent in one step.`:`\u25FC This worktree is attached to cube "${e.activeCubeName}"; in-session borg_assimilate is re-attach-only and cannot switch to "${t}" (gh#780). To work in "${t}", run \`borg assimilate\` in a terminal from that project (or spawn a fresh worktree for it).`}function o(e){return a(e)?null:`\u25FC Re-attach failed \u2014 this worktree's saved seat is unreachable (likely evicted or its session was revoked). Server said: ${e.message??String(e)}
2
+ Recover by running \`borg assimilate\` in a terminal to create a fresh seat; in-session borg_assimilate never re-mints (gh#780).`}export{s as classifyInSessionAssimilate,o as reattachFailureMessage,r as reattachOnlyRefusal};
@@ -1,2 +1,2 @@
1
- const t="\x1B[32m",r="\x1B[0m";function c(e,o,n){return[`${n?`${t}\u2713${r}`:"\u2713"} Joined as \`${e}\` in cube \`${o}\`.`,"","Next: ask your agent to run the `borg:regen` tool to see your cube.","Add a teammate: run `borg assimilate <role>` in another terminal.","You're set up \u2014 your team can now see you in the cube.",""].join(`
1
+ const t="\x1B[32m",r="\x1B[0m";function c(e,o,n){return[`${n?`${t}\u2713${r}`:"\u2713"} Joined as \`${e}\` in cube \`${o}\`.`,"","Next: ask your agent to run the `borg_regen` tool to see your cube.","Add a teammate: run `borg assimilate <role>` in another terminal.","You're set up \u2014 your team can now see you in the cube.",""].join(`
2
2
  `)}export{c as renderAssimilationWelcome};
@@ -5,7 +5,7 @@
5
5
  * Root-cause context: the pre-gh#780 funnel answered every auth failure by
6
6
  * pointing the user at `borg assimilate` (the wrong remedy; gh#794 now also
7
7
  * differentiates a dead saved login from never-signed-in, both → `borg setup`).
8
- * An in-session agent's only reachable assimilate is the borg:assimilate MCP tool, which
8
+ * An in-session agent's only reachable assimilate is the borg_assimilate MCP tool, which
9
9
  * minted a brand-new drones row — so each auth blip spawned an orphan seat
10
10
  * (the gh#780 class). Neither failure mode is fixable by assimilating:
11
11
  * assimilate rides the same broken Bearer token.
@@ -1 +1 @@
1
- function t(n){const e=n.message??"";return n.name==="RefreshTransientError"||e.includes("Failed to refresh")?"\u25FC Transient auth-refresh failure (network/Google hiccup). Your session is intact and auth self-recovers \u2014 retry the tool call in a moment. Do NOT re-assimilate: borg:assimilate cannot fix auth and would mint a duplicate drone seat.":e.includes("Authentication required")||e.includes("Authentication expired")?"\u25FC Authentication expired \u2014 re-consent needed. Run `borg setup` in a terminal to sign in again. Do NOT re-assimilate: borg:assimilate cannot fix auth and would mint a duplicate drone seat.":null}export{t as authRecoveryMessage};
1
+ function t(n){const e=n.message??"";return n.name==="RefreshTransientError"||e.includes("Failed to refresh")?"\u25FC Transient auth-refresh failure (network/Google hiccup). Your session is intact and auth self-recovers \u2014 retry the tool call in a moment. Do NOT re-assimilate: borg_assimilate cannot fix auth and would mint a duplicate drone seat.":e.includes("Authentication required")||e.includes("Authentication expired")?"\u25FC Authentication expired \u2014 re-consent needed. Run `borg setup` in a terminal to sign in again. Do NOT re-assimilate: borg_assimilate cannot fix auth and would mint a duplicate drone seat.":null}export{t as authRecoveryMessage};
@@ -24,6 +24,17 @@ export declare function resolveLaunchEnv(descriptor: string | null, ollamaBaseUr
24
24
  set: Record<string, string>;
25
25
  unset: string[];
26
26
  };
27
+ /**
28
+ * Does `requested` match one of Ollama's pulled model names? Ollama defaults a
29
+ * tagless name to `:latest`, so `qwen3-coder-next` matches a pulled
30
+ * `qwen3-coder-next:latest`. Comparison is case-insensitive (Ollama lowercases
31
+ * model names). Tag presence is judged on the LAST path segment so a
32
+ * registry-host:port prefix colon (e.g. `localhost:5000/llama3`) is not mistaken
33
+ * for a tag. NOTE: digest refs (`name@sha256:…`) can't reach here — they're
34
+ * fenced out by BACKEND_DESCRIPTOR_REGEX (no `@`); widening that regex would
35
+ * require updating this matcher in lockstep.
36
+ */
37
+ export declare function ollamaModelMatches(requested: string, available: string[]): boolean;
27
38
  export declare function checkBackendReachable(descriptor: string | null, fetchImpl: typeof fetch, ollamaBaseUrl?: string): Promise<{
28
39
  ok: boolean;
29
40
  message?: string;
@@ -1 +1 @@
1
- const A=/^(claude|ollama):[A-Za-z0-9._:\/-]+$/,d="http://localhost:11434";function c(t=process.env){const n=t.BORG_OLLAMA_BASE_URL?.trim();return n?(/^[a-z][a-z0-9+.-]*:\/\//i.test(n)?n:`http://${n}`).replace(/\/+$/,""):d}function s(t){const n=t.indexOf(":");if(n<0)throw new Error(`invalid backend descriptor: ${t} (expected <kind>:<model>)`);const e=t.substring(0,n),o=t.substring(n+1);if(e!=="claude"&&e!=="ollama")throw new Error(`invalid backend kind: ${e} (expected claude or ollama)`);return{kind:e,model:o}}function _(t,n=c()){if(!t)return{set:{},unset:[]};const{kind:e,model:o}=s(t);return e==="claude"?{set:{ANTHROPIC_MODEL:o},unset:[]}:{set:{ANTHROPIC_BASE_URL:n,ANTHROPIC_MODEL:o,ANTHROPIC_AUTH_TOKEN:"ollama"},unset:["ANTHROPIC_API_KEY"]}}async function k(t,n,e=c()){if(!t)return{ok:!0};const{kind:o}=s(t);if(o==="claude")return{ok:!0};const i=e.includes("localhost")||e.includes("127.0.0.1")||e.includes("[::1]")?"start it (ollama serve)":"check the host is up and Ollama is listening there (OLLAMA_HOST=0.0.0.0)",r={ok:!1,message:`Ollama not reachable at ${e} \u2014 ${i}, or assimilate with a Claude backend.`},a=new AbortController,l=setTimeout(()=>a.abort(),3e3);try{return(await n(`${e}/api/tags`,{signal:a.signal})).ok?{ok:!0}:r}catch{return r}finally{clearTimeout(l)}}export{A as BACKEND_DESCRIPTOR_REGEX,d as OLLAMA_DEFAULT_BASE_URL,k as checkBackendReachable,s as parseBackend,_ as resolveLaunchEnv,c as resolveOllamaBaseUrl};
1
+ const p=/^(claude|ollama):[A-Za-z0-9._:\/-]+$/,O="http://localhost:11434";function m(t=process.env){const n=t.BORG_OLLAMA_BASE_URL?.trim();return n?(/^[a-z][a-z0-9+.-]*:\/\//i.test(n)?n:`http://${n}`).replace(/\/+$/,""):O}function f(t){const n=t.indexOf(":");if(n<0)throw new Error(`invalid backend descriptor: ${t} (expected <kind>:<model>)`);const e=t.substring(0,n),a=t.substring(n+1);if(e!=="claude"&&e!=="ollama")throw new Error(`invalid backend kind: ${e} (expected claude or ollama)`);return{kind:e,model:a}}function _(t,n=m()){if(!t)return{set:{},unset:[]};const{kind:e,model:a}=f(t);return e==="claude"?{set:{ANTHROPIC_MODEL:a},unset:[]}:{set:{ANTHROPIC_BASE_URL:n,ANTHROPIC_MODEL:a,ANTHROPIC_AUTH_TOKEN:"ollama"},unset:["ANTHROPIC_API_KEY"]}}function k(t,n){const e=t.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1).includes(":")?e:`${e}:latest`;return n.some(u=>{const c=u.toLowerCase();return c===r||c===e})}async function L(t,n,e=m()){if(!t)return{ok:!0};const{kind:a,model:r}=f(t);if(a==="claude")return{ok:!0};const c=e.includes("localhost")||e.includes("127.0.0.1")||e.includes("[::1]")?"start it (ollama serve)":"check the host is up and Ollama is listening there (OLLAMA_HOST=0.0.0.0)",d={ok:!1,message:`Ollama not reachable at ${e} \u2014 ${c}, or assimilate with a Claude backend.`},h=new AbortController,A=setTimeout(()=>h.abort(),3e3);try{const i=await n(`${e}/api/tags`,{signal:h.signal});if(!i.ok)return d;let l=null;try{const s=await i.json();s&&Array.isArray(s.models)&&(l=s.models.map(o=>(o?.name??o?.model??"").replace(/[\x00-\x1F\x7F]/g,"")).filter(o=>o.length>0))}catch{}if(l&&!k(r,l)){const s=l.length===0?"no models are pulled there":`available: ${l.slice(0,12).map(o=>o.length>64?`${o.slice(0,64)}\u2026`:o).join(", ")}${l.length>12?`, \u2026 (${l.length} total)`:""}`;return{ok:!1,message:`Ollama model '${r}' not found at ${e} (${s}) \u2014 pull it with: ollama pull ${r}`}}return{ok:!0}}catch{return d}finally{clearTimeout(A)}}export{p as BACKEND_DESCRIPTOR_REGEX,O as OLLAMA_DEFAULT_BASE_URL,L as checkBackendReachable,k as ollamaModelMatches,f as parseBackend,_ as resolveLaunchEnv,m as resolveOllamaBaseUrl};
package/dist/claude.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as R}from"child_process";import{randomUUID as D}from"node:crypto";import{basename as L}from"node:path";import{createInterface as E}from"node:readline/promises";import t from"chalk";import{findProjectRoot as M,getActiveCube as O,inboxPathForDrone as F,setCodexWakeTarget as H,pruneDeadCodexWakeTargets as N}from"./cubes.js";import{handleVersionFlag as B,getPackageVersion as h}from"./version.js";import{isHelpFlag as G,setupHelpText as W,topLevelHelpText as Y}from"./cli-help.js";import{runSpawn as _}from"./spawn.js";import{parseSyncArgs as U,runSync as V}from"./sync.js";import{parseAssimilateArgs as j}from"./parse-assimilate-args.js";import{runAssimilate as K}from"./assimilate-cmd.js";import{buildDefaultAssimilateDeps as q}from"./assimilate-deps.js";import{parseLaunchAllArgs as S}from"./parse-launch-all-args.js";import{runLaunchAll as y}from"./launch-all-cmd.js";import{buildDefaultLaunchAllDeps as w}from"./launch-all-deps.js";import{discoverDroneCandidates as z}from"./launch-all-discovery.js";import{runBareLaunchMenu as X,shouldShowLaunchMenu as J}from"./bare-launch-menu.js";import{setTerminalTitle as Q}from"./terminal-title.js";import{initConsolePrefix as Z,consolePrefix as s}from"./console-prefix.js";import{initDebugFromArgv as ee}from"./debug.js";import{fetchLatestBorgmcpVersion as re,compareVersionsForStaleness as oe}from"./stale-version-check.js";import{defaultCliChoiceDeps as se,detectCliAvailability as x,installedCliNames as T,parseCliFlag as te,resolveCliChoice as ie}from"./cli-platform.js";import{getRefreshToken as ae,getIdToken as ne}from"./config.js";import{composeGetStarted as ce,shouldShowGetStarted as le}from"./get-started.js";import{prepareCodexRemoteLaunch as de,withCodexCwdArg as pe,defaultCodexRemoteDeps as ue,checkCodexBridgeHealthy as me}from"./codex-remote.js";import{findLoadedCodexThread as fe}from"./codex-app-server.js";import{buildAgentKickoffPrompt as ge,recordCodexWakeTarget as he,socketPathFromRemoteArgs as A}from"./codex-launch.js";import{codexBorgSessionConfigArgs as we}from"./launch-gate.js";import{addCodexMcpServer as xe,addCodexSessionStartHook as Ce,addCodexUserPromptSubmitHook as ve,addMcpServer as ke,addProjectSessionStartHook as be,addUserPromptSubmitHook as $e,isCodexMcpServerConfigured as Se,isMcpServerConfigured as ye,removeSessionStartHook as Te}from"./config-utils.js";async function Ae(){ee(process.argv),B(),await Z();const c=(async()=>{if(!process.stderr.isTTY)return;const e=h(),o=await re();if(!o)return;const n=oe(e,o);n.stale&&n.message&&process.stderr.write(`${s()}${n.message}
3
- `)})();if((process.argv[2]==="--help"||process.argv[2]==="-h")&&(process.stdout.write(Y(h())),process.exit(0)),process.argv[2]==="setup"){G(process.argv[3])&&(process.stdout.write(W(h())),process.exit(0)),await import("./setup.js");return}if(process.argv[2]==="assimilate"){const e=j(process.argv.slice(3));e.ok||(process.stderr.write(t.red(`${s()}\u25FC borg assimilate: ${e.error}
4
- `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const o=q(),n=await K({role:e.role,flags:e.flags},o);process.exit(n)}if(process.argv[2]==="spawn"){const e=await _();process.exit(e)}if(process.argv[2]==="sync"){const e=U(process.argv.slice(3));e.ok||(process.stderr.write(t.red(`${s()}\u25FC borg sync: ${e.error}
5
- `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const o=await V({},e.options);process.exit(o)}if(process.argv[2]==="launch-all"){const e=S(process.argv.slice(3));e.ok||(process.stderr.write(t.red(`${s()}\u25FC borg launch-all: ${e.error}
6
- `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const o=w(),n=await y(e.args,o);process.exit(n)}if(le(await ae()!==null,await ne()!==null)){const e=T(x()).length>0;process.stdout.write(ce(e)),process.exit(0)}const a=te(process.argv.slice(2));a.error&&(process.stderr.write(t.red(`${s()}\u25FC ${a.error}
7
- `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const C=async e=>{const o=E({input:process.stdin,output:process.stdout});try{return await o.question(e)}finally{o.close()}};let r=await ie(a.cli,se(C,()=>process.stdin.isTTY===!0));Ie();const i=await O();if(J({extraArgs:process.argv.slice(2),stdinIsTTY:process.stdin.isTTY===!0,stdoutIsTTY:process.stdout.isTTY===!0})){const e=T(x()).find(u=>u!==r)??null;let o=!1;i&&(o=(await z({targetCubeId:i.cubeId},w())).length>0);const n=await X({defaultCli:r,otherInstalledCli:e,hasLaunchAllTargets:o},C);if(n.kind==="launch-all"){const u=S([]),P=u.ok?await y(u.args,w()):1;process.exit(P)}r=n.cli}const l=a.rest;Q(i?{label:i.droneLabel,cubeName:i.name}:null,L(process.cwd()));const I=i&&r==="claude"?`If you haven't yet, arm a persistent Monitor running the command \`borg-inbox-monitor ${F(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([c,new Promise(e=>setTimeout(e,2e3))]);const v=r==="codex"?`borg-wake-${D()}`:null;let m,k=[],f={...process.env,BORG_SESSION:"1"},d=null,p=null;if(r==="codex"&&!l.includes("--remote")){console.error(`${s()}${t.gray("\u25FC Starting Codex remote-wake app-server\u2026")}`);const e=await de(ue());e.warning?(console.error(`${s()}${t.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.",k=e.args,f={...process.env,...e.env,BORG_SESSION:"1"},d=A(e.args),p=e.server?.cleanup??null}else r==="codex"&&l.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.",d=A(l),d&&(f={...process.env,BORG_CODEX_REMOTE_WAKE:"1",BORG_SESSION:"1"}));const b=ge({cli:r,codexWakeNonce:v,monitorClause:I,codexWakePathClause:m});let g=[...l,b];r==="codex"&&(g=[...we(),...k,...pe(g,process.cwd())]),console.error(`${s()}${t.blue(`\u25FC Launching ${r==="claude"?"Claude Code":"Codex"}\u2026`)}`);const $=R(r,g,{stdio:"inherit",shell:!1,env:f});r==="codex"&&i&&d&&(he({deps:{setCodexWakeTarget:H,findLoadedCodexThread:fe},cubeId:i.cubeId,droneId:i.droneId,socketPath:d,passthroughArgs:l,previewNeedle:v??b.slice(0,120),cwd:process.cwd(),launchedAtSeconds:Math.floor(Date.now()/1e3)}),N(e=>me(e))),$.on("error",e=>{if(p)try{p()}catch{}e.code==="ENOENT"?(console.error(`${s()}${t.red(`
2
+ import{spawn as D}from"child_process";import{randomUUID as L}from"node:crypto";import{basename as E}from"node:path";import{createInterface as H}from"node:readline/promises";import t from"chalk";import{findProjectRoot as M,getActiveCube as O,inboxPathForDrone as F,setCodexWakeTarget as N,pruneDeadCodexWakeTargets as B}from"./cubes.js";import{handleVersionFlag as _,getPackageVersion as f}from"./version.js";import{isHelpFlag as S,setupHelpText as G,topLevelHelpText as W,assimilateHelpText as Y}from"./cli-help.js";import{runSpawn as U}from"./spawn.js";import{parseSyncArgs as V,runSync as j}from"./sync.js";import{parseAssimilateArgs as K}from"./parse-assimilate-args.js";import{runAssimilate as q}from"./assimilate-cmd.js";import{buildDefaultAssimilateDeps as z}from"./assimilate-deps.js";import{parseLaunchAllArgs as y}from"./parse-launch-all-args.js";import{runLaunchAll as T}from"./launch-all-cmd.js";import{buildDefaultLaunchAllDeps as w}from"./launch-all-deps.js";import{discoverDroneCandidates as X}from"./launch-all-discovery.js";import{runBareLaunchMenu as J,shouldShowLaunchMenu as Q}from"./bare-launch-menu.js";import{setTerminalTitle as Z}from"./terminal-title.js";import{initConsolePrefix as ee,consolePrefix as s}from"./console-prefix.js";import{initDebugFromArgv as re}from"./debug.js";import{fetchLatestBorgmcpVersion as oe,compareVersionsForStaleness as se}from"./stale-version-check.js";import{defaultCliChoiceDeps as te,detectCliAvailability as x,installedCliNames as A,parseCliFlag as ie,resolveCliChoice as ae}from"./cli-platform.js";import{getRefreshToken as ne,getIdToken as ce}from"./config.js";import{composeGetStarted as le,shouldShowGetStarted as de}from"./get-started.js";import{prepareCodexRemoteLaunch as pe,withCodexCwdArg as ue,defaultCodexRemoteDeps as me,checkCodexBridgeHealthy as fe}from"./codex-remote.js";import{findLoadedCodexThread as ge}from"./codex-app-server.js";import{buildAgentKickoffPrompt as he,recordCodexWakeTarget as we,socketPathFromRemoteArgs as I}from"./codex-launch.js";import{codexBorgSessionConfigArgs as xe}from"./launch-gate.js";import{addCodexMcpServer as Ce,addCodexSessionStartHook as ve,addCodexUserPromptSubmitHook as ke,addMcpServer as be,addProjectSessionStartHook as $e,addUserPromptSubmitHook as Se,isCodexMcpServerConfigured as ye,isMcpServerConfigured as Te,removeSessionStartHook as Ae}from"./config-utils.js";async function Ie(){re(process.argv),_(),await ee();const c=(async()=>{if(!process.stderr.isTTY)return;const e=f(),o=await oe();if(!o)return;const n=se(e,o);n.stale&&n.message&&process.stderr.write(`${s()}${n.message}
3
+ `)})();if((process.argv[2]==="--help"||process.argv[2]==="-h")&&(process.stdout.write(W(f())),process.exit(0)),process.argv[2]==="setup"){S(process.argv[3])&&(process.stdout.write(G(f())),process.exit(0)),await import("./setup.js");return}if(process.argv[2]==="assimilate"){process.argv.slice(3).some(S)&&(process.stdout.write(Y(f())),process.exit(0));const e=K(process.argv.slice(3));e.ok||(process.stderr.write(t.red(`${s()}\u25FC borg assimilate: ${e.error}
4
+ `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const o=z(),n=await q({role:e.role,flags:e.flags},o);process.exit(n)}if(process.argv[2]==="spawn"){const e=await U();process.exit(e)}if(process.argv[2]==="sync"){const e=V(process.argv.slice(3));e.ok||(process.stderr.write(t.red(`${s()}\u25FC borg sync: ${e.error}
5
+ `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const o=await j({},e.options);process.exit(o)}if(process.argv[2]==="launch-all"){const e=y(process.argv.slice(3));e.ok||(process.stderr.write(t.red(`${s()}\u25FC borg launch-all: ${e.error}
6
+ `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const o=w(),n=await T(e.args,o);process.exit(n)}if(de(await ne()!==null,await ce()!==null)){const e=A(x()).length>0;process.stdout.write(le(e)),process.exit(0)}const a=ie(process.argv.slice(2));a.error&&(process.stderr.write(t.red(`${s()}\u25FC ${a.error}
7
+ `)),process.stderr.write("Run `borg --help` for usage.\n"),process.exit(1));const C=async e=>{const o=H({input:process.stdin,output:process.stdout});try{return await o.question(e)}finally{o.close()}};let r=await ae(a.cli,te(C,()=>process.stdin.isTTY===!0));Pe();const i=await O();if(Q({extraArgs:process.argv.slice(2),stdinIsTTY:process.stdin.isTTY===!0,stdoutIsTTY:process.stdout.isTTY===!0})){const e=A(x()).find(u=>u!==r)??null;let o=!1;i&&(o=(await X({targetCubeId:i.cubeId},w())).length>0);const n=await J({defaultCli:r,otherInstalledCli:e,hasLaunchAllTargets:o},C);if(n.kind==="launch-all"){const u=y([]),R=u.ok?await T(u.args,w()):1;process.exit(R)}r=n.cli}const l=a.rest;Z(i?{label:i.droneLabel,cubeName:i.name}:null,E(process.cwd()));const P=i&&r==="claude"?`If you haven't yet, arm a persistent Monitor running the command \`borg-inbox-monitor ${F(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([c,new Promise(e=>setTimeout(e,2e3))]);const v=r==="codex"?`borg-wake-${L()}`:null;let m,k=[],g={...process.env,BORG_SESSION:"1"},d=null,p=null;if(r==="codex"&&!l.includes("--remote")){console.error(`${s()}${t.gray("\u25FC Starting Codex remote-wake app-server\u2026")}`);const e=await pe(me());e.warning?(console.error(`${s()}${t.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.",k=e.args,g={...process.env,...e.env,BORG_SESSION:"1"},d=I(e.args),p=e.server?.cleanup??null}else r==="codex"&&l.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.",d=I(l),d&&(g={...process.env,BORG_CODEX_REMOTE_WAKE:"1",BORG_SESSION:"1"}));const b=he({cli:r,codexWakeNonce:v,monitorClause:P,codexWakePathClause:m});let h=[...l,b];r==="codex"&&(h=[...xe(),...k,...ue(h,process.cwd())]),console.error(`${s()}${t.blue(`\u25FC Launching ${r==="claude"?"Claude Code":"Codex"}\u2026`)}`);const $=D(r,h,{stdio:"inherit",shell:!1,env:g});r==="codex"&&i&&d&&(we({deps:{setCodexWakeTarget:N,findLoadedCodexThread:ge},cubeId:i.cubeId,droneId:i.droneId,socketPath:d,passthroughArgs:l,previewNeedle:v??b.slice(0,120),cwd:process.cwd(),launchedAtSeconds:Math.floor(Date.now()/1e3)}),B(e=>fe(e))),$.on("error",e=>{if(p)try{p()}catch{}e.code==="ENOENT"?(console.error(`${s()}${t.red(`
8
8
  \u25FC Failed to launch ${r}`)}`),console.error(`${s()}${t.gray(`Make sure ${r} is installed.
9
9
  `)}`)):console.error(`${s()}${t.red(`
10
10
  \u25FC Failed to launch ${r}: ${e.message}
11
- `)}`),process.exit(1)}),$.on("exit",e=>{if(p)try{p()}catch{}process.exit(e??0)})}function Ie(){const c=x();if(c.claude)try{ye()||ke(),be(M(process.cwd())),Te(),$e()}catch(a){console.error(`${s()}${t.yellow(`warning: Claude Code integration check failed: ${a?.message??a}`)}`)}if(c.codex)try{Se()||xe(),Ce(),ve()}catch(a){console.error(`${s()}${t.yellow(`warning: Codex integration check failed: ${a?.message??a}`)}`)}}Ae().catch(c=>{console.error(`${s()}${t.red(`
11
+ `)}`),process.exit(1)}),$.on("exit",e=>{if(p)try{p()}catch{}process.exit(e??0)})}function Pe(){const c=x();if(c.claude)try{Te()||be(),$e(M(process.cwd())),Ae(),Se()}catch(a){console.error(`${s()}${t.yellow(`warning: Claude Code integration check failed: ${a?.message??a}`)}`)}if(c.codex)try{ye()||Ce(),ve(),ke()}catch(a){console.error(`${s()}${t.yellow(`warning: Codex integration check failed: ${a?.message??a}`)}`)}}Ie().catch(c=>{console.error(`${s()}${t.red(`
12
12
  \u25FC Error: ${c.message}
13
13
  `)}`),process.exit(1)});
@@ -14,6 +14,12 @@ export declare function isHelpFlag(arg: string | undefined): boolean;
14
14
  * claude.ts, which launches agent CLIs as a side effect.
15
15
  */
16
16
  export declare function topLevelHelpText(version: string): string;
17
+ /**
18
+ * Help text for `borg assimilate --help` — the home for the full assimilate flag
19
+ * set, including `--backend` and remote-Ollama config, which the concise
20
+ * top-level help only hints at.
21
+ */
22
+ export declare function assimilateHelpText(version: string): string;
17
23
  /**
18
24
  * Help text for `borg setup --help` (gh#520 — previously this ran the setup
19
25
  * wizard instead of showing help). Mirrors the `borg setup` description in the
package/dist/cli-help.js CHANGED
@@ -1,10 +1,10 @@
1
- function r(e){return e==="--help"||e==="-h"}function o(e){return`borgmcp ${e} \u2014 run several AI coding agents on one project, together.
1
+ function n(e){return e==="--help"||e==="-h"}function o(e){return`borgmcp ${e} \u2014 run several AI coding agents on one project, together.
2
2
  They coordinate through a shared log (a "cube"). For Claude Code & Codex.
3
3
 
4
4
  Docs & quickstart: https://borgmcp.ai/get-started
5
5
 
6
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").
7
+ type \`borg_...\` inside your agent session once you've joined a cube ("assimilate").
8
8
 
9
9
  Usage:
10
10
  borg Launch your agent CLI with cube context
@@ -12,13 +12,42 @@ Usage:
12
12
  borg setup --no-browser Set up from SSH/headless terminals
13
13
  borg assimilate [role] Join a cube (creates one if needed)
14
14
  borg assimilate --worktree <name> Spawn a worktree drone (in ~/.borg/worktrees/<repo>/<name>)
15
+ borg assimilate --backend ollama:<model> Run the drone on an Ollama model (see \`borg assimilate --help\`)
15
16
  borg sync [--prune] Sync this worktree's branch to origin/main
16
17
  borg launch-all [cube] Launch all drone worktrees of a cube (default: active cube)
17
18
  borg --cli claude|codex Choose agent CLI for this project
18
19
  borg --version Show installed version
19
20
 
20
21
  All other arguments are passed through to the selected agent CLI.
21
- `}function n(e){return`borg setup (borgmcp ${e}) \u2014 set up OAuth + register the borg MCP server
22
+ `}function t(e){return`borg assimilate (borgmcp ${e}) \u2014 join a cube under a role (creates the cube if needed)
23
+
24
+ Usage:
25
+ borg assimilate [role] Join the active cube under [role] (default role if omitted)
26
+ borg assimilate [role] --worktree <name> Spawn the drone in an isolated git worktree
27
+ (~/.borg/worktrees/<repo>/<name>)
28
+ borg assimilate --here Assimilate in the current worktree (no sibling spawn)
29
+ borg assimilate --help Show this help
30
+
31
+ Flags:
32
+ --worktree <name> Create + launch the drone in a sibling git worktree
33
+ --here Stay in the current worktree (no sibling spawn)
34
+ --cube-name <name> Cube to join/create (default: repo basename)
35
+ --template <name> Bootstrap a new cube from a bundled role template
36
+ --no-template Create the cube with no template roles
37
+ --cli claude|codex Agent CLI to launch (default: claude)
38
+ --backend <kind>:<model> Model backend for this drone (default: your Claude config)
39
+ --yes, -y Skip confirmation prompts
40
+
41
+ Backends (--backend <kind>:<model>):
42
+ claude:<model> e.g. --backend claude:claude-opus-4-8
43
+ ollama:<model> Run on an Ollama model, e.g. --backend ollama:qwen3-coder-next
44
+ The model must be pulled (ollama pull <model>); borg verifies it
45
+ against the Ollama server before assimilating.
46
+
47
+ Remote Ollama: set BORG_OLLAMA_BASE_URL (default http://localhost:11434), e.g.
48
+ BORG_OLLAMA_BASE_URL=http://Mac-Studio.local:11434 \\
49
+ borg assimilate build --backend ollama:qwen3-coder-next
50
+ `}function r(e){return`borg setup (borgmcp ${e}) \u2014 set up OAuth + register the borg MCP server
22
51
 
23
52
  Borg MCP needs Claude Code or Codex installed first.
24
53
 
@@ -29,4 +58,4 @@ Usage:
29
58
  for SSH / headless / container terminals. Alias: --device.
30
59
  Auto-detected on SSH/headless; this forces it.
31
60
  borg setup --help Show this help
32
- `}export{r as isHelpFlag,n as setupHelpText,o as topLevelHelpText};
61
+ `}export{t as assimilateHelpText,n as isHelpFlag,r as setupHelpText,o as topLevelHelpText};
@@ -3,7 +3,7 @@ import { CodexAppServerClient } from './codex-app-server.js';
3
3
  import { checkCodexBridgeHealthy } from './codex-remote.js';
4
4
  export declare const CODEX_WAKE_PROMPT = "New Borg cube-log activity arrived.";
5
5
  export declare function formatCodexWakePrompt(inboxLine: string): string;
6
- export declare const CODEX_CATCHUP_PROMPT = "Borg cube activity arrived while you were busy. Run `borg:read-log unread_only=true` and DRAIN \u2014 repeat until the returned page is under the limit and behind_by is 0 \u2014 so no entries are skipped.";
6
+ export declare const CODEX_CATCHUP_PROMPT = "Borg cube activity arrived while you were busy. Run `borg_read-log unread_only=true` and DRAIN \u2014 repeat until the returned page is under the limit and behind_by is 0 \u2014 so no entries are skipped.";
7
7
  export declare function isCodexRemoteWakeEnabled(env?: NodeJS.ProcessEnv): boolean;
8
8
  export declare function resolveSessionAgentKind(env?: NodeJS.ProcessEnv): 'claude' | 'codex';
9
9
  export interface CodexWakeTarget {
@@ -57,7 +57,7 @@ export declare function wakeCodexViaAppServer(reason?: string, env?: NodeJS.Proc
57
57
  export declare const CODEX_HEARTBEAT_CADENCE_MS: number;
58
58
  /**
59
59
  * gh#857 WI-2: one tick of the codex /loop-equivalent heartbeat — a periodic,
60
- * independent re-engagement that injects a borg:read-log-unread DRAIN turn so an
60
+ * independent re-engagement that injects a borg_read-log (unread_only=true) DRAIN turn so an
61
61
  * idle codex drone re-syncs even if every per-entry wake was missed. SKIPS when a
62
62
  * delivery (per-entry wake, retry-drain, or a prior heartbeat) already landed
63
63
  * within the cadence window (shouldFireHeartbeat), so an active cube with flowing
@@ -1,2 +1,2 @@
1
1
  import{getActiveCube as C,getCodexWakeTarget as m,setCodexWakeTarget as R}from"./cubes.js";import{CodexAppServerClient as S}from"./codex-app-server.js";import{checkCodexBridgeHealthy as K}from"./codex-remote.js";import{recordEventReceipt as W}from"./health-beat.js";import{codexAppServerSocketFromEnv as O,pickFreshThread as M,wakeTargetChanged as B,wakeRetryBackoffMs as F,wakeRetryExpired as H,WAKE_RETRY_MAX_ATTEMPTS as N,shouldFireHeartbeat as j}from"./codex-wake-resolve.js";const L="New Borg cube-log activity arrived.";function ie(e){return`New Borg cube-log activity arrived:
2
- ${e}`}const D="Borg cube activity arrived while you were busy. Run `borg:read-log unread_only=true` and DRAIN \u2014 repeat until the returned page is under the limit and behind_by is 0 \u2014 so no entries are skipped.";function P(e=process.env){return e.BORG_CODEX_REMOTE_WAKE==="1"}function X(e=process.env){return P(e)?"codex":"claude"}function q(e=process.env){return P(e)?{enabled:!0}:{enabled:!1}}async function ce(e,t={}){try{const r=await(t.getCodexWakeTarget??m)(e.cubeId,e.droneId);return r?(t.checkBridge??K)(r.socketPath):!1}catch{return null}}let f=!1;const h=[],l=new Set,w=[],$=100;let g=!1,k=null;function se(){return k}function T(e){k=(e.now??Date.now)()}let v=!1,y=!1;function p(){return y?!1:(y=!0,!0)}function A(){y=!1}function V(e){return e?.code==="ENOENT"}function Y(e){return new Promise(t=>setTimeout(t,e))}function x(e,t){return t.createClient?t.createClient(e):new S(e)}async function b(e,t){const n=O(t.env??process.env);if(n){const a=x(n,t);await a.connect();try{const o=await a.loadedThreadIds(),i=[];for(const u of o){const s=await a.readThread(u);s&&i.push({id:s.id,cwd:s.cwd,updatedAt:s.updatedAt})}const c=M(i,{cwd:(t.cwd??(()=>process.cwd()))()});return c?(await G(e,{socketPath:n,threadId:c},t),{socketPath:n,threadId:c}):null}finally{a.close()}}const r=await(t.getCodexWakeTarget??m)(e.cubeId,e.droneId);return r?{socketPath:r.socketPath,threadId:r.threadId}:null}async function G(e,t,n){try{const r=n.getCodexWakeTarget??m,a=n.setCodexWakeTarget??R,o=await r(e.cubeId,e.droneId),i=o?{socketPath:o.socketPath,threadId:o.threadId}:null;B(i,t)&&await a(e.cubeId,e.droneId,t)}catch{}}function ue(e=L,t=process.env,n={}){q(t).enabled&&(h.push({reason:e,deps:n}),!f&&(f=!0,Q().finally(()=>{f=!1})))}async function Q(){for(;h.length>0;){const e=h.shift();await U(e.reason,e.deps)}}async function U(e,t){if(!p()){E(t);return}try{const n=await(t.getActiveCube??C)();if(!n)return;const r=await b(n,t);if(!r)return;const{socketPath:a,threadId:o}=r,i=`${o}\0${e}`;if(l.has(i))return;const c=x(a,t);await c.connect();try{if((await c.readThread(o))?.status?.type==="active"){E(t);return}await c.startTurn(o,e),W(),Z(i),T(t)}finally{c.close()}}catch{E(t)}finally{A()}}function E(e){g||(g=!0,z(e).finally(()=>{g=!1}))}async function z(e){const t=e.sleep??Y,n=e.now??Date.now,r=e.jitter??(()=>Math.random()*500),a=e.maxAttempts??N,o=n();let i=0;for(;!H(o,n())&&i<a;)if(await t(F(i,r())),i++,!!p())try{const c=await(e.getActiveCube??C)();if(!c)continue;const u=await b(c,e);if(!u)continue;const{socketPath:s,threadId:I}=u,d=x(s,e);await d.connect();try{if((await d.readThread(I))?.status?.type==="active")continue;await d.startTurn(I,D),W(),T(e);return}finally{d.close()}}catch{}finally{A()}}const _=20*6e4;async function J(e={},t=_){if(v)return;const n=(e.now??Date.now)();if(j(k,n,t)&&!(e.isStreamOwner&&!e.isStreamOwner())&&p()){v=!0;try{const r=await(e.getActiveCube??C)();if(!r)return;const a=await b(r,e);if(!a)return;const o=x(a.socketPath,e);await o.connect();try{if((await o.readThread(a.threadId))?.status?.type==="active")return;await o.startTurn(a.threadId,D),T(e)}finally{o.close()}}catch(r){V(r)&&e.onAppServerSocketDead?.()}finally{v=!1,A()}}}function le(e={}){if((e.agentKind??X())!=="codex")return null;const n=e.intervalMs??_,r=e.tick??(()=>{J()}),a=setInterval(r,n);return a.unref?.(),a}function de(){f=!1,h.length=0,l.clear(),w.length=0,g=!1,k=null,v=!1,y=!1}function Z(e){if(!l.has(e))for(l.add(e),w.push(e);w.length>$;){const t=w.shift();t&&l.delete(t)}}export{D as CODEX_CATCHUP_PROMPT,_ as CODEX_HEARTBEAT_CADENCE_MS,L as CODEX_WAKE_PROMPT,J as fireCodexHeartbeatTick,ie as formatCodexWakePrompt,se as getLastDeliveredAt,P as isCodexRemoteWakeEnabled,ce as probeCodexBridgeArmed,de as resetCodexWakeForTests,q as resolveCodexWakeTarget,X as resolveSessionAgentKind,le as startCodexHeartbeat,ue as wakeCodexViaAppServer};
2
+ ${e}`}const D="Borg cube activity arrived while you were busy. Run `borg_read-log unread_only=true` and DRAIN \u2014 repeat until the returned page is under the limit and behind_by is 0 \u2014 so no entries are skipped.";function P(e=process.env){return e.BORG_CODEX_REMOTE_WAKE==="1"}function X(e=process.env){return P(e)?"codex":"claude"}function q(e=process.env){return P(e)?{enabled:!0}:{enabled:!1}}async function ce(e,t={}){try{const r=await(t.getCodexWakeTarget??m)(e.cubeId,e.droneId);return r?(t.checkBridge??K)(r.socketPath):!1}catch{return null}}let f=!1;const h=[],l=new Set,w=[],$=100;let g=!1,k=null;function se(){return k}function T(e){k=(e.now??Date.now)()}let v=!1,y=!1;function p(){return y?!1:(y=!0,!0)}function A(){y=!1}function V(e){return e?.code==="ENOENT"}function Y(e){return new Promise(t=>setTimeout(t,e))}function x(e,t){return t.createClient?t.createClient(e):new S(e)}async function b(e,t){const n=O(t.env??process.env);if(n){const a=x(n,t);await a.connect();try{const o=await a.loadedThreadIds(),i=[];for(const u of o){const s=await a.readThread(u);s&&i.push({id:s.id,cwd:s.cwd,updatedAt:s.updatedAt})}const c=M(i,{cwd:(t.cwd??(()=>process.cwd()))()});return c?(await G(e,{socketPath:n,threadId:c},t),{socketPath:n,threadId:c}):null}finally{a.close()}}const r=await(t.getCodexWakeTarget??m)(e.cubeId,e.droneId);return r?{socketPath:r.socketPath,threadId:r.threadId}:null}async function G(e,t,n){try{const r=n.getCodexWakeTarget??m,a=n.setCodexWakeTarget??R,o=await r(e.cubeId,e.droneId),i=o?{socketPath:o.socketPath,threadId:o.threadId}:null;B(i,t)&&await a(e.cubeId,e.droneId,t)}catch{}}function ue(e=L,t=process.env,n={}){q(t).enabled&&(h.push({reason:e,deps:n}),!f&&(f=!0,Q().finally(()=>{f=!1})))}async function Q(){for(;h.length>0;){const e=h.shift();await U(e.reason,e.deps)}}async function U(e,t){if(!p()){E(t);return}try{const n=await(t.getActiveCube??C)();if(!n)return;const r=await b(n,t);if(!r)return;const{socketPath:a,threadId:o}=r,i=`${o}\0${e}`;if(l.has(i))return;const c=x(a,t);await c.connect();try{if((await c.readThread(o))?.status?.type==="active"){E(t);return}await c.startTurn(o,e),W(),Z(i),T(t)}finally{c.close()}}catch{E(t)}finally{A()}}function E(e){g||(g=!0,z(e).finally(()=>{g=!1}))}async function z(e){const t=e.sleep??Y,n=e.now??Date.now,r=e.jitter??(()=>Math.random()*500),a=e.maxAttempts??N,o=n();let i=0;for(;!H(o,n())&&i<a;)if(await t(F(i,r())),i++,!!p())try{const c=await(e.getActiveCube??C)();if(!c)continue;const u=await b(c,e);if(!u)continue;const{socketPath:s,threadId:I}=u,d=x(s,e);await d.connect();try{if((await d.readThread(I))?.status?.type==="active")continue;await d.startTurn(I,D),W(),T(e);return}finally{d.close()}}catch{}finally{A()}}const _=20*6e4;async function J(e={},t=_){if(v)return;const n=(e.now??Date.now)();if(j(k,n,t)&&!(e.isStreamOwner&&!e.isStreamOwner())&&p()){v=!0;try{const r=await(e.getActiveCube??C)();if(!r)return;const a=await b(r,e);if(!a)return;const o=x(a.socketPath,e);await o.connect();try{if((await o.readThread(a.threadId))?.status?.type==="active")return;await o.startTurn(a.threadId,D),T(e)}finally{o.close()}}catch(r){V(r)&&e.onAppServerSocketDead?.()}finally{v=!1,A()}}}function le(e={}){if((e.agentKind??X())!=="codex")return null;const n=e.intervalMs??_,r=e.tick??(()=>{J()}),a=setInterval(r,n);return a.unref?.(),a}function de(){f=!1,h.length=0,l.clear(),w.length=0,g=!1,k=null,v=!1,y=!1}function Z(e){if(!l.has(e))for(l.add(e),w.push(e);w.length>$;){const t=w.shift();t&&l.delete(t)}}export{D as CODEX_CATCHUP_PROMPT,_ as CODEX_HEARTBEAT_CADENCE_MS,L as CODEX_WAKE_PROMPT,J as fireCodexHeartbeatTick,ie as formatCodexWakePrompt,se as getLastDeliveredAt,P as isCodexRemoteWakeEnabled,ce as probeCodexBridgeArmed,de as resetCodexWakeForTests,q as resolveCodexWakeTarget,X as resolveSessionAgentKind,le as startCodexHeartbeat,ue as wakeCodexViaAppServer};
@@ -1 +1 @@
1
- function s(e){const r=e.codexWakeNonce?`Wake target nonce: ${e.codexWakeNonce}. `:"",t="On every Monitor wake and every ScheduleWakeup heartbeat, triage with borg:read-log unread_only=true first \u2014 it returns only entries since your last read, advancing your server-side read cursor (oldest-unread first), so you never skip a burst; and it keeps last_seen fresh. DRAIN: if it returns a full set (count == limit) or borg:roster shows behind_by>0, call read-log unread_only=true again until the return is < limit. Do NOT triage with a manual since cursor or a bare limit window \u2014 since is strict-after (skips the boundary entry) and a limit-bounded read skips older-unread during bursts (and codex has no per-entry inbox-Monitor backstop to catch them); reserve limit for explicit bounded reads. Call borg:regen only when you are about to act and need full cube/role/roster context, on session start, after context compaction, or periodically every 4-5 wakes / 15-30 minutes. Never reflexively call borg:regen for routine text-only wakes. ",a=e.codexWakePathClause??"Codex Borg wakeups use remote-control when available; if no wake arrives, run borg:regen manually when returning to the session.";return`${e.cli==="claude"?"/loop ":""}Call borg:regen and follow the playbook in its response. `+r+'Note: at session start the borg MCP server is still spinning up in parallel \u2014 if a system reminder claims "MCP server disconnected" or the borg: tools are not yet registered, do NOT bail. Recover via `ToolSearch({query: "select:mcp__borg__borg_regen,mcp__borg__borg_log,Monitor", max_results: 3})` to load the bootstrap tools in one call, then call borg:regen. The server typically becomes available within a few seconds. '+e.monitorClause+"Coordinator/Queen seats: before posting bare `Standing.`, run the anti-passive-Standing stale-check per your role text \u2014 for every in-flight dispatch / REVIEW-READY / synthesis-pending, compare elapsed-since-last-transition against the cadence-table PING thresholds; escalate per the 4-step ladder (PING / probe-liveness / reassign / suspect-systemic) when any row is overdue. Append the awaited signal when you do post Standing (`Standing for X`, never bare). "+t+(e.cli==="claude"?"Wake-path capability check: if borg:regen shows a wake-path warning, arm the Monitor before starting work. Use a 30-minute (1800s) fallback heartbeat for ScheduleWakeup.":a)}function i(e){const r=e.indexOf("--remote");if(r<0)return null;const t=e[r+1];return t?.startsWith("unix://")?t.slice(7):null}function o(e){if(e[0]==="resume"&&e[1]&&!e[1].startsWith("-"))return e[1];const r=e.indexOf("--resume");return r>=0&&e[r+1]?e[r+1]:null}async function l(e){try{const r=e.passthroughArgs?o(e.passthroughArgs):null;if(r){await e.deps.setCodexWakeTarget(e.cubeId,e.droneId,{threadId:r,socketPath:e.socketPath});return}const t=Date.now()+15e3;for(;Date.now()<t;){const a=await e.deps.findLoadedCodexThread({socketPath:e.socketPath,cwd:e.cwd,previewIncludes:e.previewNeedle,updatedAfter:e.launchedAtSeconds-5});if(a){await e.deps.setCodexWakeTarget(e.cubeId,e.droneId,{threadId:a,socketPath:e.socketPath});return}await new Promise(n=>setTimeout(n,500))}}catch{}}export{s as buildAgentKickoffPrompt,l as recordCodexWakeTarget,i as socketPathFromRemoteArgs,o as threadIdFromPassthroughArgs};
1
+ function s(e){const r=e.codexWakeNonce?`Wake target nonce: ${e.codexWakeNonce}. `:"",t="On every Monitor wake and every ScheduleWakeup heartbeat, triage with borg_read-log unread_only=true first \u2014 it returns only entries since your last read, advancing your server-side read cursor (oldest-unread first), so you never skip a burst; and it keeps last_seen fresh. DRAIN: if it returns a full set (count == limit) or borg_roster shows behind_by>0, call read-log unread_only=true again until the return is < limit. Do NOT triage with a manual since cursor or a bare limit window \u2014 since is strict-after (skips the boundary entry) and a limit-bounded read skips older-unread during bursts (and codex has no per-entry inbox-Monitor backstop to catch them); reserve limit for explicit bounded reads. Call borg_regen only when you are about to act and need full cube/role/roster context, on session start, after context compaction, or periodically every 4-5 wakes / 15-30 minutes. Never reflexively call borg_regen for routine text-only wakes. ",a=e.codexWakePathClause??"Codex Borg wakeups use remote-control when available; if no wake arrives, run borg_regen manually when returning to the session.";return`${e.cli==="claude"?"/loop ":""}Call borg_regen and follow the playbook in its response. `+r+'Note: at session start the borg MCP server is still spinning up in parallel \u2014 if a system reminder claims "MCP server disconnected" or the borg tools are not yet registered, do NOT bail. Recover via `ToolSearch({query: "select:mcp__borg__borg_regen,mcp__borg__borg_log,Monitor", max_results: 3})` to load the bootstrap tools in one call, then call borg_regen. The server typically becomes available within a few seconds. '+e.monitorClause+"Coordinator/Queen seats: before posting bare `Standing.`, run the anti-passive-Standing stale-check per your role text \u2014 for every in-flight dispatch / REVIEW-READY / synthesis-pending, compare elapsed-since-last-transition against the cadence-table PING thresholds; escalate per the 4-step ladder (PING / probe-liveness / reassign / suspect-systemic) when any row is overdue. Append the awaited signal when you do post Standing (`Standing for X`, never bare). "+t+(e.cli==="claude"?"Wake-path capability check: if borg_regen shows a wake-path warning, arm the Monitor before starting work. Use a 30-minute (1800s) fallback heartbeat for ScheduleWakeup.":a)}function i(e){const r=e.indexOf("--remote");if(r<0)return null;const t=e[r+1];return t?.startsWith("unix://")?t.slice(7):null}function o(e){if(e[0]==="resume"&&e[1]&&!e[1].startsWith("-"))return e[1];const r=e.indexOf("--resume");return r>=0&&e[r+1]?e[r+1]:null}async function l(e){try{const r=e.passthroughArgs?o(e.passthroughArgs):null;if(r){await e.deps.setCodexWakeTarget(e.cubeId,e.droneId,{threadId:r,socketPath:e.socketPath});return}const t=Date.now()+15e3;for(;Date.now()<t;){const a=await e.deps.findLoadedCodexThread({socketPath:e.socketPath,cwd:e.cwd,previewIncludes:e.previewNeedle,updatedAfter:e.launchedAtSeconds-5});if(a){await e.deps.setCodexWakeTarget(e.cubeId,e.droneId,{threadId:a,socketPath:e.socketPath});return}await new Promise(n=>setTimeout(n,500))}}catch{}}export{s as buildAgentKickoffPrompt,l as recordCodexWakeTarget,i as socketPathFromRemoteArgs,o as threadIdFromPassthroughArgs};
@@ -1 +1 @@
1
- import{mkdirSync as v,chmodSync as w,readdirSync as g,rmSync as C,writeFileSync as k,readFileSync as y}from"node:fs";import{homedir as S}from"node:os";import{join as u}from"node:path";import{randomBytes as b}from"node:crypto";import{spawn as A}from"node:child_process";import{CodexAppServerClient as E}from"./codex-app-server.js";import{codexBorgSessionConfigArgs as R,BORG_SESSION_ENV as $}from"./launch-gate.js";import{codexAppServerSocketConfigArgs as N}from"./codex-wake-resolve.js";const I=u(S(),".config","borgmcp","codex-remote");function G(e,r){return M(e)?e:["--cd",r,...e]}function M(e){return e.some(r=>r==="--cd"||r.startsWith("--cd=")||r==="-C")}function x(e){try{return process.kill(e,0),!0}catch(r){return r?.code==="EPERM"}}function X(e,r={}){if(!e)return null;const a=r.isAlive??x,i=r.readPidFile??(o=>y(o,"utf-8")),c=e.replace(/\.sock$/,".pid");try{const o=Number.parseInt(i(c).trim(),10);return Number.isNaN(o)?null:a(o)}catch{return null}}function s(e){try{C(e,{force:!0})}catch{}}function T(e,r){let a;try{a=g(e)}catch{return}for(const i of a){if(!i.endsWith(".pid"))continue;const c=u(e,i),o=u(e,i.replace(/\.pid$/,".sock"));let t;try{t=Number.parseInt(y(c,"utf-8").trim(),10)}catch{s(c);continue}(Number.isNaN(t)||!r(t))&&(s(o),s(c))}}function p(e){return{args:[],env:{},warning:e}}async function j(e){const r=e.runtimeDir??I,a=e.isAlive??x,i=e.readyTimeoutMs??8e3,c=e.pollIntervalMs??250;try{v(r,{recursive:!0,mode:448}),w(r,448),T(r,a)}catch(n){return p(`Codex remote-wake disabled: could not prepare ${r} (${n?.message??n}); run borg:regen manually.`)}const o=(e.socketId??(()=>b(16).toString("hex")))(),t=u(r,`${o}.sock`),m=u(r,`${o}.pid`);let l;try{l=e.spawnAppServer(t)}catch(n){return s(t),p(`Codex remote-wake disabled: could not start \`codex app-server\` (${n?.message??n}) \u2014 is Codex installed + up to date? This session only wakes on the ~30min /loop fallback; run borg:regen manually.`)}if(l.pid!=null)try{k(m,String(l.pid))}catch{}const f=()=>{try{l.kill()}catch{}s(t),s(m)},h=Math.max(1,Math.ceil(i/c));let d=!1;for(let n=0;n<h&&!d;n++){try{d=await e.probeReady(t)}catch{d=!1}!d&&n<h-1&&await e.sleep(c)}return d?{args:["--remote",`unix://${t}`],env:{BORG_CODEX_REMOTE_WAKE:"1"},server:{pid:l.pid,socketPath:t,cleanup:f}}:(f(),p(`Codex remote-wake disabled: could not reach a Codex app-server at ${t} within ${i}ms (is Codex up to date? \`codex app-server --listen\` is required). This session only wakes on the ~30min /loop fallback \u2014 run borg:regen manually when you return.`))}function q(){return{spawnAppServer:e=>{const r=A("codex",["app-server",...R(),...N(e),"--listen",`unix://${e}`],{stdio:"ignore",shell:!1,env:{...process.env,[$]:"1"}});return{pid:r.pid,kill:()=>{try{r.kill()}catch{}}}},probeReady:async e=>{const r=new E(e);try{return await r.connect(),await r.loadedThreadIds(),!0}catch{return!1}finally{try{r.close()}catch{}}},sleep:e=>new Promise(r=>setTimeout(r,e))}}export{I as DEFAULT_CODEX_REMOTE_DIR,X as checkCodexBridgeHealthy,q as defaultCodexRemoteDeps,x as defaultIsAlive,j as prepareCodexRemoteLaunch,G as withCodexCwdArg};
1
+ import{mkdirSync as v,chmodSync as w,readdirSync as g,rmSync as C,writeFileSync as k,readFileSync as y}from"node:fs";import{homedir as S}from"node:os";import{join as u}from"node:path";import{randomBytes as b}from"node:crypto";import{spawn as A}from"node:child_process";import{CodexAppServerClient as E}from"./codex-app-server.js";import{codexBorgSessionConfigArgs as R,BORG_SESSION_ENV as _}from"./launch-gate.js";import{codexAppServerSocketConfigArgs as $}from"./codex-wake-resolve.js";const N=u(S(),".config","borgmcp","codex-remote");function G(e,r){return I(e)?e:["--cd",r,...e]}function I(e){return e.some(r=>r==="--cd"||r.startsWith("--cd=")||r==="-C")}function x(e){try{return process.kill(e,0),!0}catch(r){return r?.code==="EPERM"}}function X(e,r={}){if(!e)return null;const a=r.isAlive??x,i=r.readPidFile??(o=>y(o,"utf-8")),c=e.replace(/\.sock$/,".pid");try{const o=Number.parseInt(i(c).trim(),10);return Number.isNaN(o)?null:a(o)}catch{return null}}function s(e){try{C(e,{force:!0})}catch{}}function M(e,r){let a;try{a=g(e)}catch{return}for(const i of a){if(!i.endsWith(".pid"))continue;const c=u(e,i),o=u(e,i.replace(/\.pid$/,".sock"));let t;try{t=Number.parseInt(y(c,"utf-8").trim(),10)}catch{s(c);continue}(Number.isNaN(t)||!r(t))&&(s(o),s(c))}}function p(e){return{args:[],env:{},warning:e}}async function j(e){const r=e.runtimeDir??N,a=e.isAlive??x,i=e.readyTimeoutMs??8e3,c=e.pollIntervalMs??250;try{v(r,{recursive:!0,mode:448}),w(r,448),M(r,a)}catch(n){return p(`Codex remote-wake disabled: could not prepare ${r} (${n?.message??n}); run borg_regen manually.`)}const o=(e.socketId??(()=>b(16).toString("hex")))(),t=u(r,`${o}.sock`),m=u(r,`${o}.pid`);let l;try{l=e.spawnAppServer(t)}catch(n){return s(t),p(`Codex remote-wake disabled: could not start \`codex app-server\` (${n?.message??n}) \u2014 is Codex installed + up to date? This session only wakes on the ~30min /loop fallback; run borg_regen manually.`)}if(l.pid!=null)try{k(m,String(l.pid))}catch{}const f=()=>{try{l.kill()}catch{}s(t),s(m)},h=Math.max(1,Math.ceil(i/c));let d=!1;for(let n=0;n<h&&!d;n++){try{d=await e.probeReady(t)}catch{d=!1}!d&&n<h-1&&await e.sleep(c)}return d?{args:["--remote",`unix://${t}`],env:{BORG_CODEX_REMOTE_WAKE:"1"},server:{pid:l.pid,socketPath:t,cleanup:f}}:(f(),p(`Codex remote-wake disabled: could not reach a Codex app-server at ${t} within ${i}ms (is Codex up to date? \`codex app-server --listen\` is required). This session only wakes on the ~30min /loop fallback \u2014 run borg_regen manually when you return.`))}function q(){return{spawnAppServer:e=>{const r=A("codex",["app-server",...R(),...$(e),"--listen",`unix://${e}`],{stdio:"ignore",shell:!1,env:{...process.env,[_]:"1"}});return{pid:r.pid,kill:()=>{try{r.kill()}catch{}}}},probeReady:async e=>{const r=new E(e);try{return await r.connect(),await r.loadedThreadIds(),!0}catch{return!1}finally{try{r.close()}catch{}}},sleep:e=>new Promise(r=>setTimeout(r,e))}}export{N as DEFAULT_CODEX_REMOTE_DIR,X as checkCodexBridgeHealthy,q as defaultCodexRemoteDeps,x as defaultIsAlive,j as prepareCodexRemoteLaunch,G as withCodexCwdArg};
@@ -43,7 +43,7 @@ export declare function removeSessionStartHook(): boolean;
43
43
  * Register a Claude Code UserPromptSubmit hook that runs `borg-log-audit`
44
44
  * before each user prompt. The audit script nudges the drone if the
45
45
  * previous assistant span used state-changing tools without calling
46
- * `borg:log`. Idempotent: re-running won't add duplicates.
46
+ * `borg_log`. Idempotent: re-running won't add duplicates.
47
47
  *
48
48
  * Returns true if a change was made, false otherwise.
49
49
  */
@@ -1,12 +1,12 @@
1
1
  /**
2
- * Pure label→id resolution for the `borg:evict-drone` tool (gh#718).
2
+ * Pure label→id resolution for the `borg_evict-drone` tool (gh#718).
3
3
  *
4
4
  * `CubeStore.evictDrone` and the owner-authed `DELETE /api/drones/:id` route
5
5
  * both take a drone UUID. Coordinators, however, see drone LABELS everywhere
6
6
  * (roster, regen, cube log) and rarely the UUIDs. This helper lets the tool
7
7
  * accept a label and resolve it to the drone id client-side, against the
8
8
  * owner-scoped cube detail returned by `getCube` (the same id+label pairs
9
- * `borg:list-drones` renders). No I/O here — a pure function so it can be
9
+ * `borg_list-drones` renders). No I/O here — a pure function so it can be
10
10
  * unit-tested in isolation; the handler in index.ts owns the network calls.
11
11
  */
12
12
  export interface EvictableDrone {