@cubicecho/agent-router-worker 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -15
- package/_agents/docs/01-install.md +74 -0
- package/_agents/docs/common-mistakes.md +139 -0
- package/_agents/docs/custom-loop.md +123 -0
- package/_agents/docs/examples/custom-loop.ts +20 -0
- package/_agents/docs/examples/test-loop.ts +53 -0
- package/_agents/docs/local-servers.md +72 -0
- package/chunks/{worker-CIZuf0jz.js → worker-knPnskLw.js} +1 -1
- package/lib.js +1 -1
- package/llms.txt +21 -0
- package/package.json +6 -1
- package/worker.js +1 -1
package/README.md
CHANGED
|
@@ -1,29 +1,55 @@
|
|
|
1
|
+
<!-- AI agents: read llms.txt and _agents/docs/ for the full, version-matched API. -->
|
|
2
|
+
|
|
1
3
|
# @cubicecho/agent-router-worker
|
|
2
4
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
5
|
+
The worker program of [agent-router](https://github.com/cubicecho/agent-router). It dials a router with a worker key and
|
|
6
|
+
runs the agent loops of the workspaces placed on it, with its own MCP servers as their tools.
|
|
7
|
+
|
|
8
|
+
An agent's tools are often on another machine than its router. Run a worker where the files, repos and programs are,
|
|
9
|
+
and the agents of a workspace use them there. It opens no port, and it keeps dialling when the router
|
|
10
|
+
goes away. It is a command, and a library for a program that runs a worker with its own agent loop.
|
|
6
11
|
|
|
7
|
-
##
|
|
12
|
+
## Install
|
|
8
13
|
|
|
9
14
|
```bash
|
|
10
15
|
npm install -g @cubicecho/agent-router-worker
|
|
11
|
-
AGENT_ROUTER_URL=http://agent-router.lan:3100 AGENT_ROUTER_WORKER_KEY=aiw_... agent-router-worker
|
|
12
16
|
```
|
|
13
17
|
|
|
14
|
-
`
|
|
15
|
-
`WORKER_ROOT` the folder its work directories go in.
|
|
18
|
+
Node 22 or later. `@cubicecho/agent-core` is a peer dependency, which npm installs beside it.
|
|
16
19
|
|
|
17
|
-
##
|
|
20
|
+
## Quick start
|
|
18
21
|
|
|
19
|
-
|
|
22
|
+
Make a worker on the router's `/graphql`, and keep its `secret`:
|
|
20
23
|
|
|
21
|
-
```
|
|
22
|
-
|
|
24
|
+
```graphql
|
|
25
|
+
mutation { createWorker(name: "box") { secret worker { id } } }
|
|
23
26
|
```
|
|
24
27
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
+
Then start it, on the machine with the tools:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
cat > worker.json <<'JSON'
|
|
32
|
+
{ "servers": { "files": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] } } }
|
|
33
|
+
JSON
|
|
34
|
+
|
|
35
|
+
AGENT_ROUTER_URL=http://agent-router.lan:3100 \
|
|
36
|
+
AGENT_ROUTER_WORKER_KEY=aiw_... \
|
|
37
|
+
WORKER_CONFIG=./worker.json \
|
|
38
|
+
agent-router-worker
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
It prints the servers that started, and `connected to` once the router has answered. Place a workspace on it with
|
|
42
|
+
`setWorkspaceWorker`, and that workspace's runs go there.
|
|
43
|
+
|
|
44
|
+
## Documentation
|
|
45
|
+
|
|
46
|
+
- [Install and run](https://github.com/cubicecho/agent-router/blob/main/worker/_agents/docs/01-install.md): the command, its environment, the Docker image
|
|
47
|
+
- [Local servers](https://github.com/cubicecho/agent-router/blob/main/worker/_agents/docs/local-servers.md): `WORKER_CONFIG`, and the built-in `workdir` server
|
|
48
|
+
- [A custom loop](https://github.com/cubicecho/agent-router/blob/main/worker/_agents/docs/custom-loop.md): the library
|
|
49
|
+
- [Common mistakes](https://github.com/cubicecho/agent-router/blob/main/worker/_agents/docs/common-mistakes.md)
|
|
50
|
+
- [`llms.txt`](https://cdn.jsdelivr.net/npm/@cubicecho/agent-router-worker/llms.txt), the index of these for agents
|
|
51
|
+
- [Changelog](https://github.com/cubicecho/agent-router/blob/main/CHANGELOG.md)
|
|
52
|
+
|
|
53
|
+
## License
|
|
28
54
|
|
|
29
|
-
|
|
55
|
+
[MIT](https://github.com/cubicecho/agent-router/blob/main/LICENSE)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Install and run a worker
|
|
2
|
+
|
|
3
|
+
`@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.
|
|
4
|
+
|
|
5
|
+
## The command
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g @cubicecho/agent-router-worker
|
|
9
|
+
AGENT_ROUTER_URL=http://agent-router.lan:3100 \
|
|
10
|
+
AGENT_ROUTER_WORKER_KEY=aiw_... \
|
|
11
|
+
agent-router-worker
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Node 22 or later. npm installs the peer dependency `@cubicecho/agent-core` beside it. The worker only makes outbound HTTP requests to the router, so it needs no open port.
|
|
15
|
+
|
|
16
|
+
Once connected it prints `[worker] connected to <url> as <host>`. SIGTERM or SIGINT stops it: its runs finish as failed with `the worker is stopping`, and its servers are closed. A second signal exits at once.
|
|
17
|
+
|
|
18
|
+
## Environment
|
|
19
|
+
|
|
20
|
+
| Variable | Default | What it is |
|
|
21
|
+
| --- | --- | --- |
|
|
22
|
+
| `AGENT_ROUTER_URL` | required | The router's address. Trailing slashes are dropped. |
|
|
23
|
+
| `AGENT_ROUTER_WORKER_KEY` | required | The worker key, which starts `aiw_`. |
|
|
24
|
+
| `WORKER_CONFIG` | none | A JSON file of the worker's own servers: [local servers](local-servers.md). |
|
|
25
|
+
| `WORKER_ROOT` | `~/agent-router-work` | The folder checkouts go in. Made when missing. |
|
|
26
|
+
| `WORKER_HOST` | the machine's host name | The name the worker gives the router for its machine. |
|
|
27
|
+
|
|
28
|
+
`WORKER_CONFIG` and `WORKER_ROOT` take `~`, `~/...`, an absolute path, or one relative to the current directory. A wrong variable or servers file prints `[worker] <what to fix>` and exits 1.
|
|
29
|
+
|
|
30
|
+
## Make a worker and place a workspace on it
|
|
31
|
+
|
|
32
|
+
The router's admin does this once, on its `/graphql`:
|
|
33
|
+
|
|
34
|
+
```graphql
|
|
35
|
+
mutation {
|
|
36
|
+
createWorker(name: "box") {
|
|
37
|
+
secret # the aiw_ key, shown only here
|
|
38
|
+
worker { id }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```graphql
|
|
44
|
+
mutation ($workspace: UUID!, $worker: UUID) {
|
|
45
|
+
setWorkspaceWorker(workspaceId: $workspace, workerId: $worker) { id }
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Every run of that workspace goes to the worker from then on. While the worker is offline, the router refuses them with 503 `worker_offline`. A null `workerId` moves the workspace back into the router.
|
|
50
|
+
|
|
51
|
+
## The Docker image
|
|
52
|
+
|
|
53
|
+
`ghcr.io/cubicecho/agent-router-worker` (amd64 and arm64) holds the same program with `git` and `ssh`. `WORKER_ROOT` is `/work`, a volume.
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
docker run -d --name agent-router-worker \
|
|
57
|
+
-e AGENT_ROUTER_URL=http://agent-router.lan:3100 \
|
|
58
|
+
-e AGENT_ROUTER_WORKER_KEY=aiw_... \
|
|
59
|
+
-v agent-router-work:/work \
|
|
60
|
+
ghcr.io/cubicecho/agent-router-worker
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## As a library
|
|
64
|
+
|
|
65
|
+
To start a worker from a program, with your own agent loop, see [a custom loop](custom-loop.md). The declarations in `types/worker/lib.d.ts` document every export.
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { readWorkerConfig, startWorker } from '@cubicecho/agent-router-worker';
|
|
69
|
+
|
|
70
|
+
const worker = await startWorker(readWorkerConfig(process.env));
|
|
71
|
+
console.log(worker.local.listing().map(({ name }) => name));
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`startWorker` resolves once the local servers have started. It dials the router in the background and keeps dialling.
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# Common mistakes with the worker
|
|
2
|
+
|
|
3
|
+
Each entry is a mistake made running a worker or building on its library, what happens, and the fix.
|
|
4
|
+
|
|
5
|
+
- [Setting a server's token in the worker's environment](#setting-a-servers-token-in-the-workers-environment)
|
|
6
|
+
- [Trusting the start to mean every server started](#trusting-the-start-to-mean-every-server-started)
|
|
7
|
+
- [Forgetting WORKER_CONFIG](#forgetting-worker_config)
|
|
8
|
+
- [Writing cwd relative to the shell](#writing-cwd-relative-to-the-shell)
|
|
9
|
+
- [Giving the worker a workspace key](#giving-the-worker-a-workspace-key)
|
|
10
|
+
- [Reading a process that stays up as connected](#reading-a-process-that-stays-up-as-connected)
|
|
11
|
+
- [Running two workers on one key](#running-two-workers-on-one-key)
|
|
12
|
+
- [Expecting runs to queue](#expecting-runs-to-queue)
|
|
13
|
+
- [Expecting open_repo to update a checkout](#expecting-open_repo-to-update-a-checkout)
|
|
14
|
+
- [Calling the model without config.fetch](#calling-the-model-without-configfetch)
|
|
15
|
+
- [Awaiting executeRun for a throw](#awaiting-executerun-for-a-throw)
|
|
16
|
+
- [Reading the config to check it](#reading-the-config-to-check-it)
|
|
17
|
+
- [Bundling a second agent-core](#bundling-a-second-agent-core)
|
|
18
|
+
|
|
19
|
+
## Setting a server's token in the worker's environment
|
|
20
|
+
|
|
21
|
+
A command server inherits only `PATH`, `HOME`, `LANG`, `TERM` and `USER`. A token exported before `agent-router-worker` never reaches it, so it starts and then fails its calls. Put it in the server's `env`:
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
{ "servers": { "github": { "command": "github-mcp-server", "args": ["stdio"], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_..." } } } }
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Trusting the start to mean every server started
|
|
28
|
+
|
|
29
|
+
A server that fails to start, is named `workdir`, or has a name like `My Tools` is left out with one `[worker] leaving out the local server` line on stderr. The worker connects, and runs just lack its tools. Check what started:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { readWorkerConfig, startWorker } from '@cubicecho/agent-router-worker';
|
|
33
|
+
|
|
34
|
+
const config = readWorkerConfig(process.env);
|
|
35
|
+
const worker = await startWorker(config);
|
|
36
|
+
const started = new Set(worker.local.listing().map(({ name }) => name));
|
|
37
|
+
const missing = Object.keys(config.servers).filter((name) => started.has(name) === false);
|
|
38
|
+
if (missing.length > 0) {
|
|
39
|
+
await worker.stop();
|
|
40
|
+
throw new Error(`These servers did not start: ${missing.join(', ')}`);
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Forgetting WORKER_CONFIG
|
|
45
|
+
|
|
46
|
+
With no `WORKER_CONFIG`, the worker starts with `workdir` alone and raises no error. A `worker.json` in the current directory isn't found by itself:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
WORKER_CONFIG=./worker.json agent-router-worker
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Writing cwd relative to the shell
|
|
53
|
+
|
|
54
|
+
A server's `cwd` is relative to the folder that holds the config file, not to where the worker was started. `WORKER_CONFIG` itself is relative to where it was started. Write an absolute path, or one from the file:
|
|
55
|
+
|
|
56
|
+
```json
|
|
57
|
+
{ "servers": { "notes": { "command": "npx", "args": ["-y", "some-mcp"], "cwd": "../notes" } } }
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Giving the worker a workspace key
|
|
61
|
+
|
|
62
|
+
A workspace key (`air_`) is refused at boot with `must be a worker key, which starts "aiw_"`. Make a worker and use its `secret`:
|
|
63
|
+
|
|
64
|
+
```graphql
|
|
65
|
+
mutation { createWorker(name: "box") { secret worker { id } } }
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Reading a process that stays up as connected
|
|
69
|
+
|
|
70
|
+
A router that is down and a wrong or rotated key look the same from outside: the process stays up and dials again, waiting up to 30 seconds. The log says `the router answered 401` for a bad key. Wait for the `[worker] connected to` line, or ask the router:
|
|
71
|
+
|
|
72
|
+
```graphql
|
|
73
|
+
{ workers { id name online } }
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Running two workers on one key
|
|
77
|
+
|
|
78
|
+
The router keeps one channel per worker. A second process on the same key takes it, the first dials back and takes it again, and they go on like that about once a second. Make one worker, with its own key, per process.
|
|
79
|
+
|
|
80
|
+
## Expecting runs to queue
|
|
81
|
+
|
|
82
|
+
A worker runs 8 at once. The router refuses one past that with 503 `worker_busy`, and nothing is recorded or queued, so the app tries again. Changing `maxRunsAtOnce` in the worker's `settings` doesn't change the router's 8: a lower one makes the worker fail what the router sends past it, with `this worker is busy`. Use a second worker for more.
|
|
83
|
+
|
|
84
|
+
## Expecting open_repo to update a checkout
|
|
85
|
+
|
|
86
|
+
`workdir__open_repo` clones once. After that it returns the checkout as the last run left it, `cloned: false`, branch and changes included. Give the agent a tool that runs git, or remove the checkout under `WORKER_ROOT`, to start fresh.
|
|
87
|
+
|
|
88
|
+
## Calling the model without config.fetch
|
|
89
|
+
|
|
90
|
+
An assignment's `config.baseUrl` is `http://models.ai-router.invalid/v1`, which no server answers. A custom loop that builds its own client from `baseUrl` alone fails on every call. Pass the run's `fetch`:
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import OpenAI from 'openai';
|
|
94
|
+
import type { Runtime } from '@cubicecho/agent-core';
|
|
95
|
+
|
|
96
|
+
export const firstTurn = ({ config, messages }: Parameters<Runtime['runAgentLoop']>[0]) => {
|
|
97
|
+
const client = new OpenAI({ baseURL: config.baseUrl, apiKey: config.apiKey || 'none', fetch: config.fetch });
|
|
98
|
+
return client.chat.completions.create({ model: 'model' in config ? config.model : '', messages });
|
|
99
|
+
};
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Awaiting executeRun for a throw
|
|
103
|
+
|
|
104
|
+
`executeRun` never rejects. A failed loop resolves with `{ ok: false, error }`, so a test that only awaits it passes. Check `ok`:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { executeRun, type RunAssignment, type RunPorts } from '@cubicecho/agent-router-worker';
|
|
108
|
+
import { runAgentLoop } from '@cubicecho/agent-core';
|
|
109
|
+
|
|
110
|
+
export async function runOrThrow(assignment: RunAssignment, ports: RunPorts): Promise<string> {
|
|
111
|
+
const outcome = await executeRun(assignment, ports, { runAgentLoop });
|
|
112
|
+
if (outcome.ok === false) {
|
|
113
|
+
throw new Error(outcome.error);
|
|
114
|
+
}
|
|
115
|
+
return String(outcome.messages.at(-1)?.content);
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## Reading the config to check it
|
|
120
|
+
|
|
121
|
+
`readWorkerConfig` creates `WORKER_ROOT` as it reads, `~/agent-router-work` by default. In a test, point it at a temporary folder:
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import { mkdtempSync } from 'node:fs';
|
|
125
|
+
import { tmpdir } from 'node:os';
|
|
126
|
+
import { join } from 'node:path';
|
|
127
|
+
import { readWorkerConfig } from '@cubicecho/agent-router-worker';
|
|
128
|
+
|
|
129
|
+
const config = readWorkerConfig({
|
|
130
|
+
AGENT_ROUTER_URL: 'http://router.lan:3100',
|
|
131
|
+
AGENT_ROUTER_WORKER_KEY: 'aiw_test',
|
|
132
|
+
WORKER_ROOT: mkdtempSync(join(tmpdir(), 'worker-')),
|
|
133
|
+
});
|
|
134
|
+
console.log(config.root);
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Bundling a second agent-core
|
|
138
|
+
|
|
139
|
+
The loop and its types are agent-core's, and it is a peer dependency. A program that bundles or pins another copy runs a loop whose types and errors may not match the ones the worker reads. Install it once, in the range `npm view @cubicecho/agent-router-worker peerDependencies` prints, and check with `npm ls @cubicecho/agent-core`.
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# Run a worker with your own loop
|
|
2
|
+
|
|
3
|
+
`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.
|
|
4
|
+
|
|
5
|
+
- [Replace the loop](#replace-the-loop)
|
|
6
|
+
- [What a loop must do](#what-a-loop-must-do)
|
|
7
|
+
- [Test a loop without a router](#test-a-loop-without-a-router)
|
|
8
|
+
- [Other things startWorker takes](#other-things-startworker-takes)
|
|
9
|
+
|
|
10
|
+
## Replace the loop
|
|
11
|
+
|
|
12
|
+
<!-- example: examples/custom-loop.ts -->
|
|
13
|
+
```ts
|
|
14
|
+
import { type Runtime, runAgentLoop } from '@cubicecho/agent-core';
|
|
15
|
+
import { readWorkerConfig, startWorker } from '@cubicecho/agent-router-worker';
|
|
16
|
+
|
|
17
|
+
// agent-core's loop, with a line logged for each turn.
|
|
18
|
+
const runtime: Pick<Runtime, 'runAgentLoop'> = {
|
|
19
|
+
runAgentLoop: (options) =>
|
|
20
|
+
runAgentLoop({
|
|
21
|
+
...options,
|
|
22
|
+
onTurn: (reply, turn) => console.log(`run ${options.session}, turn ${turn}: ${reply.finishReason}`),
|
|
23
|
+
}),
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const worker = await startWorker(readWorkerConfig(process.env), { runtime });
|
|
27
|
+
|
|
28
|
+
const stop = async (): Promise<void> => {
|
|
29
|
+
await worker.stop();
|
|
30
|
+
process.exit(0);
|
|
31
|
+
};
|
|
32
|
+
process.once('SIGTERM', stop);
|
|
33
|
+
process.once('SIGINT', stop);
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Install `@cubicecho/agent-core` in your program, in the range this package's `peerDependencies` name, so both use one copy.
|
|
37
|
+
|
|
38
|
+
## What a loop must do
|
|
39
|
+
|
|
40
|
+
The options are agent-core's `AgentLoopOptions`, and the result its `AgentLoopResult`. A loop that wraps `runAgentLoop` and passes `...options` on does all of this already. One written from scratch must:
|
|
41
|
+
|
|
42
|
+
- **Call the model through `options.config.fetch`.** `config.baseUrl` is an address nothing answers, and only that `fetch` reaches the router's models. It refuses every other address. An agent with an endpoint of its own has its own `baseUrl` and no `fetch`.
|
|
43
|
+
- **Run tools through `options.dispatch`,** which knows which tools are the worker's and which the router's. When its answer carries `end`, stop the loop: the call is the app's, handed back.
|
|
44
|
+
- **Report through `options.onEvent`,** agent-core's `RunEventInput`s. They are the run's record on the router.
|
|
45
|
+
- **Stop on `options.signal`.** It fires on a cancel and when the worker stops. The run is then finished as failed with the reason, whatever the loop returns.
|
|
46
|
+
- **Return `messages`, `usage`, `loaded` and `turn`.** A throw fails the run with its message.
|
|
47
|
+
|
|
48
|
+
## Test a loop without a router
|
|
49
|
+
|
|
50
|
+
`executeRun` runs one assignment on a loop, as the worker would, against ports you supply. It never rejects: check `outcome.ok`.
|
|
51
|
+
|
|
52
|
+
<!-- example: examples/test-loop.ts -->
|
|
53
|
+
```ts
|
|
54
|
+
import { runAgentLoop, stamp } from '@cubicecho/agent-core';
|
|
55
|
+
import { AGENT_SPEC, resolveAgentSpec } from '@cubicecho/agent-core/spec';
|
|
56
|
+
import { executeRun, type RunAssignment, type RunPorts, TOOL_ORIGIN_LOCAL } from '@cubicecho/agent-router-worker';
|
|
57
|
+
|
|
58
|
+
// The address an assignment's model calls carry. Nothing answers it: `modelFetch` does.
|
|
59
|
+
const MODELS_BASE_URL = 'http://models.ai-router.invalid/v1';
|
|
60
|
+
|
|
61
|
+
const assignment: RunAssignment = {
|
|
62
|
+
runId: 'run-1',
|
|
63
|
+
config: resolveAgentSpec([{ spec: AGENT_SPEC, endpoint: { baseUrl: MODELS_BASE_URL }, model: { model: 'fake/m1' } }]),
|
|
64
|
+
prompt: [],
|
|
65
|
+
messages: [{ role: 'user', content: 'What is in the work root?' }],
|
|
66
|
+
loaded: [],
|
|
67
|
+
tools: [{ type: 'function', function: { name: 'workdir__list_dir', parameters: { type: 'object' } } }],
|
|
68
|
+
catalog: [
|
|
69
|
+
{ id: 'workdir', label: 'workdir', tools: [{ name: 'workdir__list_dir', description: 'Lists a folder.' }] },
|
|
70
|
+
],
|
|
71
|
+
targets: { workdir__list_dir: { origin: TOOL_ORIGIN_LOCAL, server: 'workdir', tool: 'list_dir' } },
|
|
72
|
+
appTools: [],
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** One streamed chat completion that says `text`. */
|
|
76
|
+
const streamed = (text: string): Response => {
|
|
77
|
+
const chunks = [
|
|
78
|
+
{ choices: [{ index: 0, delta: { role: 'assistant', content: text }, finish_reason: null }] },
|
|
79
|
+
{ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
|
|
80
|
+
];
|
|
81
|
+
const lines = chunks.map(
|
|
82
|
+
(chunk) => `data: ${JSON.stringify({ id: 'c', object: 'chat.completion.chunk', ...chunk })}`,
|
|
83
|
+
);
|
|
84
|
+
return new Response(`${lines.join('\n\n')}\n\ndata: [DONE]\n\n`, {
|
|
85
|
+
headers: { 'content-type': 'text/event-stream' },
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
let seq = 0;
|
|
90
|
+
const ports: RunPorts = {
|
|
91
|
+
modelFetch: async (url) =>
|
|
92
|
+
String(url).endsWith('/chat/completions') ? streamed('Nothing yet.') : new Response('not found', { status: 404 }),
|
|
93
|
+
callRouterTool: async (server, tool) => `${server} has no ${tool} here`,
|
|
94
|
+
callLocalTool: async () => '{"entries":[]}',
|
|
95
|
+
publish: (event) => {
|
|
96
|
+
seq += 1;
|
|
97
|
+
return stamp(event, assignment.runId, seq, Date.now());
|
|
98
|
+
},
|
|
99
|
+
signal: new AbortController().signal,
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const outcome = await executeRun(assignment, ports, { runAgentLoop });
|
|
103
|
+
if (outcome.ok === false) {
|
|
104
|
+
throw new Error(outcome.error);
|
|
105
|
+
}
|
|
106
|
+
console.log(outcome.finishReason, outcome.messages.at(-1)?.content);
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
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.
|
|
110
|
+
|
|
111
|
+
## Other things startWorker takes
|
|
112
|
+
|
|
113
|
+
`deps` also takes `fetch` for the requests to the router, `baseEnv` for what command servers inherit, `git` for `workdir`, and `settings` and `workdir` to change timeouts and limits. The declarations document each field.
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
import { readWorkerConfig, startWorker } from '@cubicecho/agent-router-worker';
|
|
117
|
+
|
|
118
|
+
const worker = await startWorker(readWorkerConfig(process.env), {
|
|
119
|
+
settings: { reconnectMaxMs: 10_000, stopDeadlineMs: 4_000 },
|
|
120
|
+
workdir: { cloneTimeoutMs: 120_000 },
|
|
121
|
+
});
|
|
122
|
+
console.log(worker.runs.held(), worker.channel.isOpen());
|
|
123
|
+
```
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Runtime, runAgentLoop } from '@cubicecho/agent-core';
|
|
2
|
+
import { readWorkerConfig, startWorker } from '@cubicecho/agent-router-worker';
|
|
3
|
+
|
|
4
|
+
// agent-core's loop, with a line logged for each turn.
|
|
5
|
+
const runtime: Pick<Runtime, 'runAgentLoop'> = {
|
|
6
|
+
runAgentLoop: (options) =>
|
|
7
|
+
runAgentLoop({
|
|
8
|
+
...options,
|
|
9
|
+
onTurn: (reply, turn) => console.log(`run ${options.session}, turn ${turn}: ${reply.finishReason}`),
|
|
10
|
+
}),
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const worker = await startWorker(readWorkerConfig(process.env), { runtime });
|
|
14
|
+
|
|
15
|
+
const stop = async (): Promise<void> => {
|
|
16
|
+
await worker.stop();
|
|
17
|
+
process.exit(0);
|
|
18
|
+
};
|
|
19
|
+
process.once('SIGTERM', stop);
|
|
20
|
+
process.once('SIGINT', stop);
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { runAgentLoop, stamp } from '@cubicecho/agent-core';
|
|
2
|
+
import { AGENT_SPEC, resolveAgentSpec } from '@cubicecho/agent-core/spec';
|
|
3
|
+
import { executeRun, type RunAssignment, type RunPorts, TOOL_ORIGIN_LOCAL } from '@cubicecho/agent-router-worker';
|
|
4
|
+
|
|
5
|
+
// The address an assignment's model calls carry. Nothing answers it: `modelFetch` does.
|
|
6
|
+
const MODELS_BASE_URL = 'http://models.ai-router.invalid/v1';
|
|
7
|
+
|
|
8
|
+
const assignment: RunAssignment = {
|
|
9
|
+
runId: 'run-1',
|
|
10
|
+
config: resolveAgentSpec([{ spec: AGENT_SPEC, endpoint: { baseUrl: MODELS_BASE_URL }, model: { model: 'fake/m1' } }]),
|
|
11
|
+
prompt: [],
|
|
12
|
+
messages: [{ role: 'user', content: 'What is in the work root?' }],
|
|
13
|
+
loaded: [],
|
|
14
|
+
tools: [{ type: 'function', function: { name: 'workdir__list_dir', parameters: { type: 'object' } } }],
|
|
15
|
+
catalog: [
|
|
16
|
+
{ id: 'workdir', label: 'workdir', tools: [{ name: 'workdir__list_dir', description: 'Lists a folder.' }] },
|
|
17
|
+
],
|
|
18
|
+
targets: { workdir__list_dir: { origin: TOOL_ORIGIN_LOCAL, server: 'workdir', tool: 'list_dir' } },
|
|
19
|
+
appTools: [],
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** One streamed chat completion that says `text`. */
|
|
23
|
+
const streamed = (text: string): Response => {
|
|
24
|
+
const chunks = [
|
|
25
|
+
{ choices: [{ index: 0, delta: { role: 'assistant', content: text }, finish_reason: null }] },
|
|
26
|
+
{ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
|
|
27
|
+
];
|
|
28
|
+
const lines = chunks.map(
|
|
29
|
+
(chunk) => `data: ${JSON.stringify({ id: 'c', object: 'chat.completion.chunk', ...chunk })}`,
|
|
30
|
+
);
|
|
31
|
+
return new Response(`${lines.join('\n\n')}\n\ndata: [DONE]\n\n`, {
|
|
32
|
+
headers: { 'content-type': 'text/event-stream' },
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
let seq = 0;
|
|
37
|
+
const ports: RunPorts = {
|
|
38
|
+
modelFetch: async (url) =>
|
|
39
|
+
String(url).endsWith('/chat/completions') ? streamed('Nothing yet.') : new Response('not found', { status: 404 }),
|
|
40
|
+
callRouterTool: async (server, tool) => `${server} has no ${tool} here`,
|
|
41
|
+
callLocalTool: async () => '{"entries":[]}',
|
|
42
|
+
publish: (event) => {
|
|
43
|
+
seq += 1;
|
|
44
|
+
return stamp(event, assignment.runId, seq, Date.now());
|
|
45
|
+
},
|
|
46
|
+
signal: new AbortController().signal,
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const outcome = await executeRun(assignment, ports, { runAgentLoop });
|
|
50
|
+
if (outcome.ok === false) {
|
|
51
|
+
throw new Error(outcome.error);
|
|
52
|
+
}
|
|
53
|
+
console.log(outcome.finishReason, outcome.messages.at(-1)?.content);
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Local servers: the tools a worker gives its runs
|
|
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.
|
|
4
|
+
|
|
5
|
+
## The WORKER_CONFIG file
|
|
6
|
+
|
|
7
|
+
```json
|
|
8
|
+
{
|
|
9
|
+
"servers": {
|
|
10
|
+
"files": {
|
|
11
|
+
"command": "npx",
|
|
12
|
+
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/srv/notes"],
|
|
13
|
+
"env": { "LOG_LEVEL": "warn" },
|
|
14
|
+
"cwd": "~/notes"
|
|
15
|
+
},
|
|
16
|
+
"search": {
|
|
17
|
+
"url": "http://127.0.0.1:9000/mcp",
|
|
18
|
+
"headers": { "authorization": "Bearer secret" }
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
- A server has either `command`, with optional `args`, `env` and `cwd`, or `url`, with optional `headers`. Any other key refuses the file.
|
|
25
|
+
- A `command` server is started over stdio, as the worker's user, with no shell. A `url` server is reached over streamable HTTP.
|
|
26
|
+
- A server's name holds lowercase letters, digits, `.`, `-` and `_`, starts with a letter or digit, and is at most 64 characters. `workdir` is taken.
|
|
27
|
+
- Servers start once, with the worker. Restart the worker after editing the file.
|
|
28
|
+
|
|
29
|
+
## The environment a command server gets
|
|
30
|
+
|
|
31
|
+
Only `PATH`, `HOME`, `LANG`, `TERM` and `USER` come from the worker's environment. Everything else comes from the server's own `env`, so put its tokens there:
|
|
32
|
+
|
|
33
|
+
```json
|
|
34
|
+
{
|
|
35
|
+
"servers": {
|
|
36
|
+
"github": {
|
|
37
|
+
"command": "github-mcp-server",
|
|
38
|
+
"args": ["stdio"],
|
|
39
|
+
"env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_..." }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## The folder it starts in
|
|
46
|
+
|
|
47
|
+
A relative `cwd` is relative to the folder that holds the config file, and `~` is the worker user's home. With no `cwd` the server starts in the worker's own current directory. `~` is read in `cwd` only, never in `command` or `args`.
|
|
48
|
+
|
|
49
|
+
## When a server doesn't start
|
|
50
|
+
|
|
51
|
+
A server that takes over 30 seconds to start, or to list its tools, is left out with a `[worker] leaving out the local server "<name>"` line, and the worker goes on without it. The same happens to a name that breaks the rule. The router shows what is there:
|
|
52
|
+
|
|
53
|
+
```graphql
|
|
54
|
+
{ workers { id name online localServers } }
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
When a server sends `notifications/tools/list_changed`, the worker lists its tools again and tells the router. Runs started after that see the new list.
|
|
58
|
+
|
|
59
|
+
## Tool names
|
|
60
|
+
|
|
61
|
+
The model sees `<server>__<tool>`, such as `files__read_file`. A character a function name may not hold becomes `_`, and a name past 64 characters is cut and ends in a hash. A call may take 15 minutes.
|
|
62
|
+
|
|
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
|
+
|
|
65
|
+
## The built-in workdir server
|
|
66
|
+
|
|
67
|
+
| Tool | Takes | Answers |
|
|
68
|
+
| --- | --- | --- |
|
|
69
|
+
| `workdir__open_repo` | `repo`: `owner/name` on GitHub, `https://host/owner/name.git` or `git@host:owner/name.git` | `{ path, cloned, branch, head }` |
|
|
70
|
+
| `workdir__list_dir` | `path`, relative to the work root or absolute inside it, and `depth` (1 by default, at most 5) | the entries with type and size, and `truncated` past 500 |
|
|
71
|
+
|
|
72
|
+
`open_repo` clones to `<WORKER_ROOT>/<host>/<owner>/<name>` the first time, and after that returns the checkout as it is: it never fetches or resets. Git runs with the worker's whole environment and never prompts, so give a private repo's access to the worker's user, with an ssh key or a credential helper. Neither tool reaches outside the work root, symlinks included.
|
|
@@ -15525,7 +15525,7 @@ path.resolve(import.meta.dirname, "..", "..");
|
|
|
15525
15525
|
* A bundle can't read the repo's package.json the way `version()` does, because it isn't there.
|
|
15526
15526
|
*/
|
|
15527
15527
|
function workerVersion() {
|
|
15528
|
-
return "0.
|
|
15528
|
+
return "0.3.0";
|
|
15529
15529
|
}
|
|
15530
15530
|
// worker/workdir/git.ts
|
|
15531
15531
|
/** The git program, found on PATH. */
|
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-
|
|
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-knPnskLw.js";
|
package/llms.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# @cubicecho/agent-router-worker
|
|
2
|
+
|
|
3
|
+
> agent-router's worker program: runs a workspace's agent loops on another machine.
|
|
4
|
+
|
|
5
|
+
Agent-facing docs for @cubicecho/agent-router-worker, one task or concept per page. Generated from _agents/docs/ by @cubicecho/agent-docs; edit the pages, not this file.
|
|
6
|
+
|
|
7
|
+
## Docs
|
|
8
|
+
|
|
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
|
+
- [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
|
+
- [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.
|
|
13
|
+
|
|
14
|
+
## Exports
|
|
15
|
+
|
|
16
|
+
- [`@cubicecho/agent-router-worker`](types/worker/lib.d.ts): the library. The declarations it re-exports from, beside it in `types/`, carry the doc comment of every export.
|
|
17
|
+
- `@cubicecho/agent-router-worker/package.json`: the manifest.
|
|
18
|
+
|
|
19
|
+
## Elsewhere
|
|
20
|
+
|
|
21
|
+
- [The router's own pages](https://github.com/cubicecho/agent-router/tree/main/_agents/docs): its `/graphql`, `/v1`, `/mcp` and `/runs`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cubicecho/agent-router-worker",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
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",
|
|
@@ -19,9 +19,14 @@
|
|
|
19
19
|
"lib.js",
|
|
20
20
|
"chunks",
|
|
21
21
|
"types",
|
|
22
|
+
"llms.txt",
|
|
23
|
+
"_agents/docs",
|
|
22
24
|
"README.md",
|
|
23
25
|
"LICENSE"
|
|
24
26
|
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"prepack": "agent-docs llms"
|
|
29
|
+
},
|
|
25
30
|
"engines": {
|
|
26
31
|
"node": ">=22"
|
|
27
32
|
},
|
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-
|
|
2
|
+
import { o as readWorkerConfig, s as errorMessage, t as startWorker } from "./chunks/worker-knPnskLw.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;
|