borgmcp 1.0.45 → 1.0.47
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/assimilate-cmd.js +40 -40
- package/dist/cleanup-cmd.js +14 -13
- package/dist/config-utils.d.ts +17 -0
- package/dist/config-utils.js +3 -3
- package/dist/cubes.js +5 -5
- package/dist/index.js +12 -12
- package/dist/launch-all-cmd.js +30 -26
- package/dist/log-stream.d.ts +39 -3
- package/dist/log-stream.js +9 -9
- package/dist/regen-format.js +6 -6
- package/dist/remote-client.d.ts +1 -1
- package/dist/remote-client.js +1 -1
- package/dist/setup-confirm.d.ts +31 -0
- package/dist/setup-confirm.js +2 -2
- package/dist/setup.js +28 -28
- package/dist/templates.js +2 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Server as K}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as z}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as X,ListToolsRequestSchema as Y,ListPromptsRequestSchema as G,GetPromptRequestSchema as J}from"@modelcontextprotocol/sdk/types.js";import{getCubeInfo as Z,getRoleInfo as j,getRoster as ee,readLog as te,appendLog as re,submitReport as oe,ackLogEntry as ie,regen as T,listCubes as ne,createCube as se,updateCube as O,deleteCube as ae,createRole as ce,updateRole as le,patchRoleSection as S,patchTaxonomyClass as N,deleteRole as de,reassignDrone as pe,evictDrone as ue,getCube as w,checkSubscriptionStatus as me,createBillingPortalSession as be,createSubscription as he,syncRoles as ge,applyTemplate as ye,whoami as fe,roleRationale as _e,getValidToken as we}from"./remote-client.js";import{startHealthBeatTick as ve}from"./health-beat.js";import{getTemplate as $,listTemplateNames as U,resolveCubeDirectiveForCreate as xe,resolveCubeDirectiveForApply as ke,resolveMessageTaxonomyForCreate as Se}from"./templates.js";import{activeCubeWithFreshRegenIdentity as P,getActiveCube as y,setActiveCube as A,inboxPathForDrone as q}from"./cubes.js";import{addSessionStartHook as $e,addUserPromptSubmitHook as Ue}from"./config-utils.js";import{humanAgo as L,formatLogEntryMarkdown as qe,formatRegenMarkdown as M,getDronePlaybook as Ee,getDronePlaybookChapter as Ie,nullTaxonomyTip as Ce,regenWakePathDroneLabel as Re}from"./regen-format.js";import{startLogStream as De,getStreamStatus as E}from"./log-stream.js";import{renderRoleList as je}from"./list-roles-render.js";import{filterToolsForRole as Te}from"./tool-scope.js";import{getPackageVersion as v,getOnDiskVersion as Oe,handleVersionFlag as Ne}from"./version.js";import{renderStreamStatus as Pe,checkInboxMonitorHealthy as I,formatWakePathPrefix as Ae,shouldShowWakePathWarning as Le}from"./stream-status.js";import{formatRoleAgentLabel as Me,renderRoster as Be}from"./roster-render.js";import{resolveDroneIdByLabel as Fe,isUuidShape as We}from"./evict-drone.js";import{authRecoveryMessage as He}from"./auth-recovery.js";import{DroneEvictedError as Qe,DroneFrozenError as Ve,formatEvictedToolResult as Ke,formatFrozenToolResult as ze}from"./drone-lifecycle.js";import{classifyInSessionAssimilate as Xe,reattachOnlyRefusal as Ye,reattachFailureMessage as Ge}from"./assimilate-guard.js";import{gateAllowsActivation as Je,borgSessionToolNotice as Ze}from"./launch-gate.js";import{renderSyncRolesResult as et}from"./sync-roles-render.js";import{initConsolePrefix as tt,consolePrefix as x}from"./console-prefix.js";import{isCodexRemoteWakeEnabled as C,resolveSessionAgentKind as rt,probeCodexBridgeArmed as ot}from"./codex-app-wake.js";import{lifecycleSignalForMessage as it,recordLifecycleLog as B,shouldSuppressLifecycleLog as nt}from"./lifecycle-log-guard.js";import{normalizeDirectLogRecipients as st}from"./direct-log.js";import F from"open";import at from"os";function ct(){try{const p=at.hostname();return p&&p.trim()?p.trim().slice(0,255):null}catch{return null}}async function W(p,_){return await ye(p,_.name)}async function f(){const p=await y();if(!p)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");return p}async function lt(){Ne();try{$e()}catch{}try{Ue()}catch{}try{De()}catch{}try{ve({getActiveCube:y,getStreamConnected:()=>E().connected,getInboxPath:u=>q(u.cubeId,u.droneId),checkMonitor:I,isCodexRemoteWake:C,probeBridgeArmed:u=>ot({cubeId:u.cubeId,droneId:u.droneId}),resolveAgentKind:rt,resolveHostname:ct,resolveVersion:v,getToken:we,fetchImpl:globalThis.fetch.bind(globalThis)})}catch{}const p=new K({name:"borg-mcp-client",version:v()},{capabilities:{tools:{},prompts:{}}}),_=[{name:"borg_subscribe",description:"Create Stripe checkout session for Cube tier ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_upgrade-subscription",description:"Open the Stripe Billing Portal to manage Cube tier quantity ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_subscription_status",description:"Check subscription status",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_open_dashboard",description:"Open Borg MCP dashboard in browser to manage cubes, roles, and drones",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_regen",description:"Refresh your context as a Drone. Returns the active cube's directive, your role's detailed playbook, the drone roster, and recent activity log entries \u2014 everything you need to be oriented. Call on session start, and again before each new task to stay in sync with the cube. Returns \"not connected\" if no active cube; use borg_assimilate first in that case. Optional `since` (entry-id UUID or ISO-8601 timestamp) trims the recent-log section to entries strictly after the anchor \u2014 pass your last-seen entry id to skip already-processed history on each refresh.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional cursor. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple) OR an ISO-8601 timestamp. When provided, the recent-log section returns entries strictly after that anchor. Non-existent UUID falls back to default recent window."},mode:{type:"string",enum:["full","lite"],description:"Optional output mode. Use full at session start and after context compaction. Lite omits unchanged role playbook/directive/boilerplate while always showing dynamic safety information and recent activity."}},required:[]}},{name:"borg_assimilate",description:"RE-ATTACH this session to the drone seat already saved for this worktree (gh#780: this tool never creates seats). Provide the cube's name; on a match it returns the cube directive, your role's instructions, and recent activity for the EXISTING seat. To create a seat or switch cubes, run `borg assimilate` in a terminal instead.",inputSchema:{type:"object",properties:{cube_name:{type:"string",description:"The cube to connect to"}},required:["cube_name"]}},{name:"borg_cube",description:"Read the active Cube's directive and the registry of all roles in it (each role's name + short description). Use to remind yourself of cube-wide context.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role",description:"Read your assigned role's detailed description (your playbook). Other drones cannot see this \u2014 only you (drones in this role).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_version",description:"Returns the installed borgmcp client version. Use to verify which version is running in this MCP session.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_playbook",description:"Load the full operating-playbook chapter \u2014 the detailed disciplines, rationale, and examples behind the rule-spine in your regen (verification discipline v1/v2/v3, concrete source-of-truth surfaces, four-surface propagation). This detail is kept OUT of the regen bootstrap to keep it light; fetch it ONCE per session when doing review/verify-class work. Static text \u2014 do NOT re-fetch on every wake.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_whoami",description:"Returns your identity in the current cube: cube name, drone label, and role name. Use to confirm which cube/role/drone you are.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role-rationale",description:"Fetch an on-demand rationale/case-study section for a role playbook. Pass a role name/id and a plain-label section key to read the rationale without expanding every regen.",inputSchema:{type:"object",properties:{role:{type:"string",description:"Role name or role id to fetch rationale for, e.g. Builder."},section:{type:"string",description:"Plain-label role section key, e.g. Workflow rationale."}},required:["role","section"]}},{name:"borg_roster",description:"List all currently connected drones in your cube, with each drone's label, role, and last-seen time. Optional `since` argument adds a sender-side liveness column \u2014 pass either an activity_log entry id (e.g., from a dispatch you posted) or an ISO-8601 timestamp; each drone is marked `awake` if they've posted a log entry after that point, otherwise `stale-since-X`. Useful for confirming a dispatch reached its named recipients (catches the silent-wake-path-failure class where SSE delivered but the drone's /loop never woke).",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional liveness reference point. Either an activity_log entry id (UUID; server resolves to its created_at) OR an ISO-8601 timestamp. When provided, each drone in the output is tagged awake/stale relative to that point."}},required:[]}},{name:"borg_stream-status",description:"Diagnostic probe of the local SSE log-stream consumer: returns `connected`, `lastContentEventAt`, `lastWireActivityAt`, `lastHeartbeatAt`, `lastPersistedEventId`, `reconnectAttempts`, plus a wake-path check that flags if SSE is attached but no inbox-Monitor is watching the file (the silent failure where `/loop` never wakes on incoming entries). Read-only in-process state; does NOT re-open the stream. Use when troubleshooting wake-ups or verifying the stream is alive.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_read-log",description:"Read entries from the cube's activity log. Each entry is tagged with the drone that wrote it and that drone's role. For wake triage, prefer `unread_only=true` with a modest limit and drain until `has_more=false`; this reads oldest-unread-first from your server cursor and advances the watermark so bursts are not skipped. Optional `since` is a strict-after cursor for explicit bounded reads only; do not use it with the same timestamp as a notification preview because it can skip the boundary entry.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional strict-after cursor for explicit bounded reads. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple for deterministic tie-break) OR an ISO-8601 timestamp. Do not use for routine wake triage; prefer unread_only."},limit:{type:"number",description:"max entries to return (1-500)"},unread_only:{type:"boolean",description:"When true, read only entries posted after this drone last called read-log, oldest-unread-first. Server advances the watermark to the newest returned entry on every call; if has_more=true, call again until has_more=false."}}}},{name:"borg_ack",description:"Mark a log entry as explicitly acknowledged. Replaces the convention of posting `ACK: <dispatch-id>` log entries. The ack is recorded in a queryable DB flag (activity_log_acks) keyed on (entry_id, drone_id, kind). Idempotent \u2014 repeated calls on the same entry are no-ops. Use this whenever a previous workflow would have prompted you to log an ACK; it removes the noise from the cube log while keeping the signal queryable.",inputSchema:{type:"object",required:["entry_id"],properties:{entry_id:{type:"string",description:"UUID of the log entry to acknowledge."}}}},{name:"borg_log",description:"Append a message to the cube's activity log. By default entries broadcast to all drones. When a cube declares a message taxonomy, borg_log applies class-based smart defaults: prefix-matched directed classes route to their default recipients unless you pass `to:`, `class:`, or explicit visibility. Pass `to: [...]` to direct by exact drone label, drone id, the 8-hex short-uuid (the `id:` token shown in roster/read-log \u2014 a drone_id prefix that is STABLE across label renumber), 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, the 8-hex short-uuid (`id:` token from roster/read-log; stable across label renumber), role name, or role slug (resolves to all drones in that role). Omit to let class-based routing or broadcast defaults apply."},class:{type:"string",description:"Optional declared message class. Overrides prefix auto-classification when the cube declares a message taxonomy."},visibility:{type:"string",enum:["broadcast","direct"],description:"Optional explicit visibility. Overrides class-based routing defaults."}},required:["message"]}},{name:"borg_report-friction",description:"Report friction or a bug directly to the borgmcp dev team. WRITE-ONLY \u2014 you cannot read reports back. Use it when something about borg itself slowed you down, confused you, or broke: awkward UX, an unclear playbook, a missing affordance, or a bug you hit while using borg. Secrets (tokens, keys) are auto-scrubbed server-side before storage, but avoid pasting them anyway.",inputSchema:{type:"object",properties:{message:{type:"string",description:"What hit you + what you expected instead (max 10KB). Concrete and specific helps the dev team most."},kind:{type:"string",enum:["friction","bug"],description:"'friction' (default) for UX/workflow friction; 'bug' for something broken."},metadata:{type:"object",description:"Optional non-secret context. Allowed keys only: version, cube_id, os. Any other key is rejected."}},required:["message"]}},{name:"borg_list-cubes",description:"List every cube owned by this user. Returns id, name, cube_directive, and timestamps for each. Useful before assimilate to see what's available, or as a starting point for any management action.",inputSchema:{type:"object",properties:{}}},{name:"borg_create-cube",description:'Create a new cube. The server seeds a default "Drone" role atomically so the cube is assimilatable immediately. Pass an optional `template` name to apply a richer role set instead (see borg_list-templates / borg_apply-template).',inputSchema:{type:"object",properties:{name:{type:"string",description:"Cube name (lowercase letters, digits, hyphens; max 64 chars).",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"Markdown text every drone in this cube will see in regen. Anything project-specific."},template:{type:"string",description:'Optional template name to apply after cube creation (e.g. "software-dev"). Roles are merged by name; the default Drone role gets overwritten by the template if a same-named role is in the template.'}},required:["name","cube_directive"]}},{name:"borg_update-cube",description:"Update a cube's name, cube_directive, and/or message_taxonomy. Pass only what changes.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to update."},name:{type:"string",description:"New name (optional). Lowercase letters, digits, hyphens; max 64 chars.",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"New cube directive markdown (optional)."},message_taxonomy:{type:"array",description:"New message-class taxonomy (optional). REPLACES the whole taxonomy; the worker re-validates the full array (non-overlapping prefixes, unique class names, directed classes need default_to). Pass [] to clear. To change ONE class without resending the whole array, use borg_patch-taxonomy-class instead. In default_to, pass @human-seat to route to drones in the cube human-seat role(s); literal role names/slugs/labels still work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",items:{type:"object",properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (role name/slug/label, or @human-seat) for a directed class."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}}}}},required:["cube_id"]}},{name:"borg_patch-taxonomy-class",description:"Patch ONE message-class in a cube's message_taxonomy without resending the whole taxonomy (avoids clobbering). action=add|replace|remove (replace/remove match name case-insensitively). The full taxonomy is re-validated after the patch (non-overlapping prefixes, unique names, directed classes need default_to) \u2014 a patch that breaks a rule against an untouched class is rejected. In default_to, @human-seat routes to the cube's human-seat role(s); literal names/slugs/labels also work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to patch."},action:{type:"string",enum:["add","replace","remove"],description:"add / replace / remove a single class."},class_def:{type:"object",description:'The class definition (for add/replace). Shape: { class, prefixes?, routing: "broadcast"|"directed", default_to?, lifecycle? }.',properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (required for directed classes): role name/slug/label, or @human-seat."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}},required:["class","routing"]},class:{type:"string",description:"For remove only: the name of the class to drop (case-insensitive)."}},required:["cube_id","action"]}},{name:"borg_delete-cube",description:"Delete a cube and all its roles, drones, and log entries. Irreversible \u2014 confirm with the user before invoking unless the cube is clearly disposable.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to delete."}},required:["cube_id"]}},{name:"borg_create-role",description:"Create a role inside a cube. The detailed_description is the role's playbook \u2014 only drones assigned to this role see it. Setting is_default=true demotes any existing default; a cube has exactly one default role at a time.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube this role belongs to."},name:{type:"string",description:'Role name (e.g. "Builder", "Reviewer").'},short_description:{type:"string",description:"One-line summary, shown to every drone in the cube."},detailed_description:{type:"string",description:"Full playbook for drones in this role \u2014 workflow, conventions, log signals to post."},is_default:{type:"boolean",description:"If true, new drones assimilating into this cube are assigned this role. Demotes the previous default."},is_human_seat:{type:"boolean",description:"If true, this role represents the cube's human-occupied seat (where the human Queen sits directly). The class-hierarchy guard in reassign-drone allows promotion FROM a human-seat role TO the platform Queen role; promotion from non-human-seat roles is rejected."},can_broadcast:{type:"boolean",description:"If true, drones in this role may post broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"If true, drones in this role can see direct log entries as observer/audit recipients."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["cube_id","name","short_description","detailed_description"]}},{name:"borg_update-role",description:"Update a role. Pass only the fields that change. Promoting to is_default demotes the previous default in the same cube.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to update."},name:{type:"string",description:"New role name (optional)."},short_description:{type:"string",description:"New short description (optional)."},detailed_description:{type:"string",description:"New detailed playbook (optional)."},is_default:{type:"boolean",description:"Set true to make this the cube's default role (optional)."},is_human_seat:{type:"boolean",description:"Set true/false to mark/unmark this as the cube's human-occupied seat (the elevation source for the platform Queen role)."},can_broadcast:{type:"boolean",description:"Set true/false to allow or deny broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"Set true/false to grant or remove observer visibility into direct log entries."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["role_id"]}},{name:"borg_patch-role-section",description:"Surgically patch ONE named section of a role's detailed_description, leaving the rest of the field byte-identical. Sections are delimited by plain-label lines (e.g. `Workflow:`, `Project conventions:`) \u2014 NOT markdown headings; text before the first label is the preamble. Use this instead of borg_update-role when changing a single section so you don't have to resend (and risk clobbering) the whole playbook. action=replace overwrites a section's body; action=insert adds a new section (optionally after a named one, else appended); action=delete removes a section.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to patch."},action:{type:"string",enum:["replace","insert","delete"],description:"replace / insert / delete a single section."},heading:{type:"string",description:'The section label WITHOUT the trailing colon (e.g. "Workflow"). Matched case-insensitively.'},body:{type:"string",description:"New text BELOW the heading (for replace/insert). Omit for delete."},after:{type:"string",description:"For insert only: place the new section after the section with this heading. Omit/null to append at the end."}},required:["role_id","action","heading"]}},{name:"borg_delete-role",description:"Delete a role. Refuses if any drone is still assigned \u2014 reassign or evict those drones from the dashboard first.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to delete."}},required:["role_id"]}},{name:"borg_reassign-drone",description:"Reassign a drone to a different role in the same cube. Coordinator-shaped: the cube's Coordinator drone is the one expected to call this when dispatching new drones to specific work. Server refuses if you try to assign to the Coordinator role when another drone already holds it (evict or reassign that drone first).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to reassign."},role_id:{type:"string",description:"UUID of the target role. Must belong to the same cube as the drone."}},required:["drone_id","role_id"]}},{name:"borg_evict-drone",description:"Evict (soft-delete) a drone from its cube. Coordinator-shaped: the cube's Coordinator/Queen seat calls this to remove a dead, stuck, or surplus drone \u2014 it drops out of the roster and frees its slot (incl. a held Coordinator/Queen-class seat), while its activity-log history is preserved with anonymized attribution. Owner-scoped: you can only evict drones in cubes you own. Identify the drone EITHER by drone_id (UUID) OR by label + cube_id (the label as it appears in the roster/regen).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to evict. Provide this OR (label + cube_id)."},label:{type:"string",description:'Drone label to evict, e.g. "two-of-seventeen-builder". Requires cube_id. Ignored when drone_id is given.'},cube_id:{type:"string",description:"UUID of the cube the labelled drone belongs to. Required when evicting by label."}}}},{name:"borg_list-drones",description:"List every drone in a cube (owner-scoped). Returns id, label, role_id, agent_kind, last_seen, and wake_path_alert_class for each \u2014 gives the Coordinator a roster they can act on with borg_reassign-drone.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose drones to list."}},required:["cube_id"]}},{name:"borg_list-roles",description:"List every role in a cube (owner-scoped). Returns id, name, short_description, is_default, is_human_seat, can_broadcast, receives_all_direct, and role_class for each \u2014 gives Coordinator-class drones the role UUIDs they need for borg_reassign-drone (e.g. to promote a drone to the Queen role). Closes the gh#153 Queen-role-promotion UX gap (Coordinator drones previously had no way to discover role IDs without operator help).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose roles to list."}},required:["cube_id"]}},{name:"borg_list-templates",description:"List available cube templates that can be applied via borg_apply-template or passed to borg_create-cube.",inputSchema:{type:"object",properties:{}}},{name:"borg_apply-template",description:"Apply a named template to an existing cube, NON-CLOBBERINGLY. Roles are merged by name: new roles are created; existing template-named roles get template sections/classes the cube LACKS auto-applied, but EVOLVED (conflicting) text is preserved, never overwritten. Use this to retrofit an existing cube with a richer role set (e.g. add Coordinator/Reviewer/UX Expert). To review + selectively accept conflicting fragments, use borg_sync-roles (which surfaces each conflict + takes per-fragment accept decisions).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to apply the template to."},template_name:{type:"string",description:"Template to apply (see borg_list-templates)."}},required:["cube_id","template_name"]}},{name:"borg_sync-roles",description:"Non-clobbering sync of a cube's roles + message_taxonomy against the built-in template. Dry-run (default) classifies each fragment (role-text section, short_description, role flags, taxonomy class) as ADD (cube lacks it \u2014 safe auto-apply), UNCHANGED, or CONFLICT (cube has EVOLVED text). On apply, ADDs auto-apply; CONFLICTs apply ONLY via an explicit `decisions` accept (keyed on the dry-run fragment key, e.g. `role:Builder:section:Workflow`); unspecified conflicts default to reject \u2014 evolved text is NEVER silently overwritten. Custom roles untouched.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to sync."},template_name:{type:"string",description:"Template to sync against (default: software-dev)."},apply:{type:"boolean",description:"If true, commit (auto-apply ADDs + accepted conflicts). If false (default), dry-run only \u2014 classify + surface conflicts."},decisions:{type:"object",description:'Per-conflict accept/reject map, keyed on the fragment key from the dry-run (e.g. {"role:Builder:section:Workflow":"accept"}). Unspecified conflicts default to "reject" (keep the cube version).',additionalProperties:{type:"string",enum:["accept","reject"]}}},required:["cube_id"]}},{name:"borg_tool",description:`Dispatcher: invoke ANY borg tool by name, including tools not pre-loaded in your role-scoped surface. Pass {"name":"<borg_tool>","arguments":{...}}. Routes through the identical auth + validation path as a direct call. Call borg_describe-tool first to learn a deferred tool's arguments.`,inputSchema:{type:"object",properties:{name:{type:"string",description:'The borg tool to invoke, e.g. "borg_evict-drone".'},arguments:{type:"object",description:"The arguments object for that tool (same shape as a direct call)."}},required:["name"]}},{name:"borg_describe-tool",description:"Return the description + input schema for any borg tool by name \u2014 including deferred tools not pre-loaded in your surface. Schema-only; never executes the tool. Pair with borg_tool to invoke a deferred tool.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The borg tool to describe."}},required:["name"]}}];p.setRequestHandler(Y,async()=>{let u=null;try{const m=await y();m&&(u={roleName:m.roleName,roleClass:m.roleClass,isHumanSeat:m.isHumanSeat})}catch{u=null}return{tools:Te(_,u)}}),p.setRequestHandler(X,async u=>{let{name:m,arguments:r}=u.params;if(m==="borg_describe-tool"){const e=typeof r?.name=="string"?r.name:"",t=_.find(i=>i.name===e);return t?{content:[{type:"text",text:JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema},null,2)}]}:{content:[{type:"text",text:`Unknown borg tool: ${e||"(none)"}. Pass { name: "<borg_tool>" }.`}],isError:!0}}if(m==="borg_tool"){const e=typeof r?.name=="string"?r.name:"";if(!e||e==="borg_tool"||e==="borg_describe-tool")return{content:[{type:"text",text:'borg_tool: pass { name: "<borg_tool>", arguments: {...} } naming a real borg tool (not the dispatcher itself).'}],isError:!0};r=r?.arguments&&typeof r.arguments=="object"?r.arguments:{},m=e}if(!Je(`tool ${m}`))return{content:[{type:"text",text:Ze(m)}],isError:!0};try{switch(m){case"borg_regen":{const e=await y();if(!e)return{content:[{type:"text",text:'Not connected to a cube. Use `borg_assimilate cube_name="<name>"` to join one.'}]};const t=typeof r?.since=="string"?r.since:void 0,i=r?.mode==="lite"?"lite":"full",o=await T(e.sessionToken,e.apiUrl,{since:t}),s=P(e,o);s!==e&&await A(s);const n=E(),a=q(s.cubeId,s.droneId),c=C()?!0:I(a),d=Le(n,c)?Ae({inboxPath:a,droneLabel:Re(o,s.droneLabel),cubeName:s.name}):"";let b="";try{const h=v(),l=Oe();if(h!=="unknown"&&l!=="unknown"&&l!==h){const[g,R,Q]=h.split(".").map(Number),[k,D,V]=l.split(".").map(Number);(k>g||k===g&&D>R||k===g&&D===R&&V>Q)&&(b=`## \u{1F504} borgmcp ${l} installed \u2014 run /mcp and reconnect (or restart Claude Code) to apply. Currently running ${h}.
|
|
2
|
+
import{Server as K}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Y}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as z,ListToolsRequestSchema as X,ListPromptsRequestSchema as G,GetPromptRequestSchema as J}from"@modelcontextprotocol/sdk/types.js";import{getCubeInfo as Z,getRoleInfo as j,getRoster as ee,readLog as te,appendLog as re,submitReport as oe,ackLogEntry as ie,regen as O,listCubes as ne,createCube as se,updateCube as T,deleteCube as ae,createRole as ce,updateRole as le,patchRoleSection as S,patchTaxonomyClass as P,deleteRole as de,reassignDrone as pe,evictDrone as ue,getCube as w,checkSubscriptionStatus as me,createBillingPortalSession as be,createSubscription as he,syncRoles as ge,applyTemplate as ye,whoami as fe,roleRationale as _e,getValidToken as we}from"./remote-client.js";import{startHealthBeatTick as ve}from"./health-beat.js";import{getTemplate as $,listTemplateNames as E,resolveCubeDirectiveForCreate as xe,resolveCubeDirectiveForApply as ke,resolveMessageTaxonomyForCreate as Se}from"./templates.js";import{activeCubeWithFreshRegenIdentity as A,getActiveCube as y,setActiveCube as N,inboxPathForDrone as U}from"./cubes.js";import{addSessionStartHook as $e,addUserPromptSubmitHook as Ee}from"./config-utils.js";import{humanAgo as L,formatLogEntryMarkdown as Ue,formatRegenMarkdown as M,getDronePlaybook as Ie,getDronePlaybookChapter as Re,nullTaxonomyTip as qe,regenWakePathDroneLabel as Ce}from"./regen-format.js";import{startLogStream as De,getStreamStatus as I}from"./log-stream.js";import{renderRoleList as je}from"./list-roles-render.js";import{filterToolsForRole as Oe}from"./tool-scope.js";import{getPackageVersion as v,getOnDiskVersion as Te,handleVersionFlag as Pe}from"./version.js";import{renderStreamStatus as Ae,checkInboxMonitorHealthy as R,formatWakePathPrefix as Ne,shouldShowWakePathWarning as Le}from"./stream-status.js";import{formatRoleAgentLabel as Me,renderRoster as Be}from"./roster-render.js";import{resolveDroneIdByLabel as We,isUuidShape as Fe}from"./evict-drone.js";import{authRecoveryMessage as He}from"./auth-recovery.js";import{DroneEvictedError as Ve,DroneFrozenError as Qe,formatEvictedToolResult as Ke,formatFrozenToolResult as Ye}from"./drone-lifecycle.js";import{classifyInSessionAssimilate as ze,reattachOnlyRefusal as Xe,reattachFailureMessage as Ge}from"./assimilate-guard.js";import{gateAllowsActivation as Je,borgSessionToolNotice as Ze}from"./launch-gate.js";import{renderSyncRolesResult as et}from"./sync-roles-render.js";import{initConsolePrefix as tt,consolePrefix as x}from"./console-prefix.js";import{isCodexRemoteWakeEnabled as q,resolveSessionAgentKind as rt,probeCodexBridgeArmed as ot}from"./codex-app-wake.js";import{lifecycleSignalForMessage as it,recordLifecycleLog as B,shouldSuppressLifecycleLog as nt}from"./lifecycle-log-guard.js";import{normalizeDirectLogRecipients as st}from"./direct-log.js";import W from"open";import at from"os";function ct(){try{const p=at.hostname();return p&&p.trim()?p.trim().slice(0,255):null}catch{return null}}async function F(p,_){return await ye(p,_.name)}async function f(){const p=await y();if(!p)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");return p}async function lt(){Pe();try{$e()}catch{}try{Ee()}catch{}try{De()}catch{}try{ve({getActiveCube:y,getStreamConnected:()=>I().connected,getInboxPath:u=>U(u.cubeId,u.droneId),checkMonitor:R,isCodexRemoteWake:q,probeBridgeArmed:u=>ot({cubeId:u.cubeId,droneId:u.droneId}),resolveAgentKind:rt,resolveHostname:ct,resolveVersion:v,getToken:we,fetchImpl:globalThis.fetch.bind(globalThis)})}catch{}const p=new K({name:"borg-mcp-client",version:v()},{capabilities:{tools:{},prompts:{}}}),_=[{name:"borg_subscribe",description:"Create Stripe checkout session for Cube tier ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_upgrade-subscription",description:"Open the Stripe Billing Portal to manage Cube tier quantity ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_subscription_status",description:"Check subscription status",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_open_dashboard",description:"Open Borg MCP dashboard in browser to manage cubes, roles, and drones",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_regen",description:"Refresh your context as a Drone. Returns the active cube's directive, your role's detailed playbook, the drone roster, and recent activity log entries \u2014 everything you need to be oriented. Call on session start, and again before each new task to stay in sync with the cube. Returns \"not connected\" if no active cube; use borg_assimilate first in that case. Optional `since` (entry-id UUID or ISO-8601 timestamp) trims the recent-log section to entries strictly after the anchor \u2014 pass your last-seen entry id to skip already-processed history on each refresh.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional cursor. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple) OR an ISO-8601 timestamp. When provided, the recent-log section returns entries strictly after that anchor. Non-existent UUID falls back to default recent window."},mode:{type:"string",enum:["full","lite"],description:"Optional output mode. Use full at session start and after context compaction. Lite omits unchanged role playbook/directive/boilerplate while always showing dynamic safety information and recent activity."}},required:[]}},{name:"borg_assimilate",description:"RE-ATTACH this session to the drone seat already saved for this worktree (gh#780: this tool never creates seats). Provide the cube's name; on a match it returns the cube directive, your role's instructions, and recent activity for the EXISTING seat. To create a seat or switch cubes, run `borg assimilate` in a terminal instead.",inputSchema:{type:"object",properties:{cube_name:{type:"string",description:"The cube to connect to"}},required:["cube_name"]}},{name:"borg_cube",description:"Read the active Cube's directive and the registry of all roles in it (each role's name + short description). Use to remind yourself of cube-wide context.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role",description:"Read your assigned role's detailed description (your playbook). Other drones cannot see this \u2014 only you (drones in this role).",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_version",description:"Returns the installed borgmcp client version. Use to verify which version is running in this MCP session.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_playbook",description:"Load the full operating-playbook chapter \u2014 the detailed disciplines, rationale, and examples behind the rule-spine in your regen (verification discipline v1/v2/v3, concrete source-of-truth surfaces, four-surface propagation). This detail is kept OUT of the regen bootstrap to keep it light; fetch it ONCE per session when doing review/verify-class work. Static text \u2014 do NOT re-fetch on every wake.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_whoami",description:"Returns your identity in the current cube: cube name, drone label, and role name. Use to confirm which cube/role/drone you are.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_role-rationale",description:"Fetch an on-demand rationale/case-study section for a role playbook. Pass a role name/id and a plain-label section key to read the rationale without expanding every regen.",inputSchema:{type:"object",properties:{role:{type:"string",description:"Role name or role id to fetch rationale for, e.g. Builder."},section:{type:"string",description:"Plain-label role section key, e.g. Workflow rationale."}},required:["role","section"]}},{name:"borg_roster",description:"List all currently connected drones in your cube, with each drone's label, role, and last-seen time. Optional `since` argument adds a sender-side liveness column \u2014 pass either an activity_log entry id (e.g., from a dispatch you posted) or an ISO-8601 timestamp; each drone is marked `awake` if they've posted a log entry after that point, otherwise `stale-since-X`. Useful for confirming a dispatch reached its named recipients (catches the silent-wake-path-failure class where SSE delivered but the drone's /loop never woke).",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional liveness reference point. Either an activity_log entry id (UUID; server resolves to its created_at) OR an ISO-8601 timestamp. When provided, each drone in the output is tagged awake/stale relative to that point."}},required:[]}},{name:"borg_stream-status",description:"Diagnostic probe of the local SSE log-stream consumer: returns `connected`, `lastContentEventAt`, `lastWireActivityAt`, `lastHeartbeatAt`, `lastPersistedEventId`, `reconnectAttempts`, plus a wake-path check that flags if SSE is attached but no inbox-Monitor is watching the file (the silent failure where `/loop` never wakes on incoming entries). Read-only in-process state; does NOT re-open the stream. Use when troubleshooting wake-ups or verifying the stream is alive.",inputSchema:{type:"object",properties:{},required:[]}},{name:"borg_read-log",description:"Read entries from the cube's activity log. Each entry is tagged with the drone that wrote it and that drone's role. For wake triage, prefer `unread_only=true` with a modest limit and drain until `has_more=false`; this reads oldest-unread-first from your server cursor and advances the watermark so bursts are not skipped. Optional `since` is a strict-after cursor for explicit bounded reads only; do not use it with the same timestamp as a notification preview because it can skip the boundary entry.",inputSchema:{type:"object",properties:{since:{type:"string",description:"Optional strict-after cursor for explicit bounded reads. Either an activity_log entry id (UUID; server resolves to (created_at, id) tuple for deterministic tie-break) OR an ISO-8601 timestamp. Do not use for routine wake triage; prefer unread_only."},limit:{type:"number",description:"max entries to return (1-500)"},unread_only:{type:"boolean",description:"When true, read only entries posted after this drone last called read-log, oldest-unread-first. Server advances the watermark to the newest returned entry on every call; if has_more=true, call again until has_more=false."}}}},{name:"borg_ack",description:'Mark a log entry as explicitly acknowledged (kind="ack", default), or claim advisory ownership of a review gate before starting (kind="claim"). Recorded as a queryable DB flag (activity_log_acks) keyed on (entry_id, drone_id, kind); idempotent \u2014 repeated calls are no-ops. ack = receipt of a routed signal (replaces posting `ACK: <dispatch-id>`); claim = announce you are taking a REVIEW-READY so peers skip it (advisory only \u2014 merge eligibility stays keyed on REVIEW-APPROVED, never on a claim).',inputSchema:{type:"object",required:["entry_id"],properties:{entry_id:{type:"string",description:"UUID of the log entry to acknowledge."},kind:{type:"string",enum:["ack","claim"],description:'Coordination kind. "ack" (default) = receipt. "claim" = advisory ownership of a review gate on a REVIEW-READY entry (wakes the gate audience; renders stale if you go silent past the wake-path SLA).'}}}},{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, the 8-hex short-uuid (the `id:` token shown in roster/read-log \u2014 a drone_id prefix that is STABLE across label renumber), 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, the 8-hex short-uuid (`id:` token from roster/read-log; stable across label renumber), role name, or role slug (resolves to all drones in that role). Omit to let class-based routing or broadcast defaults apply."},class:{type:"string",description:"Optional declared message class. Overrides prefix auto-classification when the cube declares a message taxonomy."},visibility:{type:"string",enum:["broadcast","direct"],description:"Optional explicit visibility. Overrides class-based routing defaults."}},required:["message"]}},{name:"borg_report-friction",description:"Report friction or a bug directly to the borgmcp dev team. WRITE-ONLY \u2014 you cannot read reports back. Use it when something about borg itself slowed you down, confused you, or broke: awkward UX, an unclear playbook, a missing affordance, or a bug you hit while using borg. Secrets (tokens, keys) are auto-scrubbed server-side before storage, but avoid pasting them anyway.",inputSchema:{type:"object",properties:{message:{type:"string",description:"What hit you + what you expected instead (max 10KB). Concrete and specific helps the dev team most."},kind:{type:"string",enum:["friction","bug"],description:"'friction' (default) for UX/workflow friction; 'bug' for something broken."},metadata:{type:"object",description:"Optional non-secret context. Allowed keys only: version, cube_id, os. Any other key is rejected."}},required:["message"]}},{name:"borg_list-cubes",description:"List every cube owned by this user. Returns id, name, cube_directive, and timestamps for each. Useful before assimilate to see what's available, or as a starting point for any management action.",inputSchema:{type:"object",properties:{}}},{name:"borg_create-cube",description:'Create a new cube. The server seeds a default "Drone" role atomically so the cube is assimilatable immediately. Pass an optional `template` name to apply a richer role set instead (see borg_list-templates / borg_apply-template).',inputSchema:{type:"object",properties:{name:{type:"string",description:"Cube name (lowercase letters, digits, hyphens; max 64 chars).",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"Markdown text every drone in this cube will see in regen. Anything project-specific."},template:{type:"string",description:'Optional template name to apply after cube creation (e.g. "software-dev"). Roles are merged by name; the default Drone role gets overwritten by the template if a same-named role is in the template.'}},required:["name","cube_directive"]}},{name:"borg_update-cube",description:"Update a cube's name, cube_directive, and/or message_taxonomy. Pass only what changes.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to update."},name:{type:"string",description:"New name (optional). Lowercase letters, digits, hyphens; max 64 chars.",pattern:"^[a-z0-9-]+$",maxLength:64},cube_directive:{type:"string",description:"New cube directive markdown (optional)."},message_taxonomy:{type:"array",description:"New message-class taxonomy (optional). REPLACES the whole taxonomy; the worker re-validates the full array (non-overlapping prefixes, unique class names, directed classes need default_to). Pass [] to clear. To change ONE class without resending the whole array, use borg_patch-taxonomy-class instead. In default_to, pass @human-seat to route to drones in the cube human-seat role(s); literal role names/slugs/labels still work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",items:{type:"object",properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (role name/slug/label, or @human-seat) for a directed class."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}}}}},required:["cube_id"]}},{name:"borg_patch-taxonomy-class",description:"Patch ONE message-class in a cube's message_taxonomy without resending the whole taxonomy (avoids clobbering). action=add|replace|remove (replace/remove match name case-insensitively). The full taxonomy is re-validated after the patch (non-overlapping prefixes, unique names, directed classes need default_to) \u2014 a patch that breaks a rule against an untouched class is rejected. In default_to, @human-seat routes to the cube's human-seat role(s); literal names/slugs/labels also work. Optional lifecycle tags mark dispatch/completion classes for stuck-dispatch detection.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to patch."},action:{type:"string",enum:["add","replace","remove"],description:"add / replace / remove a single class."},class_def:{type:"object",description:'The class definition (for add/replace). Shape: { class, prefixes?, routing: "broadcast"|"directed", default_to?, lifecycle? }.',properties:{class:{type:"string",description:"Unique class name."},prefixes:{type:"array",items:{type:"string"},description:"Message prefixes routed by this class."},routing:{type:"string",enum:["broadcast","directed"],description:"Routing mode."},default_to:{type:"array",items:{type:"string"},description:"Default recipients (required for directed classes): role name/slug/label, or @human-seat."},lifecycle:{type:"string",enum:["dispatch","completion"],description:"Optional lifecycle marker for stuck-dispatch detection."}},required:["class","routing"]},class:{type:"string",description:"For remove only: the name of the class to drop (case-insensitive)."}},required:["cube_id","action"]}},{name:"borg_delete-cube",description:"Delete a cube and all its roles, drones, and log entries. Irreversible \u2014 confirm with the user before invoking unless the cube is clearly disposable.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to delete."}},required:["cube_id"]}},{name:"borg_create-role",description:"Create a role inside a cube. The detailed_description is the role's playbook \u2014 only drones assigned to this role see it. Setting is_default=true demotes any existing default; a cube has exactly one default role at a time.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube this role belongs to."},name:{type:"string",description:'Role name (e.g. "Builder", "Reviewer").'},short_description:{type:"string",description:"One-line summary, shown to every drone in the cube."},detailed_description:{type:"string",description:"Full playbook for drones in this role \u2014 workflow, conventions, log signals to post."},is_default:{type:"boolean",description:"If true, new drones assimilating into this cube are assigned this role. Demotes the previous default."},is_human_seat:{type:"boolean",description:"If true, this role represents the cube's human-occupied seat (where the human Queen sits directly). The class-hierarchy guard in reassign-drone allows promotion FROM a human-seat role TO the platform Queen role; promotion from non-human-seat roles is rejected."},can_broadcast:{type:"boolean",description:"If true, drones in this role may post broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"If true, drones in this role can see direct log entries as observer/audit recipients."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["cube_id","name","short_description","detailed_description"]}},{name:"borg_update-role",description:"Update a role. Pass only the fields that change. Promoting to is_default demotes the previous default in the same cube.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to update."},name:{type:"string",description:"New role name (optional)."},short_description:{type:"string",description:"New short description (optional)."},detailed_description:{type:"string",description:"New detailed playbook (optional)."},is_default:{type:"boolean",description:"Set true to make this the cube's default role (optional)."},is_human_seat:{type:"boolean",description:"Set true/false to mark/unmark this as the cube's human-occupied seat (the elevation source for the platform Queen role)."},can_broadcast:{type:"boolean",description:"Set true/false to allow or deny broadcast log entries when strict broadcast gating is enabled."},receives_all_direct:{type:"boolean",description:"Set true/false to grant or remove observer visibility into direct log entries."},default_model:{type:"string",description:'Default model for drones assigned to this role (e.g., "claude:claude-opus-4-8" or "ollama:qwen3-coder-next:q4_K_M"). Null = inherit from cube. Optional.'}},required:["role_id"]}},{name:"borg_patch-role-section",description:"Surgically patch ONE named section of a role's detailed_description, leaving the rest of the field byte-identical. Sections are delimited by plain-label lines (e.g. `Workflow:`, `Project conventions:`) \u2014 NOT markdown headings; text before the first label is the preamble. Use this instead of borg_update-role when changing a single section so you don't have to resend (and risk clobbering) the whole playbook. action=replace overwrites a section's body; action=insert adds a new section (optionally after a named one, else appended); action=delete removes a section.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to patch."},action:{type:"string",enum:["replace","insert","delete"],description:"replace / insert / delete a single section."},heading:{type:"string",description:'The section label WITHOUT the trailing colon (e.g. "Workflow"). Matched case-insensitively.'},body:{type:"string",description:"New text BELOW the heading (for replace/insert). Omit for delete."},after:{type:"string",description:"For insert only: place the new section after the section with this heading. Omit/null to append at the end."}},required:["role_id","action","heading"]}},{name:"borg_delete-role",description:"Delete a role. Refuses if any drone is still assigned \u2014 reassign or evict those drones from the dashboard first.",inputSchema:{type:"object",properties:{role_id:{type:"string",description:"UUID of the role to delete."}},required:["role_id"]}},{name:"borg_reassign-drone",description:"Reassign a drone to a different role in the same cube. Coordinator-shaped: the cube's Coordinator drone is the one expected to call this when dispatching new drones to specific work. Server refuses if you try to assign to the Coordinator role when another drone already holds it (evict or reassign that drone first).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to reassign."},role_id:{type:"string",description:"UUID of the target role. Must belong to the same cube as the drone."}},required:["drone_id","role_id"]}},{name:"borg_evict-drone",description:"Evict (soft-delete) a drone from its cube. Coordinator-shaped: the cube's Coordinator/Queen seat calls this to remove a dead, stuck, or surplus drone \u2014 it drops out of the roster and frees its slot (incl. a held Coordinator/Queen-class seat), while its activity-log history is preserved with anonymized attribution. Owner-scoped: you can only evict drones in cubes you own. Identify the drone EITHER by drone_id (UUID) OR by label + cube_id (the label as it appears in the roster/regen).",inputSchema:{type:"object",properties:{drone_id:{type:"string",description:"UUID of the drone to evict. Provide this OR (label + cube_id)."},label:{type:"string",description:'Drone label to evict, e.g. "two-of-seventeen-builder". Requires cube_id. Ignored when drone_id is given.'},cube_id:{type:"string",description:"UUID of the cube the labelled drone belongs to. Required when evicting by label."}}}},{name:"borg_list-drones",description:"List every drone in a cube (owner-scoped). Returns id, label, role_id, agent_kind, last_seen, and wake_path_alert_class for each \u2014 gives the Coordinator a roster they can act on with borg_reassign-drone.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose drones to list."}},required:["cube_id"]}},{name:"borg_list-roles",description:"List every role in a cube (owner-scoped). Returns id, name, short_description, is_default, is_human_seat, can_broadcast, receives_all_direct, and role_class for each \u2014 gives Coordinator-class drones the role UUIDs they need for borg_reassign-drone (e.g. to promote a drone to the Queen role). Closes the gh#153 Queen-role-promotion UX gap (Coordinator drones previously had no way to discover role IDs without operator help).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube whose roles to list."}},required:["cube_id"]}},{name:"borg_list-templates",description:"List available cube templates that can be applied via borg_apply-template or passed to borg_create-cube.",inputSchema:{type:"object",properties:{}}},{name:"borg_apply-template",description:"Apply a named template to an existing cube, NON-CLOBBERINGLY. Roles are merged by name: new roles are created; existing template-named roles get template sections/classes the cube LACKS auto-applied, but EVOLVED (conflicting) text is preserved, never overwritten. Use this to retrofit an existing cube with a richer role set (e.g. add Coordinator/Reviewer/UX Expert). To review + selectively accept conflicting fragments, use borg_sync-roles (which surfaces each conflict + takes per-fragment accept decisions).",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to apply the template to."},template_name:{type:"string",description:"Template to apply (see borg_list-templates)."}},required:["cube_id","template_name"]}},{name:"borg_sync-roles",description:"Non-clobbering sync of a cube's roles + message_taxonomy against the built-in template. Dry-run (default) classifies each fragment (role-text section, short_description, role flags, taxonomy class) as ADD (cube lacks it \u2014 safe auto-apply), UNCHANGED, or CONFLICT (cube has EVOLVED text). On apply, ADDs auto-apply; CONFLICTs apply ONLY via an explicit `decisions` accept (keyed on the dry-run fragment key, e.g. `role:Builder:section:Workflow`); unspecified conflicts default to reject \u2014 evolved text is NEVER silently overwritten. Custom roles untouched.",inputSchema:{type:"object",properties:{cube_id:{type:"string",description:"UUID of the cube to sync."},template_name:{type:"string",description:"Template to sync against (default: software-dev)."},apply:{type:"boolean",description:"If true, commit (auto-apply ADDs + accepted conflicts). If false (default), dry-run only \u2014 classify + surface conflicts."},decisions:{type:"object",description:'Per-conflict accept/reject map, keyed on the fragment key from the dry-run (e.g. {"role:Builder:section:Workflow":"accept"}). Unspecified conflicts default to "reject" (keep the cube version).',additionalProperties:{type:"string",enum:["accept","reject"]}}},required:["cube_id"]}},{name:"borg_tool",description:`Dispatcher: invoke ANY borg tool by name, including tools not pre-loaded in your role-scoped surface. Pass {"name":"<borg_tool>","arguments":{...}}. Routes through the identical auth + validation path as a direct call. Call borg_describe-tool first to learn a deferred tool's arguments.`,inputSchema:{type:"object",properties:{name:{type:"string",description:'The borg tool to invoke, e.g. "borg_evict-drone".'},arguments:{type:"object",description:"The arguments object for that tool (same shape as a direct call)."}},required:["name"]}},{name:"borg_describe-tool",description:"Return the description + input schema for any borg tool by name \u2014 including deferred tools not pre-loaded in your surface. Schema-only; never executes the tool. Pair with borg_tool to invoke a deferred tool.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The borg tool to describe."}},required:["name"]}}];p.setRequestHandler(X,async()=>{let u=null;try{const m=await y();m&&(u={roleName:m.roleName,roleClass:m.roleClass,isHumanSeat:m.isHumanSeat})}catch{u=null}return{tools:Oe(_,u)}}),p.setRequestHandler(z,async u=>{let{name:m,arguments:r}=u.params;if(m==="borg_describe-tool"){const e=typeof r?.name=="string"?r.name:"",t=_.find(o=>o.name===e);return t?{content:[{type:"text",text:JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema},null,2)}]}:{content:[{type:"text",text:`Unknown borg tool: ${e||"(none)"}. Pass { name: "<borg_tool>" }.`}],isError:!0}}if(m==="borg_tool"){const e=typeof r?.name=="string"?r.name:"";if(!e||e==="borg_tool"||e==="borg_describe-tool")return{content:[{type:"text",text:'borg_tool: pass { name: "<borg_tool>", arguments: {...} } naming a real borg tool (not the dispatcher itself).'}],isError:!0};r=r?.arguments&&typeof r.arguments=="object"?r.arguments:{},m=e}if(!Je(`tool ${m}`))return{content:[{type:"text",text:Ze(m)}],isError:!0};try{switch(m){case"borg_regen":{const e=await y();if(!e)return{content:[{type:"text",text:'Not connected to a cube. Use `borg_assimilate cube_name="<name>"` to join one.'}]};const t=typeof r?.since=="string"?r.since:void 0,o=r?.mode==="lite"?"lite":"full",i=await O(e.sessionToken,e.apiUrl,{since:t}),s=A(e,i);s!==e&&await N(s);const n=I(),a=U(s.cubeId,s.droneId),c=q()?!0:R(a),d=Le(n,c)?Ne({inboxPath:a,droneLabel:Ce(i,s.droneLabel),cubeName:s.name}):"";let b="";try{const h=v(),l=Te();if(h!=="unknown"&&l!=="unknown"&&l!==h){const[g,C,V]=h.split(".").map(Number),[k,D,Q]=l.split(".").map(Number);(k>g||k===g&&D>C||k===g&&D===C&&Q>V)&&(b=`## \u{1F504} borgmcp ${l} installed \u2014 run /mcp and reconnect (or restart Claude Code) to apply. Currently running ${h}.
|
|
3
3
|
|
|
4
|
-
`)}}catch{}return{content:[{type:"text",text:b+d+M(
|
|
5
|
-
`)+M(
|
|
4
|
+
`)}}catch{}return{content:[{type:"text",text:b+d+M(i,{mode:o})}]}}case"borg_subscribe":return{content:[{type:"text",text:`Complete your subscription at: ${await he()}`}]};case"borg_upgrade-subscription":{const e=await be();try{await W(e)}catch{}return{content:[{type:"text",text:`Manage your Borg MCP subscription at: ${e}`}]}}case"borg_subscription_status":{const e=await me();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}case"borg_open_dashboard":{const e="https://borgmcp.ai/dashboard";return await 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(),o=ze(t,e);if(o.kind!=="reattach")return{content:[{type:"text",text:Xe(o,e)}],isError:!0};try{const i=await O(t.sessionToken,t.apiUrl,{}),s=A(t,i);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(i,{mode:"full"})}]}}catch(i){const s=Ge(i??{});if(!s)throw i;return{content:[{type:"text",text:s}],isError:!0}}}case"borg_version":return{content:[{type:"text",text:`borgmcp ${v()}`}]};case"borg_playbook":return{content:[{type:"text",text:Re()}]};case"borg_whoami":{const e=await f(),t=await fe(e.sessionToken,e.apiUrl);return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}case"borg_cube":{const e=await f(),[{cube:t,roles:o}]=await Promise.all([Z(e.sessionToken,e.apiUrl),j(e.sessionToken,e.apiUrl)]),i=[];i.push(`# Cube: ${t.name}`),i.push(""),i.push("## Cube directive"),i.push(t.cube_directive||"_(none)_"),i.push("");const s=qe(t.message_taxonomy);if(s&&(i.push(s),i.push("")),i.push("## Roles in this cube"),!o.length)i.push("_(no roles defined)_");else{for(const n of o){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)_";i.push(`- **${n.name}**${c} \u2014 ${d}`)}i.push(""),i.push("_(Coordinator-class drones can fetch role IDs via `borg_list-roles` for use with `borg_reassign-drone`.)_")}return i.push(""),i.push(Ie()),{content:[{type:"text",text:i.join(`
|
|
6
6
|
`)}]}}case"borg_role":{const e=await f(),{role:t}=await j(e.sessionToken,e.apiUrl);return{content:[{type:"text",text:[`# Your role: ${t.name}`,"",t.detailed_description||"_(no detailed description set)_"].join(`
|
|
7
|
-
`)}]}}case"borg_role-rationale":{const e=await f(),t=typeof r?.role=="string"?r.role:"",
|
|
8
|
-
`)}]}}case"borg_roster":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,{drones:
|
|
7
|
+
`)}]}}case"borg_role-rationale":{const e=await f(),t=typeof r?.role=="string"?r.role:"",o=typeof r?.section=="string"?r.section:"",i=await _e(e.sessionToken,e.apiUrl,t,o);return{content:[{type:"text",text:[`# Role rationale: ${i.role} \u2014 ${i.section}`,"",i.body||"_(empty)_"].join(`
|
|
8
|
+
`)}]}}case"borg_roster":{const e=await f(),t=typeof r?.since=="string"?r.since:void 0,{drones:o,roles:i,since:s}=await ee(e.sessionToken,e.apiUrl,t);return{content:[{type:"text",text:Be({cubeName:e.name,drones:o,roles:i,resolvedSince:s??null,humanAgo:L})}]}}case"borg_stream-status":{const e=I(),t=await y(),o=t?U(t.cubeId,t.droneId):null,i=t?q()?!0:R(o):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 y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");if(it(e)){const l=await nt(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
|
|
12
|
+
`);const n=Ae({status:e,inboxMonitorHealthy:i,inboxPath:o,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,o=typeof r?.limit=="number"?r.limit:void 0,i=r?.unread_only===!0||r?.unread_only==="true",{entries:s,drones:n,roles:a,behind_by:c,has_more:d}=await te(e.sessionToken,e.apiUrl,{since:t,limit:o,unreadOnly:i}),b=new Map;for(const g of n)b.set(g.id,g);const h=new Map;for(const g of a)h.set(g.id,g);const l=[];if(l.push(`# Activity log: ${e.name}`),l.push(""),!s.length)l.push("_(no entries)_");else for(const g of s)l.push(Ue(g,b,h));return d===!0?(l.push(""),l.push("\u26A0 has_more: true \u2014 call `borg_read-log unread_only=true` again until has_more=false so you finish draining unread entries.")):typeof c=="number"&&c>0&&(l.push(""),l.push(`\u26A0 behind_by: ${c} more unread ${c===1?"entry":"entries"} addressed to you \u2014 call \`borg_read-log unread_only=true\` again until behind_by=0 so you don't skip messages.`)),{content:[{type:"text",text:l.join(`
|
|
13
|
+
`)}]}}case"borg_log":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");if(it(e)){const l=await nt(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 o=Object.prototype.hasOwnProperty.call(r??{},"to"),i=o?st(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}:{},...o?{to:i??[]}:{},...n?{visibility:n}:{}},c=await re(t.sessionToken,t.apiUrl,e,a);await B(t,e);const d=c.routing?.message?`
|
|
14
14
|
${c.routing.message}`:"",b=c.unreachableRecipients?.length?`
|
|
15
|
-
\u26A0 ${c.unreachableRecipients.length} directed recipient(s) currently unreachable (wake-path:deaf): ${c.unreachableRecipients.map(l=>l.label).join(", ")}. Message delivered \u2014 they'll read it when they return.`:"";return{content:[{type:"text",text:`Logged to cube "${t.name}" as ${t.droneLabel}. (entry id: ${c.entry.id})${d}${b}`}]}}case"borg_report-friction":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");const
|
|
16
|
-
${(
|
|
15
|
+
\u26A0 ${c.unreachableRecipients.length} directed recipient(s) currently unreachable (wake-path:deaf): ${c.unreachableRecipients.map(l=>l.label).join(", ")}. Message delivered \u2014 they'll read it when they return.`:"";return{content:[{type:"text",text:`Logged to cube "${t.name}" as ${t.droneLabel}. (entry id: ${c.entry.id})${d}${b}`}]}}case"borg_report-friction":{const e=r?.message;if(!e||typeof e!="string")throw new Error("message is required");const t=await y();if(!t)throw new Error("Not assimilated to a cube. Use borg_assimilate <cube-name> first.");const o=r?.kind==="bug"?"bug":"friction",i=r?.metadata&&typeof r.metadata=="object"&&!Array.isArray(r.metadata)?r.metadata:void 0;return{content:[{type:"text",text:(await oe(t.sessionToken,t.apiUrl,{kind:o,message:e,metadata:i})).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=r?.kind==="claim"?"claim":"ack",o=await f();return await ie(o.sessionToken,o.apiUrl,e,t),{content:[{type:"text",text:t==="claim"?`Claimed entry ${e} in cube "${o.name}" (advisory \u2014 merge stays keyed on REVIEW-APPROVED).`:`Acked entry ${e} in cube "${o.name}".`}]}}case"borg_list-cubes":{const{cubes:e}=await ne();if(!e.length)return{content:[{type:"text",text:"No cubes yet. Use borg_create-cube to make your first one."}]};const t=e.map(o=>`- **${o.name}** (id: ${o.id})
|
|
16
|
+
${(o.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,
|
|
21
|
+
`)}`}]}}case"borg_create-cube":{const e=r?.name,t=r?.cube_directive,o=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 i=null;if(o&&(i=$(o),!i))throw new Error(`Unknown template "${o}". Available: ${E().join(", ")}`);const s=xe(t,i),n=Se(void 0,i),a=await se(e,s,{message_taxonomy:n});if(i){const d=await F(a.id,i),b=s!==t?" Template cube directive applied (operator passed empty).":"";return{content:[{type:"text",text:`Created cube **${a.name}** (id: ${a.id}) with template **${o}** applied \u2014 ${d.created} role(s) created, ${d.updated} updated.${b} Use borg_assimilate ${a.name} to join as a drone.`}]}}return{content:[{type:"text",text:`Created cube **${a.name}** (id: ${a.id}). A default "Drone" role was seeded \u2014 rename or replace it via borg_update-role / borg_create-role / borg_delete-role. Use borg_assimilate ${a.name} to join as a drone.`}]}}case"borg_update-cube":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const t={};if(typeof r?.name=="string"&&(t.name=r.name),typeof r?.cube_directive=="string"&&(t.cube_directive=r.cube_directive),Array.isArray(r?.message_taxonomy)&&(t.message_taxonomy=r.message_taxonomy),Object.keys(t).length===0)throw new Error("Pass at least one of: name, cube_directive, message_taxonomy.");const{cube:o}=await T(e,t);return{content:[{type:"text",text:`Updated cube **${o.name}** (id: ${o.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 o,i;if(t==="remove"){const n=r?.class;if(!n)throw new Error("class is required for remove.");({cube:o}=await P(e,{action:t,class:n})),i=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:o}=await P(e,{action:t,class_def:n})),i=String(n.class??"")}return{content:[{type:"text",text:`${t==="add"?"Added":t==="replace"?"Replaced":"Removed"} taxonomy class **${i}** in cube **${o.name}** (id: ${o.id}).`}]}}case"borg_delete-cube":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");return await ae(e),{content:[{type:"text",text:`Deleted cube ${e} (and all its roles, drones, log entries).`}]}}case"borg_create-role":{const e=r?.cube_id,t=r?.name,o=r?.short_description,i=r?.detailed_description;if(!e)throw new Error("cube_id is required");if(!t)throw new Error("name is required");if(o===void 0)throw new Error("short_description is required (pass empty string if none)");if(i===void 0)throw new Error("detailed_description is required (pass empty string if none)");const s=r?.is_default===!0,n=r?.is_human_seat===!0,a=r?.can_broadcast===!0,c=r?.receives_all_direct===!0,{role:d}=await ce(e,{name:t,short_description:o,detailed_description:i,is_default:s,is_human_seat:n,can_broadcast:a,receives_all_direct:c,...typeof r?.default_model=="string"?{default_model:r.default_model}:{}}),b=[d.role_class==="queen"?"Queen":null,d.is_human_seat?"human-seat":null,d.is_default?"default":null].filter(Boolean).join(", "),h=b?` (${b})`:"";return{content:[{type:"text",text:`Created role **${d.name}**${h} (id: ${d.id}) in cube ${e}.`}]}}case"borg_update-role":{const e=r?.role_id;if(!e)throw new Error("role_id is required");const t={};if(typeof r?.name=="string"&&(t.name=r.name),typeof r?.short_description=="string"&&(t.short_description=r.short_description),typeof r?.detailed_description=="string"&&(t.detailed_description=r.detailed_description),typeof r?.is_default=="boolean"&&(t.is_default=r.is_default),typeof r?.is_human_seat=="boolean"&&(t.is_human_seat=r.is_human_seat),typeof r?.can_broadcast=="boolean"&&(t.can_broadcast=r.can_broadcast),typeof r?.receives_all_direct=="boolean"&&(t.receives_all_direct=r.receives_all_direct),typeof r?.default_model=="string"&&(t.default_model=r.default_model),Object.keys(t).length===0)throw new Error("Pass at least one of: name, short_description, detailed_description, is_default, is_human_seat, can_broadcast, receives_all_direct, default_model.");const{role:o}=await le(e,t),i=[o.role_class==="queen"?"Queen":null,o.is_human_seat?"human-seat":null,o.is_default?"default":null].filter(Boolean).join(", "),s=i?` (${i})`:"";return{content:[{type:"text",text:`Updated role **${o.name}**${s} (id: ${o.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 o=r?.heading;if(!o)throw new Error("heading is required");let i;if(t==="delete")({role:i}=await S(e,{action:t,heading:o}));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:i}=await S(e,{action:t,heading:o,body:n,after:a}))}else({role:i}=await S(e,{action:t,heading:o,body:n}))}return{content:[{type:"text",text:`${t==="replace"?"Replaced":t==="insert"?"Inserted":"Deleted"} section **${o}** in role **${i.name}** (id: ${i.id}).`}]}}case"borg_delete-role":{const e=r?.role_id;if(!e)throw new Error("role_id is required");return await de(e),{content:[{type:"text",text:`Deleted role ${e}.`}]}}case"borg_reassign-drone":{const e=r?.drone_id,t=r?.role_id;if(!e)throw new Error("drone_id is required");if(!t)throw new Error("role_id is required");const{drone:o}=await pe(e,t);return{content:[{type:"text",text:`Reassigned drone ${o.label} (${o.id}) to role ${o.role_id}.`}]}}case"borg_evict-drone":{const e=r?.drone_id?.trim(),t=r?.label?.trim(),o=r?.cube_id?.trim();let i,s;if(e){if(!Fe(e))throw new Error(`drone_id "${e}" is not a UUID \u2014 if that's a drone label, pass it as label + cube_id instead.`);i=e,s=e}else if(t){if(!o)throw new Error("cube_id is required when evicting by label");const{drones:n}=await w(o),a=We(n,t);if(!a)throw new Error(`No active drone labelled "${t}" in cube ${o} (it may already be evicted; check borg_list-drones).`);i=a.id,s=a.label}else throw new Error("Provide drone_id, or label + cube_id, to identify the drone to evict");return await ue(i),{content:[{type:"text",text:`Evicted drone ${s} (${i}). 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:o}=await w(e);if(!t.length)return{content:[{type:"text",text:"No drones in this cube yet."}]};const i=new Map(o.map(n=>[n.id,n])),s=t.map(n=>{const a=i.get(n.role_id),c=Me(a?.name??"?",n.agent_kind),d=n.wake_path_alert_class&&n.wake_path_alert_class!=="independent"?` \u2014 wake-path-class: ${n.wake_path_alert_class}`:"";return`- **${n.label}** (id: ${n.id}) \u2014 role: ${c} (${n.role_id}) \u2014 last seen ${n.last_seen}${d}`});return{content:[{type:"text",text:`Drones in cube ${e} (${t.length}):
|
|
22
22
|
|
|
23
23
|
${s.join(`
|
|
24
24
|
`)}`}]}}case"borg_list-roles":{const e=r?.cube_id;if(!e)throw new Error("cube_id is required");const{roles:t}=await w(e);return{content:[{type:"text",text:je(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",
|
|
26
|
+
${E().map(o=>{const i=$(o);return`- **${o}**: ${i.description}`}).join(`
|
|
27
|
+
`)}`}]};case"borg_sync-roles":{const e=r?.cube_id,t=r?.template_name||"software-dev",o=r?.apply===!0,i=r?.decisions&&typeof r.decisions=="object"?r.decisions:void 0;if(!e)throw new Error("cube_id is required");const s=await ge(e,t,o,i);return{content:[{type:"text",text:et(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 o=$(t);if(!o)throw new Error(`Unknown template "${t}". Available: ${E().join(", ")}`);const i=await F(e,o);let s="";const n=await w(e),a=ke(n.cube_directive,o);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 ${i.created} role(s) created, ${i.updated} updated.${s}`}]}}default:throw new Error(`Unknown tool: ${m}`)}}catch(e){if(e instanceof Ve)return{content:[{type:"text",text:Ke(e.message)}],isError:!0};if(e instanceof Qe)return{content:[{type:"text",text:Ye(e.message)}],isError:!0};const t=He(e??{});return t?{content:[{type:"text",text:t}],isError:!0}:{content:[{type:"text",text:`Error: ${e.message}`}],isError:!0}}}),p.setRequestHandler(G,async()=>({prompts:[{name:"borg_subscribe",description:"Set up Borg MCP Cube tier subscription ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial."},{name:"dashboard",description:"Open Borg MCP dashboard to manage cubes"}]})),p.setRequestHandler(J,async u=>{const{name:m}=u.params;switch(m){case"borg_subscribe":return{description:"Set up Borg MCP Cube tier subscription ($1/month per cube; each cube adds 8 pooled agent sessions + 1000 req/hr). Free tier is permanent (1 cube + 3 agent sessions + 100 req/hr); no trial.",messages:[{role:"user",content:{type:"text",text:"Please help me set up a Borg MCP subscription using the subscribe tool."}}]};case"dashboard":return{description:"Open Borg MCP dashboard to manage cubes",messages:[{role:"user",content:{type:"text",text:"Please open the Borg MCP dashboard using the borg_open_dashboard tool."}}]};default:throw new Error(`Unknown prompt: ${m}`)}});const H=new Y;await p.connect(H),await tt(),console.error(`${x()}\u25FC Borg MCP Client started`),console.error(`${x()}\u25FC Use borg_assimilate <cube-name> to join a cube as a drone`),console.error(`${x()}\u25FC Manage your cubes at https://borgmcp.ai/dashboard`)}lt().catch(p=>{console.error(`${x()}Fatal error:`,p),process.exit(1)});
|
package/dist/launch-all-cmd.js
CHANGED
|
@@ -1,33 +1,37 @@
|
|
|
1
|
-
import{discoverDroneCandidates as
|
|
1
|
+
import{discoverDroneCandidates as A}from"./launch-all-discovery.js";import{resolveBorgPath as x}from"./launch-all-command.js";import{sweepStaleLocks as I,isLockLive as S}from"./launch-all-locks.js";import{runTmuxBackend as D}from"./backends/launch-all-tmux.js";import{runWindowsBackend as T}from"./backends/launch-all-windows.js";import{runPastelistBackend as N}from"./backends/launch-all-pastelist.js";const L=`borg launch-all: tmux not found.
|
|
2
2
|
macOS: brew install tmux
|
|
3
3
|
Debian: sudo apt install tmux
|
|
4
4
|
Fedora: sudo dnf install tmux
|
|
5
|
-
`;function p(
|
|
6
|
-
`)
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
`),e.
|
|
10
|
-
`)
|
|
11
|
-
`),
|
|
12
|
-
`),
|
|
13
|
-
`))
|
|
14
|
-
`)
|
|
15
|
-
`);
|
|
16
|
-
`),
|
|
17
|
-
`)
|
|
18
|
-
`);
|
|
19
|
-
`);continue}
|
|
20
|
-
`),
|
|
21
|
-
`),0;
|
|
22
|
-
`);
|
|
23
|
-
`);
|
|
24
|
-
`),
|
|
25
|
-
`),
|
|
26
|
-
`)
|
|
5
|
+
`;function p(t){try{return t.runSync("tmux",["-V"]),!0}catch{return!1}}function _(t){try{return/microsoft|wsl/i.test(t.runSync("uname",["-r"]))}catch{return!1}}function C(t){return/^drone-\d+$/i.test(t)||t.toLowerCase()==="drone"}async function M(t,e){if(t.cubeName!==void 0){const a=(await e.readAllProjectIdentities()).filter(l=>l.cube.name===t.cubeName);if(a.length===0)return{error:`no cube named '${t.cubeName}' found in cubes.json \u2014 has any drone assimilated into it?`};if(a.length>1){const l=a.map(m=>` ${m.cube.cubeId} (seat in ${m.projectPath})`).join(`
|
|
6
|
+
`);return{error:`'${t.cubeName}' is ambiguous \u2014 ${a.length} cubes in cubes.json share that name:
|
|
7
|
+
${l}
|
|
8
|
+
cd into the intended project and re-run without --cube-name (resolves the active cube), or remove the stale seat(s) from cubes.json.`}}return{cubeId:a[0].cube.cubeId,name:t.cubeName}}const r=await e.getActiveCube();return r?{cubeId:r.cubeId,name:r.name}:{error:"no active cube in this directory; run `borg assimilate` first, or pass a cube name explicitly"}}function E(t,e){const r=t.flags.mode;if(e.platform()==="win32"&&!_(e))return e.stderr(`native Windows is not supported for interactive launch; using pastelist mode instead (WSL + tmux is the recommended Windows path)
|
|
9
|
+
`),{backend:"pastelist"};if(r==="windows")return{backend:"windows"};if(r==="pastelist")return{backend:"pastelist"};const a=p(e);return r==="tmux"?a?{backend:"tmux"}:{hardFail:L}:a?{backend:"tmux"}:(e.stderr(L+`Falling back to pastelist mode (paste the commands below).
|
|
10
|
+
`),{backend:"pastelist"})}function U(t,e){return t.flags.noAttach||!e.isTTY()?"none":e.getEnv("TMUX")?"switch":"attach"}function j(t,e){e.stdout(` tmux attach -t ${t} # re-attach later
|
|
11
|
+
`),e.stdout(` tmux list-windows -t ${t} # list all drone windows
|
|
12
|
+
`),e.stdout(` tmux kill-session -t ${t} # stop all drones
|
|
13
|
+
`)}function O(t){return`borg-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`}async function P(t,e,r,u,a,l=Date.now,m=d=>new Promise(h=>setTimeout(h,d))){const d=new Map;for(const f of a)d.set(f,"unconfirmed");const h=l()+1e4;for(let f=0;f<20&&!(l()>=h);f++){let c;try{c=await t.getRoster(e,r,u)}catch(i){const b=i instanceof Error?i.message:String(i),o=/Authentication required/i.test(b);t.stderr(`roster confirmation skipped (${o?"token rotated mid-launch":b}); launched drones may still be live \u2014 re-check with \`borg_roster\`.
|
|
14
|
+
`);break}for(const i of c.drones)d.get(i.id)==="unconfirmed"&&i.seen_since===!0&&d.set(i.id,"verified");if([...d.values()].every(i=>i==="verified"))break;await m(500)}return d}const F=2e3;function W(t,e){if(t!==void 0&&Number.isInteger(t)&&t>=0)return t;const r=e===void 0?"":e.trim(),u=r===""?NaN:Number(r);return Number.isInteger(u)&&u>=0?u:F}async function X(t,e,r={}){const u=r.now??Date.now,a=r.nowISO??(()=>new Date().toISOString()),l=r.borgPath??x(),m=r.sleep??(n=>new Promise(s=>setTimeout(s,n))),d=W(t.flags.launchDelayMs,e.getEnv("BORG_LAUNCH_DELAY_MS")),h=await M(t,e);if("error"in h)return e.stderr(`borg launch-all: ${h.error}
|
|
15
|
+
`),1;const{cubeId:f,name:c}=h;I(e,f,u());const i=await A({targetCubeId:f,only:t.flags.only},e);if(i.length===0)return t.flags.only!==void 0?(e.stdout(`No worktrees matched --only '${t.flags.only}' for cube '${c}'
|
|
16
|
+
`),C(t.flags.only)||e.stderr(`note: --only '${t.flags.only}' is matched best-effort by drone label; role-name matching needs a drone session and is not available here.
|
|
17
|
+
`)):e.stdout(`No worktrees found for cube '${c}' \u2014 have you run \`borg assimilate --worktree\` to create any drone seats?
|
|
18
|
+
`),0;const b=[];for(const n of i){const s=S(e,f,n.worktreeDir,u());if(s.live&&!t.flags.force){e.stderr(`skipping ${n.droneLabel} (${n.worktreeDir}): appears live. Use --force to re-launch.
|
|
19
|
+
`);continue}s.live&&t.flags.force&&e.stderr(`--force: re-launching ${n.droneLabel} (${n.worktreeDir}); the running session's token will be displaced.
|
|
20
|
+
`),b.push(n)}if(b.length===0)return e.stdout(`All ${i.length} drone(s) for cube '${c}' appear live; nothing to launch (use --force to re-launch).
|
|
21
|
+
`),0;const o=[];for(const n of b){let s;try{s=await e.probeSeat(n.sessionToken,n.apiUrl)}catch{s="indeterminate"}if(s==="evicted"){e.stderr(`skipping ${n.droneLabel} (${n.worktreeDir}): seat no longer in cube (evicted) \u2014 run \`borg cleanup --prune\` to remove the worktree, or \`borg assimilate\` to re-seat fresh.
|
|
22
|
+
`);continue}if(s==="frozen"){e.stderr(`skipping ${n.droneLabel} (${n.worktreeDir}): seat frozen (subscription downgrade) \u2014 paused, not relaunching; it resumes automatically when billing is restored.
|
|
23
|
+
`);continue}s==="indeterminate"&&e.stderr(`note: could not confirm ${n.droneLabel}'s seat is live (network/transient) \u2014 launching anyway.
|
|
24
|
+
`),o.push(n)}if(o.length===0)return e.stdout(`All ${b.length} discovered drone(s) for cube '${c}' have evicted/frozen seats; nothing to launch.
|
|
25
|
+
`),0;if(t.flags.dryRun){e.stdout(`borg launch-all (dry-run): would launch ${o.length} drone(s) for cube '${c}':
|
|
26
|
+
`);for(const n of o)e.stdout(` ${n.droneLabel} ${n.worktreeDir}
|
|
27
|
+
`);return 0}if(o.length>6&&!t.flags.yes&&(await e.prompt(`About to launch ${o.length} drones for cube '${c}'. Continue? [y/N]: `)).trim().toLowerCase()!=="y")return e.stdout(`Aborted.
|
|
28
|
+
`),0;const w=E(t,e);if("hardFail"in w)return e.stderr(w.hardFail),1;const g=O(c),k=a();try{if(w.backend==="tmux"){const n=U(t,e);await D(o,{sessionName:g,borgPath:l,attachMode:n,launchedAtISO:k,launchDelayMs:d,sleep:m},e),n==="none"&&(e.isTTY()||e.stderr(`Launching in detached mode \u2014 stdout is non-TTY. Attach manually with: tmux attach -t ${g}
|
|
29
|
+
`),j(g,e))}else if(w.backend==="windows")await T(o,{borgPath:l,platform:e.platform(),launchedAtISO:k,launchDelayMs:d,sleep:m},e);else return N(o,l,e),0}catch(n){return e.stderr(`borg launch-all: ${n instanceof Error?n.message:String(n)}
|
|
30
|
+
`),1}const v=o[0].sessionToken,y=o[0].apiUrl;let $=null;v&&y?$=await P(e,v,y,k,o.map(n=>n.droneId),r.now,r.sleep):e.stderr(`roster reconciliation skipped \u2014 no session token available
|
|
27
31
|
`),e.stdout(`
|
|
28
|
-
borg launch-all: launched ${o.length} drones for cube '${
|
|
32
|
+
borg launch-all: launched ${o.length} drones for cube '${c}'
|
|
29
33
|
|
|
30
|
-
`);for(const
|
|
34
|
+
`);for(const n of o){const s=$?$.get(n.droneId)==="verified"?"VERIFIED":"unconfirmed (may still be joining)":"launched";e.stdout(` ${n.droneLabel} ${n.worktreeDir} ${s}
|
|
31
35
|
`)}return e.stdout(`
|
|
32
36
|
Attach: tmux attach -t ${g}
|
|
33
|
-
`),0}export{
|
|
37
|
+
`),0}export{F as DEFAULT_LAUNCH_DELAY_MS,W as resolveLaunchDelayMs,X as runLaunchAll};
|
package/dist/log-stream.d.ts
CHANGED
|
@@ -23,7 +23,8 @@
|
|
|
23
23
|
* MCP tool can probe without perturbing the stream (no second
|
|
24
24
|
* connection, no second auth — just an in-process state snapshot).
|
|
25
25
|
*/
|
|
26
|
-
import {
|
|
26
|
+
import { getActiveCube } from './cubes.js';
|
|
27
|
+
import { acquireStreamLease, type StreamOwnershipSnapshot } from './stream-owner.js';
|
|
27
28
|
export declare const INBOX_TAIL_LINES_CAP = 512;
|
|
28
29
|
export declare const INBOX_TAIL_TRIM_THRESHOLD_LINES: number;
|
|
29
30
|
export type RunLoopHealth = 'connected' | 'reconnecting' | 'silent-inert' | 'never-started';
|
|
@@ -71,12 +72,21 @@ export declare function ensureCodexHeartbeatStarted(start?: () => ReturnType<typ
|
|
|
71
72
|
/**
|
|
72
73
|
* gh#861 finding 3: tear down the codex heartbeat timer — the teardown seam for
|
|
73
74
|
* the periodic interval. Called when the active cube is cleared (nothing to inject
|
|
74
|
-
* into) or the tick detects a dead app-server socket.
|
|
75
|
-
*
|
|
75
|
+
* into) or the tick detects a dead app-server socket. Also clears any pending
|
|
76
|
+
* deferred re-arm (gh#866 item 3) so a cube-cleared teardown doesn't leave a
|
|
77
|
+
* stray re-arm queued. Re-armable: ensureCodexHeartbeatStarted starts a fresh
|
|
78
|
+
* timer once an active cube returns.
|
|
76
79
|
*/
|
|
77
80
|
export declare function stopCodexHeartbeat(): void;
|
|
78
81
|
/** Test-only alias of the production teardown seam (re-testable idempotence). */
|
|
79
82
|
export declare function __resetCodexHeartbeatForTest(): void;
|
|
83
|
+
/**
|
|
84
|
+
* Test-only override of the gh#866-item3 deferred re-arm delay so the
|
|
85
|
+
* mid-session re-arm lifecycle is drivable with a tiny real delay instead of the
|
|
86
|
+
* 20-minute cadence. Reset by __resetCodexHeartbeatForTest.
|
|
87
|
+
* @internal
|
|
88
|
+
*/
|
|
89
|
+
export declare function __setCodexReArmDelayForTest(ms: number): void;
|
|
80
90
|
export declare function startLogStream(opts?: {
|
|
81
91
|
runForever?: () => void;
|
|
82
92
|
}): void;
|
|
@@ -110,6 +120,32 @@ export interface StreamDeps {
|
|
|
110
120
|
*/
|
|
111
121
|
onInboxReceipt?: (active: ActiveCube, token: string) => void;
|
|
112
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Test-only injection seam for runLoop (gh#866 item 2). Production calls
|
|
125
|
+
* `runLoop()` with no args → every dep falls back to the real import and the
|
|
126
|
+
* loop runs forever, exactly as before (zero behavior change). Tests pass stubs
|
|
127
|
+
* plus a `maxIterations` bound to drive a fixed number of iterations through the
|
|
128
|
+
* heartbeat-lifecycle seams — teardown (`stopCodexHeartbeat` on a cleared cube)
|
|
129
|
+
* and re-arm (`ensureCodexHeartbeatStarted` on an active cube) — without real
|
|
130
|
+
* network/keychain IO.
|
|
131
|
+
*/
|
|
132
|
+
export interface RunLoopTestDeps {
|
|
133
|
+
getActiveCube?: typeof getActiveCube;
|
|
134
|
+
acquireStreamLease?: typeof acquireStreamLease;
|
|
135
|
+
sleep?: (ms: number) => Promise<void>;
|
|
136
|
+
maxIterations?: number;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Test-only entry to the bounded form of runLoop (gh#866 item 2). Drives a
|
|
140
|
+
* fixed number of iterations with injected deps so the heartbeat teardown
|
|
141
|
+
* (cleared cube → `stopCodexHeartbeat`) and re-arm (active cube →
|
|
142
|
+
* `ensureCodexHeartbeatStarted`) seams are exercisable without real
|
|
143
|
+
* network/keychain IO. Never called in production.
|
|
144
|
+
*
|
|
145
|
+
* @internal — test-only surface; mirrors the `__…ForTest` convention used by
|
|
146
|
+
* `__resetStreamStateForTest` / `__resetCodexHeartbeatForTest`.
|
|
147
|
+
*/
|
|
148
|
+
export declare function __runLoopForTest(testDeps: RunLoopTestDeps): Promise<void>;
|
|
113
149
|
export interface ActiveCube {
|
|
114
150
|
cubeId: string;
|
|
115
151
|
droneId: string;
|
package/dist/log-stream.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{promises as
|
|
1
|
+
import{promises as E}from"node:fs";import oe from"node:os";import L from"node:path";import{getActiveCube as ae,inboxPathForDrone as X}from"./cubes.js";import{DroneEvictedError as J,DRONE_EVICTED_CODE as ie,EVICTED_RESULT_MARKER as se,errorCodeFromBody as ce}from"./drone-lifecycle.js";import{CODEX_HEARTBEAT_CADENCE_MS as U,fireCodexHeartbeatTick as le,formatCodexWakePrompt as de,resolveSessionAgentKind as ue,startCodexHeartbeat as fe,wakeCodexViaAppServer as pe}from"./codex-app-wake.js";import{getValidToken as me}from"./remote-client.js";import{recordEventReceipt as we,emitHealthBeat as he,getCachedMonitorHealthy as be,getCachedWakeArmed as ge}from"./health-beat.js";import{getPackageVersion as ye}from"./version.js";import{acquireStreamLease as q,readOwnershipSnapshot as S}from"./stream-owner.js";const z=9e4,Ie=2e3,_e=500,Ee=3e4,Se=50,F=512,Ze=F*2;function Te(){try{const e=oe.hostname();return e&&e.trim()?e.trim().slice(0,255):null}catch{return null}}const Ae=Date.now(),a={connected:!1,lastWireActivityAt:null,lastContentEventAt:null,lastHeartbeatAt:null,lastPersistedEventId:null,reconnectAttempts:0,runLoopRestartCount:0,ownership:{state:"unowned"}};function xe(e,t=Date.now()-Ae){return e.connected&&e.lastWireActivityAt?"connected":!e.connected&&e.reconnectAttempts>0?"reconnecting":!e.connected&&!e.lastWireActivityAt&&e.reconnectAttempts===0&&t>1e4?"silent-inert":"never-started"}function et(){return{...a,runLoopHealth:xe(a)}}function tt(){a.connected=!1,a.lastWireActivityAt=null,a.lastContentEventAt=null,a.lastHeartbeatAt=null,a.lastPersistedEventId=null,a.reconnectAttempts=0,a.runLoopRestartCount=0,a.ownership={state:"unowned"}}let k=null,T=null,P=U;function W(e=Ce){k||(k=e())}function Ce(){return fe({tick:()=>{le({isStreamOwner:()=>a.ownership?.state==="owner",onAppServerSocketDead:ke})}})}function ke(){B(),He()}function He(e=P){T||(T=setTimeout(()=>{T=null,W()},e),T.unref?.())}function B(){k&&clearInterval(k),k=null,T&&clearTimeout(T),T=null}function nt(){B(),P=U}function rt(e){P=e}function De(){(async()=>{for(;;){try{await Q(),process.stderr.write(`[borg-mcp log stream] runLoop returned unexpectedly; restarting in 5s
|
|
2
2
|
`)}catch(e){process.stderr.write(`[borg-mcp log stream] runLoop threw: ${e?.message??e}; restarting in 5s
|
|
3
|
-
`)}a.runLoopRestartCount+=1,await
|
|
4
|
-
`);return}a.connected=!1;const
|
|
5
|
-
`),
|
|
3
|
+
`)}a.runLoopRestartCount+=1,await ne(5e3)}})()}function ot(e={}){W(),(e.runForever??De)()}const Y={fetchImpl:globalThis.fetch.bind(globalThis),appendLine:Fe,hasInboxEntryId:Ve,getToken:me,wakeCodex:pe,heartbeatTimeoutMs:z,hwmDivergenceGraceMs:Ie,abortSignal:new AbortController().signal,ownerDeps:{},ownerStaleMs:7e4,onInboxReceipt:ve};function ve(e,t){we(),he(e,{sseConnected:!0,inboxMonitorHealthy:be(),wakeArmed:ge(),agentKind:ue(),hostname:Te(),version:ye(),getToken:async()=>t,fetchImpl:globalThis.fetch.bind(globalThis)})}async function Q(e={}){const t=e.getActiveCube??ae,i=e.acquireStreamLease??q,r=e.sleep??ne,c=e.maxIterations??1/0;let o=0,s=0,l=null,g=null,u=null,h=null;for(;o<c;){o+=1;const d=await t();if(!d){u&&(await u.release(),u=null,h=null),a.connected=!1,a.ownership={state:"unowned"},B(),await r(5e3);continue}W(),d.cubeId!==g&&(g=d.cubeId,l=null);const H=`${d.cubeId}:${d.droneId}`;if(u&&h!==H&&(await u.release(),u=null,h=null),u||(u=await i(d.cubeId,d.droneId),h=u?H:null),!u){a.connected=!1,a.ownership=await S(d.cubeId,d.droneId),await r(5e3);continue}a.ownership=await S(d.cubeId,d.droneId);let y=!1;try{const w=new AbortController,b=async()=>{try{await u.refresh()||(y=!0,w.abort(new Error("stream ownership lost")))}catch(p){y=!0,w.abort(p instanceof Error?p:new Error(String(p)))}},x=setInterval(()=>{b()},Math.max(1e3,Math.floor(z/2)));try{await Z(d,l,p=>{l=p},{abortSignal:w.signal})}finally{clearInterval(x)}if(y){u=null,h=null,a.connected=!1,a.ownership=await S(d.cubeId,d.droneId),await r(5e3);continue}s=0,a.reconnectAttempts=0}catch(w){if(y){u=null,h=null,a.connected=!1,a.ownership=await S(d.cubeId,d.droneId),await r(5e3);continue}if(w instanceof J){u&&await u.release().catch(()=>{}),u=null,h=null,a.connected=!1,a.ownership=await S(d.cubeId,d.droneId),process.stderr.write(`[borg-mcp log stream] drone evicted \u2014 stream terminated (no reconnect).
|
|
4
|
+
`);return}a.connected=!1;const b=Math.min(_e*2**s,Ee)+Math.random()*500;process.stderr.write(`[borg-mcp log stream] reconnect in ${Math.round(b)}ms: ${w?.message??w}
|
|
5
|
+
`),s+=1,a.reconnectAttempts=s,await r(b)}}}function at(e){return Q(e)}async function Z(e,t,i,r={}){const{fetchImpl:c,appendLine:o,hasInboxEntryId:s,getToken:l,wakeCodex:g,heartbeatTimeoutMs:u,hwmDivergenceGraceMs:h,abortSignal:d,onInboxReceipt:H}={...Y,...r},y=await l(),w={Authorization:`Bearer ${y}`,"X-Drone-Session":e.sessionToken,Accept:"text/event-stream"};t&&(w["Last-Event-ID"]=t);const b=new AbortController,x=()=>{try{b.abort(d.reason??new Error("external abort"))}catch{}};d.aborted&&x(),d.addEventListener("abort",x,{once:!0});let p=null;const V=()=>{p&&clearTimeout(p),p=setTimeout(()=>{try{b.abort(new Error("heartbeat watchdog timeout"))}catch{}},u)};V();let G=t,m=null,I=null;const C=()=>{I&&(clearTimeout(I.timer),I=null)};let D=null;const v=(n,f)=>{const R={id:n,created_at:f};D&&f&&D.created_at&&A(R,D)<=0||(D=R,G=n,a.lastPersistedEventId=n,i(n))},M=n=>{n&&(m=!m||A(n,m)>0?n:m,I&&A(m,I.hwm)>=0&&C())},re=n=>{if(I?.hwm.id===n.id)return;C();const f=setTimeout(()=>{if(m&&A(m,n)>=0){C();return}try{b.abort(new Error("hwm divergence \u2014 reconnect for catchup"))}catch{}},h);I={hwm:n,timer:f}},N=new Set,O=[];let j=t!==null;const K=async n=>{const f=Oe(Me(n.data,n.id));return j&&await s(e.cubeId,e.droneId,n.id,f)?(v(n.id,n.data?.created_at??""),"persisted-skip"):(await o(e.cubeId,e.droneId,f),g(de(f)),H(e,y),"written")},$=n=>{for(N.add(n.id),O.push(n.id);O.length>Se;){const f=O.shift();f&&N.delete(f)}v(n.id,n.data?.created_at??""),M(te(n))};let _;try{_=await c(`${e.apiUrl}/api/drone/stream`,{method:"GET",headers:w,signal:b.signal})}catch(n){throw p&&clearTimeout(p),n}if(!_.ok||!_.body){if(p&&clearTimeout(p),_.status===410){const n=await _.text().catch(()=>"");if(ce(n)===ie)throw new J}throw new Error(`stream HTTP ${_.status}`)}a.connected=!0;try{for await(const n of Re(_.body)){V();const f=new Date().toISOString();if(a.lastWireActivityAt=f,(n.type==="log"||n.type==="bookmark")&&(a.lastContentEventAt=f),n.type==="eviction"){a.lastContentEventAt=f;try{await o(e.cubeId,e.droneId,$e(n.reason))}catch{}break}if(n.type==="heartbeat"){if(a.lastHeartbeatAt=f,n.hwm&&m===null){M(n.hwm),G===null&&v(n.hwm.id,n.hwm.created_at);continue}if(n.hwm&&m&&A(n.hwm,m)<=0){C();continue}n.hwm&&m&&A(n.hwm,m)>0&&re(n.hwm);continue}if(n.type==="bookmark"){j=!1;continue}if(n.type==="log"){if(N.has(n.id)){v(n.id,n.data?.created_at??""),M(te(n));continue}const R=typeof n.data?.message=="string"&&n.data.message.startsWith("[HEARTBEAT-PING]");if(n.data?.kind==="ack"){if(n.data?.author_drone_id===e.droneId&&await K(n)==="persisted-skip")continue;$(n);continue}if(n.data?.drone_id===e.droneId&&!R){$(n);continue}if(await K(n)==="persisted-skip")continue;$(n)}}}finally{d.removeEventListener("abort",x),p&&clearTimeout(p),C(),a.connected=!1}}async function it(e,t,i,r={}){const{ownerDeps:c,ownerStaleMs:o}={...Y,...r},s=await q(e.cubeId,e.droneId,o,c);if(!s)return a.connected=!1,a.ownership=await S(e.cubeId,e.droneId,c),"skipped";a.ownership=await S(e.cubeId,e.droneId,c);try{return await Z(e,t,i,r),"streamed"}finally{await s.release()}}async function*Re(e){const t=e.getReader(),i=new TextDecoder;let r="";try{for(;;){const{value:c,done:o}=await t.read();if(o){if(r.trim()){const l=ee(r);l&&(yield l)}return}r+=i.decode(c,{stream:!0});let s;for(;(s=r.indexOf(`
|
|
6
6
|
|
|
7
|
-
`))!==-1;){const l=
|
|
8
|
-
`))
|
|
9
|
-
`);if(!t)return null;if(t==="log"){if(!i)return null;let
|
|
10
|
-
`,"utf-8"),await
|
|
7
|
+
`))!==-1;){const l=r.slice(0,s);r=r.slice(s+2);const g=ee(l);g&&(yield g)}}}finally{try{t.releaseLock()}catch{}}}function ee(e){let t=null,i=null,r=[];for(const o of e.split(`
|
|
8
|
+
`))o.startsWith("event:")?t=o.slice(6).trim():o.startsWith("id:")?i=o.slice(3).trim():o.startsWith("data:")&&r.push(o.slice(5).trim());const c=r.join(`
|
|
9
|
+
`);if(!t)return null;if(t==="log"){if(!i)return null;let o;try{o=JSON.parse(c)}catch{return null}return{type:"log",id:i,data:o}}if(t==="heartbeat"){let o=null,s=null;try{const l=JSON.parse(c);o=typeof l.ts=="string"?l.ts:null,s=Le(l.hwm)}catch{}return{type:"heartbeat",ts:o,hwm:s}}if(t==="bookmark"){let o=null;try{const s=JSON.parse(c);o=typeof s.as_of=="string"?s.as_of:null}catch{}return{type:"bookmark",as_of:o}}if(t==="eviction"){let o=null,s=null;try{const l=JSON.parse(c);o=typeof l.cube_id=="string"?l.cube_id:null,s=typeof l.reason=="string"?l.reason:null}catch{}return{type:"eviction",cube_id:o,reason:s}}return{type:"unknown",raw:e}}function Le(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.id=="string"&&t.id.length>0&&typeof t.created_at=="string"&&t.created_at.length>0?{id:t.id,created_at:t.created_at}:null}function A(e,t){const i=Date.parse(e.created_at),r=Date.parse(t.created_at);return Number.isFinite(i)&&Number.isFinite(r)&&i!==r?i-r:e.created_at!==t.created_at?e.created_at<t.created_at?-1:1:e.id.localeCompare(t.id)}function te(e){if(e.data?.visibility==="direct"||e.data?.kind==="ack")return null;const t=e.data?.created_at;return typeof t=="string"&&t.length>0?{id:e.id,created_at:t}:null}function Me(e,t){return!e||typeof e!="object"?{id:t}:typeof e.id=="string"&&e.id.length>0?e:{...e,id:t}}function Ne(...e){for(const t of e)if(typeof t=="string"&&t.length>0)return t;return""}function Oe(e){const t=typeof e.created_at=="string"?new Date(e.created_at).toISOString():new Date().toISOString(),i=e.drone_label??"?",r=e.role_name??"?",c=typeof e.message=="string"?e.message:"",o=Ne(e.id,e.entry_id),s=o?`[entry_id: ${o}] `:"",l=c.replace(/\r\n|\r|\n/g," \u23CE ");return`${t} ${i} (${r}): ${s}${l}`}function $e(e){const t=new Date().toISOString(),i=e&&e.trim().length>0?e:"evicted from cube";return`${t} SYSTEM (eviction): ${se} ${i} \u2014 confirm with any borg_* call; on DRONE_EVICTED (410) shut down: print the terminal message, TaskStop the inbox Monitor, do NOT reschedule /loop.`}async function Fe(e,t,i){const r=X(e,t);await Pe(r,i,F)}async function Pe(e,t,i=F,r=i*2){await E.mkdir(L.dirname(e),{recursive:!0}),await E.appendFile(e,t+`
|
|
10
|
+
`,"utf-8"),await We(e,i,r)}async function We(e,t,i=t){if(!Number.isInteger(t)||t<1)throw new Error("maxLines must be a positive integer");if(!Number.isInteger(i)||i<t)throw new Error("trimThresholdLines must be an integer >= maxLines");const c=(await E.readFile(e,"utf-8")).split(/\r?\n/);if(c.at(-1)===""&&c.pop(),c.length<=i)return;const o=c.slice(-t),s=L.join(L.dirname(e),`.${L.basename(e)}.${process.pid}.${Date.now()}.tmp`);try{await E.writeFile(s,o.join(`
|
|
11
11
|
`)+`
|
|
12
|
-
`,"utf-8"),await
|
|
12
|
+
`,"utf-8"),await E.rename(s,e)}catch(l){throw await E.rm(s,{force:!0}),l}}function Be(e,t,i){if(t&&e.includes(`[entry_id: ${t}]`))return!0;const r=t?i.replace(`[entry_id: ${t}] `,""):i;return!!(r&&e.split(/\r?\n/).includes(r))}async function Ve(e,t,i,r){const c=X(e,t);let o;try{o=await E.readFile(c,"utf-8")}catch(s){if(s?.code==="ENOENT")return!1;throw s}return Be(o,i,r)}function ne(e){return new Promise(t=>setTimeout(t,e))}export{F as INBOX_TAIL_LINES_CAP,Ze as INBOX_TAIL_TRIM_THRESHOLD_LINES,nt as __resetCodexHeartbeatForTest,tt as __resetStreamStateForTest,at as __runLoopForTest,rt as __setCodexReArmDelayForTest,Pe as appendCappedInboxLine,xe as classifyRunLoopHealth,A as compareBroadcastHwm,W as ensureCodexHeartbeatStarted,$e as formatEvictionSentinelLine,Oe as formatInboxLine,et as getStreamStatus,Be as inboxRawHasEntry,Re as parseSSE,ot as startLogStream,B as stopCodexHeartbeat,Z as streamOnce,it as streamOnceIfOwner,We as trimInboxFileToRecentLines};
|