@0xmaxma/claude-gateway 2.1.7 → 2.1.9
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/api/connectors-router.d.ts.map +1 -1
- package/dist/api/connectors-router.js +27 -3
- package/dist/api/connectors-router.js.map +1 -1
- package/dist/automation/browser-trace.d.ts +1 -1
- package/dist/build-provenance.json +4 -4
- package/dist/connectors/custom-connectors-store.d.ts.map +1 -1
- package/dist/connectors/custom-connectors-store.js +6 -1
- package/dist/connectors/custom-connectors-store.js.map +1 -1
- package/dist/connectors/custom.d.ts +14 -0
- package/dist/connectors/custom.d.ts.map +1 -1
- package/dist/connectors/custom.js +43 -2
- package/dist/connectors/custom.js.map +1 -1
- package/dist/connectors/proxy.d.ts +8 -0
- package/dist/connectors/proxy.d.ts.map +1 -1
- package/dist/connectors/proxy.js +53 -5
- package/dist/connectors/proxy.js.map +1 -1
- package/dist/connectors/resolve.d.ts.map +1 -1
- package/dist/connectors/resolve.js +16 -2
- package/dist/connectors/resolve.js.map +1 -1
- package/dist/connectors/sidecar.d.ts +131 -0
- package/dist/connectors/sidecar.d.ts.map +1 -0
- package/dist/connectors/sidecar.js +768 -0
- package/dist/connectors/sidecar.js.map +1 -0
- package/dist/connectors/token-env.d.ts +2 -0
- package/dist/connectors/token-env.d.ts.map +1 -1
- package/dist/connectors/token-env.js +16 -0
- package/dist/connectors/token-env.js.map +1 -1
- package/dist/connectors/types.d.ts +4 -0
- package/dist/connectors/types.d.ts.map +1 -1
- package/dist/connectors/uv-runtime.d.ts +37 -0
- package/dist/connectors/uv-runtime.d.ts.map +1 -0
- package/dist/connectors/uv-runtime.js +236 -0
- package/dist/connectors/uv-runtime.js.map +1 -0
- package/dist/index.js +10 -1
- package/dist/index.js.map +1 -1
- package/dist/jev/browser-evidence-summary.d.ts +1 -1
- package/dist/orchestration/connector-context.d.ts +17 -0
- package/dist/orchestration/connector-context.d.ts.map +1 -0
- package/dist/orchestration/connector-context.js +56 -0
- package/dist/orchestration/connector-context.js.map +1 -0
- package/dist/orchestration/runtime.d.ts.map +1 -1
- package/dist/orchestration/runtime.js +4 -0
- package/dist/orchestration/runtime.js.map +1 -1
- package/dist/orchestration/share-path.d.ts.map +1 -1
- package/dist/orchestration/share-path.js +59 -33
- package/dist/orchestration/share-path.js.map +1 -1
- package/dist/orchestration/tasks/driver.d.ts.map +1 -1
- package/dist/orchestration/tasks/driver.js +4 -0
- package/dist/orchestration/tasks/driver.js.map +1 -1
- package/dist/session/managed-connectors.d.ts +2 -0
- package/dist/session/managed-connectors.d.ts.map +1 -1
- package/dist/session/managed-connectors.js +9 -4
- package/dist/session/managed-connectors.js.map +1 -1
- package/dist/session/process.d.ts +3 -0
- package/dist/session/process.d.ts.map +1 -1
- package/dist/session/process.js +21 -3
- package/dist/session/process.js.map +1 -1
- package/dist/voice/errors.d.ts +1 -1
- package/mcp/fixtures/workspace-mcp-tools.json +260 -0
- package/mcp/lazy-tools.test.ts +137 -1
- package/mcp/lazy-tools.ts +40 -7
- package/package.json +1 -1
|
@@ -0,0 +1,768 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Connector sidecars: an HTTP connector whose MCP server the gateway runs itself.
|
|
4
|
+
*
|
|
5
|
+
* A custom connector entry of type `http`/`streamable-http` may carry
|
|
6
|
+
*
|
|
7
|
+
* sidecar: { command, args?, env?, path? = "/mcp", readyTimeoutMs? = 120000 }
|
|
8
|
+
*
|
|
9
|
+
* instead of a `url`. While the entry exists, is connected and is not paused, the
|
|
10
|
+
* supervisor below keeps that command running on a loopback port it allocates and passes as `PORT`,
|
|
11
|
+
* and resolve.ts points the entry's url at `http://127.0.0.1:<port><path>`. Agents
|
|
12
|
+
* still reach it only through the loopback proxy (connectors/proxy.ts), which adds
|
|
13
|
+
* the entry's `headers` per request, so the credential never enters the sidecar's
|
|
14
|
+
* argv or environment, and a token-only update never restarts it.
|
|
15
|
+
*
|
|
16
|
+
* The desired set of sidecars is always "every sidecar entry in customConnectors that
|
|
17
|
+
* is connected and not paused": every config write calls `reconcile` with the whole
|
|
18
|
+
* map and every secret write re-runs it with the last one, so the supervisor converges
|
|
19
|
+
* on the same state however many times, and in whatever order, it is told.
|
|
20
|
+
*/
|
|
21
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
22
|
+
if (k2 === undefined) k2 = k;
|
|
23
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
24
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
25
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
26
|
+
}
|
|
27
|
+
Object.defineProperty(o, k2, desc);
|
|
28
|
+
}) : (function(o, m, k, k2) {
|
|
29
|
+
if (k2 === undefined) k2 = k;
|
|
30
|
+
o[k2] = m[k];
|
|
31
|
+
}));
|
|
32
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
33
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
34
|
+
}) : function(o, v) {
|
|
35
|
+
o["default"] = v;
|
|
36
|
+
});
|
|
37
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
38
|
+
var ownKeys = function(o) {
|
|
39
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
40
|
+
var ar = [];
|
|
41
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
42
|
+
return ar;
|
|
43
|
+
};
|
|
44
|
+
return ownKeys(o);
|
|
45
|
+
};
|
|
46
|
+
return function (mod) {
|
|
47
|
+
if (mod && mod.__esModule) return mod;
|
|
48
|
+
var result = {};
|
|
49
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
50
|
+
__setModuleDefault(result, mod);
|
|
51
|
+
return result;
|
|
52
|
+
};
|
|
53
|
+
})();
|
|
54
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
55
|
+
exports.connectorSidecars = exports.SidecarSupervisor = void 0;
|
|
56
|
+
exports.parseSidecarSpec = parseSidecarSpec;
|
|
57
|
+
const child_process_1 = require("child_process");
|
|
58
|
+
const fs = __importStar(require("fs"));
|
|
59
|
+
const net = __importStar(require("net"));
|
|
60
|
+
const os = __importStar(require("os"));
|
|
61
|
+
const path = __importStar(require("path"));
|
|
62
|
+
const custom_1 = require("./custom");
|
|
63
|
+
const token_env_1 = require("./token-env");
|
|
64
|
+
const uv_runtime_1 = require("./uv-runtime");
|
|
65
|
+
const SIDECAR_FIELDS = new Set(['command', 'args', 'env', 'path', 'readyTimeoutMs']);
|
|
66
|
+
const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
67
|
+
const DEFAULT_PATH = '/mcp';
|
|
68
|
+
const DEFAULT_READY_TIMEOUT_MS = 120000;
|
|
69
|
+
const MAX_READY_TIMEOUT_MS = 600000;
|
|
70
|
+
/**
|
|
71
|
+
* The entry's sidecar spec, `undefined` when it has none, or the reason it is unusable.
|
|
72
|
+
* Run at the API boundary (a 400) and again on every reconcile, since config.json can
|
|
73
|
+
* also be edited by hand.
|
|
74
|
+
*/
|
|
75
|
+
function parseSidecarSpec(config) {
|
|
76
|
+
const raw = config.sidecar;
|
|
77
|
+
if (raw === undefined)
|
|
78
|
+
return undefined;
|
|
79
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
80
|
+
return { error: 'sidecar must be an object' };
|
|
81
|
+
if (!(0, custom_1.isStreamableHttpType)(config.type))
|
|
82
|
+
return { error: "sidecar requires config.type 'http' or 'streamable-http'" };
|
|
83
|
+
if (config.url !== undefined)
|
|
84
|
+
return { error: 'config.url must be omitted with sidecar: the gateway serves it on a loopback port it allocates' };
|
|
85
|
+
if (config.headersHelper !== undefined || config.oauth !== undefined)
|
|
86
|
+
return { error: 'sidecar cannot be combined with headersHelper or oauth' };
|
|
87
|
+
const sidecar = raw;
|
|
88
|
+
const unknown = Object.keys(sidecar).filter(key => !SIDECAR_FIELDS.has(key));
|
|
89
|
+
if (unknown.length)
|
|
90
|
+
return { error: `sidecar has unknown field(s): ${unknown.join(', ')}` };
|
|
91
|
+
if ((0, custom_1.extractPlaceholders)(sidecar).length)
|
|
92
|
+
return { error: 'sidecar must not contain {placeholders}: secrets reach the sidecar only as request headers' };
|
|
93
|
+
const { command, args = [], env = {}, path: mcpPath = DEFAULT_PATH, readyTimeoutMs = DEFAULT_READY_TIMEOUT_MS } = sidecar;
|
|
94
|
+
if (typeof command !== 'string' || !command.trim())
|
|
95
|
+
return { error: 'sidecar.command must be a non-empty string' };
|
|
96
|
+
if (!Array.isArray(args) || !args.every(arg => typeof arg === 'string'))
|
|
97
|
+
return { error: 'sidecar.args must be an array of strings' };
|
|
98
|
+
if (!env || typeof env !== 'object' || Array.isArray(env))
|
|
99
|
+
return { error: 'sidecar.env must be an object of strings' };
|
|
100
|
+
for (const [name, value] of Object.entries(env)) {
|
|
101
|
+
if (!ENV_NAME_RE.test(name) || typeof value !== 'string')
|
|
102
|
+
return { error: 'sidecar.env must map variable names to strings' };
|
|
103
|
+
if (name === 'PORT')
|
|
104
|
+
return { error: 'sidecar.env must not set PORT: the gateway assigns it' };
|
|
105
|
+
}
|
|
106
|
+
if (typeof mcpPath !== 'string' || !mcpPath.startsWith('/'))
|
|
107
|
+
return { error: "sidecar.path must start with '/'" };
|
|
108
|
+
if (typeof readyTimeoutMs !== 'number' || !Number.isInteger(readyTimeoutMs) || readyTimeoutMs < 1000 || readyTimeoutMs > MAX_READY_TIMEOUT_MS) {
|
|
109
|
+
return { error: `sidecar.readyTimeoutMs must be an integer from 1000 to ${MAX_READY_TIMEOUT_MS}` };
|
|
110
|
+
}
|
|
111
|
+
return { command: command.trim(), args: args, env: env, path: mcpPath, readyTimeoutMs };
|
|
112
|
+
}
|
|
113
|
+
/** Equal for two specs exactly when restarting from one to the other changes nothing. */
|
|
114
|
+
function specKey(spec) {
|
|
115
|
+
return JSON.stringify([spec.command, spec.args, Object.entries(spec.env).sort(([a], [b]) => a.localeCompare(b)), spec.path, spec.readyTimeoutMs]);
|
|
116
|
+
}
|
|
117
|
+
const DEFAULT_BACKOFF_MS = [1000, 2000, 5000, 10000, 30000, 60000];
|
|
118
|
+
const STDERR_LINES_PER_MINUTE = 120;
|
|
119
|
+
const MAX_LOG_LINE = 2000;
|
|
120
|
+
/** In a sidecar's working directory while its process group runs: `{pgid, command, args}`. */
|
|
121
|
+
const PGID_FILE = 'pgid';
|
|
122
|
+
class SidecarSupervisor {
|
|
123
|
+
constructor(options) {
|
|
124
|
+
this.sidecars = new Map();
|
|
125
|
+
this.closed = false;
|
|
126
|
+
/** Children between SIGTERM and exit. Their sidecar's phase is already past them, so the shutdown paths look here. */
|
|
127
|
+
this.stopping = new Map();
|
|
128
|
+
/** Aborted by close(), so a uv download in progress does not hold up shutdown. */
|
|
129
|
+
this.shutdown = new AbortController();
|
|
130
|
+
/** Bumped on every secret write, so the output mask stops trusting its cached secrets. */
|
|
131
|
+
this.secretWrites = 0;
|
|
132
|
+
this.options = {
|
|
133
|
+
backoffMs: DEFAULT_BACKOFF_MS,
|
|
134
|
+
stableMs: 30000,
|
|
135
|
+
stopGraceMs: 5000,
|
|
136
|
+
random: Math.random,
|
|
137
|
+
log: line => console.error(line),
|
|
138
|
+
...options,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** Converge on one running sidecar per connected, non-paused sidecar entry in `entries`. */
|
|
142
|
+
reconcile(entries) {
|
|
143
|
+
if (this.closed)
|
|
144
|
+
return;
|
|
145
|
+
this.entries = entries;
|
|
146
|
+
const desired = new Map();
|
|
147
|
+
let tokenEnv;
|
|
148
|
+
for (const [id, entry] of Object.entries(entries ?? {})) {
|
|
149
|
+
if (!(0, custom_1.isValidConnectorId)(id)) {
|
|
150
|
+
this.options.log(`connector-sidecar: invalid persisted connector id rejected`);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (!entry || entry.paused === true || !entry.config || typeof entry.config !== 'object')
|
|
154
|
+
continue;
|
|
155
|
+
const parsed = parseSidecarSpec(entry.config);
|
|
156
|
+
if (parsed && isConnected(id, entry, tokenEnv ?? (tokenEnv = (0, token_env_1.readTokenEnv)())))
|
|
157
|
+
desired.set(id, parsed);
|
|
158
|
+
}
|
|
159
|
+
for (const id of this.sidecars.keys())
|
|
160
|
+
if (!desired.has(id))
|
|
161
|
+
this.remove(id, true);
|
|
162
|
+
for (const [id, parsed] of desired) {
|
|
163
|
+
const key = 'error' in parsed ? `invalid:${parsed.error}` : specKey(parsed);
|
|
164
|
+
const current = this.sidecars.get(id);
|
|
165
|
+
if (current?.key === key)
|
|
166
|
+
continue;
|
|
167
|
+
const sidecar = current ?? this.create(id);
|
|
168
|
+
sidecar.key = key;
|
|
169
|
+
sidecar.failures = 0;
|
|
170
|
+
if ('error' in parsed) {
|
|
171
|
+
sidecar.spec = undefined;
|
|
172
|
+
this.enqueue(sidecar, async () => {
|
|
173
|
+
await this.halt(sidecar);
|
|
174
|
+
sidecar.phase = { kind: 'invalid' };
|
|
175
|
+
sidecar.lastError = parsed.error;
|
|
176
|
+
this.options.log(`connector-sidecar: connector=${id} not started: ${parsed.error}`);
|
|
177
|
+
});
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
sidecar.spec = parsed;
|
|
181
|
+
const restarting = current !== undefined;
|
|
182
|
+
this.enqueue(sidecar, async () => {
|
|
183
|
+
await this.halt(sidecar);
|
|
184
|
+
if (restarting)
|
|
185
|
+
sidecar.restarts++;
|
|
186
|
+
await this.start(sidecar);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** Reconcile the last entries again: a connect or disconnect changes only the secrets. */
|
|
191
|
+
secretsChanged() {
|
|
192
|
+
this.secretWrites++;
|
|
193
|
+
this.reconcile(this.entries);
|
|
194
|
+
}
|
|
195
|
+
/** The upstream url while the sidecar is ready, else undefined. */
|
|
196
|
+
urlOf(id) {
|
|
197
|
+
const sidecar = this.sidecars.get(id);
|
|
198
|
+
if (!sidecar?.spec || sidecar.phase.kind !== 'ready')
|
|
199
|
+
return undefined;
|
|
200
|
+
return `http://127.0.0.1:${sidecar.phase.port}${sidecar.spec.path}`;
|
|
201
|
+
}
|
|
202
|
+
statusOf(id) {
|
|
203
|
+
const sidecar = this.sidecars.get(id);
|
|
204
|
+
if (!sidecar)
|
|
205
|
+
return undefined;
|
|
206
|
+
const { phase } = sidecar;
|
|
207
|
+
// A listed sidecar that is stopped is between a stop and its next start.
|
|
208
|
+
const state = phase.kind === 'ready' ? 'ready'
|
|
209
|
+
: phase.kind === 'starting' || phase.kind === 'stopped' ? 'starting'
|
|
210
|
+
: phase.kind === 'invalid' ? 'invalid'
|
|
211
|
+
: 'crashed';
|
|
212
|
+
const pid = phase.kind === 'ready' || phase.kind === 'starting' ? phase.child?.pid : undefined;
|
|
213
|
+
return {
|
|
214
|
+
state,
|
|
215
|
+
...(pid !== undefined ? { pid } : {}),
|
|
216
|
+
restarts: sidecar.restarts,
|
|
217
|
+
...(sidecar.lastError && state !== 'ready' ? { lastError: sidecar.lastError } : {}),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
/** Resolves with the url once ready; undefined when it fails first, after its readyTimeoutMs, on `signal`, or when it is not running. */
|
|
221
|
+
waitUntilReady(id, signal) {
|
|
222
|
+
const sidecar = this.sidecars.get(id);
|
|
223
|
+
if (!sidecar || sidecar.phase.kind === 'ready')
|
|
224
|
+
return Promise.resolve(this.urlOf(id));
|
|
225
|
+
// 'stopped' is not final here: a listed sidecar is stopped only between a halt and its next start.
|
|
226
|
+
if (!sidecar.spec || sidecar.phase.kind === 'invalid')
|
|
227
|
+
return Promise.resolve(undefined);
|
|
228
|
+
const timeoutMs = sidecar.spec.readyTimeoutMs;
|
|
229
|
+
return new Promise(resolve => {
|
|
230
|
+
const done = () => {
|
|
231
|
+
clearTimeout(timer);
|
|
232
|
+
sidecar.waiters.delete(done);
|
|
233
|
+
signal?.removeEventListener('abort', done);
|
|
234
|
+
resolve(this.urlOf(id));
|
|
235
|
+
};
|
|
236
|
+
const timer = setTimeout(done, timeoutMs);
|
|
237
|
+
sidecar.waiters.add(done);
|
|
238
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
/** Stop every sidecar and refuse new ones: gateway shutdown. */
|
|
242
|
+
async close() {
|
|
243
|
+
this.closed = true;
|
|
244
|
+
this.shutdown.abort(new Error('gateway shutting down'));
|
|
245
|
+
const sidecars = [...this.sidecars.values()];
|
|
246
|
+
// A stop normally ends within stopGraceMs; one stuck behind a slow lifecycle step
|
|
247
|
+
// in its queue must not hold up the gateway's exit.
|
|
248
|
+
let timer;
|
|
249
|
+
const timedOut = new Promise(resolve => { timer = setTimeout(() => resolve(true), 2 * this.options.stopGraceMs); });
|
|
250
|
+
const stopped = Promise.all([...sidecars.map(sidecar => this.remove(sidecar.id, false)), ...this.stopping.values()]).then(() => false);
|
|
251
|
+
if (await Promise.race([stopped, timedOut]))
|
|
252
|
+
killGroups(sidecars, this.stopping.keys());
|
|
253
|
+
clearTimeout(timer);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Kill the sidecars a previous gateway left running: one that was SIGKILLed or
|
|
257
|
+
* OOM-killed never ran close(), and its detached process groups outlive it. Run at
|
|
258
|
+
* boot before the first reconcile.
|
|
259
|
+
*/
|
|
260
|
+
async reclaimOrphans() {
|
|
261
|
+
const dir = path.join(this.options.runtimeRoot, 'sidecars');
|
|
262
|
+
let ids;
|
|
263
|
+
try {
|
|
264
|
+
ids = fs.readdirSync(dir);
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
for (const id of ids) {
|
|
270
|
+
await this.reclaimGroup(id);
|
|
271
|
+
// Empty unless the sidecar wrote there; reconcile recreates it for a configured id.
|
|
272
|
+
try {
|
|
273
|
+
fs.rmdirSync(this.workDir(id));
|
|
274
|
+
}
|
|
275
|
+
catch { /* not empty */ }
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/** Last-resort synchronous kill for process exit paths that cannot await. */
|
|
279
|
+
killAllNow() {
|
|
280
|
+
killGroups(this.sidecars.values(), this.stopping.keys());
|
|
281
|
+
}
|
|
282
|
+
create(id) {
|
|
283
|
+
const sidecar = { id, key: '', phase: { kind: 'stopped' }, failures: 0, restarts: 0, queue: Promise.resolve(), waiters: new Set() };
|
|
284
|
+
this.sidecars.set(id, sidecar);
|
|
285
|
+
return sidecar;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Stop and forget a sidecar; `purge` also deletes its working directory. Reconcile
|
|
289
|
+
* purges whenever an entry stops being desired (removed, disconnected or paused);
|
|
290
|
+
* close() does not, since the gateway is stopping, not the connector.
|
|
291
|
+
*/
|
|
292
|
+
remove(id, purge) {
|
|
293
|
+
const sidecar = this.sidecars.get(id);
|
|
294
|
+
if (!sidecar)
|
|
295
|
+
return Promise.resolve();
|
|
296
|
+
this.sidecars.delete(id);
|
|
297
|
+
sidecar.key = '';
|
|
298
|
+
return this.enqueue(sidecar, async () => {
|
|
299
|
+
await this.halt(sidecar);
|
|
300
|
+
sidecar.phase = { kind: 'stopped' };
|
|
301
|
+
this.notify(sidecar);
|
|
302
|
+
if (purge && !this.sidecars.has(id))
|
|
303
|
+
fs.rmSync(this.workDir(id), { recursive: true, force: true });
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
workDir(id) {
|
|
307
|
+
if (!(0, custom_1.isValidConnectorId)(id))
|
|
308
|
+
throw new Error('invalid connector id for sidecar directory');
|
|
309
|
+
return path.join(this.options.runtimeRoot, 'sidecars', id);
|
|
310
|
+
}
|
|
311
|
+
/** Drop the group record, unless a later start of the same id has replaced it. */
|
|
312
|
+
forgetGroup(id, pgid) {
|
|
313
|
+
const file = path.join(this.workDir(id), PGID_FILE);
|
|
314
|
+
try {
|
|
315
|
+
if (JSON.parse(fs.readFileSync(file, 'utf8')).pgid === pgid)
|
|
316
|
+
fs.rmSync(file, { force: true });
|
|
317
|
+
}
|
|
318
|
+
catch { /* none recorded */ }
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* SIGKILL the process group recorded for `id` by an earlier spawn whose stop never
|
|
322
|
+
* ran. A recorded leader that is alive must still run the recorded command line, so a
|
|
323
|
+
* recycled pid is never killed; only its args are compared when it has some, because
|
|
324
|
+
* uvx re-execs itself as `uv tool uvx <args>`. A group whose leader exited but whose members live on
|
|
325
|
+
* (python after uvx) cannot have been recycled: a pgid is not reused while the group exists.
|
|
326
|
+
*/
|
|
327
|
+
async reclaimGroup(id) {
|
|
328
|
+
const file = path.join(this.workDir(id), PGID_FILE);
|
|
329
|
+
let record;
|
|
330
|
+
try {
|
|
331
|
+
record = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
332
|
+
}
|
|
333
|
+
catch {
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
try {
|
|
337
|
+
if (!Number.isInteger(record.pgid) || record.pgid <= 1)
|
|
338
|
+
return;
|
|
339
|
+
const members = (await listProcesses()).filter(p => p.pgid === record.pgid);
|
|
340
|
+
const leader = members.find(p => p.pid === record.pgid);
|
|
341
|
+
const runsRecorded = (line) => record.args ? line.endsWith(` ${record.args}`) : line === record.command;
|
|
342
|
+
if (!members.length || (leader && !runsRecorded(leader.command)))
|
|
343
|
+
return;
|
|
344
|
+
try {
|
|
345
|
+
process.kill(-record.pgid, 'SIGKILL');
|
|
346
|
+
}
|
|
347
|
+
catch (err) {
|
|
348
|
+
if (err.code !== 'ESRCH')
|
|
349
|
+
throw err;
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
this.options.log(`connector-sidecar: connector=${id} reclaimed orphaned process group ${record.pgid} (${members.length} process(es))`);
|
|
353
|
+
}
|
|
354
|
+
catch (err) {
|
|
355
|
+
this.options.log(`connector-sidecar: connector=${id} orphan check failed: ${err.message}`);
|
|
356
|
+
}
|
|
357
|
+
finally {
|
|
358
|
+
fs.rmSync(file, { force: true });
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
enqueue(sidecar, op) {
|
|
362
|
+
sidecar.queue = sidecar.queue.then(op).catch(err => {
|
|
363
|
+
this.options.log(`connector-sidecar: connector=${sidecar.id} lifecycle error: ${err.message}`);
|
|
364
|
+
});
|
|
365
|
+
return sidecar.queue;
|
|
366
|
+
}
|
|
367
|
+
notify(sidecar) {
|
|
368
|
+
for (const waiter of [...sidecar.waiters])
|
|
369
|
+
waiter();
|
|
370
|
+
}
|
|
371
|
+
current(sidecar, key) {
|
|
372
|
+
return this.sidecars.get(sidecar.id) === sidecar && sidecar.key === key && !this.closed;
|
|
373
|
+
}
|
|
374
|
+
async start(sidecar) {
|
|
375
|
+
const spec = sidecar.spec;
|
|
376
|
+
if (!spec)
|
|
377
|
+
return;
|
|
378
|
+
const key = sidecar.key;
|
|
379
|
+
sidecar.phase = { kind: 'starting' };
|
|
380
|
+
let child;
|
|
381
|
+
let port;
|
|
382
|
+
try {
|
|
383
|
+
const command = (0, uv_runtime_1.isUvCommand)(spec.command)
|
|
384
|
+
? await (0, uv_runtime_1.resolveUvCommand)(spec.command, { installRoot: this.options.runtimeRoot, searchPath: this.options.searchPath, signal: this.shutdown.signal })
|
|
385
|
+
: spec.command;
|
|
386
|
+
if (!this.current(sidecar, key))
|
|
387
|
+
return;
|
|
388
|
+
await this.reclaimGroup(sidecar.id);
|
|
389
|
+
if (!this.current(sidecar, key))
|
|
390
|
+
return;
|
|
391
|
+
port = await allocatePort(sidecar.lastPort);
|
|
392
|
+
if (!this.current(sidecar, key))
|
|
393
|
+
return;
|
|
394
|
+
sidecar.lastPort = port;
|
|
395
|
+
const cwd = this.workDir(sidecar.id);
|
|
396
|
+
fs.mkdirSync(cwd, { recursive: true, mode: 0o700 });
|
|
397
|
+
child = (0, child_process_1.spawn)(command, spec.args, {
|
|
398
|
+
cwd,
|
|
399
|
+
env: this.childEnv(spec, command, port),
|
|
400
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
401
|
+
// Its own process group, so stopping it also stops what it spawned (uvx runs python).
|
|
402
|
+
detached: true,
|
|
403
|
+
});
|
|
404
|
+
// Detached, so the group id is the leader's pid. Kept until halt, for reclaimOrphans.
|
|
405
|
+
if (child.pid !== undefined) {
|
|
406
|
+
fs.writeFileSync(path.join(cwd, PGID_FILE), JSON.stringify({ pgid: child.pid, command, args: spec.args.join(' ') }), { mode: 0o600 });
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
catch (err) {
|
|
410
|
+
if (child?.pid !== undefined)
|
|
411
|
+
await this.stop(child);
|
|
412
|
+
this.failed(sidecar, key, err.message);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
if (!child)
|
|
416
|
+
return;
|
|
417
|
+
sidecar.phase = { kind: 'starting', child, port };
|
|
418
|
+
this.pipeOutput(sidecar, child);
|
|
419
|
+
let exited = false;
|
|
420
|
+
child.once('error', err => {
|
|
421
|
+
exited = true;
|
|
422
|
+
if (sidecar.phase.kind !== 'stopped' && sidecar.phase.child === child)
|
|
423
|
+
this.failed(sidecar, key, err.message);
|
|
424
|
+
});
|
|
425
|
+
child.once('exit', (code, signal) => {
|
|
426
|
+
exited = true;
|
|
427
|
+
if (sidecar.phase.child !== child)
|
|
428
|
+
return;
|
|
429
|
+
// The leader is gone but what it started (uvx's python) may still hold the port.
|
|
430
|
+
signalGroup(child, 'SIGKILL');
|
|
431
|
+
this.forgetGroup(sidecar.id, child.pid);
|
|
432
|
+
const ranFor = sidecar.phase.kind === 'ready' ? Date.now() - sidecar.phase.since : 0;
|
|
433
|
+
if (ranFor >= this.options.stableMs)
|
|
434
|
+
sidecar.failures = 0;
|
|
435
|
+
this.failed(sidecar, key, `exited ${signal ? `by ${signal}` : `with code ${code}`}`);
|
|
436
|
+
});
|
|
437
|
+
// Without a pid the spawn failed (ENOENT) and its 'error' event reports that.
|
|
438
|
+
if (child.pid !== undefined)
|
|
439
|
+
this.options.log(`connector-sidecar: connector=${sidecar.id} started pid=${child.pid} port=${port}`);
|
|
440
|
+
// Not awaited: the queue must stay free for a stop while a slow server comes up.
|
|
441
|
+
void this.awaitReady(sidecar, key, child, port, spec, () => exited);
|
|
442
|
+
}
|
|
443
|
+
async awaitReady(sidecar, key, child, port, spec, exited) {
|
|
444
|
+
const running = () => !exited() && this.current(sidecar, key) && sidecar.phase.child === child;
|
|
445
|
+
const timeoutMs = spec.readyTimeoutMs;
|
|
446
|
+
const deadline = Date.now() + timeoutMs;
|
|
447
|
+
// lsof and ps are slow; a foreign listener holding the port is unlikely to leave soon.
|
|
448
|
+
let ownershipPollMs = 50;
|
|
449
|
+
while (running() && Date.now() < deadline) {
|
|
450
|
+
if (!await answersHttp(port, spec.path)) {
|
|
451
|
+
await delay(50);
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
if (await listenerInGroup(port, child.pid)) {
|
|
455
|
+
if (!running())
|
|
456
|
+
return;
|
|
457
|
+
sidecar.phase = { kind: 'ready', child, port, since: Date.now() };
|
|
458
|
+
sidecar.lastError = undefined;
|
|
459
|
+
this.options.log(`connector-sidecar: connector=${sidecar.id} ready on 127.0.0.1:${port}`);
|
|
460
|
+
this.notify(sidecar);
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
await delay(Math.min(ownershipPollMs, Math.max(0, deadline - Date.now())));
|
|
464
|
+
ownershipPollMs = Math.min(2 * ownershipPollMs, 1000);
|
|
465
|
+
}
|
|
466
|
+
if (!running())
|
|
467
|
+
return;
|
|
468
|
+
this.enqueue(sidecar, async () => {
|
|
469
|
+
if (!running())
|
|
470
|
+
return;
|
|
471
|
+
sidecar.phase = { kind: 'starting' };
|
|
472
|
+
await this.stop(child);
|
|
473
|
+
this.failed(sidecar, key, `not listening on its port within ${timeoutMs}ms`);
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
/** Record a failed start or a crash and schedule the next attempt. */
|
|
477
|
+
failed(sidecar, key, error) {
|
|
478
|
+
sidecar.lastError = error;
|
|
479
|
+
this.options.log(`connector-sidecar: connector=${sidecar.id} ${error}`);
|
|
480
|
+
if (!this.current(sidecar, key))
|
|
481
|
+
return;
|
|
482
|
+
const backoff = this.options.backoffMs;
|
|
483
|
+
// +/-20%, so sidecars that failed together do not all retry together.
|
|
484
|
+
const wait = Math.round(backoff[Math.min(sidecar.failures, backoff.length - 1)] * (0.8 + 0.4 * this.options.random()));
|
|
485
|
+
sidecar.failures++;
|
|
486
|
+
const timer = setTimeout(() => {
|
|
487
|
+
if (!this.current(sidecar, key) || sidecar.phase.kind !== 'backoff' || sidecar.phase.timer !== timer)
|
|
488
|
+
return;
|
|
489
|
+
sidecar.restarts++;
|
|
490
|
+
this.enqueue(sidecar, () => this.start(sidecar));
|
|
491
|
+
}, wait);
|
|
492
|
+
timer.unref();
|
|
493
|
+
sidecar.phase = { kind: 'backoff', timer };
|
|
494
|
+
this.notify(sidecar);
|
|
495
|
+
}
|
|
496
|
+
/** Stop whatever this sidecar is running or waiting to run. */
|
|
497
|
+
async halt(sidecar) {
|
|
498
|
+
const phase = sidecar.phase;
|
|
499
|
+
if (phase.kind === 'backoff')
|
|
500
|
+
clearTimeout(phase.timer);
|
|
501
|
+
const child = phase.child;
|
|
502
|
+
sidecar.phase = { kind: 'stopped' };
|
|
503
|
+
if (child) {
|
|
504
|
+
await this.stop(child);
|
|
505
|
+
this.forgetGroup(sidecar.id, child.pid);
|
|
506
|
+
this.options.log(`connector-sidecar: connector=${sidecar.id} stopped pid=${child.pid}`);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
stop(child) {
|
|
510
|
+
const stopped = stopChild(child, this.options.stopGraceMs).finally(() => this.stopping.delete(child));
|
|
511
|
+
this.stopping.set(child, stopped);
|
|
512
|
+
return stopped;
|
|
513
|
+
}
|
|
514
|
+
searchPath() {
|
|
515
|
+
return this.options.searchPath ?? process.env.PATH ?? '';
|
|
516
|
+
}
|
|
517
|
+
/** PATH, HOME and LANG from the gateway, then the spec's env, then PORT. Nothing else of the gateway's. */
|
|
518
|
+
childEnv(spec, command, port) {
|
|
519
|
+
const dirs = [path.dirname(command), ...this.searchPath().split(path.delimiter)].filter(dir => dir && dir !== '.');
|
|
520
|
+
const env = { PATH: [...new Set(dirs)].join(path.delimiter), HOME: os.homedir() };
|
|
521
|
+
if (process.env.LANG)
|
|
522
|
+
env.LANG = process.env.LANG;
|
|
523
|
+
return { ...env, ...spec.env, PORT: String(port) };
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Copy the sidecar's output to the gateway log, prefixed and rate-limited. Bearer
|
|
527
|
+
* values and this connector's stored secrets are masked: a server that logs its
|
|
528
|
+
* request headers must not put the credential in the gateway log.
|
|
529
|
+
*/
|
|
530
|
+
pipeOutput(sidecar, child) {
|
|
531
|
+
const prefix = `connector-sidecar: connector=${sidecar.id}`;
|
|
532
|
+
let windowStart = Date.now();
|
|
533
|
+
let lines = 0;
|
|
534
|
+
let suppressed = 0;
|
|
535
|
+
let secrets;
|
|
536
|
+
const secretValues = () => {
|
|
537
|
+
if (!secrets || secrets.writes !== this.secretWrites || Date.now() - secrets.at > 10000) {
|
|
538
|
+
const env = (0, token_env_1.readTokenEnv)();
|
|
539
|
+
const mark = (0, custom_1.customSecretKey)(sidecar.id, '');
|
|
540
|
+
secrets = { at: Date.now(), writes: this.secretWrites, values: Object.entries(env).filter(([name, value]) => name.startsWith(mark) && value.length >= 8).map(([, value]) => value) };
|
|
541
|
+
}
|
|
542
|
+
return secrets.values;
|
|
543
|
+
};
|
|
544
|
+
const emit = (line) => {
|
|
545
|
+
if (!line.trim())
|
|
546
|
+
return;
|
|
547
|
+
const now = Date.now();
|
|
548
|
+
if (now - windowStart >= 60000) {
|
|
549
|
+
if (suppressed)
|
|
550
|
+
this.options.log(`${prefix} output: ${suppressed} line(s) suppressed`);
|
|
551
|
+
windowStart = now;
|
|
552
|
+
lines = 0;
|
|
553
|
+
suppressed = 0;
|
|
554
|
+
}
|
|
555
|
+
if (++lines > STDERR_LINES_PER_MINUTE) {
|
|
556
|
+
suppressed++;
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
// Mask before cutting: a secret that crosses the cut would otherwise keep its first part.
|
|
560
|
+
let masked = line.replace(/(Bearer\s+)[^\s"',]+/gi, '$1[redacted]');
|
|
561
|
+
for (const value of secretValues())
|
|
562
|
+
masked = masked.split(value).join('[redacted]');
|
|
563
|
+
this.options.log(`${prefix} output: ${masked.slice(0, MAX_LOG_LINE)}`);
|
|
564
|
+
};
|
|
565
|
+
for (const stream of [child.stdout, child.stderr]) {
|
|
566
|
+
let partial = '';
|
|
567
|
+
let omitted = false;
|
|
568
|
+
stream?.on('data', (chunk) => {
|
|
569
|
+
const parts = chunk.toString('utf8').split('\n');
|
|
570
|
+
for (const [index, part] of parts.entries()) {
|
|
571
|
+
if (!omitted) {
|
|
572
|
+
partial += part;
|
|
573
|
+
if (partial.length > MAX_LOG_LINE) {
|
|
574
|
+
partial = '';
|
|
575
|
+
omitted = true;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
if (index < parts.length - 1) {
|
|
579
|
+
emit(omitted ? '[line omitted: exceeds 2000 characters]' : partial);
|
|
580
|
+
partial = '';
|
|
581
|
+
omitted = false;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
});
|
|
585
|
+
stream?.on('end', () => {
|
|
586
|
+
emit(omitted ? '[line omitted: exceeds 2000 characters]' : partial);
|
|
587
|
+
partial = '';
|
|
588
|
+
if (suppressed)
|
|
589
|
+
this.options.log(`${prefix} output: ${suppressed} line(s) suppressed`);
|
|
590
|
+
suppressed = 0;
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
exports.SidecarSupervisor = SidecarSupervisor;
|
|
596
|
+
/** A hand-edited entry without `secretNames` is reported disconnected, so it runs nothing. */
|
|
597
|
+
function isConnected(id, entry, tokenEnv) {
|
|
598
|
+
try {
|
|
599
|
+
return (0, custom_1.hasAllSecrets)(id, entry, tokenEnv);
|
|
600
|
+
}
|
|
601
|
+
catch {
|
|
602
|
+
return false;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
function killGroups(sidecars, stopping) {
|
|
606
|
+
for (const sidecar of sidecars) {
|
|
607
|
+
const child = sidecar.phase.child;
|
|
608
|
+
if (child)
|
|
609
|
+
signalGroup(child, 'SIGKILL');
|
|
610
|
+
}
|
|
611
|
+
for (const child of stopping)
|
|
612
|
+
signalGroup(child, 'SIGKILL');
|
|
613
|
+
}
|
|
614
|
+
function signalGroup(child, signal) {
|
|
615
|
+
if (child.pid === undefined)
|
|
616
|
+
return;
|
|
617
|
+
try {
|
|
618
|
+
process.kill(-child.pid, signal);
|
|
619
|
+
}
|
|
620
|
+
catch {
|
|
621
|
+
try {
|
|
622
|
+
child.kill(signal);
|
|
623
|
+
}
|
|
624
|
+
catch { /* already gone */ }
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
/** SIGTERM the sidecar's process group, then SIGKILL it after `graceMs`. */
|
|
628
|
+
async function stopChild(child, graceMs) {
|
|
629
|
+
// A failed spawn has no pid and emits 'error' and 'close', never 'exit'.
|
|
630
|
+
if (child.pid === undefined)
|
|
631
|
+
return;
|
|
632
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
633
|
+
signalGroup(child, 'SIGKILL');
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
const exited = new Promise(resolve => { child.once('exit', () => resolve()); child.once('close', () => resolve()); });
|
|
637
|
+
signalGroup(child, 'SIGTERM');
|
|
638
|
+
const timer = setTimeout(() => signalGroup(child, 'SIGKILL'), graceMs);
|
|
639
|
+
await exited;
|
|
640
|
+
clearTimeout(timer);
|
|
641
|
+
// The leader exited; anything it left in its group goes with it.
|
|
642
|
+
signalGroup(child, 'SIGKILL');
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* A free loopback port other than `avoid`, the previous run's. Its connections can
|
|
646
|
+
* leave that port in TIME_WAIT, and workspace-mcp then exits with "address already in
|
|
647
|
+
* use" (it binds without SO_REUSEADDR). Nothing depends on the port staying the same:
|
|
648
|
+
* the proxy looks the url up per request.
|
|
649
|
+
*/
|
|
650
|
+
async function allocatePort(avoid) {
|
|
651
|
+
const tryListen = (port) => new Promise(resolve => {
|
|
652
|
+
const server = net.createServer();
|
|
653
|
+
server.once('error', () => resolve(undefined));
|
|
654
|
+
server.listen(port, '127.0.0.1', () => {
|
|
655
|
+
const address = server.address();
|
|
656
|
+
server.close(() => resolve(address.port));
|
|
657
|
+
});
|
|
658
|
+
});
|
|
659
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
660
|
+
const port = await tryListen(0);
|
|
661
|
+
if (port && port !== avoid)
|
|
662
|
+
return port;
|
|
663
|
+
}
|
|
664
|
+
throw new Error('no free loopback port');
|
|
665
|
+
}
|
|
666
|
+
/** Every process's pid, process group and full command line. */
|
|
667
|
+
function listProcesses() {
|
|
668
|
+
return new Promise((resolve, reject) => {
|
|
669
|
+
(0, child_process_1.execFile)('ps', ['-ww', '-eo', 'pid=,pgid=,args='], { maxBuffer: 8 * 1024 * 1024 }, (err, stdout) => {
|
|
670
|
+
if (err) {
|
|
671
|
+
reject(err);
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
resolve(stdout.split('\n').flatMap(line => {
|
|
675
|
+
const match = /^\s*(\d+)\s+(\d+)\s(.*)$/.exec(line);
|
|
676
|
+
return match ? [{ pid: Number(match[1]), pgid: Number(match[2]), command: match[3].trim() }] : [];
|
|
677
|
+
}));
|
|
678
|
+
});
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
/*
|
|
682
|
+
* Readiness, and why it is two checks. The proxy sends the connector's credential to
|
|
683
|
+
* whatever answers on the sidecar's port, and allocatePort releases its probe socket
|
|
684
|
+
* before the spawn, so another local process can take the port first. A sidecar is
|
|
685
|
+
* ready only when something on the port answers HTTP on its MCP path (any status: an
|
|
686
|
+
* MCP server answers a bare GET with 405 or 401) AND every process listening on the
|
|
687
|
+
* port is in the sidecar's process group.
|
|
688
|
+
*
|
|
689
|
+
* What this does not cover: a process that binds the port after
|
|
690
|
+
* the sidecar became ready and the sidecar released it; and anything the sidecar's
|
|
691
|
+
* own command starts in its group.
|
|
692
|
+
*/
|
|
693
|
+
/**
|
|
694
|
+
* True once an HTTP server answers a GET on `mcpPath` with any status line. A raw
|
|
695
|
+
* socket that this side closes first: with `Connection: close` the server would close
|
|
696
|
+
* first and leave its port in TIME_WAIT, and workspace-mcp refuses to bind a port in
|
|
697
|
+
* TIME_WAIT when it restarts on the same one.
|
|
698
|
+
*/
|
|
699
|
+
function answersHttp(port, mcpPath) {
|
|
700
|
+
return new Promise(resolve => {
|
|
701
|
+
const socket = net.connect({ host: '127.0.0.1', port });
|
|
702
|
+
let head = '';
|
|
703
|
+
const finish = (ok) => { socket.destroy(); resolve(ok); };
|
|
704
|
+
socket.setTimeout(1000, () => finish(false));
|
|
705
|
+
socket.once('connect', () => socket.write(`GET ${mcpPath} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\n\r\n`));
|
|
706
|
+
socket.on('data', (chunk) => {
|
|
707
|
+
head += chunk.toString('latin1');
|
|
708
|
+
if (head.length >= 13)
|
|
709
|
+
finish(/^HTTP\/1\.[01] \d{3}[ \r]/.test(head));
|
|
710
|
+
});
|
|
711
|
+
socket.once('end', () => finish(false));
|
|
712
|
+
socket.once('error', () => finish(false));
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
/** True when every process listening on `port` is in process group `pgid`; missing inspection fails closed. */
|
|
716
|
+
function listenerInGroup(port, pgid) {
|
|
717
|
+
return new Promise(resolve => {
|
|
718
|
+
(0, child_process_1.execFile)('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-Fp'], (err, stdout) => {
|
|
719
|
+
if (err?.code === 'ENOENT' && process.platform === 'linux') {
|
|
720
|
+
(0, child_process_1.execFile)('ss', ['-H', '-ltnp', `( sport = :${port} )`], (ssError, ssOutput) => {
|
|
721
|
+
if (ssError) {
|
|
722
|
+
resolve(false);
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
const rows = ssOutput.trim().split('\n').filter(Boolean);
|
|
726
|
+
if (!rows.length || rows.some(row => !/\bpid=\d+\b/.test(row))) {
|
|
727
|
+
resolve(false);
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
const listeners = rows.flatMap(row => [...row.matchAll(/\bpid=(\d+)\b/g)].map(match => Number(match[1])));
|
|
731
|
+
listProcesses().then(processes => resolve(listeners.length > 0 && listeners.every(pid => processes.some(p => p.pid === pid && p.pgid === pgid))), () => resolve(false));
|
|
732
|
+
});
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
if (err) {
|
|
736
|
+
resolve(false);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
const listeners = stdout.split('\n').filter(line => line.startsWith('p')).map(line => Number(line.slice(1)));
|
|
740
|
+
if (!listeners.length) {
|
|
741
|
+
resolve(false);
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
listProcesses().then(processes => resolve(listeners.every(pid => processes.some(p => p.pid === pid && p.pgid === pgid))), () => resolve(false));
|
|
745
|
+
});
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
function delay(ms) {
|
|
749
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
750
|
+
}
|
|
751
|
+
let shared;
|
|
752
|
+
let unsubscribe;
|
|
753
|
+
function install(supervisor) {
|
|
754
|
+
unsubscribe?.();
|
|
755
|
+
shared = supervisor;
|
|
756
|
+
unsubscribe = (0, token_env_1.onSecretsWritten)(() => supervisor.secretsChanged());
|
|
757
|
+
return supervisor;
|
|
758
|
+
}
|
|
759
|
+
/** The gateway's one supervisor. `configure` replaces it (boot, tests). */
|
|
760
|
+
exports.connectorSidecars = {
|
|
761
|
+
configure(options) {
|
|
762
|
+
return install(new SidecarSupervisor(options));
|
|
763
|
+
},
|
|
764
|
+
get() {
|
|
765
|
+
return shared ?? install(new SidecarSupervisor({ runtimeRoot: path.join(os.homedir(), '.claude-gateway', 'runtimes') }));
|
|
766
|
+
},
|
|
767
|
+
};
|
|
768
|
+
//# sourceMappingURL=sidecar.js.map
|