@cubicecho/agent-router-worker 0.10.1 → 0.11.1

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.
@@ -119,6 +119,8 @@ if (outcome.ok === false) {
119
119
  console.log(outcome.finishReason, outcome.messages.at(-1)?.content);
120
120
  ```
121
121
 
122
+ `RunPorts.elicit` is the router's side of a worker server's question, so a test's ports may leave it out. The worker program asks the router itself, from inside `options.dispatch`.
123
+
122
124
  Set the endpoint's `baseUrl` to exactly `http://models.ai-router.invalid/v1`, as the router's assignments do. `executeRun` hands `modelFetch` only to endpoints at that address, and the loop calls any other directly.
123
125
 
124
126
  ## Other things startWorker takes
@@ -1,6 +1,6 @@
1
1
  # Local servers: the tools a worker gives its runs
2
2
 
3
- A worker's runs reach its built-in `workdir` server and each MCP server the `WORKER_CONFIG` file names. This page covers that file, the environment and folder a server starts with, how tools are named, and what `workdir` offers.
3
+ A worker's runs reach its built-in `workdir` server and each MCP server the `WORKER_CONFIG` file names. This page covers that file, the environment and folder a server starts with, how tools are named, questions a server asks, and what `workdir` offers.
4
4
 
5
5
  ## The WORKER_CONFIG file
6
6
 
@@ -62,6 +62,12 @@ The model sees `<server>__<tool>`, such as `files__read_file`. A character a fun
62
62
 
63
63
  Every agent of a workspace on the worker reaches all the worker's servers. A request can narrow them with `agent_core.servers`, a list of server names. A router's server of the same name is used in place of the worker's.
64
64
 
65
+ ## Questions a server asks
66
+
67
+ The worker tells its servers it can answer questions in form mode (MCP elicitation). A question goes to the router and on to whoever called the agent: the app or client at the top, through every agent between. Their answer comes back to the server, or a decline when no one there can answer. The 15 minutes a call may take stop while a question waits.
68
+
69
+ MCP doesn't say which call a question belongs to, so a server with two calls going at once has its questions declined.
70
+
65
71
  ## The built-in workdir server
66
72
 
67
73
  | Tool | Takes | Answers |
@@ -5,10 +5,10 @@ import { z } from "zod";
5
5
  import { RunEventKind, ToolDiscovery, failedRun, runAgentLoop, stamp } from "@cubicecho/agent-core";
6
6
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
7
7
  import { EventSourceParserStream } from "eventsource-parser/stream";
8
+ import { CallToolResultSchema, ElicitRequestSchema, ElicitResultSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
8
9
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
9
10
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
10
11
  import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
11
- import { CallToolResultSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
12
12
  import { spawn } from "node:child_process";
13
13
  import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";
14
14
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
@@ -231,7 +231,8 @@ const WORKER_DEFAULTS = Object.freeze({
231
231
  eventFlushMs: 250,
232
232
  maxRunsAtOnce: 8,
233
233
  cancelGraceMs: 1e4,
234
- bodyLimit: "8mb"
234
+ bodyLimit: "8mb",
235
+ doorKeepAliveMs: 3e4
235
236
  });
236
237
  Object.freeze({
237
238
  maxAppTools: 128,
@@ -290,6 +291,8 @@ const WorkerDoor = {
290
291
  Model: "/model",
291
292
  /** `POST` a {@link RouterToolCall}, answered with a {@link RouterToolAnswer}. */
292
293
  Tools: "/tools/call",
294
+ /** `POST` a {@link WorkerQuestion}, answered with an MCP `ElicitResult`. */
295
+ Elicit: "/elicit",
293
296
  /** `POST` an {@link EventBatch}. */
294
297
  Events: "/events",
295
298
  /** `POST` the stretch's {@link RunOutcome}. */
@@ -372,6 +375,18 @@ z.object({
372
375
  name: z.string().min(1)
373
376
  })
374
377
  });
378
+ z.object({
379
+ /** The model's call the server was answering when it asked, as the loop numbered it. */
380
+ call: z.object({
381
+ id: z.string().min(1),
382
+ name: z.string().min(1)
383
+ }),
384
+ /** The question, as MCP's `elicitation/create` sends it. The router reads the rest of its shape. */
385
+ params: z.looseObject({
386
+ message: z.string(),
387
+ mode: z.string().optional()
388
+ })
389
+ });
375
390
  z.object({ events: z.array(z.looseObject({ kind: z.string().min(1) })) });
376
391
  z.discriminatedUnion("ok", [z.looseObject({
377
392
  ok: z.literal(true),
@@ -678,6 +693,8 @@ async function executeRun(assignment, ports, runtime) {
678
693
  }
679
694
  }
680
695
  // worker/run.ts
696
+ /** What a question gets when the router can't be asked. */
697
+ const DECLINED$1 = { action: "decline" };
681
698
  /** Why a run ended when a door answered 404: the router no longer runs it on this worker. */
682
699
  const RUN_DROPPED = "the router dropped this run";
683
700
  /** How an assignment past `maxRunsAtOnce` is finished. */
@@ -823,6 +840,27 @@ function createRunHost(options, overrides = {}) {
823
840
  });
824
841
  return response.status === HttpStatus.NotFound && await isRunNotFound(response.clone()) ? checked(response) : response;
825
842
  };
843
+ /**
844
+ * Puts a local server's question to whoever the run answers to, through the router's questions door.
845
+ *
846
+ * @param call - The model's call the server was answering.
847
+ * @param params - The question.
848
+ * @param signal - Aborted when the answer is no longer wanted.
849
+ * @returns The answer, or a decline when the router can't be asked or its answer doesn't read.
850
+ */
851
+ const ask = async (call, params, signal) => {
852
+ try {
853
+ const response = await checked(await post(runId, WorkerDoor.Elicit, {
854
+ call,
855
+ params
856
+ }, AbortSignal.any([signal, runSignal])));
857
+ const answer = response.ok ? ElicitResultSchema.safeParse(await response.json()) : null;
858
+ return answer?.success ? answer.data : DECLINED$1;
859
+ } catch (error) {
860
+ console.warn(`[worker] could not ask run ${runId}'s question: ${errorMessage(error)}`);
861
+ return DECLINED$1;
862
+ }
863
+ };
826
864
  return {
827
865
  modelFetch,
828
866
  callRouterTool: async (server, tool, args, { call, signal }) => {
@@ -840,7 +878,7 @@ function createRunHost(options, overrides = {}) {
840
878
  if (answer.ok === false) throw new Error(answer.error);
841
879
  return answer.text;
842
880
  },
843
- ...local === void 0 ? {} : { callLocalTool: (server, tool, args, { signal }) => local.callTool(server, tool, args, signal) },
881
+ ...local === void 0 ? {} : { callLocalTool: (server, tool, args, { call, signal }) => local.callTool(server, tool, args, signal, (params, asked) => ask(call, params, asked.signal)) },
844
882
  publish: (event) => {
845
883
  events.push(event);
846
884
  return stamp(event, runId, 0, Date.now());
@@ -1097,7 +1135,7 @@ path.resolve(import.meta.dirname, "..", "..");
1097
1135
  * A bundle can't read the repo's package.json the way `version()` does, because it isn't there.
1098
1136
  */
1099
1137
  function workerVersion() {
1100
- return "0.10.1";
1138
+ return "0.11.1";
1101
1139
  }
1102
1140
  // worker/workdir/git.ts
1103
1141
  /** The git program, found on PATH. */
@@ -1553,9 +1591,49 @@ const LOCAL_ENV_ALLOWLIST = Object.freeze([
1553
1591
  ]);
1554
1592
  /** The worker's name, as its local servers see their client. */
1555
1593
  const CLIENT_NAME = "agent-router-worker";
1594
+ /** What the worker's servers are told it can do: answer a question in form mode, through the router. */
1595
+ const CLIENT_CAPABILITIES = { elicitation: { form: {} } };
1596
+ /** The longest delay `setTimeout` keeps; past it, a timer fires at once. */
1597
+ const LONGEST_TIMER_MS = 0x7fffffff;
1598
+ /** What a question gets when no one can answer it. */
1599
+ const DECLINED = { action: "decline" };
1556
1600
  /** The rule every local server's name is checked against: the router's own name rule. */
1557
1601
  const serverName = nameSchema("A local server name");
1558
1602
  /**
1603
+ * Starts a time limit that can stop while a question waits.
1604
+ *
1605
+ * @param limitMs - How long the call may run, its pauses left out.
1606
+ * @param reason - What the call is aborted with when the time is up.
1607
+ * @returns The deadline, running.
1608
+ */
1609
+ function pausableDeadline(limitMs, reason) {
1610
+ const expired = new AbortController();
1611
+ let leftMs = limitMs;
1612
+ let startedAt = Date.now();
1613
+ let timer;
1614
+ let pauses = 0;
1615
+ const run = () => {
1616
+ startedAt = Date.now();
1617
+ timer = setTimeout(() => expired.abort(reason()), leftMs);
1618
+ };
1619
+ run();
1620
+ return {
1621
+ signal: expired.signal,
1622
+ pause: () => {
1623
+ pauses += 1;
1624
+ if (pauses === 1) {
1625
+ clearTimeout(timer);
1626
+ leftMs -= Date.now() - startedAt;
1627
+ }
1628
+ },
1629
+ resume: () => {
1630
+ pauses -= 1;
1631
+ if (pauses === 0 && expired.signal.aborted === false) run();
1632
+ },
1633
+ stop: () => clearTimeout(timer)
1634
+ };
1635
+ }
1636
+ /**
1559
1637
  * Builds the environment a command server starts with: the allowlisted variables of the worker's own, then its config's.
1560
1638
  *
1561
1639
  * @param config - The server's config.
@@ -1636,11 +1714,25 @@ async function startLocalServers(options, overrides = {}) {
1636
1714
  const client = new Client({
1637
1715
  name: CLIENT_NAME,
1638
1716
  version: workerVersion()
1639
- });
1717
+ }, { capabilities: CLIENT_CAPABILITIES });
1640
1718
  const entry = {
1641
1719
  client,
1642
- tools: []
1720
+ tools: [],
1721
+ calls: /* @__PURE__ */ new Set()
1643
1722
  };
1723
+ client.setRequestHandler(ElicitRequestSchema, async (question, extra) => {
1724
+ const [only, ...others] = [...entry.calls];
1725
+ const onElicit = others.length === 0 ? only?.onElicit : void 0;
1726
+ if (only === void 0 || onElicit === void 0) return DECLINED;
1727
+ only.deadline.pause();
1728
+ try {
1729
+ return await onElicit(question.params, { signal: extra.signal });
1730
+ } catch {
1731
+ return DECLINED;
1732
+ } finally {
1733
+ only.deadline.resume();
1734
+ }
1735
+ });
1644
1736
  client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
1645
1737
  try {
1646
1738
  entry.tools = await listTools(client, settings.localStartTimeoutMs);
@@ -1684,9 +1776,16 @@ async function startLocalServers(options, overrides = {}) {
1684
1776
  name,
1685
1777
  tools
1686
1778
  })),
1687
- callTool: async (server, tool, args, signal) => {
1779
+ callTool: async (server, tool, args, signal, onElicit) => {
1688
1780
  const entry = started.get(server);
1689
1781
  if (entry === void 0) throw new Error(`This worker has no local server named "${server}".`);
1782
+ const limitMs = settings.localToolTimeoutMs;
1783
+ const deadline = pausableDeadline(limitMs, () => /* @__PURE__ */ new Error(`"${tool}" on the local server "${server}" took longer than ${limitMs} ms.`));
1784
+ const call = {
1785
+ onElicit,
1786
+ deadline
1787
+ };
1788
+ entry.calls.add(call);
1690
1789
  const result = await entry.client.request({
1691
1790
  method: "tools/call",
1692
1791
  params: {
@@ -1694,8 +1793,11 @@ async function startLocalServers(options, overrides = {}) {
1694
1793
  arguments: args
1695
1794
  }
1696
1795
  }, CallToolResultSchema, {
1697
- signal,
1698
- timeout: settings.localToolTimeoutMs
1796
+ signal: AbortSignal.any([signal, deadline.signal]),
1797
+ timeout: LONGEST_TIMER_MS
1798
+ }).finally(() => {
1799
+ deadline.stop();
1800
+ entry.calls.delete(call);
1699
1801
  });
1700
1802
  if (isToolError(result)) throw new Error(toolResultText(result));
1701
1803
  return toolResultContent(result);
package/lib.js CHANGED
@@ -1 +1 @@
1
- export { r as TOOL_ORIGIN_LOCAL, i as TOOL_ORIGIN_ROUTER, a as WorkerConfigError, n as executeRun, o as readWorkerConfig, t as startWorker } from "./chunks/worker-CnoYOZ1h.js";
1
+ export { r as TOOL_ORIGIN_LOCAL, i as TOOL_ORIGIN_ROUTER, a as WorkerConfigError, n as executeRun, o as readWorkerConfig, t as startWorker } from "./chunks/worker-B2CXQ9MW.js";
package/llms.txt CHANGED
@@ -9,7 +9,7 @@ Agent-facing docs for @cubicecho/agent-router-worker, one task or concept per pa
9
9
  - [Install and run a worker](_agents/docs/01-install.md): `@cubicecho/agent-router-worker` is agent-router's worker: a program that dials a router with a worker key and runs the agent loops of the workspaces placed on it, with its own MCP servers as their tools. This page covers the command, its environment, and placing a workspace on it.
10
10
  - [Common mistakes with the worker](_agents/docs/common-mistakes.md): Each entry is a mistake made running a worker or building on its library, what happens, and the fix.
11
11
  - [Run a worker with your own loop](_agents/docs/custom-loop.md): `startWorker` runs each assignment on agent-core's `runAgentLoop`, or on the one its `runtime` names. This page covers replacing the loop, what a replacement must do, and testing one with `executeRun` and no router.
12
- - [Local servers: the tools a worker gives its runs](_agents/docs/local-servers.md): A worker's runs reach its built-in `workdir` server and each MCP server the `WORKER_CONFIG` file names. This page covers that file, the environment and folder a server starts with, how tools are named, and what `workdir` offers.
12
+ - [Local servers: the tools a worker gives its runs](_agents/docs/local-servers.md): A worker's runs reach its built-in `workdir` server and each MCP server the `WORKER_CONFIG` file names. This page covers that file, the environment and folder a server starts with, how tools are named, questions a server asks, and what `workdir` offers.
13
13
 
14
14
  ## Exports
15
15
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cubicecho/agent-router-worker",
3
- "version": "0.10.1",
3
+ "version": "0.11.1",
4
4
  "description": "agent-router's worker program: runs a workspace's agent loops on another machine.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -91,6 +91,11 @@ export interface WorkerSettings {
91
91
  cancelGraceMs: number;
92
92
  /** Largest JSON body the worker doors accept, as `express.json` reads it: a model call carries the transcript. */
93
93
  bodyLimit: string;
94
+ /**
95
+ * How often a door whose answer may wait on a tool or a person writes a space, so the worker's `fetch` doesn't give
96
+ * up on a quiet answer: Node's waits 300 s for headers and 300 s between chunks.
97
+ */
98
+ doorKeepAliveMs: number;
94
99
  }
95
100
  export declare const WORKER_DEFAULTS: Readonly<WorkerSettings>;
96
101
  /**
@@ -49,7 +49,20 @@ export declare const AGENT_DEPTH_META_KEY = "cubicecho.com/agent-depth";
49
49
  /** The `_meta` key a task's progress notification carries the run's `RunEvent` under. */
50
50
  export declare const RUN_EVENT_META_KEY = "cubicecho.com/run-event";
51
51
  /**
52
- * The `_meta` key a tool call says its caller can answer a server's questions under. `/mcp` is stateless, so it can't
53
- * read that from the caller's `initialize`.
52
+ * The `_meta` key every request names its client's capabilities under, as MCP's 2026-07-28 revision has it. `/mcp` is
53
+ * stateless, so a caller says on each call whether it can answer a server's questions, and in which modes.
54
+ */
55
+ export declare const CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities";
56
+ /**
57
+ * The `_meta` key a tool call said its caller can answer a server's questions under, in form mode, before MCP named
58
+ * {@link CLIENT_CAPABILITIES_META_KEY}.
59
+ *
60
+ * @deprecated Read until ai-router's tools area sends the spec's key; send {@link CLIENT_CAPABILITIES_META_KEY}.
54
61
  */
55
62
  export declare const CAN_ELICIT_META_KEY = "cubicecho.com/can-elicit";
63
+ /** The ways a server may ask a question: a form the client fills in, or a URL it opens. */
64
+ export declare const ElicitMode: {
65
+ readonly Form: 'form';
66
+ readonly Url: 'url';
67
+ };
68
+ export type ElicitMode = (typeof ElicitMode)[keyof typeof ElicitMode];
@@ -1,4 +1,4 @@
1
- import type { AgentLoopOptions, AgentLoopResult, RunEvent, RunEventInput } from '@cubicecho/agent-core';
1
+ import type { AgentLoopOptions, AgentLoopResult, ElicitAnswer, ElicitParams, RunEvent, RunEventInput } from '@cubicecho/agent-core';
2
2
  import type { ResolvedAgent } from '@cubicecho/agent-core/spec';
3
3
  /** A tool the router calls for the run: one of a server's tools, through the run's workspace instance. */
4
4
  export declare const TOOL_ORIGIN_ROUTER: 'router';
@@ -88,6 +88,15 @@ export interface RunPorts {
88
88
  * @returns What the tool said, as the model reads it.
89
89
  */
90
90
  callLocalTool?(server: string, tool: string, args: Record<string, unknown>, options: ToolCallOptions): Promise<string>;
91
+ /**
92
+ * Asks whoever the run answers to a question one of the worker's own servers put during a call: the app or client at
93
+ * the top, through every agent between. Absent, the question is declined.
94
+ *
95
+ * @param params - The question, as MCP's `elicitation/create` sends it.
96
+ * @param options - The call it was asked during, and its signal.
97
+ * @returns The answer, or a decline when no one can answer.
98
+ */
99
+ elicit?(params: ElicitParams, options: ToolCallOptions): Promise<ElicitAnswer>;
91
100
  /**
92
101
  * Tells the router one of the loop's events.
93
102
  *
@@ -22,6 +22,8 @@ export declare const WorkerDoor: {
22
22
  readonly Model: '/model';
23
23
  /** `POST` a {@link RouterToolCall}, answered with a {@link RouterToolAnswer}. */
24
24
  readonly Tools: '/tools/call';
25
+ /** `POST` a {@link WorkerQuestion}, answered with an MCP `ElicitResult`. */
26
+ readonly Elicit: '/elicit';
25
27
  /** `POST` an {@link EventBatch}. */
26
28
  readonly Events: '/events';
27
29
  /** `POST` the stretch's {@link RunOutcome}. */
@@ -121,6 +123,18 @@ export declare const routerToolCallSchema: z.ZodObject<{
121
123
  }, z.core.$strip>;
122
124
  }, z.core.$strip>;
123
125
  export type RouterToolCall = z.infer<typeof routerToolCallSchema>;
126
+ /** A question one of the worker's own servers put during a call of the run's, for whoever the run answers to. */
127
+ export declare const workerQuestionSchema: z.ZodObject<{
128
+ call: z.ZodObject<{
129
+ id: z.ZodString;
130
+ name: z.ZodString;
131
+ }, z.core.$strip>;
132
+ params: z.ZodObject<{
133
+ message: z.ZodString;
134
+ mode: z.ZodOptional<z.ZodString>;
135
+ }, z.core.$loose>;
136
+ }, z.core.$strip>;
137
+ export type WorkerQuestion = z.infer<typeof workerQuestionSchema>;
124
138
  /** What a router tool said: its text, or the failure the model is told. */
125
139
  export type RouterToolAnswer = {
126
140
  ok: true;
@@ -1,9 +1,20 @@
1
+ import { type ElicitRequest, type ElicitResult } from '@modelcontextprotocol/sdk/types.js';
1
2
  import type { LocalServer } from '../server/runner/protocol.ts';
2
3
  import type { CommandServerConfig, LocalServerConfig } from './config.ts';
3
4
  import { type WorkdirSettings, type WorkerProgramSettings } from './defaults.ts';
4
5
  import type { GitRunner } from './workdir/git.ts';
5
6
  /** The variables a command server gets from the worker's own environment. Everything else comes from its config. */
6
7
  export declare const LOCAL_ENV_ALLOWLIST: readonly string[];
8
+ /**
9
+ * Answers a question a local server asks during a call.
10
+ *
11
+ * @param params - The question, as MCP's `elicitation/create` sends it.
12
+ * @param options - `signal` aborts when the answer is no longer wanted.
13
+ * @returns The answer.
14
+ */
15
+ export type LocalElicit = (params: ElicitRequest['params'], options: {
16
+ signal: AbortSignal;
17
+ }) => Promise<ElicitResult>;
7
18
  /** The worker's own servers, started and listed. */
8
19
  export interface LocalServers {
9
20
  /**
@@ -19,10 +30,12 @@ export interface LocalServers {
19
30
  * @param tool - The tool's own name.
20
31
  * @param args - What the model called it with.
21
32
  * @param signal - Aborted when the answer is no longer wanted.
33
+ * @param [onElicit] - Answers the server's questions during the call. Absent, each is declined. The call's time
34
+ * limit stops while one waits.
22
35
  * @returns What the tool said, as the model reads it.
23
- * @throws When the server is unknown or the tool reports a failure: the model is told it.
36
+ * @throws When the server is unknown, the call takes too long, or the tool reports a failure: the model is told it.
24
37
  */
25
- callTool(server: string, tool: string, args: Record<string, unknown>, signal: AbortSignal): Promise<string>;
38
+ callTool(server: string, tool: string, args: Record<string, unknown>, signal: AbortSignal, onElicit?: LocalElicit): Promise<string>;
26
39
  /**
27
40
  * Stops every server.
28
41
  *
package/worker.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { o as readWorkerConfig, s as errorMessage, t as startWorker } from "./chunks/worker-CnoYOZ1h.js";
2
+ import { o as readWorkerConfig, s as errorMessage, t as startWorker } from "./chunks/worker-B2CXQ9MW.js";
3
3
  // worker/index.ts
4
4
  /** Exits with this when the worker can't start, or is stopped twice. */
5
5
  const EXIT_FAILED = 1;