@cubicecho/agent-router-worker 0.8.0 → 0.9.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.
@@ -23,7 +23,7 @@ Once connected it prints `[worker] connected to <url> as <host>`. SIGTERM or SIG
23
23
  | `AGENT_ROUTER_WORKER_KEY` | required | The worker key, which starts `aiw_`. |
24
24
  | `WORKER_CONFIG` | none | A JSON file of the worker's own servers: [local servers](local-servers.md). |
25
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. |
26
+ | `WORKER_HOST` | the machine's host name | The name the worker gives the router for its machine. Set it in a container. |
27
27
 
28
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
29
 
@@ -60,6 +60,13 @@ docker run -d --name agent-router-worker \
60
60
  ghcr.io/cubicecho/agent-router-worker
61
61
  ```
62
62
 
63
+ ### Name the machine
64
+
65
+ Inside a container, the host name is the container's id, which names no machine and changes each time the container is
66
+ made again. Set `WORKER_HOST` to the machine's name (`-e WORKER_HOST=gpu-box`), or give the container one (`--hostname
67
+ gpu-box`, or compose's `hostname:`). Without either, the worker starts with `[worker] WORKER_HOST is unset, so this
68
+ worker tells the router it runs on "<id>"…`.
69
+
63
70
  ## As a library
64
71
 
65
72
  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.
@@ -44,6 +44,15 @@ The options are agent-core's `AgentLoopOptions`, and the result its `AgentLoopRe
44
44
  - **Report through `options.onEvent`,** agent-core's `RunEventInput`s. They are the run's record on the router.
45
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
46
  - **Return `messages`, `usage`, `loaded` and `turn`.** A throw fails the run with its message.
47
+ - **Say the model, if you call one yourself.** A loop that calls its model through `options.config.fetch` needs do nothing: the router records the model each call asks for. One that calls a model of its own adds `model` to its result, typed by `LoopRuntime`, and the run records that. Pass `startWorker` the same name as `model`, so the worker's hello says it too.
48
+
49
+ ```ts
50
+ import type { LoopRuntime } from '@cubicecho/agent-router-worker';
51
+
52
+ const runtime: LoopRuntime = {
53
+ runAgentLoop: async (options) => ({ ...(await callMyOwnModel(options)), model: 'my-provider/my-model' }),
54
+ };
55
+ ```
47
56
 
48
57
  ## Test a loop without a router
49
58
 
@@ -110,7 +119,7 @@ Set the endpoint's `baseUrl` to exactly `http://models.ai-router.invalid/v1`, as
110
119
 
111
120
  ## Other things startWorker takes
112
121
 
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.
122
+ `deps` also takes `model`, the model a loop of your own calls, which the hello says; `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
123
 
115
124
  ```ts
116
125
  import { readWorkerConfig, startWorker } from '@cubicecho/agent-router-worker';
