borgmcp 5.4.0 → 5.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -0
- package/dist/assimilate-cmd.d.ts +8 -1
- package/dist/assimilate-cmd.d.ts.map +1 -1
- package/dist/assimilate-cmd.js +54 -21
- package/dist/assimilate-cmd.js.map +1 -1
- package/dist/claude.d.ts.map +1 -1
- package/dist/claude.js +22 -0
- package/dist/claude.js.map +1 -1
- package/dist/cli-help.d.ts +1 -0
- package/dist/cli-help.d.ts.map +1 -1
- package/dist/cli-help.js +42 -0
- package/dist/cli-help.js.map +1 -1
- package/dist/docs-sections.d.ts.map +1 -1
- package/dist/docs-sections.js +8 -0
- package/dist/docs-sections.js.map +1 -1
- package/dist/local-server-cursor.d.ts +1 -1
- package/dist/local-server-cursor.d.ts.map +1 -1
- package/dist/local-server-cursor.js +14 -4
- package/dist/local-server-cursor.js.map +1 -1
- package/dist/remote-client.d.ts +14 -0
- package/dist/remote-client.d.ts.map +1 -1
- package/dist/remote-client.js +30 -14
- package/dist/remote-client.js.map +1 -1
- package/dist/representative-cmd.d.ts +87 -0
- package/dist/representative-cmd.d.ts.map +1 -0
- package/dist/representative-cmd.js +286 -0
- package/dist/representative-cmd.js.map +1 -0
- package/dist/representative-core.d.ts +197 -0
- package/dist/representative-core.d.ts.map +1 -0
- package/dist/representative-core.js +493 -0
- package/dist/representative-core.js.map +1 -0
- package/dist/representative-mcp.d.ts +30 -0
- package/dist/representative-mcp.d.ts.map +1 -0
- package/dist/representative-mcp.js +182 -0
- package/dist/representative-mcp.js.map +1 -0
- package/dist/representative-owner.d.ts +10 -0
- package/dist/representative-owner.d.ts.map +1 -0
- package/dist/representative-owner.js +107 -0
- package/dist/representative-owner.js.map +1 -0
- package/dist/representative-store.d.ts +61 -0
- package/dist/representative-store.d.ts.map +1 -0
- package/dist/representative-store.js +158 -0
- package/dist/representative-store.js.map +1 -0
- package/dist/seat-store.d.ts +13 -0
- package/dist/seat-store.d.ts.map +1 -1
- package/dist/seat-store.js +55 -10
- package/dist/seat-store.js.map +1 -1
- package/dist/stream-owner.d.ts +10 -0
- package/dist/stream-owner.d.ts.map +1 -1
- package/dist/stream-owner.js +98 -19
- package/dist/stream-owner.js.map +1 -1
- package/dist/unknown-subcommand.d.ts +1 -1
- package/dist/unknown-subcommand.d.ts.map +1 -1
- package/dist/unknown-subcommand.js +1 -0
- package/dist/unknown-subcommand.js.map +1 -1
- package/docs/HUMAN_REPRESENTATIVE.md +269 -0
- package/docs/RELEASING.md +2 -2
- package/package.json +2 -2
- package/src/assimilate-cmd.ts +73 -22
- package/src/claude.ts +22 -0
- package/src/cli-help.ts +45 -0
- package/src/docs-sections.ts +8 -0
- package/src/local-server-cursor.ts +11 -3
- package/src/remote-client.ts +45 -12
- package/src/representative-cmd.ts +363 -0
- package/src/representative-core.ts +699 -0
- package/src/representative-mcp.ts +209 -0
- package/src/representative-owner.ts +105 -0
- package/src/representative-store.ts +208 -0
- package/src/seat-store.ts +61 -10
- package/src/stream-owner.ts +96 -19
- package/src/unknown-subcommand.ts +1 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Restricted stdio MCP facade for the human representative.
|
|
3
|
+
*
|
|
4
|
+
* A Borg server speaks pinned-TLS HTTPS, not MCP, so a generic MCP host reaches
|
|
5
|
+
* it through this local stdio process. The surface is four tools: status, send
|
|
6
|
+
* (to the ONE bound Coordinator), read (that Coordinator's replies) and ack.
|
|
7
|
+
* There is deliberately no log/broadcast/dispatch, roster-management, grant,
|
|
8
|
+
* evict, release, regen or server-lifecycle tool, and no dispatcher escape hatch.
|
|
9
|
+
*
|
|
10
|
+
* The connection context is resolved per call and injected, so the same facade
|
|
11
|
+
* runs over the real seat-scoped backend or a controlled test backend.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { ErrorCode } from 'borgmcp-shared/protocol';
|
|
15
|
+
import type { Readable, Writable } from 'node:stream';
|
|
16
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
17
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
18
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
19
|
+
import {
|
|
20
|
+
REPRESENTATIVE_DELIVERY_NOTE,
|
|
21
|
+
REPRESENTATIVE_MESSAGE_LIMIT_BYTES,
|
|
22
|
+
RepresentativeError,
|
|
23
|
+
ackRepresentativeReply,
|
|
24
|
+
readRepresentativeReplies,
|
|
25
|
+
representativeStatus,
|
|
26
|
+
sendRepresentativeMessage,
|
|
27
|
+
type RepresentativeContext,
|
|
28
|
+
} from './representative-core.js';
|
|
29
|
+
import { RepresentativeStoreError } from './representative-store.js';
|
|
30
|
+
import { createRepresentativeOwner } from './representative-owner.js';
|
|
31
|
+
|
|
32
|
+
export const REPRESENTATIVE_TOOL_NAMES = [
|
|
33
|
+
'borg_representative-status',
|
|
34
|
+
'borg_representative-send',
|
|
35
|
+
'borg_representative-read',
|
|
36
|
+
'borg_representative-ack',
|
|
37
|
+
] as const;
|
|
38
|
+
|
|
39
|
+
export const REPRESENTATIVE_INSTRUCTIONS =
|
|
40
|
+
'You are connected as the human representative of one Borg cube: an automated delegate that relays the ' +
|
|
41
|
+
'human\'s requests, questions and decisions to ONE bound Coordinator drone and reads its replies. You are not the ' +
|
|
42
|
+
'Coordinator and not the human: never plan or dispatch work for other drones — the Coordinator does that. ' +
|
|
43
|
+
'Mark content user_authorized ONLY when the human explicitly said it; everything you originate is model_advice. ' +
|
|
44
|
+
'A relayed decision authorizes only its own text, never broader approval. ' +
|
|
45
|
+
REPRESENTATIVE_DELIVERY_NOTE;
|
|
46
|
+
|
|
47
|
+
const TOOLS = [
|
|
48
|
+
{
|
|
49
|
+
name: 'borg_representative-status',
|
|
50
|
+
description:
|
|
51
|
+
'Show which cube, representative drone and Coordinator this connection is bound to, whether the live cube still matches, ' +
|
|
52
|
+
'any unresolved (ambiguous) sends, process ownership and the delivery limits. Read-only; never takes ownership.',
|
|
53
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: 'borg_representative-send',
|
|
57
|
+
description:
|
|
58
|
+
'Relay ONE human request, question or decision to the bound Coordinator. The recipient is fixed; workers and broadcast ' +
|
|
59
|
+
'are not addressable. Returns a request_id. If the outcome is "ambiguous" (the result names the cause), retry only ' +
|
|
60
|
+
'with the SAME request_id and identical content (server-deduplicated); never re-send under a new id. A ' +
|
|
61
|
+
'SEND_REJECTED error names the refusal and its recovery. Do not issue overlapping sends of the same content.',
|
|
62
|
+
inputSchema: {
|
|
63
|
+
type: 'object',
|
|
64
|
+
properties: {
|
|
65
|
+
kind: { type: 'string', enum: ['request', 'question', 'decision'] },
|
|
66
|
+
authorization: {
|
|
67
|
+
type: 'string',
|
|
68
|
+
enum: ['user_authorized', 'model_advice'],
|
|
69
|
+
description:
|
|
70
|
+
'user_authorized: the human explicitly said/approved this exact content. model_advice: your own suggestion. ' +
|
|
71
|
+
'A decision must be user_authorized.',
|
|
72
|
+
},
|
|
73
|
+
message: { type: 'string', description: `Plain text, at most ${REPRESENTATIVE_MESSAGE_LIMIT_BYTES} bytes.` },
|
|
74
|
+
request_id: {
|
|
75
|
+
type: 'string',
|
|
76
|
+
description: 'Omit for a new request. To retry, pass the request_id returned earlier with identical content.',
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
required: ['kind', 'authorization', 'message'],
|
|
80
|
+
additionalProperties: false,
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
name: 'borg_representative-read',
|
|
85
|
+
description:
|
|
86
|
+
'Read unread replies from the bound Coordinator addressed to this representative. Replies arrive only when this tool ' +
|
|
87
|
+
'is called; there is no background wake. Each call DRAINS the whole fetched unread page for this drone — returned ' +
|
|
88
|
+
'replies and ignored entries alike (other drones\' entries are counted, never returned) — so they will not appear ' +
|
|
89
|
+
'unread again: persist the result, then route each reply by in_reply_to to its conversation or hold it for the human. If the host stops before persisting, the reply ' +
|
|
90
|
+
'is no longer in the unread view.',
|
|
91
|
+
inputSchema: {
|
|
92
|
+
type: 'object',
|
|
93
|
+
properties: {
|
|
94
|
+
include_broadcast: { type: 'boolean', description: 'Also return the Coordinator\'s cube-wide broadcasts (marked as such).' },
|
|
95
|
+
limit: {
|
|
96
|
+
type: 'integer', minimum: 1, maximum: 200,
|
|
97
|
+
description: 'Page-size hint, not a hard cap: a large unread backlog may return (and drain) more entries.',
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
additionalProperties: false,
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
name: 'borg_representative-ack',
|
|
105
|
+
description:
|
|
106
|
+
'Signal to the Coordinator that one of its direct replies (entry_id from borg_representative-read) was received. ' +
|
|
107
|
+
'It is only that signal: it does not make delivery reliable, does not move or restore the unread cursor, and is ' +
|
|
108
|
+
'not needed for reading.',
|
|
109
|
+
inputSchema: {
|
|
110
|
+
type: 'object',
|
|
111
|
+
properties: { entry_id: { type: 'string' } },
|
|
112
|
+
required: ['entry_id'],
|
|
113
|
+
additionalProperties: false,
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
] as const;
|
|
117
|
+
|
|
118
|
+
function errorBody(error: unknown): { error: { code: string; message: string; details?: unknown } } {
|
|
119
|
+
if (error instanceof RepresentativeError || error instanceof RepresentativeStoreError) {
|
|
120
|
+
const details = error instanceof RepresentativeError ? error.details : undefined;
|
|
121
|
+
return { error: { code: error.code, message: error.message, ...(details ? { details } : {}) } };
|
|
122
|
+
}
|
|
123
|
+
const code = (error as { code?: unknown } | null)?.code;
|
|
124
|
+
return {
|
|
125
|
+
error: {
|
|
126
|
+
code: typeof code === 'string' ? code : 'BACKEND_ERROR',
|
|
127
|
+
message: error instanceof Error ? error.message : 'Unknown error',
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const toolResult = (body: unknown, isError = false) => ({
|
|
133
|
+
content: [{ type: 'text' as const, text: JSON.stringify(body, null, 2) }],
|
|
134
|
+
...(isError ? { isError: true } : {}),
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
export interface ServeRepresentativeOptions {
|
|
138
|
+
/** Resolved on every call; a throw fails that call closed. */
|
|
139
|
+
context: () => Promise<RepresentativeContext>;
|
|
140
|
+
version: string;
|
|
141
|
+
stdin?: Readable;
|
|
142
|
+
stdout?: Writable;
|
|
143
|
+
/** Internal timing seam for heartbeat controls; production uses 20 seconds. */
|
|
144
|
+
heartbeatIntervalMs?: number;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export async function serveRepresentativeMcp(
|
|
148
|
+
options: ServeRepresentativeOptions,
|
|
149
|
+
): Promise<{ close: () => Promise<void>; closed: Promise<void> }> {
|
|
150
|
+
const owner = createRepresentativeOwner(options.heartbeatIntervalMs);
|
|
151
|
+
const server = new Server(
|
|
152
|
+
{ name: 'borg-human-representative', version: options.version },
|
|
153
|
+
{ capabilities: { tools: {} }, instructions: REPRESENTATIVE_INSTRUCTIONS },
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS.map((tool) => ({ ...tool })) }));
|
|
157
|
+
|
|
158
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
159
|
+
const name = request.params.name;
|
|
160
|
+
const args = request.params.arguments ?? {};
|
|
161
|
+
try {
|
|
162
|
+
if (!(REPRESENTATIVE_TOOL_NAMES as readonly string[]).includes(name)) {
|
|
163
|
+
throw new RepresentativeError(ErrorCode.INVALID_INPUT, `Unknown tool ${JSON.stringify(name)}; this connection exposes only the representative tools.`);
|
|
164
|
+
}
|
|
165
|
+
const ctx = await options.context();
|
|
166
|
+
if (name === 'borg_representative-status') {
|
|
167
|
+
return toolResult({ ...await representativeStatus(ctx), ownership: await owner.snapshot(ctx.binding) });
|
|
168
|
+
}
|
|
169
|
+
await owner.ensure(ctx.binding);
|
|
170
|
+
// Recheck at each network boundary, not just at tool dispatch: a process
|
|
171
|
+
// may have paused or lost its lease while awaiting live verification.
|
|
172
|
+
const backend = ctx.backend;
|
|
173
|
+
const guarded = { ...ctx, backend: Object.fromEntries(['whoami', 'roster', 'append', 'readUnread', 'readEntry', 'ack'].map((key) => [key, async (...args: unknown[]) => {
|
|
174
|
+
await owner.ensure(ctx.binding);
|
|
175
|
+
if (key === 'readUnread') args[1] = () => owner.ensure(ctx.binding);
|
|
176
|
+
const result = await (backend[key as keyof typeof backend] as (...args: unknown[]) => Promise<unknown>).apply(backend, args);
|
|
177
|
+
await owner.ensure(ctx.binding);
|
|
178
|
+
return result;
|
|
179
|
+
}])) as unknown as typeof backend };
|
|
180
|
+
switch (name) {
|
|
181
|
+
case 'borg_representative-send': {
|
|
182
|
+
const sent = await sendRepresentativeMessage(guarded, args);
|
|
183
|
+
return toolResult(sent, sent.outcome === 'ambiguous');
|
|
184
|
+
}
|
|
185
|
+
case 'borg_representative-read':
|
|
186
|
+
return toolResult(await readRepresentativeReplies(guarded, args));
|
|
187
|
+
default:
|
|
188
|
+
return toolResult(await ackRepresentativeReply(guarded, args));
|
|
189
|
+
}
|
|
190
|
+
} catch (error) {
|
|
191
|
+
return toolResult(errorBody(error), true);
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
const transport = new StdioServerTransport(options.stdin, options.stdout);
|
|
196
|
+
let finish!: () => void;
|
|
197
|
+
const closed = new Promise<void>((resolve) => { finish = resolve; });
|
|
198
|
+
const shutdown = async () => {
|
|
199
|
+
process.removeListener('SIGTERM', signalClose);
|
|
200
|
+
process.removeListener('SIGINT', signalClose);
|
|
201
|
+
try { await owner.close(); } finally { finish(); }
|
|
202
|
+
};
|
|
203
|
+
const signalClose = () => { void server.close(); };
|
|
204
|
+
server.onclose = () => { void shutdown().catch(() => {}); };
|
|
205
|
+
process.once('SIGTERM', signalClose);
|
|
206
|
+
process.once('SIGINT', signalClose);
|
|
207
|
+
try { await server.connect(transport); } catch (error) { await shutdown(); throw error; }
|
|
208
|
+
return { close: async () => { await server.close(); await closed; }, closed };
|
|
209
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/** Lifecycle adapter for the existing stream lease; no separate lock protocol. */
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { borgConfigRoot, borgHomeRoot } from './private-root.js';
|
|
5
|
+
import {
|
|
6
|
+
acquireStreamLease, readOwnershipSnapshot, STREAM_OWNER_STALE_MS,
|
|
7
|
+
type StreamLease, type StreamOwnerDeps, type StreamOwnershipSnapshot,
|
|
8
|
+
} from './stream-owner.js';
|
|
9
|
+
import { RepresentativeError } from './representative-core.js';
|
|
10
|
+
import type { RepresentativeBinding } from './representative-store.js';
|
|
11
|
+
|
|
12
|
+
export function representativeOwnerDeps(binding: RepresentativeBinding): StreamOwnerDeps {
|
|
13
|
+
const authority = createHash('sha256').update(JSON.stringify([binding.origin, binding.trustIdentity])).digest('hex');
|
|
14
|
+
return {
|
|
15
|
+
// Separate from stream-locks, which borg_stream-status inspects. One lease
|
|
16
|
+
// across all worktrees using this authority/cube/drone, never one per host.
|
|
17
|
+
locksDir: join(borgConfigRoot(), 'representative-host-locks', authority),
|
|
18
|
+
privateRoot: { root: borgConfigRoot(), boundary: borgHomeRoot() },
|
|
19
|
+
worktree: binding.worktree, droneLabel: binding.representativeLabel, cubeName: binding.cubeName,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function representativeOwnership(binding: RepresentativeBinding): Promise<StreamOwnershipSnapshot> {
|
|
24
|
+
return privateStorage(() => readOwnershipSnapshot(binding.cubeId, binding.representativeDroneId, representativeOwnerDeps(binding)));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function privateStorage<T>(operation: () => Promise<T>): Promise<T> {
|
|
28
|
+
try { return await operation(); }
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error instanceof RepresentativeError) throw error;
|
|
31
|
+
const message = error instanceof Error ? error.message : 'invalid private state';
|
|
32
|
+
// Only this exact directory-mode refusal permits manual permission recovery.
|
|
33
|
+
// Symlink, ownership and other failures must not suggest chmod through a path.
|
|
34
|
+
const looseDirectory = /^Borg credential store root (.+) has insecure permissions; expected 0700$/s.exec(message);
|
|
35
|
+
const detail = looseDirectory
|
|
36
|
+
? `directory ${looseDirectory[1]} has insecure permissions; expected 0700. ` +
|
|
37
|
+
'Check that the named path is a real directory you own and not a symlink, then set it to 0700 and retry. ' +
|
|
38
|
+
'Restart a process that had already lost ownership.'
|
|
39
|
+
: message.replace(/^Borg credential store /, '');
|
|
40
|
+
throw new RepresentativeError('REPRESENTATIVE_OWNERSHIP_REQUIRED',
|
|
41
|
+
'Representative lease storage refused: ' + detail);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function createRepresentativeOwner(heartbeatIntervalMs = 20_000) {
|
|
46
|
+
let lease: StreamLease | null = null;
|
|
47
|
+
let selected: RepresentativeBinding | undefined;
|
|
48
|
+
let deps: StreamOwnerDeps;
|
|
49
|
+
let lost = false, closed = false;
|
|
50
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
51
|
+
let tail: Promise<unknown> = Promise.resolve();
|
|
52
|
+
const processNonce = randomUUID();
|
|
53
|
+
// Serialize lease mutations, including heartbeats, but NOT tool execution:
|
|
54
|
+
// overlapping sends still use the existing atomic request reservation.
|
|
55
|
+
const serial = <T>(op: () => Promise<T>): Promise<T> => {
|
|
56
|
+
const result = tail.then(op);
|
|
57
|
+
tail = result.catch(() => {});
|
|
58
|
+
return result;
|
|
59
|
+
};
|
|
60
|
+
const snapshot = (binding: RepresentativeBinding) => privateStorage(() => readOwnershipSnapshot(
|
|
61
|
+
binding.cubeId, binding.representativeDroneId,
|
|
62
|
+
{ ...representativeOwnerDeps(binding), processNonce },
|
|
63
|
+
));
|
|
64
|
+
const refuse = async (binding: RepresentativeBinding): Promise<never> => {
|
|
65
|
+
const owner = await snapshot(binding);
|
|
66
|
+
throw new RepresentativeError(
|
|
67
|
+
'REPRESENTATIVE_OWNERSHIP_REQUIRED',
|
|
68
|
+
`This representative is owned by another MCP process (pid ${owner.pid ?? 'unknown'}, started ${owner.startedAt ?? 'unknown'}), ` +
|
|
69
|
+
'or this process lost its lease. Use the owning host; after it exits or its lease expires, retry from the intended host. ' +
|
|
70
|
+
'Restart a process that lost ownership before using it again. Status remains available.',
|
|
71
|
+
{ owner },
|
|
72
|
+
);
|
|
73
|
+
};
|
|
74
|
+
const refresh = async () => {
|
|
75
|
+
try {
|
|
76
|
+
if (!lease || !await lease.refresh()) lost = true;
|
|
77
|
+
} catch { lost = true; }
|
|
78
|
+
if (lost && timer) { clearInterval(timer); timer = undefined; }
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
snapshot,
|
|
82
|
+
ensure: (binding: RepresentativeBinding) => serial(async () => {
|
|
83
|
+
if (selected && (selected.origin !== binding.origin || selected.trustIdentity !== binding.trustIdentity ||
|
|
84
|
+
selected.cubeId !== binding.cubeId || selected.representativeDroneId !== binding.representativeDroneId)) lost = true;
|
|
85
|
+
if (closed || lost) return refuse(binding);
|
|
86
|
+
if (lease) {
|
|
87
|
+
await refresh();
|
|
88
|
+
if (lost) return refuse(binding);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
deps = { ...representativeOwnerDeps(binding), processNonce };
|
|
92
|
+
lease = await privateStorage(() => acquireStreamLease(binding.cubeId, binding.representativeDroneId, STREAM_OWNER_STALE_MS, deps));
|
|
93
|
+
if (!lease) return refuse(binding);
|
|
94
|
+
selected = binding;
|
|
95
|
+
timer = setInterval(() => { void serial(refresh); }, heartbeatIntervalMs);
|
|
96
|
+
timer.unref();
|
|
97
|
+
}),
|
|
98
|
+
close: () => serial(async () => {
|
|
99
|
+
closed = true;
|
|
100
|
+
if (timer) { clearInterval(timer); timer = undefined; }
|
|
101
|
+
await lease?.release();
|
|
102
|
+
lease = null;
|
|
103
|
+
}),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Private on-disk state for the human representative connection.
|
|
3
|
+
*
|
|
4
|
+
* One 0600 file under the Borg config root holds, per representative worktree:
|
|
5
|
+
* - the BINDING: the one explicit cube + Coordinator drone this worktree's
|
|
6
|
+
* dedicated seat may talk to. Changing it requires an explicit operator rebind.
|
|
7
|
+
* - the REQUEST LEDGER: one record per sent request id, so a retry never becomes
|
|
8
|
+
* a second message and an ambiguous send survives a reconnect.
|
|
9
|
+
*
|
|
10
|
+
* The file never holds a bearer (the seat store owns credentials) and never
|
|
11
|
+
* holds message text (only a payload digest).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { decodeUuid } from 'borgmcp-shared/protocol';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { borgConfigRoot } from './private-root.js';
|
|
17
|
+
import { shellEscape } from './shell-escape.js';
|
|
18
|
+
import { readStoreFile, withStore } from './seat-store.js';
|
|
19
|
+
|
|
20
|
+
export function isRepresentativeUuid(value: unknown): value is string {
|
|
21
|
+
try { decodeUuid(value); return true; } catch { return false; }
|
|
22
|
+
}
|
|
23
|
+
const SETTLED_REQUEST_LIMIT = 200;
|
|
24
|
+
|
|
25
|
+
export interface RepresentativeBinding {
|
|
26
|
+
/** Canonical worktree holding the dedicated representative seat. */
|
|
27
|
+
worktree: string;
|
|
28
|
+
origin: string;
|
|
29
|
+
trustIdentity: string;
|
|
30
|
+
cubeId: string;
|
|
31
|
+
cubeName: string;
|
|
32
|
+
representativeDroneId: string;
|
|
33
|
+
representativeLabel: string;
|
|
34
|
+
representativeRoleName: string;
|
|
35
|
+
coordinatorDroneId: string;
|
|
36
|
+
coordinatorLabel: string;
|
|
37
|
+
coordinatorRoleName: string;
|
|
38
|
+
repositoryOrigin?: string;
|
|
39
|
+
boundAt: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function representativeRecoveryCommand(binding: RepresentativeBinding): string {
|
|
43
|
+
return `cd ${shellEscape(binding.worktree)} && borg representative prepare --coordinator ${shellEscape(binding.coordinatorLabel)} --role ${shellEscape(binding.representativeRoleName)} --rebind`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type RepresentativeRequestState = 'pending' | 'ambiguous' | 'sent' | 'rejected';
|
|
47
|
+
|
|
48
|
+
export interface RepresentativeRequestRecord {
|
|
49
|
+
/** Stable request identity; also the protocol `post_id` idempotency key. */
|
|
50
|
+
requestId: string;
|
|
51
|
+
/** sha256 of kind, authorization, message, cube and Coordinator — never the text. */
|
|
52
|
+
payloadDigest: string;
|
|
53
|
+
kind: string;
|
|
54
|
+
authorization: string;
|
|
55
|
+
state: RepresentativeRequestState;
|
|
56
|
+
entryId?: string;
|
|
57
|
+
/** An attempt under this id may have reached the log; a later refusal must not clear that. */
|
|
58
|
+
maybeStored?: boolean;
|
|
59
|
+
createdAt: string;
|
|
60
|
+
updatedAt: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface RepresentativeFile {
|
|
64
|
+
version: 1;
|
|
65
|
+
bindings: Record<string, RepresentativeBinding>;
|
|
66
|
+
requests: Record<string, RepresentativeRequestRecord[]>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export class RepresentativeStoreError extends Error {
|
|
70
|
+
constructor(readonly code: 'BINDING_CONFLICT', message: string) {
|
|
71
|
+
super(message);
|
|
72
|
+
this.name = 'RepresentativeStoreError';
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface RepresentativeStore {
|
|
77
|
+
getBinding(worktree: string): Promise<RepresentativeBinding | null>;
|
|
78
|
+
readRequests(worktree: string): Promise<RepresentativeRequestRecord[]>;
|
|
79
|
+
saveBinding(
|
|
80
|
+
binding: RepresentativeBinding,
|
|
81
|
+
options: { rebind: boolean },
|
|
82
|
+
): Promise<'created' | 'unchanged' | 'rebound'>;
|
|
83
|
+
/** Read-compare-write over one worktree's ledger under the store lock. */
|
|
84
|
+
transactRequests<T>(
|
|
85
|
+
worktree: string,
|
|
86
|
+
op: (records: RepresentativeRequestRecord[]) => T,
|
|
87
|
+
): Promise<T>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const BINDING_STRING_FIELDS = [
|
|
91
|
+
'worktree', 'origin', 'trustIdentity', 'cubeId', 'cubeName',
|
|
92
|
+
'representativeDroneId', 'representativeLabel', 'representativeRoleName',
|
|
93
|
+
'coordinatorDroneId', 'coordinatorLabel', 'coordinatorRoleName', 'boundAt',
|
|
94
|
+
] as const;
|
|
95
|
+
|
|
96
|
+
function validBinding(value: unknown, key: string): value is RepresentativeBinding {
|
|
97
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
98
|
+
const binding = value as Record<string, unknown>;
|
|
99
|
+
return BINDING_STRING_FIELDS.every((field) => typeof binding[field] === 'string' && binding[field] !== '') &&
|
|
100
|
+
binding.worktree === key &&
|
|
101
|
+
isRepresentativeUuid(binding.cubeId as string) &&
|
|
102
|
+
isRepresentativeUuid(binding.representativeDroneId as string) &&
|
|
103
|
+
isRepresentativeUuid(binding.coordinatorDroneId as string) &&
|
|
104
|
+
binding.representativeDroneId !== binding.coordinatorDroneId &&
|
|
105
|
+
(binding.repositoryOrigin === undefined || typeof binding.repositoryOrigin === 'string');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function validRequest(value: unknown): value is RepresentativeRequestRecord {
|
|
109
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
110
|
+
const record = value as Record<string, unknown>;
|
|
111
|
+
return isRepresentativeUuid(String(record.requestId ?? '')) &&
|
|
112
|
+
typeof record.payloadDigest === 'string' &&
|
|
113
|
+
typeof record.kind === 'string' &&
|
|
114
|
+
typeof record.authorization === 'string' &&
|
|
115
|
+
['pending', 'ambiguous', 'sent', 'rejected'].includes(record.state as string) &&
|
|
116
|
+
(record.entryId === undefined || typeof record.entryId === 'string') &&
|
|
117
|
+
(record.maybeStored === undefined || typeof record.maybeStored === 'boolean') &&
|
|
118
|
+
typeof record.createdAt === 'string' &&
|
|
119
|
+
typeof record.updatedAt === 'string';
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function parseFile(raw: string): RepresentativeFile | null {
|
|
123
|
+
const parsed = JSON.parse(raw) as Partial<RepresentativeFile> | null;
|
|
124
|
+
if (
|
|
125
|
+
parsed === null || typeof parsed !== 'object' || parsed.version !== 1 ||
|
|
126
|
+
parsed.bindings === null || typeof parsed.bindings !== 'object' || Array.isArray(parsed.bindings) ||
|
|
127
|
+
parsed.requests === null || typeof parsed.requests !== 'object' || Array.isArray(parsed.requests)
|
|
128
|
+
) return null;
|
|
129
|
+
for (const [key, binding] of Object.entries(parsed.bindings)) {
|
|
130
|
+
if (!validBinding(binding, key)) return null;
|
|
131
|
+
}
|
|
132
|
+
for (const records of Object.values(parsed.requests)) {
|
|
133
|
+
if (!Array.isArray(records) || !records.every(validRequest)) return null;
|
|
134
|
+
}
|
|
135
|
+
return parsed as RepresentativeFile;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const emptyFile = (): RepresentativeFile => ({ version: 1, bindings: {}, requests: {} });
|
|
139
|
+
|
|
140
|
+
function sameSelection(a: RepresentativeBinding, b: RepresentativeBinding): boolean {
|
|
141
|
+
return a.origin === b.origin &&
|
|
142
|
+
a.trustIdentity === b.trustIdentity &&
|
|
143
|
+
a.cubeId === b.cubeId &&
|
|
144
|
+
a.representativeDroneId === b.representativeDroneId &&
|
|
145
|
+
a.coordinatorDroneId === b.coordinatorDroneId;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Settled history is bounded; unresolved (pending/ambiguous) records are never dropped. */
|
|
149
|
+
function pruneSettled(records: RepresentativeRequestRecord[]): RepresentativeRequestRecord[] {
|
|
150
|
+
const settled = records.filter((record) => record.state === 'sent' || record.state === 'rejected');
|
|
151
|
+
if (settled.length <= SETTLED_REQUEST_LIMIT) return records;
|
|
152
|
+
const drop = new Set(settled.slice(0, settled.length - SETTLED_REQUEST_LIMIT).map((record) => record.requestId));
|
|
153
|
+
return records.filter((record) => !drop.has(record.requestId));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function representativeStorePath(): string {
|
|
157
|
+
return join(borgConfigRoot(), 'representative.json');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function createRepresentativeStore(storePath: string = representativeStorePath()): RepresentativeStore {
|
|
161
|
+
// Atomic writer renames make a single read a complete snapshot, without a
|
|
162
|
+
// store-lock write or pruning settled history during read-only status.
|
|
163
|
+
const read = async () => {
|
|
164
|
+
const raw = await readStoreFile(storePath);
|
|
165
|
+
if (raw === null) return emptyFile();
|
|
166
|
+
let data: RepresentativeFile | null;
|
|
167
|
+
try { data = parseFile(raw); } catch { data = null; }
|
|
168
|
+
if (!data) throw new Error('Borg representative store is malformed or unsupported; refusing to read it');
|
|
169
|
+
return data;
|
|
170
|
+
};
|
|
171
|
+
return {
|
|
172
|
+
getBinding: async (worktree) => (await read()).bindings[worktree] ?? null,
|
|
173
|
+
readRequests: async (worktree) => (await read()).requests[worktree] ?? [],
|
|
174
|
+
|
|
175
|
+
saveBinding: (binding, options) => withStore(storePath, emptyFile, parseFile, async (txn) => {
|
|
176
|
+
if (!validBinding(binding, binding.worktree)) {
|
|
177
|
+
throw new Error('Refusing to save an invalid representative binding');
|
|
178
|
+
}
|
|
179
|
+
const existing = txn.data.bindings[binding.worktree];
|
|
180
|
+
if (existing && sameSelection(existing, binding)) return 'unchanged' as const;
|
|
181
|
+
if (existing && !options.rebind) {
|
|
182
|
+
throw new RepresentativeStoreError(
|
|
183
|
+
'BINDING_CONFLICT',
|
|
184
|
+
`This worktree is already bound to Coordinator ${existing.coordinatorLabel} in cube ${existing.cubeName}. ` +
|
|
185
|
+
`To confirm the new selection, run \`${representativeRecoveryCommand(binding)}\`.`,
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
txn.data.bindings[binding.worktree] = binding;
|
|
189
|
+
// A different selection invalidates the old ledger: its post ids belong to
|
|
190
|
+
// another cube/Coordinator conversation.
|
|
191
|
+
if (existing) delete txn.data.requests[binding.worktree];
|
|
192
|
+
await txn.commit();
|
|
193
|
+
return existing ? 'rebound' as const : 'created' as const;
|
|
194
|
+
}),
|
|
195
|
+
|
|
196
|
+
transactRequests: (worktree, op) => withStore(storePath, emptyFile, parseFile, async (txn) => {
|
|
197
|
+
const records = txn.data.requests[worktree] ?? [];
|
|
198
|
+
const before = JSON.stringify(records);
|
|
199
|
+
const result = op(records);
|
|
200
|
+
const next = pruneSettled(records);
|
|
201
|
+
if (JSON.stringify(next) !== before) {
|
|
202
|
+
txn.data.requests[worktree] = next;
|
|
203
|
+
await txn.commit();
|
|
204
|
+
}
|
|
205
|
+
return result;
|
|
206
|
+
}),
|
|
207
|
+
};
|
|
208
|
+
}
|
package/src/seat-store.ts
CHANGED
|
@@ -49,16 +49,24 @@ interface LockPayload {
|
|
|
49
49
|
export interface SecureStoreOptions {
|
|
50
50
|
secureRoot?: string;
|
|
51
51
|
rootMode?: 'private' | 'owner-controlled';
|
|
52
|
+
/** Harden leaf publication for private lease records; default store behavior is unchanged. */
|
|
53
|
+
verifyLeafIdentity?: boolean;
|
|
54
|
+
/** Publish without replacing an existing leaf (lease takeover marker). */
|
|
55
|
+
exclusive?: boolean;
|
|
56
|
+
/** Read-only lease inspection must not recreate a directory moved by its owner. */
|
|
57
|
+
createRoot?: boolean;
|
|
52
58
|
}
|
|
53
59
|
|
|
54
60
|
function expectedUid(): number | null {
|
|
55
61
|
return typeof process.getuid === 'function' ? process.getuid() : null;
|
|
56
62
|
}
|
|
57
63
|
|
|
58
|
-
|
|
64
|
+
/** Shared directory policy; create=false validates without mutating and returns false if absent. */
|
|
65
|
+
export async function assertSecureRoot(
|
|
59
66
|
root: string,
|
|
60
67
|
rootMode: SecureStoreOptions['rootMode'] = 'private',
|
|
61
|
-
|
|
68
|
+
create = true,
|
|
69
|
+
): Promise<boolean> {
|
|
62
70
|
if (!isCanonicalPath(root)) {
|
|
63
71
|
throw new Error(`Borg credential store path ${root} is not canonical`);
|
|
64
72
|
}
|
|
@@ -67,6 +75,7 @@ async function assertSecureRoot(
|
|
|
67
75
|
metadata = await lstat(root);
|
|
68
76
|
} catch (error) {
|
|
69
77
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
78
|
+
if (!create) return false;
|
|
70
79
|
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
71
80
|
metadata = await lstat(root);
|
|
72
81
|
}
|
|
@@ -87,6 +96,7 @@ async function assertSecureRoot(
|
|
|
87
96
|
if (!isCanonicalPath(root)) {
|
|
88
97
|
throw new Error(`Borg credential store root ${root} is not canonical or contains a symlink`);
|
|
89
98
|
}
|
|
99
|
+
return true;
|
|
90
100
|
}
|
|
91
101
|
|
|
92
102
|
async function assertSecureFile(filePath: string): Promise<Awaited<ReturnType<typeof lstat>> | null> {
|
|
@@ -115,7 +125,9 @@ async function assertSecurePath(filePath: string, options: SecureStoreOptions):
|
|
|
115
125
|
if (!isAbsolute(filePath) || resolve(filePath) !== filePath || dirname(filePath) !== secureRoot) {
|
|
116
126
|
throw new Error(`Borg credential store file path ${filePath} is not canonical`);
|
|
117
127
|
}
|
|
118
|
-
await assertSecureRoot(secureRoot, options.rootMode)
|
|
128
|
+
if (!await assertSecureRoot(secureRoot, options.rootMode, options.createRoot !== false)) {
|
|
129
|
+
throw Object.assign(new Error('Borg private store directory disappeared'), { code: 'ENOENT' });
|
|
130
|
+
}
|
|
119
131
|
}
|
|
120
132
|
|
|
121
133
|
/**
|
|
@@ -223,13 +235,28 @@ export async function atomicWrite0600(
|
|
|
223
235
|
else await ensureParentDir(filePath);
|
|
224
236
|
if (options.secureRoot) await assertSecureFile(filePath);
|
|
225
237
|
const tmp = `${filePath}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
|
|
226
|
-
const handle = await open(tmp,
|
|
238
|
+
const handle = await open(tmp, options.verifyLeafIdentity
|
|
239
|
+
? constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW
|
|
240
|
+
: 'wx', 0o600);
|
|
241
|
+
let opened: Awaited<ReturnType<typeof handle.stat>> | null = null;
|
|
242
|
+
const cleanup = async () => {
|
|
243
|
+
if (options.verifyLeafIdentity) {
|
|
244
|
+
const current = await lstat(tmp).catch(() => null);
|
|
245
|
+
if (!opened || !current || current.dev !== opened.dev || current.ino !== opened.ino) return;
|
|
246
|
+
}
|
|
247
|
+
await unlink(tmp).catch(() => {});
|
|
248
|
+
};
|
|
227
249
|
try {
|
|
250
|
+
opened = options.verifyLeafIdentity ? await handle.stat() : null;
|
|
251
|
+
if (opened && (!opened.isFile() || (opened.mode & 0o777) !== 0o600 ||
|
|
252
|
+
(expectedUid() !== null && opened.uid !== expectedUid()))) {
|
|
253
|
+
throw new Error('Borg private store temporary file is not private');
|
|
254
|
+
}
|
|
228
255
|
await handle.writeFile(data);
|
|
229
256
|
await handle.sync();
|
|
230
257
|
} catch (err) {
|
|
231
258
|
await handle.close().catch(() => {});
|
|
232
|
-
await
|
|
259
|
+
await cleanup();
|
|
233
260
|
throw err;
|
|
234
261
|
}
|
|
235
262
|
await handle.close();
|
|
@@ -238,7 +265,17 @@ export async function atomicWrite0600(
|
|
|
238
265
|
await assertSecurePath(filePath, options);
|
|
239
266
|
await assertSecureFile(filePath);
|
|
240
267
|
}
|
|
241
|
-
|
|
268
|
+
if (opened) {
|
|
269
|
+
const current = await lstat(tmp);
|
|
270
|
+
if (!current.isFile() || current.dev !== opened.dev || current.ino !== opened.ino ||
|
|
271
|
+
current.uid !== opened.uid || (current.mode & 0o777) !== 0o600) {
|
|
272
|
+
throw new Error('Borg private store temporary file identity changed');
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (options.exclusive) {
|
|
276
|
+
await link(tmp, filePath);
|
|
277
|
+
await unlink(tmp);
|
|
278
|
+
} else await rename(tmp, filePath);
|
|
242
279
|
const parent = await open(dirname(filePath), 'r');
|
|
243
280
|
try {
|
|
244
281
|
await parent.sync();
|
|
@@ -246,7 +283,7 @@ export async function atomicWrite0600(
|
|
|
246
283
|
await parent.close();
|
|
247
284
|
}
|
|
248
285
|
} catch (err) {
|
|
249
|
-
await
|
|
286
|
+
await cleanup();
|
|
250
287
|
throw err;
|
|
251
288
|
}
|
|
252
289
|
}
|
|
@@ -283,6 +320,20 @@ async function assertSecureStorePerms(
|
|
|
283
320
|
}
|
|
284
321
|
}
|
|
285
322
|
|
|
323
|
+
/** Identity drift is retryable only when inspecting an acquisition lock. */
|
|
324
|
+
export class StoreFileIdentityChangedError extends Error {
|
|
325
|
+
readonly code = 'STORE_FILE_IDENTITY_CHANGED';
|
|
326
|
+
|
|
327
|
+
constructor() {
|
|
328
|
+
super('Borg credential store file changed while it was being opened');
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function isLockTurnover(error: unknown): boolean {
|
|
333
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
334
|
+
return code === 'ENOENT' || code === 'STORE_FILE_IDENTITY_CHANGED';
|
|
335
|
+
}
|
|
336
|
+
|
|
286
337
|
/**
|
|
287
338
|
* Read the store file, or null when it does not exist (ONLY the missing-file
|
|
288
339
|
* no-op path initializes empty). When the file exists, the 0600-store + 0700-parent
|
|
@@ -310,7 +361,7 @@ export async function readStoreFile(
|
|
|
310
361
|
try {
|
|
311
362
|
const opened = await handle.stat();
|
|
312
363
|
if (opened.dev !== before.dev || opened.ino !== before.ino) {
|
|
313
|
-
throw new
|
|
364
|
+
throw new StoreFileIdentityChangedError();
|
|
314
365
|
}
|
|
315
366
|
const raw = await handle.readFile('utf8');
|
|
316
367
|
const after = await handle.stat();
|
|
@@ -399,7 +450,7 @@ export async function withStoreLock<T>(
|
|
|
399
450
|
if (stored === null) continue;
|
|
400
451
|
raw = stored;
|
|
401
452
|
} catch (readErr) {
|
|
402
|
-
if ((readErr
|
|
453
|
+
if (isLockTurnover(readErr)) continue; // released or replaced — retry
|
|
403
454
|
throw readErr;
|
|
404
455
|
}
|
|
405
456
|
const held = parseLockPayload(raw);
|
|
@@ -422,7 +473,7 @@ export async function withStoreLock<T>(
|
|
|
422
473
|
: {},
|
|
423
474
|
);
|
|
424
475
|
} catch (readErr) {
|
|
425
|
-
if ((readErr
|
|
476
|
+
if (isLockTurnover(readErr)) continue;
|
|
426
477
|
throw readErr;
|
|
427
478
|
}
|
|
428
479
|
if (currentRaw === null || currentRaw !== raw) continue;
|