@stage-labs/metro 0.1.0-beta.304 → 0.1.0-beta.306
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/cli.js +1 -1
- package/dist/memory.js +2 -3
- package/dist/runtime-install.js +3 -11
- package/dist/voice.js +1 -1
- package/{runtime/marketplace/plugin/bin → hooks}/guard.mjs +9 -4
- package/{runtime/marketplace/plugin/bin → hooks}/policy.mjs +1 -32
- package/{runtime/marketplace/plugin/bin → hooks}/session-start.mjs +2 -2
- package/package.json +4 -2
- package/runtime/node_modules/@metro-labs/core/package.json +0 -1
- package/runtime/node_modules/@metro-labs/daemon/src/agent-user/home-fs.ts +2 -29
- package/runtime/node_modules/@metro-labs/daemon/src/agent-user/provision.ts +2 -15
- package/runtime/node_modules/@metro-labs/daemon/src/agent-user/user.ts +0 -1
- package/runtime/node_modules/@metro-labs/daemon/src/agent-user/view.ts +3 -3
- package/runtime/node_modules/@metro-labs/daemon/src/agents/api.ts +3 -5
- package/runtime/node_modules/@metro-labs/daemon/src/approvals/pending.ts +1 -7
- package/runtime/node_modules/@metro-labs/daemon/src/boot/boot.ts +16 -17
- package/runtime/node_modules/@metro-labs/daemon/src/claude/cli-files.ts +28 -0
- package/runtime/node_modules/@metro-labs/daemon/src/claude/hooks.ts +60 -0
- package/runtime/node_modules/@metro-labs/daemon/src/claude/plugin-cleanup.ts +121 -0
- package/runtime/node_modules/@metro-labs/daemon/src/claude/session.ts +2 -4
- package/runtime/node_modules/@metro-labs/daemon/src/claude/setup.ts +38 -30
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/enroll-api.ts +0 -2
- package/runtime/node_modules/@metro-labs/daemon/src/mcp/index.ts +6 -0
- package/runtime/node_modules/@metro-labs/daemon/src/mcp/instructions.ts +4 -2
- package/runtime/node_modules/@metro-labs/daemon/src/mcp/permission-prompt.ts +1 -13
- package/runtime/node_modules/@metro-labs/daemon/src/mcp/policy-gate.ts +2 -1
- package/runtime/node_modules/@metro-labs/daemon/src/mcp/policy-snapshot.ts +2 -16
- package/runtime/node_modules/@metro-labs/daemon/src/mcp/server-approvals.ts +15 -16
- package/runtime/node_modules/@metro-labs/daemon/src/mcp/session.ts +4 -0
- package/runtime/node_modules/@metro-labs/daemon/src/mcp/tool-catalog.ts +20 -8
- package/runtime/node_modules/@metro-labs/daemon/src/mcp/tool-dispatch.ts +14 -8
- package/runtime/node_modules/@metro-labs/daemon/src/mcp-server/announced.ts +68 -0
- package/runtime/node_modules/@metro-labs/daemon/src/mcp-server/config.ts +2 -2
- package/runtime/node_modules/@metro-labs/daemon/src/mcp-server/connector-tools.ts +114 -0
- package/runtime/node_modules/@metro-labs/daemon/src/mcp-server/link.ts +12 -1
- package/runtime/node_modules/@metro-labs/daemon/src/mcp-server/rpc.ts +67 -0
- package/runtime/node_modules/@metro-labs/daemon/src/policy/policy.ts +6 -5
- package/runtime/node_modules/@metro-labs/daemon/src/routes/http.ts +0 -2
- package/runtime/node_modules/@metro-labs/daemon/src/routes/local-mode.ts +2 -27
- package/runtime/node_modules/@metro-labs/daemon/src/routes/session-apis.ts +0 -5
- package/runtime/node_modules/@metro-labs/http/package.json +3 -3
- package/runtime/node_modules/@metro-labs/http/src/connector-grant.ts +0 -51
- package/runtime/node_modules/@metro-labs/http/src/mcp-server-protocol.ts +9 -4
- package/runtime/node_modules/@metro-labs/http/src/mcp-server-tools.ts +93 -0
- package/runtime/runtime.json +1 -1
- package/runtime/sdk-runner/node_modules/@metro-labs/core/package.json +0 -1
- package/runtime/sdk-runner/runner.json +1 -1
- package/{runtime/marketplace/plugin → skills}/METRO.md +8 -3
- package/runtime/marketplace/.claude-plugin/marketplace.json +0 -12
- package/runtime/marketplace/plugin/.claude-plugin/plugin.json +0 -17
- package/runtime/marketplace/plugin/.mcp.json +0 -1
- package/runtime/marketplace/plugin/bin/metro-plugin.mjs +0 -48
- package/runtime/marketplace/plugin/hooks/hooks.json +0 -25
- package/runtime/node_modules/@metro-labs/core/src/connector-sync.ts +0 -17
- package/runtime/node_modules/@metro-labs/daemon/src/claude/plugin-install.ts +0 -149
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/gates.ts +0 -104
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-adopt.ts +0 -57
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-relay.ts +0 -61
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-runtime-discovery.ts +0 -115
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-runtime.ts +0 -271
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync-api.ts +0 -25
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync-control.ts +0 -173
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync-setting.ts +0 -60
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync-watch.ts +0 -38
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/org-sync.ts +0 -208
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/plugin-sync.ts +0 -145
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/publication.ts +0 -40
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay-id.ts +0 -2
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay-policy.ts +0 -90
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay-session.ts +0 -10
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay-target.ts +0 -4
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/relay.ts +0 -287
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/server-keys.ts +0 -59
- package/runtime/node_modules/@metro-labs/daemon/src/connectors/tools.ts +0 -1
- package/runtime/node_modules/@metro-labs/http/src/connector-delivery-validation.ts +0 -116
- package/runtime/node_modules/@metro-labs/http/src/connector-delivery.ts +0 -19
- package/runtime/node_modules/@metro-labs/http/src/connector-migration.ts +0 -178
- package/runtime/node_modules/@metro-labs/http/src/transfer-crypto.ts +0 -44
- package/runtime/sdk-runner/node_modules/@metro-labs/core/src/connector-sync.ts +0 -17
- /package/{runtime/marketplace/plugin → skills}/MEMORY.md +0 -0
- /package/{runtime/marketplace/plugin → skills}/STAGE.md +0 -0
|
@@ -1,208 +0,0 @@
|
|
|
1
|
-
import { randomBytes } from 'node:crypto';
|
|
2
|
-
import { log } from '@metro-labs/core/log';
|
|
3
|
-
import type { ConnectorSyncReceipt } from '@metro-labs/core/connector-sync';
|
|
4
|
-
import { ApiError } from '@metro-labs/http/api-error';
|
|
5
|
-
import { AGENT_CLOCK_SKEW_MS } from '@metro-labs/http/agent-signature';
|
|
6
|
-
import { CONNECTOR_DELIVERY_LEASE_MS, CONNECTOR_DELIVERY_MAX_BYTES, openConnectorDelivery, type DeliveryContext, type DeliverySnapshot } from '@metro-labs/http/connector-delivery';
|
|
7
|
-
import type { AgentKey } from './agent-key.js';
|
|
8
|
-
import { agentCall, MetroApiRefusal, type MetroApi } from './metro-api.js';
|
|
9
|
-
|
|
10
|
-
interface Identity {
|
|
11
|
-
key: AgentKey;
|
|
12
|
-
context: Omit<DeliveryContext, 'requestId'>;
|
|
13
|
-
token: string;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export interface OrgSyncDeps {
|
|
17
|
-
enabled: () => boolean;
|
|
18
|
-
owner: () => string | null;
|
|
19
|
-
key: () => AgentKey | null;
|
|
20
|
-
api: MetroApi;
|
|
21
|
-
monotonic?: () => number;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
interface RefreshRequest {
|
|
25
|
-
connectorId: string;
|
|
26
|
-
revision: string;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const invalid = (): ApiError => new ApiError('Metro received an invalid or expired organization connector snapshot.', 503);
|
|
30
|
-
|
|
31
|
-
function lease(snapshot: DeliverySnapshot, started: number, elapsed: number, now: number): number {
|
|
32
|
-
const duration = snapshot.expiresAt - snapshot.issuedAt;
|
|
33
|
-
if (duration <= 0 || duration > CONNECTOR_DELIVERY_LEASE_MS || snapshot.issuedAt > now + AGENT_CLOCK_SKEW_MS || snapshot.issuedAt < started - AGENT_CLOCK_SKEW_MS) throw invalid();
|
|
34
|
-
const expiries = snapshot.connectors.flatMap((row) => row.state === 'ready' && row.expiresAt !== undefined ? [row.expiresAt] : []);
|
|
35
|
-
const remaining = Math.min(duration, ...expiries.map((at) => at - snapshot.issuedAt)) - elapsed;
|
|
36
|
-
if (remaining <= 0) throw invalid();
|
|
37
|
-
return remaining;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export class OrgConnectorSync {
|
|
41
|
-
private snapshot: DeliverySnapshot | null = null;
|
|
42
|
-
private token: string | null = null;
|
|
43
|
-
private controller: AbortController | null = null;
|
|
44
|
-
private receiptToken: string | null = null;
|
|
45
|
-
private receipt: ConnectorSyncReceipt = { state: 'waiting', lastReceivedAt: null, leaseExpiresAt: null, counts: null };
|
|
46
|
-
private deadline = 0;
|
|
47
|
-
private wallDeadline = 0;
|
|
48
|
-
private generation = 0;
|
|
49
|
-
private running: Promise<void> | null = null;
|
|
50
|
-
private recovery: Promise<void> | null = null;
|
|
51
|
-
private expiry: ReturnType<typeof setTimeout> | null = null;
|
|
52
|
-
private readonly monotonic: () => number;
|
|
53
|
-
private readonly listeners = new Set<() => void>();
|
|
54
|
-
|
|
55
|
-
constructor(private readonly deps: OrgSyncDeps) {
|
|
56
|
-
this.monotonic = deps.monotonic ?? (() => performance.now());
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
onChange(listener: () => void): () => void {
|
|
60
|
-
this.listeners.add(listener);
|
|
61
|
-
return () => { this.listeners.delete(listener); };
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
epoch(): number {
|
|
65
|
-
return this.generation;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
private notify(): void {
|
|
69
|
-
for (const listener of [...this.listeners]) {
|
|
70
|
-
try {
|
|
71
|
-
listener();
|
|
72
|
-
} catch {
|
|
73
|
-
log.warn('organization connectors: a memory change listener failed');
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
private identity(): Identity | null {
|
|
79
|
-
if (!this.deps.enabled()) return null;
|
|
80
|
-
const owner = this.deps.owner();
|
|
81
|
-
const key = this.deps.key();
|
|
82
|
-
const enrollment = key?.enrollment;
|
|
83
|
-
if (owner === null || key === null || enrollment === null || enrollment === undefined || enrollment.organization !== owner) return null;
|
|
84
|
-
const context = { owner, agent: enrollment.server, keyId: key.keyId };
|
|
85
|
-
return { key, context, token: JSON.stringify([context, key.sealingKey]) };
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
private forget(): void {
|
|
89
|
-
this.snapshot = null;
|
|
90
|
-
this.deadline = 0;
|
|
91
|
-
this.wallDeadline = 0;
|
|
92
|
-
if (this.expiry !== null) clearTimeout(this.expiry);
|
|
93
|
-
this.expiry = null;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
private refused = false;
|
|
97
|
-
private settled = false;
|
|
98
|
-
|
|
99
|
-
lapsed(): boolean {
|
|
100
|
-
return !this.refused && (!this.settled || this.receipt.state === 'expired' || this.receipt.state === 'unavailable');
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
invalidate(reason: 'waiting' | 'expired' | 'unavailable' = 'waiting'): void {
|
|
104
|
-
if (reason === 'waiting') this.settled = true;
|
|
105
|
-
this.generation += 1;
|
|
106
|
-
this.controller?.abort();
|
|
107
|
-
this.controller = null;
|
|
108
|
-
if (reason === 'waiting') {
|
|
109
|
-
this.receiptToken = null;
|
|
110
|
-
this.receipt = { state: reason, lastReceivedAt: null, leaseExpiresAt: null, counts: null };
|
|
111
|
-
} else this.receipt = { ...this.receipt, state: reason, counts: null };
|
|
112
|
-
this.token = null;
|
|
113
|
-
this.forget();
|
|
114
|
-
this.notify();
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
private validate(identity: Identity | null): void {
|
|
118
|
-
if (this.token === null) return;
|
|
119
|
-
if (identity === null || identity.token !== this.token) this.invalidate();
|
|
120
|
-
else if (this.snapshot !== null && (this.monotonic() >= this.deadline || this.deps.api.now() >= this.wallDeadline)) this.invalidate('expired');
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
read(): DeliverySnapshot | null {
|
|
124
|
-
if (this.token === null) return null;
|
|
125
|
-
try {
|
|
126
|
-
this.validate(this.identity());
|
|
127
|
-
} catch {
|
|
128
|
-
this.invalidate();
|
|
129
|
-
log.warn('organization connectors: memory could not be checked and was cleared');
|
|
130
|
-
}
|
|
131
|
-
return this.snapshot === null ? null : structuredClone(this.snapshot);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
status(): ConnectorSyncReceipt {
|
|
135
|
-
this.read();
|
|
136
|
-
try {
|
|
137
|
-
if (this.receiptToken !== null && this.identity()?.token !== this.receiptToken) this.invalidate();
|
|
138
|
-
} catch {
|
|
139
|
-
this.invalidate();
|
|
140
|
-
}
|
|
141
|
-
return structuredClone(this.receipt);
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
async sync(refresh?: RefreshRequest): Promise<void> {
|
|
145
|
-
let identity: Identity | null;
|
|
146
|
-
try {
|
|
147
|
-
identity = this.identity();
|
|
148
|
-
this.validate(identity);
|
|
149
|
-
} catch (err) {
|
|
150
|
-
this.invalidate();
|
|
151
|
-
throw err;
|
|
152
|
-
}
|
|
153
|
-
if (identity === null) return;
|
|
154
|
-
if (this.running !== null) return refresh === undefined ? this.running : this.running.then(() => this.sync(refresh));
|
|
155
|
-
this.token = identity.token;
|
|
156
|
-
const generation = this.generation;
|
|
157
|
-
this.controller = new AbortController();
|
|
158
|
-
this.running = this.fetch(identity, refresh, generation, this.controller.signal).then(() => {
|
|
159
|
-
this.refused = false;
|
|
160
|
-
}, (err: unknown) => {
|
|
161
|
-
if (generation === this.generation) {
|
|
162
|
-
this.refused = err instanceof MetroApiRefusal && err.upstreamStatus < 500;
|
|
163
|
-
this.invalidate('unavailable');
|
|
164
|
-
}
|
|
165
|
-
throw err;
|
|
166
|
-
}).finally(() => { this.running = null; });
|
|
167
|
-
return this.running;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
recover(): Promise<void> {
|
|
171
|
-
if (this.read() !== null) return Promise.resolve();
|
|
172
|
-
this.recovery ??= this.syncFresh().finally(() => { this.recovery = null; });
|
|
173
|
-
return this.recovery;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
async syncFresh(refresh?: RefreshRequest): Promise<void> {
|
|
177
|
-
if (this.running !== null) {
|
|
178
|
-
await this.running.catch(() => {
|
|
179
|
-
log.debug('organization connectors: a previous sync failed before a fresh check');
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
return this.sync(refresh);
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
private async fetch(identity: Identity, refresh: RefreshRequest | undefined, generation: number, signal: AbortSignal): Promise<void> {
|
|
186
|
-
const requestId = randomBytes(32).toString('base64url');
|
|
187
|
-
const context = { ...identity.context, requestId };
|
|
188
|
-
const started = this.deps.api.now();
|
|
189
|
-
const clock = this.monotonic();
|
|
190
|
-
const response = await agentCall(this.deps.api, identity.key, '/api/agents/connectors?policy_layers=1', { requestId, ...(refresh === undefined ? {} : { refresh }) }, { answerMax: CONNECTOR_DELIVERY_MAX_BYTES, timeoutMs: 60_000, signal });
|
|
191
|
-
this.validate(this.identity());
|
|
192
|
-
if (generation !== this.generation || this.token !== identity.token) throw invalid();
|
|
193
|
-
const snapshot = openConnectorDelivery(identity.key.sealing, context, response.sealed);
|
|
194
|
-
const remaining = lease(snapshot, started, this.monotonic() - clock, this.deps.api.now());
|
|
195
|
-
this.forget();
|
|
196
|
-
this.snapshot = snapshot;
|
|
197
|
-
this.deadline = this.monotonic() + remaining;
|
|
198
|
-
this.wallDeadline = this.deps.api.now() + remaining;
|
|
199
|
-
this.receiptToken = identity.token;
|
|
200
|
-
const total = snapshot.connectors.length;
|
|
201
|
-
const ready = snapshot.connectors.filter((row) => row.state === 'ready').length;
|
|
202
|
-
this.settled = true;
|
|
203
|
-
this.receipt = { state: 'received', lastReceivedAt: this.deps.api.now(), leaseExpiresAt: this.wallDeadline, counts: { total, ready, unavailable: total - ready } };
|
|
204
|
-
this.expiry = setTimeout(() => { this.invalidate('expired'); }, remaining);
|
|
205
|
-
this.expiry.unref();
|
|
206
|
-
this.notify();
|
|
207
|
-
}
|
|
208
|
-
}
|
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
import { existsSync, readdirEntries, readFileSync } from '../agent-user/agent-fs.js';
|
|
2
|
-
import { writeHomeInPlace } from '../agent-user/home-fs.js';
|
|
3
|
-
import { agentMarketplaceDir, agentUser } from '../agent-user/user.js';
|
|
4
|
-
import { join } from 'node:path';
|
|
5
|
-
import { errMsg, log } from '@metro-labs/core/log';
|
|
6
|
-
import { claudeDir } from '../claude/files.js';
|
|
7
|
-
import { loopbackBase } from '../files/attach-serve.js';
|
|
8
|
-
import { MCP_SERVER_KEY, mcpServerUrl } from '../mcp-server/config.js';
|
|
9
|
-
|
|
10
|
-
const MARKER = join('bin', 'metro-plugin.mjs');
|
|
11
|
-
const FILE = '.mcp.json';
|
|
12
|
-
const HELPER = 'node "${CLAUDE_PLUGIN_ROOT}/bin/metro-plugin.mjs" headers';
|
|
13
|
-
const MCP_HELPER = 'node "${CLAUDE_PLUGIN_ROOT}/bin/metro-plugin.mjs" mcp-headers';
|
|
14
|
-
const SLUG_MAX = 40;
|
|
15
|
-
|
|
16
|
-
export interface PluginRow {
|
|
17
|
-
id: string;
|
|
18
|
-
name: string;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export interface PluginServer {
|
|
22
|
-
type: 'http';
|
|
23
|
-
url: string;
|
|
24
|
-
headersHelper: string;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export function serverKey(name: string): string {
|
|
28
|
-
const slug = name
|
|
29
|
-
.toLowerCase()
|
|
30
|
-
.replace(/[^a-z0-9]+/g, '-')
|
|
31
|
-
.replace(/^-+|-+$/g, '')
|
|
32
|
-
.slice(0, SLUG_MAX)
|
|
33
|
-
.replace(/-+$/, '');
|
|
34
|
-
return slug === '' ? 'connector' : slug;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function availableKey(wanted: string, reserved: ReadonlySet<string>): string {
|
|
38
|
-
let key = wanted;
|
|
39
|
-
let suffix = 1;
|
|
40
|
-
while (reserved.has(key)) key = `${wanted}-${String(suffix++)}`;
|
|
41
|
-
return key;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const reservedKeys = (): ReadonlySet<string> => new Set(mcpServerUrl() === null ? [] : [MCP_SERVER_KEY]);
|
|
45
|
-
|
|
46
|
-
export function serverKeysOf(rows: PluginRow[], saved?: ReadonlyMap<string, string>, reserved: ReadonlySet<string> = reservedKeys()): Map<string, string> {
|
|
47
|
-
const keys = new Map([...(saved ?? [])].filter(([, key]) => !reserved.has(key)));
|
|
48
|
-
const used = new Set([...keys.values(), ...reserved]);
|
|
49
|
-
for (const row of [...rows].sort((a, b) => a.id.localeCompare(b.id))) {
|
|
50
|
-
if (keys.has(row.id)) continue;
|
|
51
|
-
const key = availableKey(serverKey(row.name), used);
|
|
52
|
-
used.add(key);
|
|
53
|
-
keys.set(row.id, key);
|
|
54
|
-
}
|
|
55
|
-
return keys;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export function pluginServers(rows: PluginRow[], base: string, keys: ReadonlyMap<string, string> = serverKeysOf(rows), mcpUrl = mcpServerUrl()): Record<string, PluginServer> {
|
|
59
|
-
const out: Record<string, PluginServer> = {};
|
|
60
|
-
const visible = new Set(rows.map((row) => row.id));
|
|
61
|
-
for (const [id, key] of keys) if (visible.has(id)) out[key] = { type: 'http', url: `${base}/relay/${id}`, headersHelper: HELPER };
|
|
62
|
-
if (mcpUrl !== null) out[MCP_SERVER_KEY] = { type: 'http', url: mcpUrl, headersHelper: MCP_HELPER };
|
|
63
|
-
return out;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const SEARCH_DEPTH = 5;
|
|
67
|
-
|
|
68
|
-
function pluginRootsUnder(dir: string, depth: number, out: string[]): void {
|
|
69
|
-
if (depth < 0 || out.length >= 8) return;
|
|
70
|
-
let entries;
|
|
71
|
-
try {
|
|
72
|
-
entries = readdirEntries(dir);
|
|
73
|
-
} catch {
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
if (entries.some((e) => e.name === 'bin' && e.isDirectory()) && existsSync(join(dir, MARKER))) {
|
|
77
|
-
out.push(dir);
|
|
78
|
-
return;
|
|
79
|
-
}
|
|
80
|
-
for (const entry of entries)
|
|
81
|
-
if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules')
|
|
82
|
-
pluginRootsUnder(join(dir, entry.name), depth - 1, out);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function stagedPluginDir(env: NodeJS.ProcessEnv = process.env): string | null {
|
|
86
|
-
const store = env.METRO_RUNTIME_STORE?.trim() ?? '';
|
|
87
|
-
if (store === '') return null;
|
|
88
|
-
const user = agentUser();
|
|
89
|
-
return join(user === null ? join(store, 'marketplace') : agentMarketplaceDir(user), 'plugin');
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
export function installedPluginFiles(dir = claudeDir(), staged = stagedPluginDir()): string[] {
|
|
93
|
-
const roots: string[] = [];
|
|
94
|
-
const root = join(dir, 'plugins');
|
|
95
|
-
if (existsSync(root)) pluginRootsUnder(root, SEARCH_DEPTH, roots);
|
|
96
|
-
if (staged !== null && existsSync(join(staged, MARKER)) && !roots.includes(staged)) roots.push(staged);
|
|
97
|
-
return roots.map((found) => join(found, FILE));
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
const readOrNull = (path: string): string | null => {
|
|
101
|
-
try {
|
|
102
|
-
return readFileSync(path, 'utf8');
|
|
103
|
-
} catch {
|
|
104
|
-
return null;
|
|
105
|
-
}
|
|
106
|
-
};
|
|
107
|
-
|
|
108
|
-
function writeIfChanged(path: string, text: string): boolean {
|
|
109
|
-
if (readOrNull(path) === text) return false;
|
|
110
|
-
writeHomeInPlace(path, text, 0o644);
|
|
111
|
-
return true;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
export interface PluginSyncOptions {
|
|
115
|
-
dir?: string;
|
|
116
|
-
base?: string;
|
|
117
|
-
staged?: string | null;
|
|
118
|
-
keys?: ReadonlyMap<string, string>;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
function filesFor(opts: PluginSyncOptions): string[] {
|
|
122
|
-
const staged = opts.staged === undefined ? stagedPluginDir() : opts.staged;
|
|
123
|
-
return installedPluginFiles(opts.dir ?? claudeDir(), staged);
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
export function syncPluginServers(rows: PluginRow[], opts: PluginSyncOptions = {}): number {
|
|
127
|
-
const files = filesFor(opts);
|
|
128
|
-
if (files.length === 0) return 0;
|
|
129
|
-
const servers = pluginServers(rows, opts.base ?? loopbackBase(), opts.keys);
|
|
130
|
-
const text = `${JSON.stringify(servers, null, 2)}\n`;
|
|
131
|
-
let written = 0;
|
|
132
|
-
for (const file of files) {
|
|
133
|
-
try {
|
|
134
|
-
if (writeIfChanged(file, text)) written += 1;
|
|
135
|
-
} catch (err) {
|
|
136
|
-
log.warn({ file, err: errMsg(err) }, 'plugin: could not write the connector servers');
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
if (written > 0)
|
|
140
|
-
log.info(
|
|
141
|
-
{ files: written, servers: Object.keys(servers).length },
|
|
142
|
-
'plugin: connector servers written; run /reload-plugins --force to pick them up in a running session',
|
|
143
|
-
);
|
|
144
|
-
return written;
|
|
145
|
-
}
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import { registerConnectors, type GateRow } from './gates.js';
|
|
2
|
-
import { syncPluginServers } from './plugin-sync.js';
|
|
3
|
-
import { persistentServerKeys } from './server-keys.js';
|
|
4
|
-
|
|
5
|
-
let organization: GateRow[] | null = null;
|
|
6
|
-
const BOOT = Date.now();
|
|
7
|
-
const READY_WAIT_MS = 30_000;
|
|
8
|
-
|
|
9
|
-
export const connectorsReady = (now = Date.now()): boolean => organization !== null || now - BOOT >= READY_WAIT_MS;
|
|
10
|
-
|
|
11
|
-
function metadata(rows: readonly GateRow[]): GateRow[] {
|
|
12
|
-
return rows.map((row) => structuredClone({
|
|
13
|
-
id: row.id,
|
|
14
|
-
name: row.name,
|
|
15
|
-
config: {
|
|
16
|
-
...(row.config.policy === undefined ? {} : { policy: row.config.policy }),
|
|
17
|
-
...(row.config.toolGroups === undefined ? {} : { toolGroups: row.config.toolGroups }),
|
|
18
|
-
},
|
|
19
|
-
}));
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function publishConnectors(): void {
|
|
23
|
-
if (organization === null) return;
|
|
24
|
-
let keys: Map<string, string>;
|
|
25
|
-
try {
|
|
26
|
-
keys = persistentServerKeys(organization);
|
|
27
|
-
}
|
|
28
|
-
catch (error) {
|
|
29
|
-
registerConnectors([]);
|
|
30
|
-
syncPluginServers([]);
|
|
31
|
-
throw error;
|
|
32
|
-
}
|
|
33
|
-
registerConnectors(organization, keys);
|
|
34
|
-
syncPluginServers(organization, { keys });
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function publishOrgConnectors(rows: readonly GateRow[]): void {
|
|
38
|
-
organization = metadata(rows);
|
|
39
|
-
publishConnectors();
|
|
40
|
-
}
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import type { ServerResponse } from 'node:http';
|
|
2
|
-
import { isRecord } from '@metro-labs/core/is-record';
|
|
3
|
-
import { log } from '@metro-labs/core/log';
|
|
4
|
-
|
|
5
|
-
export type BlockedReason = (connectorId: string, tool: string, args: Record<string, unknown>) => string | null;
|
|
6
|
-
|
|
7
|
-
export interface Screened {
|
|
8
|
-
forward: Uint8Array<ArrayBuffer> | null;
|
|
9
|
-
answers: Record<string, unknown>[];
|
|
10
|
-
batch: boolean;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
const encoder = new TextEncoder();
|
|
14
|
-
|
|
15
|
-
function parsed(body: Uint8Array): unknown {
|
|
16
|
-
try {
|
|
17
|
-
return JSON.parse(new TextDecoder().decode(body));
|
|
18
|
-
} catch {
|
|
19
|
-
return undefined;
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function toolOf(message: unknown): string | null {
|
|
24
|
-
if (!isRecord(message) || message.method !== 'tools/call' || !isRecord(message.params)) return null;
|
|
25
|
-
const name = message.params.name;
|
|
26
|
-
return typeof name === 'string' ? name : null;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function blockedAnswer(message: Record<string, unknown>, reason: string): Record<string, unknown> | null {
|
|
30
|
-
if (!('id' in message)) return null;
|
|
31
|
-
return { jsonrpc: '2.0', id: message.id, result: { isError: true, content: [{ type: 'text', text: reason }] } };
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function argsOf(message: unknown): Record<string, unknown> {
|
|
35
|
-
if (!isRecord(message) || !isRecord(message.params)) return {};
|
|
36
|
-
return isRecord(message.params.arguments) ? message.params.arguments : {};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function reasonFor(message: unknown, connectorId: string, blocked: BlockedReason): string | null {
|
|
40
|
-
const tool = toolOf(message);
|
|
41
|
-
return tool === null ? null : blocked(connectorId, tool, argsOf(message));
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export function screenCalls(body: Uint8Array<ArrayBuffer>, connectorId: string, blocked: BlockedReason): Screened | null {
|
|
45
|
-
const message = parsed(body);
|
|
46
|
-
const batch = Array.isArray(message);
|
|
47
|
-
const list: unknown[] = batch ? message : [message];
|
|
48
|
-
const answers: Record<string, unknown>[] = [];
|
|
49
|
-
const kept: unknown[] = [];
|
|
50
|
-
for (const item of list) {
|
|
51
|
-
const reason = reasonFor(item, connectorId, blocked);
|
|
52
|
-
if (reason === null || !isRecord(item)) {
|
|
53
|
-
kept.push(item);
|
|
54
|
-
continue;
|
|
55
|
-
}
|
|
56
|
-
log.info({ connector: connectorId, tool: toolOf(item) }, 'relay: a call the owner blocked was answered without the connector');
|
|
57
|
-
const answer = blockedAnswer(item, reason);
|
|
58
|
-
if (answer !== null) answers.push(answer);
|
|
59
|
-
}
|
|
60
|
-
if (kept.length === list.length) return null;
|
|
61
|
-
const forward = kept.length === 0 ? null : new Uint8Array(encoder.encode(JSON.stringify(kept)));
|
|
62
|
-
return { forward, answers, batch };
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export function answerBlocked(res: ServerResponse, screened: Screened): void {
|
|
66
|
-
if (res.headersSent) return;
|
|
67
|
-
if (screened.answers.length === 0) {
|
|
68
|
-
res.writeHead(202).end();
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
const body = screened.batch ? screened.answers : screened.answers[0];
|
|
72
|
-
res.writeHead(200, { 'content-type': 'application/json' });
|
|
73
|
-
res.end(JSON.stringify(body));
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const sseFrames = (answers: Record<string, unknown>[]): string =>
|
|
77
|
-
answers.map((answer) => `event: message\ndata: ${JSON.stringify(answer)}\n\n`).join('');
|
|
78
|
-
|
|
79
|
-
export async function mergeBlocked(res: ServerResponse, upstream: Response, headers: Record<string, string>, answers: Record<string, unknown>[]): Promise<void> {
|
|
80
|
-
const text = await upstream.text();
|
|
81
|
-
if ((headers['content-type'] ?? '').includes('text/event-stream')) {
|
|
82
|
-
res.writeHead(upstream.status, headers);
|
|
83
|
-
res.end(`${text}${sseFrames(answers)}`);
|
|
84
|
-
return;
|
|
85
|
-
}
|
|
86
|
-
const theirs = text.trim() === '' ? [] : parsed(encoder.encode(text));
|
|
87
|
-
const list: unknown[] = Array.isArray(theirs) ? theirs : theirs === undefined || theirs === null ? [] : [theirs];
|
|
88
|
-
res.writeHead(200, { ...headers, 'content-type': 'application/json' });
|
|
89
|
-
res.end(JSON.stringify([...list, ...answers]));
|
|
90
|
-
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { BlockedReason } from './relay-policy.js';
|
|
2
|
-
import type { RelayTarget } from './relay-target.js';
|
|
3
|
-
|
|
4
|
-
export interface RelaySession {
|
|
5
|
-
target: (force: boolean) => Promise<RelayTarget>;
|
|
6
|
-
current: () => RelayTarget;
|
|
7
|
-
blocker: () => BlockedReason;
|
|
8
|
-
signal: AbortSignal;
|
|
9
|
-
close: () => void;
|
|
10
|
-
}
|