@@ -1,4 +1,4 @@
1
- import { mkdirSync, readFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
2
2
  import { homedir, hostname } from "node:os";
3
3
  import path, { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
4
  import { z } from "zod";
@@ -62,6 +62,10 @@ const DEFAULT_ROOT_FOLDER = "agent-router-work";
62
62
  const HOME_PREFIX = "~/";
63
63
  /** A lone `~`: the home folder itself. */
64
64
  const HOME = "~";
65
+ /** A file Docker puts at the root of every container it runs. */
66
+ const DOCKER_MARKER = "/.dockerenv";
67
+ /** A container id, short or full, as a container's own host name. */
68
+ const CONTAINER_ID = /^(?:[0-9a-f]{12}|[0-9a-f]{64})$/;
65
69
  /** A local server the worker starts itself: a command, run as the worker's user. */
66
70
  const commandServerSchema = z.strictObject({
67
71
  command: z.string().min(1, "A server's \"command\" cannot be empty."),
@@ -147,6 +151,18 @@ function readServersFile(path) {
147
151
  }));
148
152
  }
149
153
  /**
154
+ * Says why a worker's own host name probably names no machine: inside a container it is the container's id, which
155
+ * changes each time the container is made again.
156
+ *
157
+ * @param name - The host name the worker would report.
158
+ * @param inContainer - Whether the worker runs in a container.
159
+ * @returns The warning, or null when the name looks like a machine's.
160
+ */
161
+ function containerHostWarning(name, inContainer) {
162
+ if (inContainer === false && CONTAINER_ID.test(name) === false) return null;
163
+ return `WORKER_HOST is unset, so this worker tells the router it runs on "${name}", the container's own host name. Set WORKER_HOST to the machine's name, or give the container one (compose's hostname:).`;
164
+ }
165
+ /**
150
166
  * Reads the worker's config from its environment, and makes its work root.
151
167
  *
152
168
  * @param env - The environment, `process.env` at boot.
@@ -165,12 +181,15 @@ function readWorkerConfig(env, cwd = process.cwd()) {
165
181
  throw new WorkerConfigError(`WORKER_ROOT is ${root}, which can't be made: ${errorMessage(error)}`);
166
182
  }
167
183
  const servers = WORKER_CONFIG ? readServersFile(absolutePath(WORKER_CONFIG, cwd)) : {};
184
+ const host = WORKER_HOST || hostname();
185
+ const hostWarning = WORKER_HOST ? null : containerHostWarning(host, existsSync(DOCKER_MARKER));
168
186
  return {
169
187
  url: AGENT_ROUTER_URL.replace(/\/+$/, ""),
170
188
  key: AGENT_ROUTER_WORKER_KEY,
171
189
  root,
172
- host: WORKER_HOST || hostname(),
173
- servers
190
+ host,
191
+ servers,
192
+ ...hostWarning === null ? {} : { hostWarning }
174
193
  };
175
194
  }
176
195
  // server/runner/protocol.ts
@@ -247,7 +266,12 @@ z.object({
247
266
  * 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
267
  * a worker that restarted holds none. Absent, from a worker older than the field, the router keeps them.
249
268
  */
250
- runs: z.array(z.string().min(1)).optional()
269
+ runs: z.array(z.string().min(1)).optional(),
270
+ /**
271
+ * The model its own loop calls, for a worker whose loop picks its model itself rather than calling the router's.
272
+ * Absent for one that calls the router's, or from a worker older than the field.
273
+ */
274
+ model: z.string().min(1).optional()
251
275
  });
