@cubicecho/agent-router-worker 0.3.0 → 0.4.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.
@@ -0,0 +1,1744 @@
1
+ import { mkdirSync, readFileSync } from "node:fs";
2
+ import { homedir, hostname } from "node:os";
3
+ import path, { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { z } from "zod";
5
+ import { RunEventKind, ToolDiscovery, failedRun, runAgentLoop, stamp } from "@cubicecho/agent-core";
6
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
7
+ import { EventSourceParserStream } from "eventsource-parser/stream";
8
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
9
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
10
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
11
+ import { CallToolResultSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
12
+ import { spawn } from "node:child_process";
13
+ import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
14
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
15
+ import { lstat, mkdir, readdir, realpath, stat } from "node:fs/promises";
16
+ // server/core/error-message.ts
17
+ /**
18
+ * Reads the message of any caught value.
19
+ *
20
+ * @param error - Whatever was thrown.
21
+ * @returns `error.message` for an Error, otherwise `String(error)`.
22
+ *
23
+ * @remarks
24
+ * server-kit has one too, but the runner and the worker program use this, and its entry would bundle Yoga into theirs.
25
+ */
26
+ function errorMessage(error) {
27
+ return error instanceof Error ? error.message : String(error);
28
+ }
29
+ // server/core/wire.ts
30
+ /** The HTTP statuses this server sends by hand. */
31
+ const HttpStatus = {
32
+ Ok: 200,
33
+ Accepted: 202,
34
+ Found: 302,
35
+ BadRequest: 400,
36
+ Unauthorized: 401,
37
+ Forbidden: 403,
38
+ NotFound: 404,
39
+ MethodNotAllowed: 405,
40
+ Conflict: 409,
41
+ PayloadTooLarge: 413,
42
+ UnprocessableEntity: 422,
43
+ TooManyRequests: 429,
44
+ InternalServerError: 500,
45
+ BadGateway: 502,
46
+ ServiceUnavailable: 503,
47
+ GatewayTimeout: 504
48
+ };
49
+ /** What every worker key starts with, so no door for apps or people mistakes one for theirs. */
50
+ const WORKER_KEY_PREFIX = "aiw_";
51
+ /**
52
+ * The address a run's endpoint points at when it uses the router's models. No server answers it: the run's model
53
+ * `fetch` hands every call to the models area. `.invalid` is reserved, so a call that escaped would go nowhere.
54
+ */
55
+ const MODELS_BASE_URL = "http://models.ai-router.invalid/v1";
56
+ /** Milliseconds in one second. */
57
+ const MS_PER_SECOND = 1e3;
58
+ // worker/config.ts
59
+ /** Where the work root is when `WORKER_ROOT` is unset, under the worker user's home. */
60
+ const DEFAULT_ROOT_FOLDER = "agent-router-work";
61
+ /** What a path starting with the home folder starts with. */
62
+ const HOME_PREFIX = "~/";
63
+ /** A lone `~`: the home folder itself. */
64
+ const HOME = "~";
65
+ /** A local server the worker starts itself: a command, run as the worker's user. */
66
+ const commandServerSchema = z.strictObject({
67
+ command: z.string().min(1, "A server's \"command\" cannot be empty."),
68
+ args: z.array(z.string()).optional(),
69
+ env: z.record(z.string(), z.string()).optional(),
70
+ /** Relative to the config file's folder. */
71
+ cwd: z.string().min(1).optional()
72
+ });
73
+ /** A local server the worker reaches at an address, over streamable HTTP. */
74
+ const addressServerSchema = z.strictObject({
75
+ url: z.url("A server's \"url\" must be an absolute URL."),
76
+ headers: z.record(z.string(), z.string()).optional()
77
+ });
78
+ /** One of the servers `WORKER_CONFIG` names. */
79
+ const localServerConfigSchema = z.union([commandServerSchema, addressServerSchema]);
80
+ /** The file `WORKER_CONFIG` points at. */
81
+ const workerFileSchema = z.strictObject({ servers: z.record(z.string(), localServerConfigSchema).default({}) });
82
+ /** The environment the worker reads. */
83
+ const workerEnvSchema = z.object({
84
+ AGENT_ROUTER_URL: z.url("AGENT_ROUTER_URL must be the router's address, such as \"http://router.lan:3000\"."),
85
+ AGENT_ROUTER_WORKER_KEY: z.string({ error: "AGENT_ROUTER_WORKER_KEY is required: the key shown when the worker was made in the router." }).startsWith(WORKER_KEY_PREFIX, `AGENT_ROUTER_WORKER_KEY must be a worker key, which starts "${WORKER_KEY_PREFIX}".`),
86
+ WORKER_ROOT: z.string().optional(),
87
+ WORKER_CONFIG: z.string().optional(),
88
+ WORKER_HOST: z.string().optional()
89
+ });
90
+ /** The worker's environment or config file is wrong: the message says which variable or file, and how to fix it. */
91
+ var WorkerConfigError = class extends Error {
92
+ /**
93
+ * @param message - What is wrong, and what to set.
94
+ */
95
+ constructor(message) {
96
+ super(message);
97
+ this.name = "WorkerConfigError";
98
+ }
99
+ };
100
+ /**
101
+ * Turns a leading `~` into the home folder, and a relative path into an absolute one.
102
+ *
103
+ * @param path - The path as written.
104
+ * @param base - What a relative path is relative to.
105
+ * @returns The absolute path.
106
+ */
107
+ function absolutePath(path, base) {
108
+ if (path === HOME) return homedir();
109
+ if (path.startsWith(HOME_PREFIX)) return join(homedir(), path.slice(2));
110
+ return isAbsolute(path) ? path : resolve(base, path);
111
+ }
112
+ /**
113
+ * Words a zod failure as one line per problem.
114
+ *
115
+ * @param error - The failure.
116
+ * @returns The problems, each with where it is.
117
+ */
118
+ function describeIssues(error) {
119
+ return error.issues.map((issue) => {
120
+ const where = issue.path.join(".");
121
+ return where === "" ? issue.message : `${where}: ${issue.message}`;
122
+ }).join("\n");
123
+ }
124
+ /**
125
+ * Reads the servers file.
126
+ *
127
+ * @param path - The file, absolute.
128
+ * @returns Its servers, each command server's `cwd` made absolute against the file's folder.
129
+ * @throws WorkerConfigError when the file is missing, isn't JSON or doesn't match the shape.
130
+ */
131
+ function readServersFile(path) {
132
+ let raw;
133
+ try {
134
+ raw = JSON.parse(readFileSync(path, "utf8"));
135
+ } catch (error) {
136
+ throw new WorkerConfigError(`WORKER_CONFIG names ${path}, which can't be read as JSON: ${errorMessage(error)}`);
137
+ }
138
+ const parsed = workerFileSchema.safeParse(raw);
139
+ if (parsed.success === false) throw new WorkerConfigError(`WORKER_CONFIG names ${path}, which should be { "servers": { "<name>": { "command", "args"?, "env"?, "cwd"? } | { "url", "headers"? } } }:\n${describeIssues(parsed.error)}`);
140
+ const folder = dirname(path);
141
+ return Object.fromEntries(Object.entries(parsed.data.servers).map(([name, server]) => {
142
+ if ("command" in server && server.cwd !== void 0) return [name, {
143
+ ...server,
144
+ cwd: absolutePath(server.cwd, folder)
145
+ }];
146
+ return [name, server];
147
+ }));
148
+ }
149
+ /**
150
+ * Reads the worker's config from its environment, and makes its work root.
151
+ *
152
+ * @param env - The environment, `process.env` at boot.
153
+ * @param cwd - What relative paths in it are relative to.
154
+ * @returns The config.
155
+ * @throws WorkerConfigError naming the variable or file that is wrong.
156
+ */
157
+ function readWorkerConfig(env, cwd = process.cwd()) {
158
+ const parsed = workerEnvSchema.safeParse(env);
159
+ if (parsed.success === false) throw new WorkerConfigError(describeIssues(parsed.error));
160
+ const { AGENT_ROUTER_URL, AGENT_ROUTER_WORKER_KEY, WORKER_ROOT, WORKER_CONFIG, WORKER_HOST } = parsed.data;
161
+ const root = absolutePath(WORKER_ROOT || join(homedir(), DEFAULT_ROOT_FOLDER), cwd);
162
+ try {
163
+ mkdirSync(root, { recursive: true });
164
+ } catch (error) {
165
+ throw new WorkerConfigError(`WORKER_ROOT is ${root}, which can't be made: ${errorMessage(error)}`);
166
+ }
167
+ const servers = WORKER_CONFIG ? readServersFile(absolutePath(WORKER_CONFIG, cwd)) : {};
168
+ return {
169
+ url: AGENT_ROUTER_URL.replace(/\/+$/, ""),
170
+ key: AGENT_ROUTER_WORKER_KEY,
171
+ root,
172
+ host: WORKER_HOST || hostname(),
173
+ servers
174
+ };
175
+ }
176
+ // server/runner/protocol.ts
177
+ /**
178
+ * The worker protocol: what a remote worker and the router say to each other, shared by both ends.
179
+ *
180
+ * @remarks
181
+ * A worker dials in with its worker key and holds one server-sent event stream open, the channel, which carries what
182
+ * the router asks of it. Everything the worker says goes up as an ordinary request, each scoped to one run the router
183
+ * assigned it. The router answers every run-scoped request for a run that is not running on that worker with 404.
184
+ *
185
+ * It lives beside the runner, not in `workers/`, because the worker program imports it without the router.
186
+ */
187
+ /** Where the worker doors are mounted. */
188
+ const WORKERS_PATH = "/workers";
189
+ /** The doors, under {@link WORKERS_PATH}. */
190
+ const WorkerDoor = {
191
+ /** `GET`: the channel, a server-sent event stream of {@link ChannelMessage}s. */
192
+ Channel: "/channel",
193
+ /** `POST` a {@link WorkerHello}: who the worker is and the tools it offers. */
194
+ Hello: "/hello",
195
+ /** The run's model calls, as an OpenAI-compatible base URL: `/chat/completions`, `/models`. */
196
+ Model: "/model",
197
+ /** `POST` a {@link RouterToolCall}, answered with a {@link RouterToolAnswer}. */
198
+ Tools: "/tools/call",
199
+ /** `POST` an {@link EventBatch}. */
200
+ Events: "/events",
201
+ /** `POST` the stretch's {@link RunOutcome}. */
202
+ Finish: "/finish"
203
+ };
204
+ /**
205
+ * The path of one of a run's doors, under {@link WORKERS_PATH}.
206
+ *
207
+ * @param runId - The run.
208
+ * @param door - Its door.
209
+ * @returns The path, such as `/runs/<id>/events`.
210
+ */
211
+ function runDoorPath(runId, door) {
212
+ return `/runs/${encodeURIComponent(runId)}${door}`;
213
+ }
214
+ /**
215
+ * The `code` of a run door's 404 for a run that is not executing on the calling worker: the router dropped it, or
216
+ * never assigned it there. Distinct from the models area's own 404s, which the model door passes through.
217
+ */
218
+ const RUN_NOT_FOUND = "run_not_found";
219
+ /** What the channel carries, by its server-sent event name. */
220
+ const ChannelMessageType = {
221
+ /** A stretch of a run to execute: a {@link RunAssignment}. */
222
+ Assign: "assign",
223
+ /** Stop a run: its loop, its model and tool calls. */
224
+ Cancel: "cancel",
225
+ /** Nothing, so a quiet channel is known to be open. */
226
+ Ping: "ping"
227
+ };
228
+ /** One of a local server's tools, as MCP lists it. */
229
+ const localToolSchema = z.object({
230
+ name: z.string().min(1),
231
+ description: z.string().optional(),
232
+ inputSchema: z.record(z.string(), z.unknown())
233
+ });
234
+ /** One of the worker's own servers, and its tools. */
235
+ const localServerSchema = z.object({
236
+ name: z.string().min(1),
237
+ tools: z.array(localToolSchema)
238
+ });
239
+ z.object({
240
+ /** The machine it runs on, as its owner would recognise it. */
241
+ host: z.string().min(1),
242
+ /** The worker program's version. */
243
+ version: z.string().min(1),
244
+ /** The servers it offers runs, called on the worker itself. */
245
+ servers: z.array(localServerSchema),
246
+ /**
247
+ * The runs it holds now. The router ends at once any run it sent this worker on an earlier channel that is not here:
248
+ * a worker that restarted holds none. Absent, from a worker older than the field, the router keeps them.
249
+ */
250
+ runs: z.array(z.string().min(1)).optional()
251
+ });
252
+ z.object({
253
+ /** The server's id, as the run's targets name it. */
254
+ server: z.string().min(1),
255
+ /** The tool's own name on its server. */
256
+ tool: z.string().min(1),
257
+ args: z.record(z.string(), z.unknown()),
258
+ /** The model's call, as the loop numbered it. */
259
+ call: z.object({
260
+ id: z.string().min(1),
261
+ name: z.string().min(1)
262
+ })
263
+ });
264
+ z.object({ events: z.array(z.looseObject({ kind: z.string().min(1) })) });
265
+ z.discriminatedUnion("ok", [z.looseObject({
266
+ ok: z.literal(true),
267
+ messages: z.array(z.unknown()),
268
+ usage: z.unknown(),
269
+ loaded: z.array(z.string()),
270
+ finishReason: z.unknown(),
271
+ handedBack: z.array(z.string())
272
+ }), z.object({
273
+ ok: z.literal(false),
274
+ error: z.string(),
275
+ usage: z.unknown().optional()
276
+ })]);
277
+ Object.freeze({
278
+ secretBytes: 32,
279
+ visibleChars: 6
280
+ });
281
+ const NAME_DEFAULTS = Object.freeze({ maxLength: 64 });
282
+ Object.freeze({
283
+ maxDocumentBytes: 262144,
284
+ maxMessageLength: 500
285
+ });
286
+ Object.freeze({
287
+ timeoutMinutes: 30,
288
+ idempotencyHours: 24,
289
+ retentionDays: 30,
290
+ pruneEveryHours: 6,
291
+ bodyLimit: "8mb",
292
+ heartbeatSeconds: 15,
293
+ maxIdempotencyKeyLength: 255,
294
+ maxUserLength: 256,
295
+ maxErrorLength: 2e3,
296
+ eventFlushMs: 250,
297
+ streamHoldMs: 1e4,
298
+ eventBatchSize: 500,
299
+ eventPageSize: 500,
300
+ maxEventPageSize: 5e3,
301
+ runPageSize: 25,
302
+ maxRunPageSize: 100,
303
+ sessionTitleLength: 80,
304
+ waitTimeoutHours: 24,
305
+ expireEveryMinutes: 5,
306
+ taskPollIntervalMs: 2e3,
307
+ maxAgentDepth: 3
308
+ });
309
+ const WORKER_DEFAULTS = Object.freeze({
310
+ heartbeatMs: 15e3,
311
+ reconnectGraceMs: 6e4,
312
+ eventBatchSize: 100,
313
+ eventFlushMs: 250,
314
+ maxRunsAtOnce: 8,
315
+ cancelGraceMs: 1e4,
316
+ bodyLimit: "8mb"
317
+ });
318
+ Object.freeze({
319
+ maxAppTools: 128,
320
+ pruneAppToolsAcrossServers: false,
321
+ unlistedFields: "refuse"
322
+ });
323
+ Object.freeze({
324
+ idleHours: 72,
325
+ maxIdLength: 255
326
+ });
327
+ Object.freeze({
328
+ maxNameLength: 120,
329
+ maxDescriptionLength: 2e3,
330
+ maxKeyNameLength: 120,
331
+ maxKeyExpiryDays: 3650,
332
+ maxToolNameLength: 128
333
+ });
334
+ Object.freeze({ closeTimeoutSeconds: 5 });
335
+ // worker/defaults.ts
336
+ const WORKDIR_DEFAULTS = Object.freeze({
337
+ cloneTimeoutMs: 6e5,
338
+ gitCommandTimeoutMs: 1e4,
339
+ maxEntries: 500,
340
+ maxDepth: 5
341
+ });
342
+ const WORKER_PROGRAM_DEFAULTS = Object.freeze({
343
+ reconnectMinMs: 1e3,
344
+ reconnectMaxMs: 3e4,
345
+ silentHeartbeats: 3,
346
+ sendAttempts: 5,
347
+ sendRetryMs: 1e3,
348
+ stopDeadlineMs: 8e3,
349
+ localToolTimeoutMs: 9e5,
350
+ localStartTimeoutMs: 3e4,
351
+ localCloseGraceMs: 2e3
352
+ });
353
+ // worker/channel.ts
354
+ /** What the channel asks the router for. */
355
+ const EVENT_STREAM = "text/event-stream";
356
+ /** What each failed dial multiplies the wait before the next by. */
357
+ const BACKOFF_FACTOR = 2;
358
+ /** Why a cancel stopped a run when the router gave no reason. */
359
+ const NO_REASON = "cancelled by the router";
360
+ /** An `assign` event's data: the assignment, its run named. */
361
+ const assignDataSchema = z.looseObject({ assignment: z.looseObject({ runId: z.string().min(1) }) });
362
+ /** A `cancel` event's data. */
363
+ const cancelDataSchema = z.looseObject({
364
+ runId: z.string().min(1),
365
+ reason: z.string().optional()
366
+ });
367
+ /**
368
+ * Reads one server-sent event as a channel message.
369
+ *
370
+ * @param event - The event's name: the message's type.
371
+ * @param data - Its data, JSON.
372
+ * @returns The message, or undefined for one this worker doesn't know or can't read, which is logged.
373
+ *
374
+ * @remarks
375
+ * The type is the event's name. The data may repeat it, as the message object itself, or leave it out.
376
+ */
377
+ function parseChannelMessage(event, data) {
378
+ if (event === ChannelMessageType.Ping) return { type: ChannelMessageType.Ping };
379
+ let body;
380
+ try {
381
+ body = JSON.parse(data);
382
+ } catch {
383
+ console.warn(`[worker] ignoring a "${event ?? "message"}" on the channel whose data is not JSON`);
384
+ return;
385
+ }
386
+ if (event === ChannelMessageType.Assign) {
387
+ const parsed = assignDataSchema.safeParse(body);
388
+ if (parsed.success) {
389
+ const assignment = parsed.data.assignment;
390
+ return {
391
+ type: ChannelMessageType.Assign,
392
+ assignment
393
+ };
394
+ }
395
+ }
396
+ if (event === ChannelMessageType.Cancel) {
397
+ const parsed = cancelDataSchema.safeParse(body);
398
+ if (parsed.success) return {
399
+ type: ChannelMessageType.Cancel,
400
+ runId: parsed.data.runId,
401
+ reason: parsed.data.reason ?? NO_REASON
402
+ };
403
+ }
404
+ console.warn(`[worker] ignoring a "${event ?? "message"}" on the channel this worker can't read`);
405
+ }
406
+ /**
407
+ * Dials the router's channel and keeps it open: each drop is dialled again, after a wait that doubles up to a cap.
408
+ *
409
+ * @param options - The router, the key, and who hears the channel.
410
+ * @param [overrides] - Settings that replace `WORKER_DEFAULTS` and `WORKER_PROGRAM_DEFAULTS`.
411
+ * @returns The channel.
412
+ *
413
+ * @remarks
414
+ * Nothing on the channel, a ping included, for `silentHeartbeats` heartbeats drops it as dead.
415
+ */
416
+ function openChannel(options, overrides = {}) {
417
+ const { url, key, onOpen, onMessage, fetch = globalThis.fetch } = options;
418
+ const settings = {
419
+ ...WORKER_DEFAULTS,
420
+ ...WORKER_PROGRAM_DEFAULTS,
421
+ ...overrides
422
+ };
423
+ const deadAfterMs = settings.heartbeatMs * settings.silentHeartbeats;
424
+ const channelUrl = `${url}${WORKERS_PATH}${WorkerDoor.Channel}`;
425
+ const stopping = new AbortController();
426
+ let isOpen = false;
427
+ /**
428
+ * Holds one connection open until it drops.
429
+ *
430
+ * @returns Resolves with why it dropped, and whether it got as far as its hello.
431
+ */
432
+ const hold = async () => {
433
+ let opened = false;
434
+ const connection = new AbortController();
435
+ let watchdog;
436
+ const heard = () => {
437
+ clearTimeout(watchdog);
438
+ watchdog = setTimeout(() => connection.abort(/* @__PURE__ */ new Error(`nothing on the channel for ${deadAfterMs / MS_PER_SECOND}s`)), deadAfterMs);
439
+ };
440
+ const signal = AbortSignal.any([stopping.signal, connection.signal]);
441
+ try {
442
+ heard();
443
+ const response = await fetch(channelUrl, {
444
+ headers: {
445
+ authorization: `Bearer ${key}`,
446
+ accept: EVENT_STREAM
447
+ },
448
+ signal
449
+ });
450
+ const { body } = response;
451
+ if (response.ok === false || body === null) {
452
+ await response.body?.cancel().catch(() => void 0);
453
+ return {
454
+ reason: `the router answered ${response.status}`,
455
+ opened
456
+ };
457
+ }
458
+ await onOpen();
459
+ isOpen = true;
460
+ opened = true;
461
+ const events = body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({ onComment: heard }));
462
+ for await (const event of events) {
463
+ heard();
464
+ const message = parseChannelMessage(event.event, event.data);
465
+ if (message !== void 0 && message.type !== ChannelMessageType.Ping) onMessage(message);
466
+ }
467
+ return {
468
+ reason: "the router closed the channel",
469
+ opened
470
+ };
471
+ } catch (error) {
472
+ return {
473
+ reason: errorMessage(connection.signal.aborted ? connection.signal.reason : error),
474
+ opened
475
+ };
476
+ } finally {
477
+ isOpen = false;
478
+ clearTimeout(watchdog);
479
+ connection.abort();
480
+ }
481
+ };
482
+ const loop = async () => {
483
+ let waitMs = settings.reconnectMinMs;
484
+ while (stopping.signal.aborted === false) {
485
+ const { reason, opened } = await hold();
486
+ if (stopping.signal.aborted) return;
487
+ if (opened) waitMs = settings.reconnectMinMs;
488
+ console.warn(`[worker] the channel dropped: ${reason}. Dialling again in ${waitMs / MS_PER_SECOND}s.`);
489
+ await setTimeout$1(waitMs, void 0, { signal: stopping.signal }).catch(() => void 0);
490
+ waitMs = Math.min(waitMs * BACKOFF_FACTOR, settings.reconnectMaxMs);
491
+ }
492
+ };
493
+ const done = loop();
494
+ return {
495
+ isOpen: () => isOpen,
496
+ close: async () => {
497
+ stopping.abort();
498
+ await done;
499
+ }
500
+ };
501
+ }
502
+ // server/runner/assignment.ts
503
+ /** A tool the router calls for the run: one of a server's tools, through the run's workspace instance. */
504
+ const TOOL_ORIGIN_ROUTER = "router";
505
+ /** A tool the worker calls itself, where the loop runs. */
506
+ const TOOL_ORIGIN_LOCAL = "local";
507
+ // server/runner/model-fetch.ts
508
+ /**
509
+ * Gives every endpoint of a resolved agent that points at the router's models the run's `fetch`.
510
+ *
511
+ * @param resolved - The resolved agent.
512
+ * @param fetch - The run's model `fetch`: `Forwarder.fetchFor` in the router.
513
+ * @returns The config the loop runs with. An endpoint of the agent's own is left as it is, and called directly.
514
+ */
515
+ function withRouterFetch(resolved, fetch) {
516
+ const isRouter = (baseUrl) => baseUrl === MODELS_BASE_URL;
517
+ const tasks = Object.fromEntries(Object.entries(resolved.tasks).map(([name, task]) => [name, isRouter(task.endpoint.baseUrl) ? {
518
+ ...task,
519
+ endpoint: {
520
+ ...task.endpoint,
521
+ fetch
522
+ }
523
+ } : task]));
524
+ return {
525
+ ...resolved,
526
+ ...isRouter(resolved.baseUrl) ? { fetch } : {},
527
+ tasks
528
+ };
529
+ }
530
+ // server/runner/execute.ts
531
+ /**
532
+ * What the transcript holds for a handed-back call until the app answers it. A resume replaces it; the model never
533
+ * reads it.
534
+ */
535
+ const HANDED_BACK = "(handed back to the app)";
536
+ /** Why the loop stopped at an app tool, as its `end` says it. */
537
+ const HANDED_BACK_REASON = "handed back to the app";
538
+ /**
539
+ * Finds what answers a tool the model called.
540
+ *
541
+ * @param targets - The run's tools, by function name.
542
+ * @param name - The name the model called.
543
+ * @returns The target, or undefined for a name the run has no tool by.
544
+ */
545
+ function targetOf(targets, name) {
546
+ return Object.hasOwn(targets, name) ? targets[name] : void 0;
547
+ }
548
+ /**
549
+ * Runs one stretch of a run's agent loop: to its answer, or until the model calls an app tool.
550
+ *
551
+ * @param assignment - The stretch.
552
+ * @param ports - What the router lends it: model calls, tool calls, events and the run's signal.
553
+ * @param runtime - agent-core's runtime, whose caches the loop uses.
554
+ * @returns How the loop ended. Never rejects: a failure is a failed outcome.
555
+ *
556
+ * @remarks
557
+ * Each app tool call ends the loop with a stand-in answer, which the app replaces when it resumes the run, so the
558
+ * stand-in's result is never published.
559
+ */
560
+ async function executeRun(assignment, ports, runtime) {
561
+ const { runId, config, targets } = assignment;
562
+ const appNames = new Set(assignment.appTools.map((tool) => tool.function.name));
563
+ /** The loop ids of the calls handed back, in the order they were made. */
564
+ const handedBack = [];
565
+ const onEvent = (event) => {
566
+ if (event.kind === RunEventKind.ToolResult && event.id !== void 0 && appNames.has(event.name ?? "") && handedBack.includes(event.id)) return;
567
+ ports.publish(event);
568
+ };
569
+ const dispatch = async (call, callSignal) => {
570
+ if (appNames.has(call.name)) {
571
+ handedBack.push(call.id);
572
+ return {
573
+ text: HANDED_BACK,
574
+ end: { reason: HANDED_BACK_REASON }
575
+ };
576
+ }
577
+ const target = targetOf(targets, call.name);
578
+ if (target === void 0) throw new Error(`This run has no tool named "${call.name}".`);
579
+ const options = {
580
+ call: {
581
+ id: call.id,
582
+ name: call.name
583
+ },
584
+ signal: callSignal ?? ports.signal
585
+ };
586
+ if (target.origin === "local") {
587
+ if (ports.callLocalTool === void 0) throw new Error(`This worker has no tool named "${target.tool}".`);
588
+ return ports.callLocalTool(target.server, target.tool, call.args, options);
589
+ }
590
+ return ports.callRouterTool(target.server, target.tool, call.args, options);
591
+ };
592
+ const isEager = config.toolDiscovery === ToolDiscovery.Eager;
593
+ try {
594
+ const result = await runtime.runAgentLoop({
595
+ config: withRouterFetch(config, ports.modelFetch),
596
+ systemPrompt: assignment.prompt,
597
+ messages: assignment.messages,
598
+ tools: assignment.tools,
599
+ hostTools: assignment.appTools,
600
+ loaded: assignment.loaded,
601
+ ...isEager ? {} : { catalog: assignment.catalog },
602
+ dispatch,
603
+ dedupeToolCalls: (call) => appNames.has(call.name) === false,
604
+ signal: ports.signal,
605
+ session: runId,
606
+ onEvent
607
+ });
608
+ return {
609
+ ok: true,
610
+ messages: result.messages,
611
+ usage: result.usage,
612
+ loaded: result.loaded,
613
+ finishReason: result.turn.finishReason,
614
+ handedBack
615
+ };
616
+ } catch (error) {
617
+ return {
618
+ ok: false,
619
+ error: errorMessage(error),
620
+ usage: failedRun(error)?.usage
621
+ };
622
+ }
623
+ }
624
+ // worker/run.ts
625
+ /** Why a run ended when a door answered 404: the router no longer runs it on this worker. */
626
+ const RUN_DROPPED = "the router dropped this run";
627
+ /** How an assignment past `maxRunsAtOnce` is finished. */
628
+ const WORKER_BUSY = "this worker is busy";
629
+ /** How a stopping worker's runs, and an assignment it gets while stopping, are finished. */
630
+ const WORKER_STOPPING = "the worker is stopping";
631
+ /** What a request to the router's doors carries. */
632
+ const JSON_TYPE = "application/json";
633
+ /** The methods that send no body. */
634
+ const BODYLESS_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
635
+ /** What the tools door answers. */
636
+ const routerToolAnswerSchema = z.discriminatedUnion("ok", [z.object({
637
+ ok: z.literal(true),
638
+ text: z.string()
639
+ }), z.object({
640
+ ok: z.literal(false),
641
+ error: z.string()
642
+ })]);
643
+ /** A run door's own 404, as the router writes it: `{ error, code }`. */
644
+ const runNotFoundSchema = z.object({ code: z.literal(RUN_NOT_FOUND) });
645
+ /**
646
+ * Whether a 404 is a run door's own, saying the router no longer runs the run here, rather than one the router's
647
+ * models answered.
648
+ *
649
+ * @param response - A copy of the 404, whose body this reads.
650
+ * @returns Whether its body carries the `run_not_found` code.
651
+ */
652
+ async function isRunNotFound(response) {
653
+ const body = await response.json().catch(() => void 0);
654
+ return runNotFoundSchema.safeParse(body).success;
655
+ }
656
+ /**
657
+ * Starts the runs the router assigns this worker, each through its own doors.
658
+ *
659
+ * @param options - The router, the key, the local servers and the runtime.
660
+ * @param [overrides] - Settings that replace `WORKER_DEFAULTS` and `WORKER_PROGRAM_DEFAULTS`.
661
+ * @returns The host.
662
+ */
663
+ function createRunHost(options, overrides = {}) {
664
+ const { url, key, local, runtime, fetch = globalThis.fetch } = options;
665
+ const settings = {
666
+ ...WORKER_DEFAULTS,
667
+ ...WORKER_PROGRAM_DEFAULTS,
668
+ ...overrides
669
+ };
670
+ const authorization = `Bearer ${key}`;
671
+ const runs = /* @__PURE__ */ new Map();
672
+ let isStopping = false;
673
+ const doorUrl = (runId, door) => `${url}${WORKERS_PATH}${runDoorPath(runId, door)}`;
674
+ const post = (runId, door, body, signal) => fetch(doorUrl(runId, door), {
675
+ method: "POST",
676
+ headers: {
677
+ authorization,
678
+ "content-type": JSON_TYPE
679
+ },
680
+ body: JSON.stringify(body),
681
+ ...signal === void 0 ? {} : { signal }
682
+ });
683
+ /** Posts, sending again after a network error, `sendAttempts` times in all. */
684
+ const postWithRetry = async (runId, door, body) => {
685
+ for (let attempt = 1;; attempt += 1) try {
686
+ return await post(runId, door, body);
687
+ } catch (error) {
688
+ if (attempt >= settings.sendAttempts) throw error;
689
+ await setTimeout$1(settings.sendRetryMs);
690
+ }
691
+ };
692
+ const finish = async (runId, outcome) => {
693
+ try {
694
+ const response = await postWithRetry(runId, WorkerDoor.Finish, outcome);
695
+ await response.body?.cancel().catch(() => void 0);
696
+ if (response.status === HttpStatus.NotFound) console.warn(`[worker] run ${runId} finished, but ${RUN_DROPPED}`);
697
+ else if (response.ok === false) console.error(`[worker] the router refused run ${runId}'s finish: ${response.status}`);
698
+ } catch (error) {
699
+ console.error(`[worker] could not send run ${runId}'s finish: ${errorMessage(error)}`);
700
+ }
701
+ };
702
+ const failAtOnce = (runId, error) => {
703
+ finish(runId, {
704
+ ok: false,
705
+ error,
706
+ usage: void 0
707
+ });
708
+ };
709
+ const eventQueue = (runId, held, drop) => {
710
+ let pending = [];
711
+ let timer;
712
+ let sending = Promise.resolve();
713
+ const sendAll = async () => {
714
+ while (pending.length > 0) {
715
+ if (held.dropped) {
716
+ pending = [];
717
+ return;
718
+ }
719
+ const events = pending.splice(0, settings.eventBatchSize);
720
+ try {
721
+ const response = await postWithRetry(runId, WorkerDoor.Events, { events });
722
+ await response.body?.cancel().catch(() => void 0);
723
+ if (response.status === HttpStatus.NotFound) drop();
724
+ else if (response.ok === false) console.error(`[worker] the router refused ${events.length} of run ${runId}'s events: ${response.status}`);
725
+ } catch (error) {
726
+ console.error(`[worker] could not send ${events.length} of run ${runId}'s events: ${errorMessage(error)}`);
727
+ }
728
+ }
729
+ };
730
+ const flush = () => {
731
+ clearTimeout(timer);
732
+ timer = void 0;
733
+ sending = sending.then(sendAll);
734
+ return sending;
735
+ };
736
+ return {
737
+ push: (event) => {
738
+ pending.push(event);
739
+ if (pending.length >= settings.eventBatchSize) flush();
740
+ else if (timer === void 0) timer = setTimeout(() => void flush(), settings.eventFlushMs);
741
+ },
742
+ drain: flush
743
+ };
744
+ };
745
+ const portsFor = (runId, held, events, drop) => {
746
+ const runSignal = held.controller.signal;
747
+ /** Reads a door's answer: a 404 means the router dropped the run, which ends it here too. */
748
+ const checked = async (response) => {
749
+ if (response.status === HttpStatus.NotFound) {
750
+ await response.body?.cancel().catch(() => void 0);
751
+ drop();
752
+ throw new Error(RUN_DROPPED);
753
+ }
754
+ return response;
755
+ };
756
+ const modelFetch = async (input, init) => {
757
+ const request = new Request(input, init);
758
+ if ((request.url === "http://models.ai-router.invalid/v1" || request.url.startsWith(`http://models.ai-router.invalid/v1/`)) === false) throw new TypeError(`A run on this worker may call only the router's models, not ${request.url}.`);
759
+ const headers = new Headers(request.headers);
760
+ headers.set("authorization", authorization);
761
+ const hasBody = BODYLESS_METHODS.has(request.method) === false;
762
+ const response = await fetch(`${doorUrl(runId, WorkerDoor.Model)}${request.url.slice(34)}`, {
763
+ method: request.method,
764
+ headers,
765
+ ...hasBody ? { body: await request.arrayBuffer() } : {},
766
+ signal: AbortSignal.any([request.signal, runSignal])
767
+ });
768
+ return response.status === HttpStatus.NotFound && await isRunNotFound(response.clone()) ? checked(response) : response;
769
+ };
770
+ return {
771
+ modelFetch,
772
+ callRouterTool: async (server, tool, args, { call, signal }) => {
773
+ const response = await checked(await post(runId, WorkerDoor.Tools, {
774
+ server,
775
+ tool,
776
+ args,
777
+ call
778
+ }, signal));
779
+ if (response.ok === false) {
780
+ const text = await response.text().catch(() => "");
781
+ throw new Error(`The router's tools door answered ${response.status}: ${text}`.trim());
782
+ }
783
+ const answer = routerToolAnswerSchema.parse(await response.json());
784
+ if (answer.ok === false) throw new Error(answer.error);
785
+ return answer.text;
786
+ },
787
+ ...local === void 0 ? {} : { callLocalTool: (server, tool, args, { signal }) => local.callTool(server, tool, args, signal) },
788
+ publish: (event) => {
789
+ events.push(event);
790
+ return stamp(event, runId, 0, Date.now());
791
+ },
792
+ signal: runSignal
793
+ };
794
+ };
795
+ const run = async (assignment, held) => {
796
+ const { runId } = assignment;
797
+ const drop = () => {
798
+ if (held.dropped) return;
799
+ held.dropped = true;
800
+ console.warn(`[worker] stopping run ${runId}: ${RUN_DROPPED}`);
801
+ held.controller.abort(/* @__PURE__ */ new Error(RUN_DROPPED));
802
+ };
803
+ const events = eventQueue(runId, held, drop);
804
+ const outcome = await executeRun(assignment, portsFor(runId, held, events, drop), runtime);
805
+ await events.drain();
806
+ if (held.dropped) return;
807
+ const { stoppedFor } = held;
808
+ const reported = stoppedFor === void 0 ? outcome : {
809
+ ok: false,
810
+ error: stoppedFor,
811
+ usage: outcome.usage
812
+ };
813
+ console.log(`[worker] run ${runId} ${reported.ok ? "finished" : `failed: ${reported.error}`}`);
814
+ await finish(runId, reported);
815
+ };
816
+ return {
817
+ assign: (assignment) => {
818
+ const { runId } = assignment;
819
+ if (runs.has(runId)) {
820
+ console.warn(`[worker] ignoring a second assignment of run ${runId}, which is still going here`);
821
+ return;
822
+ }
823
+ if (isStopping) {
824
+ failAtOnce(runId, WORKER_STOPPING);
825
+ return;
826
+ }
827
+ if (runs.size >= settings.maxRunsAtOnce) {
828
+ console.warn(`[worker] turning down run ${runId}: ${settings.maxRunsAtOnce} runs are going already`);
829
+ failAtOnce(runId, WORKER_BUSY);
830
+ return;
831
+ }
832
+ const held = {
833
+ controller: new AbortController(),
834
+ stoppedFor: void 0,
835
+ dropped: false,
836
+ done: Promise.resolve()
837
+ };
838
+ runs.set(runId, held);
839
+ console.log(`[worker] run ${runId} started: agent ${assignment.config.id}`);
840
+ held.done = run(assignment, held).catch((error) => console.error(`[worker] run ${runId} failed here: ${errorMessage(error)}`)).finally(() => runs.delete(runId));
841
+ },
842
+ cancel: (runId, reason) => {
843
+ const held = runs.get(runId);
844
+ if (held === void 0) return;
845
+ held.stoppedFor ??= reason;
846
+ held.controller.abort(new Error(reason));
847
+ },
848
+ held: () => runs.size,
849
+ ids: () => [...runs.keys()],
850
+ stop: async () => {
851
+ isStopping = true;
852
+ const going = [...runs.values()];
853
+ for (const held of going) {
854
+ held.stoppedFor ??= WORKER_STOPPING;
855
+ held.controller.abort(/* @__PURE__ */ new Error(WORKER_STOPPING));
856
+ }
857
+ const deadline = setTimeout$1(settings.stopDeadlineMs, void 0, { ref: false });
858
+ await Promise.race([Promise.all(going.map((held) => held.done)), deadline]);
859
+ }
860
+ };
861
+ }
862
+ // server/core/names.ts
863
+ /**
864
+ * What a router name may look like: lowercase letters, digits, dots, dashes and underscores,
865
+ * starting with a letter or digit. llm-router and mcp-router use the same rule.
866
+ */
867
+ const NAME_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
868
+ /**
869
+ * Builds the schema for a router name: a workspace's slug, a provider's or pool's name, and later a
870
+ * server's or agent's.
871
+ *
872
+ * @param label - What the name names, as the message starts it ("Slug").
873
+ * @returns The zod schema, which trims before it checks.
874
+ */
875
+ function nameSchema(label) {
876
+ const { maxLength } = NAME_DEFAULTS;
877
+ return z.string().trim().min(1, `${label} cannot be empty.`).max(maxLength, `${label} is longer than ${maxLength} characters.`).regex(NAME_PATTERN, `${label} may hold lowercase letters, digits, dots, dashes and underscores, and must start with a letter or digit.`);
878
+ }
879
+ // server/tools/child-transport.ts
880
+ /** The signals a stopping program gets, in order, after its stdin closes. */
881
+ const STOP_SIGNALS = ["SIGTERM", "SIGKILL"];
882
+ /**
883
+ * Speaks MCP over a child's stdin and stdout, with exactly the environment it is given.
884
+ *
885
+ * @remarks
886
+ * The SDK's `StdioClientTransport` merges `HOME`, `LOGNAME`, `PATH`, `SHELL`, `TERM` and `USER` from the router's
887
+ * own environment under the env it is handed, so a variable the allowlist leaves out would still reach the child.
888
+ * This one spawns with the env as given, and an argument array with no shell. The router's instances and the worker
889
+ * program's own servers both run over it.
890
+ */
891
+ var ChildTransport = class {
892
+ onclose;
893
+ onerror;
894
+ onmessage;
895
+ spec;
896
+ closeGraceMs;
897
+ onStderr;
898
+ buffer = new ReadBuffer();
899
+ child;
900
+ /**
901
+ * Builds the transport; nothing runs until `start`.
902
+ *
903
+ * @param spec - The program, its arguments, env and folder.
904
+ * @param closeGraceMs - How long `close` waits after each step before the next.
905
+ * @param onStderr - Hears everything the program writes to stderr.
906
+ */
907
+ constructor(spec, closeGraceMs, onStderr) {
908
+ this.spec = spec;
909
+ this.closeGraceMs = closeGraceMs;
910
+ this.onStderr = onStderr;
911
+ }
912
+ /**
913
+ * Starts the program.
914
+ *
915
+ * @returns Resolves once it is running, and rejects when it can't be spawned.
916
+ */
917
+ start() {
918
+ return new Promise((resolve, reject) => {
919
+ const { command, args, env, cwd } = this.spec;
920
+ const child = spawn(command, args, {
921
+ env,
922
+ cwd,
923
+ stdio: [
924
+ "pipe",
925
+ "pipe",
926
+ "pipe"
927
+ ],
928
+ shell: false
929
+ });
930
+ this.child = child;
931
+ child.once("spawn", () => resolve());
932
+ child.on("error", (error) => {
933
+ reject(error);
934
+ this.onerror?.(error);
935
+ });
936
+ child.once("close", () => this.finish(child));
937
+ child.stdin.on("error", (error) => this.onerror?.(error));
938
+ child.stdout.on("data", (chunk) => this.read(chunk));
939
+ child.stderr.on("data", (chunk) => this.onStderr(chunk.toString()));
940
+ });
941
+ }
942
+ /**
943
+ * Hands on every whole message the program has written.
944
+ *
945
+ * @param chunk - What just arrived on stdout.
946
+ */
947
+ read(chunk) {
948
+ this.buffer.append(chunk);
949
+ for (;;) try {
950
+ const message = this.buffer.readMessage();
951
+ if (message === null) return;
952
+ this.onmessage?.(message);
953
+ } catch (error) {
954
+ this.onerror?.(error instanceof Error ? error : new Error(errorMessage(error)));
955
+ }
956
+ }
957
+ /**
958
+ * Writes one message to the program.
959
+ *
960
+ * @param message - The message.
961
+ * @returns Resolves once the write is flushed or buffered.
962
+ */
963
+ send(message) {
964
+ const child = this.child;
965
+ if (child === void 0) return Promise.reject(/* @__PURE__ */ new Error("Not connected"));
966
+ return new Promise((resolve) => {
967
+ if (child.stdin.write(serializeMessage(message))) resolve();
968
+ else child.stdin.once("drain", () => resolve());
969
+ });
970
+ }
971
+ /**
972
+ * Stops the program: closes its stdin, then sends SIGTERM, then SIGKILL, waiting `closeGraceMs` between.
973
+ *
974
+ * @returns Resolves once it has exited, or the last signal is sent.
975
+ *
976
+ * @remarks
977
+ * An MCP server exits when its input ends, so closing stdin is what usually stops it. The signals go through
978
+ * `spec.signal`: straight from the router for a program running as its user, through the helper for an isolated one.
979
+ */
980
+ async close() {
981
+ const child = this.child;
982
+ if (child === void 0) return;
983
+ const exited = new Promise((resolve) => child.once("close", () => resolve(true)));
984
+ child.stdin.end();
985
+ for (const signal of STOP_SIGNALS) {
986
+ if (await Promise.race([exited, setTimeout$1(this.closeGraceMs, false, { ref: false })])) return;
987
+ await this.spec.signal(child, signal);
988
+ }
989
+ }
990
+ /**
991
+ * Notes that the program has exited and its pipes are closed.
992
+ *
993
+ * @param child - The program that closed. Ignored once it is no longer this transport's.
994
+ */
995
+ finish(child) {
996
+ if (this.child !== child) return;
997
+ this.child = void 0;
998
+ this.buffer.clear();
999
+ this.onclose?.();
1000
+ }
1001
+ };
1002
+ /**
1003
+ * Signals a program that runs as the router's own user.
1004
+ *
1005
+ * @param child - The program.
1006
+ * @param signal - The signal.
1007
+ * @returns Resolves at once.
1008
+ */
1009
+ function signalDirectly(child, signal) {
1010
+ child.kill(signal);
1011
+ return Promise.resolve();
1012
+ }
1013
+ // server/tools/tool-result.ts
1014
+ /** What a failed result that says nothing is reported as. */
1015
+ const SILENT_FAILURE = "The tool reported an error and said nothing more.";
1016
+ /**
1017
+ * Whether a tool call that answered is in fact the tool reporting a failure.
1018
+ *
1019
+ * @param result - What `tools/call` answered.
1020
+ * @returns true when the result sets `isError`.
1021
+ */
1022
+ function isToolError(result) {
1023
+ return result.isError === true;
1024
+ }
1025
+ /**
1026
+ * Reads what a tool said, as the model reads it.
1027
+ *
1028
+ * @param result - What `tools/call` answered.
1029
+ * @returns The text blocks and embedded text resources joined, else the structured content as JSON, else empty.
1030
+ */
1031
+ function toolResultContent(result) {
1032
+ const text = result.content.flatMap((block) => {
1033
+ if (block.type === "text") return [block.text];
1034
+ if (block.type === "resource" && "text" in block.resource) return [block.resource.text];
1035
+ return [];
1036
+ }).join("\n").trim();
1037
+ if (text !== "") return text;
1038
+ return result.structuredContent === void 0 ? "" : JSON.stringify(result.structuredContent);
1039
+ }
1040
+ /**
1041
+ * Reads what a tool said, as one line of text for an error message.
1042
+ *
1043
+ * @param result - What `tools/call` answered.
1044
+ * @returns What `toolResultContent` reads, else a fixed message.
1045
+ */
1046
+ function toolResultText(result) {
1047
+ const content = toolResultContent(result);
1048
+ return content === "" ? SILENT_FAILURE : content;
1049
+ }
1050
+ path.resolve(import.meta.dirname, "..", "..");
1051
+ // worker/version.ts
1052
+ /**
1053
+ * Says which version of the worker program this is: the bundled package's own, or, from a checkout, the repo's.
1054
+ *
1055
+ * @returns The version, as the hello and the MCP clients name it.
1056
+ *
1057
+ * @remarks
1058
+ * A bundle can't read the repo's package.json the way `version()` does, because it isn't there.
1059
+ */
1060
+ function workerVersion() {
1061
+ return "0.4.0";
1062
+ }
1063
+ // worker/workdir/git.ts
1064
+ /** The git program, found on PATH. */
1065
+ const GIT_COMMAND = "git";
1066
+ /**
1067
+ * Builds the real runner, which spawns git with no shell and no prompt for credentials.
1068
+ *
1069
+ * @returns A runner over `child_process.spawn`.
1070
+ */
1071
+ function createGitRunner() {
1072
+ return (args, { cwd, timeoutMs }) => new Promise((resolve, reject) => {
1073
+ const child = spawn(GIT_COMMAND, [...args], {
1074
+ cwd,
1075
+ env: {
1076
+ ...process.env,
1077
+ GIT_TERMINAL_PROMPT: "0"
1078
+ },
1079
+ stdio: [
1080
+ "ignore",
1081
+ "pipe",
1082
+ "pipe"
1083
+ ],
1084
+ signal: AbortSignal.timeout(timeoutMs)
1085
+ });
1086
+ const stdout = [];
1087
+ const stderr = [];
1088
+ child.stdout.on("data", (chunk) => stdout.push(chunk));
1089
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
1090
+ child.once("error", (error) => {
1091
+ reject(error.name === "AbortError" ? /* @__PURE__ */ new Error(`git ${args[0]} took longer than ${timeoutMs} ms and was stopped.`) : error);
1092
+ });
1093
+ child.once("close", (exitCode) => {
1094
+ resolve({
1095
+ exitCode,
1096
+ stdout: Buffer.concat(stdout).toString("utf8"),
1097
+ stderr: Buffer.concat(stderr).toString("utf8")
1098
+ });
1099
+ });
1100
+ });
1101
+ }
1102
+ // worker/workdir/refusal.ts
1103
+ /** A request the workdir server turns down, with a message that says what to send instead. */
1104
+ var WorkdirRefusal = class extends Error {
1105
+ /**
1106
+ * Builds the refusal.
1107
+ *
1108
+ * @param message - What was wrong, written for the agent that asked.
1109
+ */
1110
+ constructor(message) {
1111
+ super(message);
1112
+ this.name = "WorkdirRefusal";
1113
+ }
1114
+ };
1115
+ // worker/workdir/root.ts
1116
+ /** The path `relative` gives for the folder above. */
1117
+ const PARENT = "..";
1118
+ /**
1119
+ * Makes the root if it is missing, and resolves its real path.
1120
+ *
1121
+ * @param root - The root as configured.
1122
+ * @returns The root with every symlink resolved.
1123
+ */
1124
+ async function realRoot(root) {
1125
+ await mkdir(root, { recursive: true });
1126
+ return realpath(root);
1127
+ }
1128
+ /**
1129
+ * Tells whether a real path is the root or inside it.
1130
+ *
1131
+ * @param rootPath - The real root, from {@link realRoot}.
1132
+ * @param path - A real path.
1133
+ * @returns true when `path` is `rootPath` or below it.
1134
+ */
1135
+ function isInsideRoot(rootPath, path) {
1136
+ const fromRoot = relative(rootPath, path);
1137
+ return (fromRoot === PARENT || fromRoot.startsWith(`${PARENT}${sep}`) || isAbsolute(fromRoot)) === false;
1138
+ }
1139
+ /**
1140
+ * Resolves a path a caller sent to the real path it names, inside the root.
1141
+ *
1142
+ * @param rootPath - The real root, from {@link realRoot}.
1143
+ * @param path - Relative to the root, or absolute.
1144
+ * @returns The real path, every symlink resolved.
1145
+ * @throws {@link WorkdirRefusal} If nothing is there, or the path or a symlink on it leads outside the root.
1146
+ */
1147
+ async function resolveInsideRoot(rootPath, path) {
1148
+ const outside = new WorkdirRefusal(`${JSON.stringify(path)} is outside the work root, ${rootPath}.`);
1149
+ const asked = resolve(rootPath, path);
1150
+ if (isInsideRoot(rootPath, asked) === false) throw outside;
1151
+ const real = await realpath(asked).catch((error) => {
1152
+ if (error.code === "ENOENT") throw new WorkdirRefusal(`Nothing is at ${JSON.stringify(path)} under the work root.`);
1153
+ throw error;
1154
+ });
1155
+ if (isInsideRoot(rootPath, real) === false) throw outside;
1156
+ return real;
1157
+ }
1158
+ // worker/workdir/list-dir.ts
1159
+ /** What kind of thing an entry is. A symlink is never followed. */
1160
+ const EntryType = {
1161
+ File: "file",
1162
+ Dir: "dir",
1163
+ Symlink: "symlink",
1164
+ Other: "other"
1165
+ };
1166
+ /** The folder whose contents are named but never listed. */
1167
+ const GIT_DIR$1 = ".git";
1168
+ /**
1169
+ * Lists a directory under the root, its subfolders to a depth.
1170
+ *
1171
+ * @param rootPath - The real root.
1172
+ * @param path - Relative to the root, or absolute inside it.
1173
+ * @param askedDepth - Levels to list; 1 is the directory's own entries.
1174
+ * @param settings - The entry and depth caps.
1175
+ * @returns The entries and whether a cap cut them short.
1176
+ * @throws {@link WorkdirRefusal} If the path is not a directory, or leads outside the root.
1177
+ */
1178
+ async function listDir(rootPath, path, askedDepth, settings) {
1179
+ const directory = await resolveInsideRoot(rootPath, path);
1180
+ if ((await stat(directory)).isDirectory() === false) throw new WorkdirRefusal(`${JSON.stringify(path)} is a file, not a directory.`);
1181
+ const depth = Math.min(askedDepth, settings.maxDepth);
1182
+ const entries = [];
1183
+ let truncated = false;
1184
+ const walk = async (folder, prefix, levelsLeft) => {
1185
+ const children = sortEntries(await readdir(folder, { withFileTypes: true }));
1186
+ for (const child of children) {
1187
+ if (entries.length >= settings.maxEntries) {
1188
+ truncated = true;
1189
+ return;
1190
+ }
1191
+ const childPath = join(folder, child.name);
1192
+ const type = entryTypeOf(child);
1193
+ const size = type === EntryType.File ? (await lstat(childPath)).size : null;
1194
+ entries.push({
1195
+ path: `${prefix}${child.name}`,
1196
+ type,
1197
+ size
1198
+ });
1199
+ if (type === EntryType.Dir && levelsLeft > 1 && child.name !== GIT_DIR$1) await walk(childPath, `${prefix}${child.name}/`, levelsLeft - 1);
1200
+ }
1201
+ };
1202
+ await walk(directory, "", depth);
1203
+ return {
1204
+ path: directory,
1205
+ depth,
1206
+ depthCapped: askedDepth > settings.maxDepth,
1207
+ entries,
1208
+ truncated
1209
+ };
1210
+ }
1211
+ /**
1212
+ * Orders a folder's entries: folders first, then by name.
1213
+ *
1214
+ * @param children - What `readdir` gave.
1215
+ * @returns A sorted copy.
1216
+ */
1217
+ function sortEntries(children) {
1218
+ return [...children].sort((a, b) => {
1219
+ const byKind = Number(b.isDirectory()) - Number(a.isDirectory());
1220
+ return byKind === 0 ? a.name.localeCompare(b.name) : byKind;
1221
+ });
1222
+ }
1223
+ /**
1224
+ * Names what kind of thing an entry is, without following a symlink.
1225
+ *
1226
+ * @param child - A `readdir` entry.
1227
+ * @returns Its type.
1228
+ */
1229
+ function entryTypeOf(child) {
1230
+ if (child.isSymbolicLink()) return EntryType.Symlink;
1231
+ if (child.isDirectory()) return EntryType.Dir;
1232
+ if (child.isFile()) return EntryType.File;
1233
+ return EntryType.Other;
1234
+ }
1235
+ // worker/workdir/open-repo.ts
1236
+ /** The folder that makes a directory a git checkout. */
1237
+ const GIT_DIR = ".git";
1238
+ /**
1239
+ * Returns the checkout of a repo under the root, cloning it first when there is none.
1240
+ *
1241
+ * @param rootPath - The real root.
1242
+ * @param ref - The repo, already checked by `parseRepo`.
1243
+ * @param git - Runs git.
1244
+ * @param settings - The clone and command timeouts.
1245
+ * @returns Where the checkout is and what it has checked out.
1246
+ * @throws {@link WorkdirRefusal} If the place is taken by something else, a symlink leads outside the root, or the
1247
+ * clone fails.
1248
+ */
1249
+ async function openRepo(rootPath, ref, git, settings) {
1250
+ const ownerPath = await makeFolderInside(rootPath, [ref.host, ref.owner]);
1251
+ const checkout = join(ownerPath, ref.name);
1252
+ if (await lstat(checkout).then(() => true, () => false)) {
1253
+ const real = await realpath(checkout);
1254
+ if (isInsideRoot(rootPath, real) === false) throw new WorkdirRefusal(`The checkout of ${ref.cloneUrl} is a symlink that leads outside the work root.`);
1255
+ if (await lstat(join(real, GIT_DIR)).then(() => true, () => false) === false) throw new WorkdirRefusal(`${real} is already there and is not a git checkout, so ${ref.cloneUrl} can't go there.`);
1256
+ return {
1257
+ path: real,
1258
+ cloned: false,
1259
+ ...await describeCheckout(real, git, settings)
1260
+ };
1261
+ }
1262
+ const clone = await git([
1263
+ "clone",
1264
+ "--",
1265
+ ref.cloneUrl,
1266
+ checkout
1267
+ ], {
1268
+ cwd: ownerPath,
1269
+ timeoutMs: settings.cloneTimeoutMs
1270
+ });
1271
+ if (clone.exitCode !== 0) throw new WorkdirRefusal(`git clone of ${ref.cloneUrl} failed: ${clone.stderr.trim() || `exit ${clone.exitCode}`}`);
1272
+ return {
1273
+ path: checkout,
1274
+ cloned: true,
1275
+ ...await describeCheckout(checkout, git, settings)
1276
+ };
1277
+ }
1278
+ /**
1279
+ * Makes each folder of a path under the root, checking after each that no symlink has led outside it.
1280
+ *
1281
+ * @param rootPath - The real root.
1282
+ * @param segments - Folder names, each already checked.
1283
+ * @returns The real path of the last folder.
1284
+ * @throws {@link WorkdirRefusal} If one of the folders is a symlink that leads outside the root.
1285
+ */
1286
+ async function makeFolderInside(rootPath, segments) {
1287
+ let current = rootPath;
1288
+ for (const segment of segments) {
1289
+ const next = join(current, segment);
1290
+ await mkdir(next).catch((error) => {
1291
+ if (error.code !== "EEXIST") throw error;
1292
+ });
1293
+ current = await realpath(next);
1294
+ if (isInsideRoot(rootPath, current) === false) throw new WorkdirRefusal(`${next} is a symlink that leads outside the work root.`);
1295
+ }
1296
+ return current;
1297
+ }
1298
+ /**
1299
+ * Reads a checkout's branch and HEAD.
1300
+ *
1301
+ * @param checkout - The checkout's real path.
1302
+ * @param git - Runs git.
1303
+ * @param settings - The command timeout.
1304
+ * @returns The branch and sha, each null when git has none to give.
1305
+ */
1306
+ async function describeCheckout(checkout, git, settings) {
1307
+ const options = {
1308
+ cwd: checkout,
1309
+ timeoutMs: settings.gitCommandTimeoutMs
1310
+ };
1311
+ const [branch, head] = await Promise.all([git([
1312
+ "symbolic-ref",
1313
+ "--short",
1314
+ "-q",
1315
+ "HEAD"
1316
+ ], options), git([
1317
+ "rev-parse",
1318
+ "--verify",
1319
+ "-q",
1320
+ "HEAD"
1321
+ ], options)]);
1322
+ return {
1323
+ branch: answerOf(branch),
1324
+ head: answerOf(head)
1325
+ };
1326
+ }
1327
+ /**
1328
+ * Reads a git command's one-line answer.
1329
+ *
1330
+ * @param result - How the command ended.
1331
+ * @returns Its trimmed output, or null when it failed or said nothing.
1332
+ */
1333
+ function answerOf(result) {
1334
+ const answer = result.stdout.trim();
1335
+ return result.exitCode === 0 && answer !== "" ? answer : null;
1336
+ }
1337
+ // worker/workdir/repo-ref.ts
1338
+ /** The host a bare `owner/name` means. */
1339
+ const DEFAULT_HOST = "github.com";
1340
+ /** The suffix a clone URL may carry after the repo's name. */
1341
+ const GIT_SUFFIX = ".git";
1342
+ /** An owner or a repo name: starts with a letter, digit or `_`, so never `.`, `..` or an option. */
1343
+ const SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
1344
+ /** A DNS host name, in lowercase labels. */
1345
+ const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
1346
+ /** `owner/name`, with an optional `.git`. */
1347
+ const SHORT_FORM = /^([^/:@]+)\/([^/:@]+)$/;
1348
+ /** scp-like ssh, `git@host:owner/name.git`. */
1349
+ const SSH_FORM = /^git@([^/:@]+):([^/:@]+)\/([^/:@]+)$/;
1350
+ /** A repo cloned over https. */
1351
+ const CLONE_HTTPS = "https";
1352
+ /** A repo cloned over ssh. */
1353
+ const CLONE_SSH = "ssh";
1354
+ /** The URL scheme an https repo is named with. */
1355
+ const HTTPS_PROTOCOL = "https:";
1356
+ /** An https URL's path, `/owner/name`. */
1357
+ const HTTPS_PATH = /^\/([^/]+)\/([^/]+)$/;
1358
+ /**
1359
+ * Reads a repo string into the repo it names.
1360
+ *
1361
+ * @param repo - `owner/name` (on GitHub), `https://host/owner/name.git` or `git@host:owner/name.git`.
1362
+ * @returns The repo and its clone URL.
1363
+ * @throws {@link WorkdirRefusal} If the string is none of those, or a part of it could leave the root.
1364
+ */
1365
+ function parseRepo(repo) {
1366
+ const trimmed = repo.trim();
1367
+ const short = SHORT_FORM.exec(trimmed);
1368
+ if (short) {
1369
+ const [, owner = "", name = ""] = short;
1370
+ return buildRef(DEFAULT_HOST, owner, name, CLONE_HTTPS, repo);
1371
+ }
1372
+ const ssh = SSH_FORM.exec(trimmed);
1373
+ if (ssh) {
1374
+ const [, host = "", owner = "", name = ""] = ssh;
1375
+ return buildRef(host, owner, name, CLONE_SSH, repo);
1376
+ }
1377
+ if (trimmed.startsWith(`${HTTPS_PROTOCOL}//`)) return parseHttpsRepo(trimmed, repo);
1378
+ throw refuseRepo(repo, "it is not `owner/name`, an https URL or `git@host:owner/name.git`");
1379
+ }
1380
+ /**
1381
+ * Reads an https repo URL.
1382
+ *
1383
+ * @param url - The trimmed string, starting `https://`.
1384
+ * @param repo - The string as sent, for the refusal.
1385
+ * @returns The repo.
1386
+ * @throws {@link WorkdirRefusal} If the URL has a login, a port, a query or a path other than `/owner/name`.
1387
+ */
1388
+ function parseHttpsRepo(url, repo) {
1389
+ const parsed = URL.canParse(url) ? new URL(url) : null;
1390
+ if (parsed === null) throw refuseRepo(repo, "it is not a valid URL");
1391
+ if (parsed.username !== "" || parsed.password !== "" || parsed.port !== "" || parsed.search !== "" || parsed.hash !== "") throw refuseRepo(repo, "an https URL may hold only a host and `/owner/name`, with no login, port or query");
1392
+ const path = HTTPS_PATH.exec(parsed.pathname);
1393
+ if (path === null) throw refuseRepo(repo, "its path must be exactly `/owner/name`");
1394
+ const [, owner = "", name = ""] = path;
1395
+ return buildRef(parsed.hostname, owner, name, CLONE_HTTPS, repo);
1396
+ }
1397
+ /**
1398
+ * Checks each part of a repo and builds its clone URL.
1399
+ *
1400
+ * @param host - Host name as written.
1401
+ * @param owner - Owner as written.
1402
+ * @param rawName - Name as written, maybe ending `.git`.
1403
+ * @param scheme - How the repo is cloned.
1404
+ * @param repo - The string as sent, for the refusal.
1405
+ * @returns The repo.
1406
+ * @throws {@link WorkdirRefusal} If a part has a character a folder name shouldn't.
1407
+ */
1408
+ function buildRef(host, owner, rawName, scheme, repo) {
1409
+ const lowerHost = host.toLowerCase();
1410
+ const name = rawName.endsWith(GIT_SUFFIX) ? rawName.slice(0, -4) : rawName;
1411
+ if (HOST.test(lowerHost) === false) throw refuseRepo(repo, `\`${host}\` is not a host name`);
1412
+ for (const segment of [owner, name]) if (SEGMENT.test(segment) === false || segment.includes("..")) throw refuseRepo(repo, `\`${segment}\` may hold only letters, digits, \`.\`, \`_\` and \`-\`, and not \`..\``);
1413
+ return {
1414
+ host: lowerHost,
1415
+ owner,
1416
+ name,
1417
+ cloneUrl: scheme === CLONE_SSH ? `git@${lowerHost}:${owner}/${name}${GIT_SUFFIX}` : `https://${lowerHost}/${owner}/${name}${GIT_SUFFIX}`
1418
+ };
1419
+ }
1420
+ /**
1421
+ * Builds the refusal for a repo string.
1422
+ *
1423
+ * @param repo - The string as sent.
1424
+ * @param reason - What is wrong with it.
1425
+ * @returns The refusal, for the caller to throw.
1426
+ */
1427
+ function refuseRepo(repo, reason) {
1428
+ return new WorkdirRefusal(`Can't open repo ${JSON.stringify(repo)}: ${reason}.`);
1429
+ }
1430
+ // worker/workdir/server.ts
1431
+ /** The server's name, as an MCP client sees it. */
1432
+ const WORKDIR_SERVER_NAME = "workdir";
1433
+ /** The server's version, as an MCP client sees it. */
1434
+ const WORKDIR_SERVER_VERSION = "1.0.0";
1435
+ /** `list_dir`'s depth when the call names none: the directory's own entries. */
1436
+ const DEFAULT_LIST_DEPTH = 1;
1437
+ /**
1438
+ * Builds the worker's built-in MCP server, which gives each run a work directory per repo.
1439
+ *
1440
+ * @param options - The root, and the git runner.
1441
+ * @param [overrides] - Settings that replace `WORKDIR_DEFAULTS`.
1442
+ * @returns The server, not yet connected to a transport.
1443
+ *
1444
+ * @remarks
1445
+ * It offers `open_repo`, which clones a repo under the root or returns the checkout already there, and `list_dir`.
1446
+ * Nothing either tool reads or writes is outside the root, symlinks included.
1447
+ */
1448
+ function createWorkdirServer(options, overrides = {}) {
1449
+ const { root, git = createGitRunner() } = options;
1450
+ const settings = {
1451
+ ...WORKDIR_DEFAULTS,
1452
+ ...overrides
1453
+ };
1454
+ const server = new McpServer({
1455
+ name: WORKDIR_SERVER_NAME,
1456
+ version: WORKDIR_SERVER_VERSION
1457
+ });
1458
+ const opening = /* @__PURE__ */ new Map();
1459
+ server.registerTool("open_repo", {
1460
+ description: "Returns a work directory holding a checkout of a git repo, cloning it the first time. Answers JSON: { path, cloned, branch, head }.",
1461
+ inputSchema: { repo: z.string().describe("`owner/name` on GitHub, an https clone URL, or an ssh one like `git@host:owner/name.git`.") }
1462
+ }, ({ repo }) => answer(async () => {
1463
+ const ref = parseRepo(repo);
1464
+ const rootPath = await realRoot(root);
1465
+ const key = `${ref.host}/${ref.owner}/${ref.name}`;
1466
+ const pending = opening.get(key) ?? openRepo(rootPath, ref, git, settings);
1467
+ opening.set(key, pending);
1468
+ try {
1469
+ return await pending;
1470
+ } finally {
1471
+ opening.delete(key);
1472
+ }
1473
+ }));
1474
+ server.registerTool("list_dir", {
1475
+ description: `Lists a directory under the work root: each entry with its type (file, dir, symlink, other) and size. Symlinks are not followed, and .git is never listed inside. Answers JSON with \`truncated\` when it held more than ${settings.maxEntries} entries.`,
1476
+ inputSchema: {
1477
+ path: z.string().describe("Relative to the work root, or absolute inside it."),
1478
+ depth: z.number().int().min(1).optional().describe(`Levels to list; 1 lists the directory's own entries. At most ${settings.maxDepth}.`)
1479
+ }
1480
+ }, ({ path, depth = DEFAULT_LIST_DEPTH }) => answer(async () => listDir(await realRoot(root), path, depth, settings)));
1481
+ return server;
1482
+ }
1483
+ /**
1484
+ * Runs a tool's work and answers with its result as JSON, or with its failure as a tool error.
1485
+ *
1486
+ * @param work - The tool's work.
1487
+ * @returns The tool result. A failure is `isError: true` with its message, never a thrown error.
1488
+ */
1489
+ async function answer(work) {
1490
+ try {
1491
+ const result = await work();
1492
+ return { content: [{
1493
+ type: "text",
1494
+ text: JSON.stringify(result)
1495
+ }] };
1496
+ } catch (error) {
1497
+ return {
1498
+ content: [{
1499
+ type: "text",
1500
+ text: errorMessage(error)
1501
+ }],
1502
+ isError: true
1503
+ };
1504
+ }
1505
+ }
1506
+ // worker/servers.ts
1507
+ /** The variables a command server gets from the worker's own environment. Everything else comes from its config. */
1508
+ const LOCAL_ENV_ALLOWLIST = Object.freeze([
1509
+ "PATH",
1510
+ "HOME",
1511
+ "LANG",
1512
+ "TERM",
1513
+ "USER"
1514
+ ]);
1515
+ /** The worker's name, as its local servers see their client. */
1516
+ const CLIENT_NAME = "agent-router-worker";
1517
+ /** The rule every local server's name is checked against: the router's own name rule. */
1518
+ const serverName = nameSchema("A local server name");
1519
+ /**
1520
+ * Builds the environment a command server starts with: the allowlisted variables of the worker's own, then its config's.
1521
+ *
1522
+ * @param config - The server's config.
1523
+ * @param baseEnv - The worker's environment.
1524
+ * @returns The whole environment. Nothing else reaches the program.
1525
+ */
1526
+ function commandEnv(config, baseEnv) {
1527
+ const inherited = LOCAL_ENV_ALLOWLIST.flatMap((key) => {
1528
+ const value = baseEnv[key];
1529
+ return value === void 0 ? [] : [[key, value]];
1530
+ });
1531
+ return {
1532
+ ...Object.fromEntries(inherited),
1533
+ ...config.env
1534
+ };
1535
+ }
1536
+ /**
1537
+ * Builds the transport for a configured server.
1538
+ *
1539
+ * @param name - Its name, for its stderr lines.
1540
+ * @param config - Its config.
1541
+ * @param baseEnv - The worker's environment.
1542
+ * @param closeGraceMs - How long a stopping program gets after each step.
1543
+ * @returns The transport, not yet started.
1544
+ */
1545
+ function transportFor(name, config, baseEnv, closeGraceMs) {
1546
+ if ("url" in config) return new StreamableHTTPClientTransport(new URL(config.url), { requestInit: { headers: config.headers } });
1547
+ return new ChildTransport({
1548
+ command: config.command,
1549
+ args: config.args ?? [],
1550
+ env: commandEnv(config, baseEnv),
1551
+ cwd: config.cwd,
1552
+ signal: signalDirectly
1553
+ }, closeGraceMs, (text) => {
1554
+ for (const line of text.trimEnd().split("\n")) console.error(`[worker] ${name}: ${line}`);
1555
+ });
1556
+ }
1557
+ /**
1558
+ * Lists every tool a server has, page by page.
1559
+ *
1560
+ * @param client - The connected client.
1561
+ * @param timeout - How long each page may take.
1562
+ * @returns The tools, as the hello says them.
1563
+ */
1564
+ async function listTools(client, timeout) {
1565
+ const tools = [];
1566
+ let cursor;
1567
+ do {
1568
+ const page = await client.listTools(cursor === void 0 ? {} : { cursor }, { timeout });
1569
+ for (const tool of page.tools) tools.push({
1570
+ name: tool.name,
1571
+ ...tool.description === void 0 ? {} : { description: tool.description },
1572
+ inputSchema: tool.inputSchema
1573
+ });
1574
+ cursor = page.nextCursor;
1575
+ } while (cursor !== void 0);
1576
+ return tools;
1577
+ }
1578
+ /**
1579
+ * Starts the worker's own servers: `workdir`, in process, and each configured one. A server whose name breaks the
1580
+ * router's name rule, or that fails to start, is left out with a `[worker]` line.
1581
+ *
1582
+ * @param options - The root, the configured servers, and who hears of tool changes.
1583
+ * @param [overrides] - Settings that replace `WORKER_PROGRAM_DEFAULTS`.
1584
+ * @returns The servers that started.
1585
+ *
1586
+ * @remarks
1587
+ * Configured servers run as the worker's user, on its machine: the owner's trust, not the router's sandbox.
1588
+ */
1589
+ async function startLocalServers(options, overrides = {}) {
1590
+ const { root, servers, onChange, baseEnv = process.env, git, workdir } = options;
1591
+ const settings = {
1592
+ ...WORKER_PROGRAM_DEFAULTS,
1593
+ ...overrides
1594
+ };
1595
+ const started = /* @__PURE__ */ new Map();
1596
+ const connect = async (name, transport) => {
1597
+ const client = new Client({
1598
+ name: CLIENT_NAME,
1599
+ version: workerVersion()
1600
+ });
1601
+ const entry = {
1602
+ client,
1603
+ tools: []
1604
+ };
1605
+ client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
1606
+ try {
1607
+ entry.tools = await listTools(client, settings.localStartTimeoutMs);
1608
+ onChange();
1609
+ } catch (error) {
1610
+ console.warn(`[worker] could not list "${name}"'s tools again: ${errorMessage(error)}`);
1611
+ }
1612
+ });
1613
+ try {
1614
+ await client.connect(transport, { timeout: settings.localStartTimeoutMs });
1615
+ entry.tools = await listTools(client, settings.localStartTimeoutMs);
1616
+ } catch (error) {
1617
+ console.error(`[worker] leaving out the local server "${name}": it did not start: ${errorMessage(error)}`);
1618
+ await client.close().catch(() => void 0);
1619
+ return;
1620
+ }
1621
+ started.set(name, entry);
1622
+ };
1623
+ const [workdirSide, clientSide] = InMemoryTransport.createLinkedPair();
1624
+ await createWorkdirServer({
1625
+ root,
1626
+ ...git === void 0 ? {} : { git }
1627
+ }, workdir).connect(workdirSide);
1628
+ await connect(WORKDIR_SERVER_NAME, clientSide);
1629
+ const configured = Object.entries(servers).filter(([name]) => {
1630
+ if (name === "workdir") {
1631
+ console.error(`[worker] leaving out the local server "${name}": the built-in server has that name.`);
1632
+ return false;
1633
+ }
1634
+ const checked = serverName.safeParse(name);
1635
+ if (checked.success === false || checked.data !== name) {
1636
+ const why = checked.error?.issues[0]?.message ?? "it has spaces around it.";
1637
+ console.error(`[worker] leaving out the local server "${name}": ${why}`);
1638
+ return false;
1639
+ }
1640
+ return true;
1641
+ });
1642
+ await Promise.all(configured.map(([name, config]) => connect(name, transportFor(name, config, baseEnv, settings.localCloseGraceMs))));
1643
+ return {
1644
+ listing: () => [...started].map(([name, { tools }]) => ({
1645
+ name,
1646
+ tools
1647
+ })),
1648
+ callTool: async (server, tool, args, signal) => {
1649
+ const entry = started.get(server);
1650
+ if (entry === void 0) throw new Error(`This worker has no local server named "${server}".`);
1651
+ const result = await entry.client.request({
1652
+ method: "tools/call",
1653
+ params: {
1654
+ name: tool,
1655
+ arguments: args
1656
+ }
1657
+ }, CallToolResultSchema, {
1658
+ signal,
1659
+ timeout: settings.localToolTimeoutMs
1660
+ });
1661
+ if (isToolError(result)) throw new Error(toolResultText(result));
1662
+ return toolResultContent(result);
1663
+ },
1664
+ close: async () => {
1665
+ const clients = [...started.values()].map(({ client }) => client);
1666
+ started.clear();
1667
+ await Promise.all(clients.map((client) => client.close().catch(() => void 0)));
1668
+ }
1669
+ };
1670
+ }
1671
+ // worker/worker.ts
1672
+ /**
1673
+ * Starts a worker: its local servers, then its channel to the router, whose assignments it runs.
1674
+ *
1675
+ * @param config - The router, the key, the work root, the host and the servers.
1676
+ * @param [deps] - Stand-ins for what it talks to, and settings.
1677
+ * @returns The running worker.
1678
+ */
1679
+ async function startWorker(config, deps = {}) {
1680
+ const { url, key, root, host, servers } = config;
1681
+ const { fetch = globalThis.fetch, runtime = { runAgentLoop }, baseEnv, git, settings = {}, workdir } = deps;
1682
+ let channel;
1683
+ const sayHello = async () => {
1684
+ const hello = {
1685
+ host,
1686
+ version: workerVersion(),
1687
+ servers: local.listing(),
1688
+ runs: runs.ids()
1689
+ };
1690
+ const response = await fetch(`${url}${WORKERS_PATH}${WorkerDoor.Hello}`, {
1691
+ method: "POST",
1692
+ headers: {
1693
+ authorization: `Bearer ${key}`,
1694
+ "content-type": "application/json"
1695
+ },
1696
+ body: JSON.stringify(hello)
1697
+ });
1698
+ await response.body?.cancel().catch(() => void 0);
1699
+ if (response.ok === false) throw new Error(`the router refused the hello: ${response.status}`);
1700
+ };
1701
+ const local = await startLocalServers({
1702
+ root,
1703
+ servers,
1704
+ ...baseEnv === void 0 ? {} : { baseEnv },
1705
+ ...git === void 0 ? {} : { git },
1706
+ ...workdir === void 0 ? {} : { workdir },
1707
+ onChange: () => {
1708
+ if (channel?.isOpen()) sayHello().catch((error) => console.error(`[worker] could not say the new tools: ${errorMessage(error)}`));
1709
+ }
1710
+ }, settings);
1711
+ const runs = createRunHost({
1712
+ url,
1713
+ key,
1714
+ local,
1715
+ runtime,
1716
+ fetch
1717
+ }, settings);
1718
+ const onMessage = (message) => {
1719
+ if (message.type === ChannelMessageType.Assign) runs.assign(message.assignment);
1720
+ if (message.type === ChannelMessageType.Cancel) runs.cancel(message.runId, message.reason);
1721
+ };
1722
+ const opened = openChannel({
1723
+ url,
1724
+ key,
1725
+ fetch,
1726
+ onOpen: async () => {
1727
+ await sayHello();
1728
+ console.log(`[worker] connected to ${url} as ${host}`);
1729
+ },
1730
+ onMessage
1731
+ }, settings);
1732
+ channel = opened;
1733
+ return {
1734
+ local,
1735
+ runs,
1736
+ channel: opened,
1737
+ stop: async () => {
1738
+ await opened.close();
1739
+ await runs.stop();
1740
+ await local.close();
1741
+ }
1742
+ };
1743
+ }
1744
+ export { WorkerConfigError as a, TOOL_ORIGIN_ROUTER as i, executeRun as n, readWorkerConfig as o, TOOL_ORIGIN_LOCAL as r, errorMessage as s, startWorker as t };