252
276
  z.object({
253
277
  /** The server's id, as the run's targets name it. */
@@ -268,11 +292,13 @@ z.discriminatedUnion("ok", [z.looseObject({
268
292
  usage: z.unknown(),
269
293
  loaded: z.array(z.string()),
270
294
  finishReason: z.unknown(),
271
- handedBack: z.array(z.string())
295
+ handedBack: z.array(z.string()),
296
+ model: z.string().min(1).optional()
272
297
  }), z.object({
273
298
  ok: z.literal(false),
274
299
  error: z.string(),
275
- usage: z.unknown().optional()
300
+ usage: z.unknown().optional(),
301
+ model: z.string().min(1).optional()
276
302
  })]);
277
303
  Object.freeze({
278
304
  secretBytes: 32,
@@ -611,7 +637,8 @@ async function executeRun(assignment, ports, runtime) {
611
637
  usage: result.usage,
612
638
  loaded: result.loaded,
613
639
  finishReason: result.turn.finishReason,
614
- handedBack
640
+ handedBack,
641
+ ...typeof result.model === "string" && result.model !== "" ? { model: result.model } : {}
615
642
  };
616
643
  } catch (error) {
617
644
  return {
@@ -1058,7 +1085,7 @@ path.resolve(import.meta.dirname, "..", "..");
1058
1085
  * A bundle can't read the repo's package.json the way `version()` does, because it isn't there.
1059
1086
  */
1060
1087
  function workerVersion() {
1061
- return "0.8.0";
1088
+ return "0.9.0";
1062
1089
  }
1063
1090
  // worker/workdir/git.ts
1064
1091
  /** The git program, found on PATH. */
@@ -1677,15 +1704,17 @@ async function startLocalServers(options, overrides = {}) {
1677
1704
  * @returns The running worker.
1678
1705
  */
1679
1706
  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;
1707
+ const { url, key, root, host, servers, hostWarning } = config;
1708
+ const { fetch = globalThis.fetch, runtime = { runAgentLoop }, baseEnv, git, settings = {}, workdir, model } = deps;
1709
+ if (hostWarning !== void 0) console.warn(`[worker] ${hostWarning}`);
1682
1710
  let channel;
1683
1711
  const sayHello = async () => {
1684
1712
  const hello = {
1685
1713
  host,
1686
1714
  version: workerVersion(),
1687
1715
  servers: local.listing(),
1688
- runs: runs.ids()
1716
+ runs: runs.ids(),
1717
+ ...model === void 0 ? {} : { model }
1689
1718
  };
1690
1719
  const response = await fetch(`${url}${WORKERS_PATH}${WorkerDoor.Hello}`, {
1691
1720
  method: "POST",
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-DobLEExh.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-NNsrVSoq.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cubicecho/agent-router-worker",
3
- "version": "0.8.0",
3
+ "version": "0.9.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",
@@ -109,6 +109,8 @@ export interface AnsweredOutcome {
109
109
  finishReason: AgentLoopResult['turn']['finishReason'];
110
110
  /** The loop ids of the app tool calls handed back, in the order they were made. Empty for an answer. */
111
111
  handedBack: string[];
112
+ /** The model the loop called, when it called one itself rather than through `RunPorts.modelFetch`. */
113
+ model?: string;
112
114
  }
113
115
  /** A stretch the loop failed, or was stopped. */
114
116
  export interface FailedOutcome {
@@ -117,6 +119,8 @@ export interface FailedOutcome {
117
119
  error: string;
118
120
  /** What the model spent before it failed, when the loop knows. */
119
121
  usage: LoopUsage | undefined;
122
+ /** The model the loop called, when it called one itself rather than through `RunPorts.modelFetch`. */
123
+ model?: string;
120
124
  }
121
125
  /** How a stretch's loop ended. */
122
126
  export type RunOutcome = AnsweredOutcome | FailedOutcome;
@@ -1,5 +1,14 @@
1
1
  import { type Runtime } from '@cubicecho/agent-core';
2
2
  import { type RunAssignment, type RunOutcome, type RunPorts } from './assignment.ts';
3
+ /**
4
+ * The loop an assignment runs on: agent-core's `runAgentLoop`, or one in its place. A loop that calls its model itself,
5
+ * rather than through the assignment's `fetch`, adds the model's name to its result as `model`, and the run records it.
6
+ */
7
+ export interface LoopRuntime {
8
+ runAgentLoop: (options: Parameters<Runtime['runAgentLoop']>[0]) => Promise<Awaited<ReturnType<Runtime['runAgentLoop']>> & {
9
+ model?: string;
10
+ }>;
11
+ }
3
12
  /**
4
13
  * Runs one stretch of a run's agent loop: to its answer, or until the model calls an app tool.
5
14
  *
@@ -12,4 +21,4 @@ import { type RunAssignment, type RunOutcome, type RunPorts } from './assignment
12
21
  * Each app tool call ends the loop with a stand-in answer, which the app replaces when it resumes the run, so the
13
22
  * stand-in's result is never published.
14
23
  */
15
- export declare function executeRun(assignment: RunAssignment, ports: RunPorts, runtime: Pick<Runtime, 'runAgentLoop'>): Promise<RunOutcome>;
24
+ export declare function executeRun(assignment: RunAssignment, ports: RunPorts, runtime: LoopRuntime): Promise<RunOutcome>;
@@ -98,6 +98,7 @@ export declare const workerHelloSchema: z.ZodObject<{
98
98
  }, z.core.$strip>>;
99
99
  }, z.core.$strip>>;
100
100
  runs: z.ZodOptional<z.ZodArray<z.ZodString>>;
101
+ model: z.ZodOptional<z.ZodString>;
101
102
  }, z.core.$strip>;
102
103
  export type WorkerHello = z.infer<typeof workerHelloSchema>;
103
104
  /** A call to one of the router's servers, made for the run. */
@@ -137,10 +138,12 @@ export declare const runOutcomeSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
137
138
  loaded: z.ZodArray<z.ZodString>;
138
139
  finishReason: z.ZodUnknown;
139
140
  handedBack: z.ZodArray<z.ZodString>;
141
+ model: z.ZodOptional<z.ZodString>;
140
142
  }, z.core.$loose>, z.ZodObject<{
141
143
  ok: z.ZodLiteral<false>;
142
144
  error: z.ZodString;
143
145
  usage: z.ZodOptional<z.ZodUnknown>;
146
+ model: z.ZodOptional<z.ZodString>;
144
147
  }, z.core.$strip>], "ok">;
145
148
  /** Re-exported so both ends name the same shapes. */
146
149
  export type { RunAssignment, RunOutcome };
@@ -34,6 +34,11 @@ export interface WorkerConfig {
34
34
  root: string;
35
35
  /** The machine it says it runs on. */
36
36
  host: string;
37
+ /**
38
+ * Why `host` probably names no machine: `WORKER_HOST` is unset and the worker runs in a container, whose own host
39
+ * name is its id. `startWorker` logs it. Absent when `host` is fine.
40
+ */
41
+ hostWarning?: string;
37
42
  /** Its own servers, by name, with each command server's `cwd` made absolute. */
38
43
  servers: Record<string, LocalServerConfig>;
39
44
  }
@@ -44,6 +49,15 @@ export declare class WorkerConfigError extends Error {
44
49
  */
45
50
  constructor(message: string);
46
51
  }
52
+ /**
53
+ * Says why a worker's own host name probably names no machine: inside a container it is the container's id, which
54
+ * changes each time the container is made again.
55
+ *
56
+ * @param name - The host name the worker would report.
57
+ * @param inContainer - Whether the worker runs in a container.
58
+ * @returns The warning, or null when the name looks like a machine's.
59
+ */
60
+ export declare function containerHostWarning(name: string, inContainer: boolean): string | null;
47
61
  /**
48
62
  * Reads the worker's config from its environment, and makes its work root.
49
63
  *
@@ -7,6 +7,6 @@
7
7
  */
8
8
  export type { AppToolDefinition, RunAssignment, RunOutcome, RunPorts, ToolDefinition, ToolTarget, TranscriptMessage, } from '../server/runner/assignment.ts';
9
9
  export { TOOL_ORIGIN_LOCAL, TOOL_ORIGIN_ROUTER } from '../server/runner/assignment.ts';
10
- export { executeRun } from '../server/runner/execute.ts';
10
+ export { executeRun, type LoopRuntime } from '../server/runner/execute.ts';
11
11
  export { readWorkerConfig, type WorkerConfig, WorkerConfigError } from './config.ts';
12
12
  export { type RunningWorker, startWorker, type WorkerDeps } from './worker.ts';
@@ -1,6 +1,6 @@
1
- import { type Runtime } from '@cubicecho/agent-core';
2
1
  import { type WorkerSettings } from '../server/core/defaults.ts';
3
2
  import type { RunAssignment } from '../server/runner/assignment.ts';
3
+ import { type LoopRuntime } from '../server/runner/execute.ts';
4
4
  import { type WorkerProgramSettings } from './defaults.ts';
5
5
  import type { LocalServers } from './servers.ts';
6
6
  /** Why a run ended when a door answered 404: the router no longer runs it on this worker. */
@@ -18,7 +18,7 @@ export interface RunHostOptions {
18
18
  /** The worker's own servers. Absent when it has none. */
19
19
  local?: LocalServers;
20
20
  /** agent-core's runtime, whose loop the runs use. */
21
- runtime: Pick<Runtime, 'runAgentLoop'>;
21
+ runtime: LoopRuntime;
22
22
  /**
23
23
  * Makes the requests.
24
24
  *
@@ -1,5 +1,5 @@
1
- import { type Runtime } from '@cubicecho/agent-core';
2
1
  import type { WorkerSettings } from '../server/core/defaults.ts';
2
+ import type { LoopRuntime } from '../server/runner/execute.ts';
3
3
  import { type Channel } from './channel.ts';
4
4
  import type { WorkerConfig } from './config.ts';
5
5
  import type { WorkdirSettings, WorkerProgramSettings } from './defaults.ts';
@@ -19,7 +19,7 @@ export interface WorkerDeps {
19
19
  *
20
20
  * @defaultValue agent-core's `runAgentLoop`
21
21
  */
22
- runtime?: Pick<Runtime, 'runAgentLoop'>;
22
+ runtime?: LoopRuntime;
23
23
  /**
24
24
  * The environment a command server's allowlist reads from.
25
25
  *
@@ -32,6 +32,11 @@ export interface WorkerDeps {
32
32
  settings?: Partial<WorkerSettings & WorkerProgramSettings>;
33
33
  /** Settings for `workdir`. */
34
34
  workdir?: Partial<WorkdirSettings>;
35
+ /**
36
+ * The model the loop calls, for a `runtime` that calls its model itself rather than through the assignment's `fetch`.
37
+ * Said in the hello, so the router can show it. Each run's own is what its loop's result says as `model`.
38
+ */
39
+ model?: string;
35
40
  }
36
41
  /** A worker that is running. */
37
42
  export interface RunningWorker {
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-DobLEExh.js";
2
+ import { o as readWorkerConfig, s as errorMessage, t as startWorker } from "./chunks/worker-NNsrVSoq.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;