@clearideas/agent-runtime-cli 0.8.0 → 0.10.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/NOTICE CHANGED
@@ -3,6 +3,6 @@ Copyright 2026 Clear Ideas Incorporated
3
3
 
4
4
  Clear Ideas is a trademark of Clear Ideas Incorporated.
5
5
 
6
- The documentation site includes @clearideas/analytics 1.16.11, distributed
6
+ The documentation site includes @clearideas/consent-analytics 0.1.0-rc.1, distributed
7
7
  under the MIT License. Its license text is available at
8
- docs/public/assets/analytics/LICENSE.clearideas-analytics.txt.
8
+ docs/public/assets/analytics/LICENSE.clearideas-consent-analytics.txt.
package/README.md CHANGED
@@ -1,7 +1,8 @@
1
1
  # Clear Ideas Agent Runtime CLI
2
2
 
3
3
  The `agent-runtime` CLI validates and runs agent manifests, resumes stored
4
- runs, inspects events, and starts worker processes.
4
+ runs, inspects events, starts worker processes, and serves manifests over an
5
+ OpenAI-compatible API.
5
6
 
6
7
  Install it in a project and run it with `npx`:
7
8
 
@@ -19,12 +20,30 @@ npx agent-runtime connections inspect ./agent-runtime.config.yaml --format yaml
19
20
  npx agent-runtime run ./agent.yaml --config ./agent-runtime.config.yaml --store ./.agent-runtime
20
21
  npx agent-runtime run ./agent.yaml --max-total-tokens 100000 --store ./.agent-runtime
21
22
  npx agent-runtime resume run_123 --max-total-tokens 150000 --store ./.agent-runtime
23
+ npx agent-runtime resume run_123 --limits ./raised-limits.yaml --store ./.agent-runtime
24
+ npx agent-runtime restart run_123 --list --store ./.agent-runtime
25
+ npx agent-runtime restart run_123 --from review --run-id run_124 --store ./.agent-runtime
22
26
  npx agent-runtime inspect run_123 --store ./.agent-runtime
23
27
  npx agent-runtime events ./.agent-runtime/events.jsonl --run run_123 --tail 20
24
28
  npx agent-runtime examples run variables --stream
25
29
  npx agent-runtime run ./agent.yaml --store-driver sqlite --store ./.agent-runtime/runs.sqlite
30
+ npx agent-runtime serve ./support-chat.agent.yaml --port 8000
31
+ npx agent-runtime serve --server-config ./agent-runtime.server.yaml
26
32
  ```
27
33
 
34
+ Options accept `--name value` or `--name=value`.
35
+
36
+ A run that reaches one of its limits, or whose step fails with an error that is
37
+ not fatal, is blocked rather than failed; the pretty view prints why. A
38
+ runtime module can export `limits` (replacing default run limits) and
39
+ `enforcedLimits` (ceilings) for every run.
40
+ `--limits` grants higher limits from a JSON or YAML file (for example
41
+ `maxTotalTokens: 50000000`) for that attempt and later ones. `inspect` shows
42
+ the run, its latest checkpoint (including `ledger.blocked`), and its restart
43
+ points. `restart` starts a new run from a completed step of another run: the
44
+ last one by default, or the one `--from` names by step path, execution key, or
45
+ checkpoint sequence.
46
+
28
47
  `--stream` shows model text on stdout and lifecycle progress on stderr. Use
29
48
  `--format ndjson` for a machine-readable stream containing event and result
30
49
  messages, and `--show-reasoning` to opt into reasoning deltas in the pretty
@@ -247,3 +266,23 @@ newline-delimited `ready`, `event`, `result`, or `error` messages to stdout.
247
266
  Child-process and remote execution adapters launch this command. The worker
248
267
  uses only host-pinned `--config` and `--runtime-module` files; request-supplied
249
268
  paths and inline configuration are rejected by default.
269
+
270
+ ## Serve command
271
+
272
+ `agent-runtime serve` exposes agent manifests as models on an
273
+ OpenAI-compatible API (`/v1/models`, `/v1/chat/completions`), so chat front
274
+ ends and OpenAI SDKs can run whole agents:
275
+
276
+ ```sh
277
+ export AGENT_RUNTIME_API_KEY="a-key-you-choose"
278
+ npx agent-runtime serve ./support-chat.agent.yaml --config ./runtime.yaml --port 8000
279
+ ```
280
+
281
+ With no arguments, it reads `agent-runtime.server.yaml` (or `.yml`, `.json`)
282
+ from the working directory; `--server-config <file>` selects another file.
283
+ Manifests that declare `messages` receive the chat as conversation turns;
284
+ others receive variables mapped with `--input <variable>=<source>`. Serve
285
+ follows the worker's trust rules: webhook steps need an authorizing executor
286
+ from the runtime module, and requests never supply configuration. `--check`
287
+ validates everything and exits. See
288
+ [Serve agents over an OpenAI-compatible API](https://agent-runtime.clearideas.com/serving).
package/dist/index.d.ts CHANGED
@@ -1,45 +1,14 @@
1
- import type { AgentManifest, RunResult, ExecutionPolicies } from "@clearideas/agent-runtime-contracts";
2
- import { type ArtifactStore, type ApprovalAdapter, type ConnectionCredentialProvider, type EventSink, type ModelAdapter, type RunSandboxProvider, type RunStore, type SandboxAdapter, type StepExecutor, type SubRunAdapter, type ContextSummarizerAdapter, type AgentRuntimeMessagesOptions, type ToolAdapter, type WorkspaceProvider } from "@clearideas/agent-runtime-core";
3
- import type { SandboxProvider } from "@clearideas/agent-runtime-sandbox";
1
+ import type { AgentManifest, RunResult } from "@clearideas/agent-runtime-contracts";
4
2
  import { type ExecutionRequest, type WorkerInvocation, type WorkerMessage } from "@clearideas/agent-runtime-execution";
5
3
  import { type AgentRuntimeConfig, type ConfiguredMcpToolAdapterOptions, type ModelAuthorizationPolicy, type WorkspaceCompositionOptions } from "@clearideas/agent-runtime-config";
4
+ import { type HostRuntime, type HostRuntimeModule, type ServeOptions } from "@clearideas/agent-runtime-server";
6
5
  export interface CliIo {
7
6
  stdout: (text: string) => void;
8
7
  stderr: (text: string) => void;
9
8
  }
10
9
  export type CliStoreDriver = "file" | "sqlite";
11
10
  /** Adapters a local runtime module may contribute to CLI execution. */
12
- export interface CliRuntime {
13
- /** Called once after execution, including failed setup. Own only module-created resources. */
14
- shutdown?: () => void | Promise<void>;
15
- runStore?: RunStore;
16
- artifactStore?: ArtifactStore;
17
- model?: ModelAdapter;
18
- tools?: ToolAdapter;
19
- connectionCredentials?: ConnectionCredentialProvider;
20
- approvals?: ApprovalAdapter;
21
- sandbox?: SandboxAdapter;
22
- subRuns?: SubRunAdapter;
23
- /** Resolves manifest workspace bindings instead of the configuration's `workspaces` section. */
24
- workspaces?: WorkspaceProvider;
25
- /** Opens run sandboxes instead of the configuration's `sandbox` section. */
26
- runSandbox?: RunSandboxProvider;
27
- /** Backs `sandbox.driver: host` in the configuration. */
28
- sandboxProvider?: SandboxProvider;
29
- eventSinks?: EventSink[];
30
- stepExecutors?: StepExecutor[];
31
- /** Host default execution policies; manifests and steps override them. */
32
- policies?: ExecutionPolicies;
33
- /** Host execution policies applied last; manifests cannot override them. */
34
- enforcedPolicies?: ExecutionPolicies;
35
- /** Observes, changes, or replaces context summarization. */
36
- summarizer?: ContextSummarizerAdapter;
37
- /**
38
- * Conversation message options, merged over the configuration's `messages`
39
- * section: for example `authorizeArtifact` or a KMS-backed signer.
40
- */
41
- messages?: AgentRuntimeMessagesOptions;
42
- }
11
+ export type CliRuntime = HostRuntime;
43
12
  export interface CliRuntimeContext {
44
13
  manifest: AgentManifest;
45
14
  runId?: string;
@@ -50,20 +19,7 @@ export interface CliRuntimeContext {
50
19
  artifactDirectory?: string;
51
20
  }
52
21
  export type CliStoreContext = Omit<CliRuntimeContext, "manifest">;
53
- export interface CliRuntimeModule extends CliRuntime {
54
- store?: RunStore;
55
- artifacts?: ArtifactStore;
56
- modelAdapter?: ModelAdapter;
57
- toolAdapter?: ToolAdapter;
58
- credentialProvider?: ConnectionCredentialProvider;
59
- approvalAdapter?: ApprovalAdapter;
60
- sandboxAdapter?: SandboxAdapter;
61
- subRunAdapter?: SubRunAdapter;
62
- workspaceProvider?: WorkspaceProvider;
63
- runSandboxProvider?: RunSandboxProvider;
64
- eventSink?: EventSink;
65
- executors?: StepExecutor[];
66
- }
22
+ export type CliRuntimeModule = HostRuntimeModule;
67
23
  export interface PortableWorkerOptions {
68
24
  storeDirectory: string;
69
25
  storeDriver?: CliStoreDriver;
@@ -105,6 +61,10 @@ export interface PortableWorkerOptions {
105
61
  }
106
62
  /** Runs one provider-neutral worker invocation in the current process. */
107
63
  export declare const executeWorkerInvocation: (invocation: WorkerInvocation, options: PortableWorkerOptions) => Promise<RunResult>;
64
+ /** Parse `agent-runtime serve` arguments into server options. */
65
+ export declare const parseServeArguments: (args: string[]) => ServeOptions & {
66
+ check?: boolean;
67
+ };
108
68
  export interface CliRunOptions {
109
69
  signal?: AbortSignal;
110
70
  }
package/dist/index.js CHANGED
@@ -1,14 +1,11 @@
1
- import { access, readFile, writeFile } from "node:fs/promises";
1
+ import { readFile, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { fileURLToPath, pathToFileURL } from "node:url";
4
- import { JexlConditionEvaluator } from "@clearideas/agent-runtime-condition-jexl";
5
- import { executionPoliciesSchema, messagesSignatureSchema, parseAgentVariableOverrides, parseConversationMessages, } from "@clearideas/agent-runtime-contracts";
3
+ import { fileURLToPath } from "node:url";
4
+ import { messagesSignatureSchema, parseAgentVariableOverrides, parseConversationMessages, runLimitsSchema, } from "@clearideas/agent-runtime-contracts";
6
5
  import { AgentRuntime, } from "@clearideas/agent-runtime-core";
7
6
  import { EXECUTION_PROTOCOL_VERSION, parseWorkerInvocation, serializeWorkerMessage, } from "@clearideas/agent-runtime-execution";
8
- import { composeRuntime, discoverMcpConnectionTools, emptyAgentRuntimeConfig, loadAgentRuntimeConfig, parseAgentRuntimeConfig, validateRuntimeConfiguration, } from "@clearideas/agent-runtime-config";
9
- import { LoopStepExecutor } from "@clearideas/agent-runtime-step-loop";
10
- import { PromptMessageHistoryCompactor, PromptStepExecutor, } from "@clearideas/agent-runtime-step-prompt";
11
- import { ApprovalStepExecutor, CodeStepExecutor, SubRunStepExecutor, WebhookStepExecutor, } from "@clearideas/agent-runtime-step-standard";
7
+ import { discoverMcpConnectionTools, loadAgentRuntimeConfig, parseAgentRuntimeConfig, validateRuntimeConfiguration, } from "@clearideas/agent-runtime-config";
8
+ import { composeHostRuntime, hostRuntimeDependencies, loadHostRunStore, loadHostRuntime, resolveAgentRuntimeConfig, runServe, validateHostRuntime, } from "@clearideas/agent-runtime-server";
12
9
  import { FileArtifactStore, FileAgentManifestSource, FileAgentRunManifestSource, FileRunStore, JsonlEventSink, } from "@clearideas/agent-runtime-store-local";
13
10
  import { Document as YamlDocument, YAMLMap, isPair, isScalar, parse as parseYamlDocument, } from "yaml";
14
11
  const defaultIo = {
@@ -21,15 +18,19 @@ Usage:
21
18
  agent-runtime validate <manifest.json|manifest.yaml> [--config <config.yaml>]
22
19
  agent-runtime config validate <config.json|config.yaml>
23
20
  agent-runtime connections inspect <config.json|config.yaml> [--connection <name>] [--runtime-module <local-js-file>] [--format <json|yaml>]
24
- agent-runtime run <manifest.json|manifest.yaml> [--variables <overrides.json>] [--messages <messages.json|messages.yaml>] [--messages-scope <scope>] [--messages-out <file>] [--max-total-tokens <count>] [--config <config.yaml>] [--run-id <id>] [--store <path>] [--store-driver <file|sqlite>] [--events <file|none>] [--artifacts <directory|none>] [--runtime-module <local-js-file>] [--stream] [--format <json|pretty|ndjson>] [--show-reasoning]
21
+ agent-runtime run <manifest.json|manifest.yaml> [--variables <overrides.json>] [--messages <messages.json|messages.yaml>] [--messages-scope <scope>] [--messages-out <file>] [--max-total-tokens <count>] [--limits <limits.json|limits.yaml>] [--config <config.yaml>] [--run-id <id>] [--store <path>] [--store-driver <file|sqlite>] [--events <file|none>] [--artifacts <directory|none>] [--runtime-module <local-js-file>] [--stream] [--format <json|pretty|ndjson>] [--show-reasoning]
25
22
  agent-runtime run-manifest <run.json|run.yaml> [--messages-scope <scope>] [--messages-out <file>] [--config <config.yaml>] [--store <path>] [--store-driver <file|sqlite>] [--events <file|none>] [--artifacts <directory|none>] [--runtime-module <local-js-file>] [--stream] [--format <json|pretty|ndjson>] [--show-reasoning]
26
- agent-runtime resume <run-id> [--max-total-tokens <count>] [--config <config.yaml>] [--store <path>] [--store-driver <file|sqlite>] [--events <file|none>] [--artifacts <directory|none>] [--runtime-module <local-js-file>] [--stream] [--format <json|pretty|ndjson>] [--show-reasoning]
23
+ agent-runtime resume <run-id> [--max-total-tokens <count>] [--limits <limits.json|limits.yaml>] [--config <config.yaml>] [--store <path>] [--store-driver <file|sqlite>] [--events <file|none>] [--artifacts <directory|none>] [--runtime-module <local-js-file>] [--stream] [--format <json|pretty|ndjson>] [--show-reasoning]
24
+ agent-runtime restart <run-id> [--from <step-path|execution-key|sequence>] [--list] [--run-id <new-id>] [--max-total-tokens <count>] [--limits <limits.json|limits.yaml>] [--config <config.yaml>] [--store <path>] [--store-driver <file|sqlite>] [--events <file|none>] [--artifacts <directory|none>] [--runtime-module <local-js-file>] [--stream] [--format <json|pretty|ndjson>] [--show-reasoning]
27
25
  agent-runtime inspect <run-id> [--store <path>] [--store-driver <file|sqlite>] [--runtime-module <local-js-file>]
28
26
  agent-runtime events <events.jsonl> [--run <run-id>] [--type <event-type>] [--tail <count>]
29
27
  agent-runtime examples list
30
28
  agent-runtime examples show <variables|conditions|loops>
31
29
  agent-runtime examples run <variables|conditions|loops> [run options]
32
30
  agent-runtime worker [--store <path>] [--store-driver <file|sqlite>] [--config <config.yaml>] [--runtime-module <local-js-file>]
31
+ agent-runtime serve [<manifest>] [--server-config <server.yaml>] [--no-server-config] [--served-model-name <name>] [--config <runtime.yaml>] [--runtime-module <local-js-file>] [--host <host>] [--port <port>] [--api-key-env <VAR>] [--allow-unauthenticated] [--input <variable>=<source>]... [--output <final|step:id|variable:name>] [--stream-mode <auto|live|committed>] [--progress <none|status>] [--store-driver <memory|sqlite>] [--store <path>] [--ledger <memory|sqlite:path>] [--on-unrecognized <unsigned|reject|restart>] [--client-tools <ignore|reject>] [--max-concurrent-runs <count>] [--request-timeout <ms>] [--warmup] [--check]
32
+
33
+ Options accept --name value or --name=value.
33
34
  `;
34
35
  const packageDirectory = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
35
36
  const bundledExamplesDirectory = path.join(packageDirectory, "examples");
@@ -81,33 +82,55 @@ const resolveCliStore = async (parsed) => {
81
82
  },
82
83
  };
83
84
  };
84
- const parseOptions = (args, allowed, flags = new Set()) => {
85
+ /**
86
+ * Parse `--name value` and `--name=value` options. Flags take no value;
87
+ * repeatable options may appear more than once.
88
+ */
89
+ const parseOptions = (args, allowed, flags = new Set(), repeatable = new Set()) => {
85
90
  const positional = [];
86
91
  const options = new Map();
92
+ const repeated = new Map();
87
93
  for (let index = 0; index < args.length; index += 1) {
88
94
  const value = args[index];
89
95
  if (!value.startsWith("--")) {
90
96
  positional.push(value);
91
97
  continue;
92
98
  }
93
- const name = value.slice(2);
99
+ const separator = value.indexOf("=");
100
+ const name = value.slice(2, separator < 0 ? undefined : separator);
101
+ const option = `--${name}`;
94
102
  if (!allowed.has(name))
95
- throw new Error(`Unknown option: ${value}`);
103
+ throw new Error(`Unknown option: ${option}`);
96
104
  if (flags.has(name)) {
105
+ if (separator >= 0)
106
+ throw new Error(`Option ${option} does not take a value.`);
97
107
  if (options.has(name))
98
- throw new Error(`Option ${value} may only be provided once.`);
108
+ throw new Error(`Option ${option} may only be provided once.`);
99
109
  options.set(name, "true");
100
110
  continue;
101
111
  }
102
- const optionValue = args[index + 1];
103
- if (!optionValue || optionValue.startsWith("--"))
104
- throw new Error(`Option ${value} requires a value.`);
112
+ let optionValue;
113
+ if (separator >= 0) {
114
+ optionValue = value.slice(separator + 1);
115
+ }
116
+ else {
117
+ optionValue = args[index + 1];
118
+ if (optionValue?.startsWith("--"))
119
+ optionValue = undefined;
120
+ index += 1;
121
+ }
122
+ if (!optionValue)
123
+ throw new Error(`Option ${option} requires a value.`);
124
+ if (repeatable.has(name)) {
125
+ repeated.set(name, [...(repeated.get(name) ?? []), optionValue]);
126
+ options.set(name, optionValue);
127
+ continue;
128
+ }
105
129
  if (options.has(name))
106
- throw new Error(`Option ${value} may only be provided once.`);
130
+ throw new Error(`Option ${option} may only be provided once.`);
107
131
  options.set(name, optionValue);
108
- index += 1;
109
132
  }
110
- return { positional, options };
133
+ return { positional, options, repeated };
111
134
  };
112
135
  const requireOnePositional = (parsed, label) => {
113
136
  if (parsed.positional.length !== 1)
@@ -210,7 +233,7 @@ const inspectConnections = async (args, io) => {
210
233
  throw new Error(`Unknown connection "${name}".`);
211
234
  }
212
235
  const runtimeModulePath = parsed.options.get("runtime-module");
213
- const moduleRuntime = await loadRuntime(runtimeModulePath, {
236
+ const moduleRuntime = await loadHostRuntime(runtimeModulePath, {
214
237
  manifest: {
215
238
  schemaVersion: "1.0",
216
239
  connections: names.map((ref) => ({ ref })),
@@ -260,7 +283,7 @@ const inspect = async (args, io) => {
260
283
  const runId = requireOnePositional(parsed, "run id");
261
284
  const resolved = await resolveCliStore(parsed);
262
285
  try {
263
- const store = (await loadRuntimeStore(parsed.options.get("runtime-module"), {
286
+ const store = (await loadHostRunStore(parsed.options.get("runtime-module"), {
264
287
  runId,
265
288
  storeDirectory: resolved.baseDirectory,
266
289
  storeDriver: resolved.driver,
@@ -270,7 +293,11 @@ const inspect = async (args, io) => {
270
293
  if (!run)
271
294
  throw new Error(`Run not found: ${runId}`);
272
295
  const checkpoint = await store.loadLatestCheckpoint(runId);
273
- io.stdout(`${JSON.stringify({ run, checkpoint }, null, 2)}\n`);
296
+ // The steps a new run can restart from (agent-runtime restart --from).
297
+ const restartPoints = store.listCheckpoints
298
+ ? await store.listCheckpoints(runId, { boundaries: true })
299
+ : undefined;
300
+ io.stdout(`${JSON.stringify({ run, checkpoint, ...(restartPoints ? { restartPoints } : {}) }, null, 2)}\n`);
274
301
  }
275
302
  finally {
276
303
  resolved.close();
@@ -304,244 +331,6 @@ const events = async (args, io) => {
304
331
  for (const event of selected)
305
332
  io.stdout(`${JSON.stringify(event)}\n`);
306
333
  };
307
- const adapterMethod = (value, name) => value != null &&
308
- typeof value === "object" &&
309
- typeof value[name] === "function";
310
- const validateRuntime = (runtime) => {
311
- if (runtime.shutdown !== undefined && typeof runtime.shutdown !== "function")
312
- throw new Error("Runtime shutdown must be a function.");
313
- if (runtime.runStore &&
314
- (!adapterMethod(runtime.runStore, "createRun") ||
315
- !adapterMethod(runtime.runStore, "loadRun") ||
316
- !adapterMethod(runtime.runStore, "saveCheckpoint"))) {
317
- throw new Error("Runtime runStore must implement the RunStore lifecycle methods.");
318
- }
319
- if (runtime.artifactStore &&
320
- (!adapterMethod(runtime.artifactStore, "put") ||
321
- !adapterMethod(runtime.artifactStore, "get"))) {
322
- throw new Error("Runtime artifactStore must implement ArtifactStore.put() and get().");
323
- }
324
- if (runtime.model && !adapterMethod(runtime.model, "generate"))
325
- throw new Error("Runtime model must implement ModelAdapter.generate().");
326
- if (runtime.tools &&
327
- (!adapterMethod(runtime.tools, "listTools") ||
328
- !adapterMethod(runtime.tools, "executeTool"))) {
329
- throw new Error("Runtime tools must implement ToolAdapter.listTools() and executeTool().");
330
- }
331
- if (runtime.connectionCredentials &&
332
- !adapterMethod(runtime.connectionCredentials, "getCredential")) {
333
- throw new Error("Runtime connectionCredentials must implement ConnectionCredentialProvider.getCredential().");
334
- }
335
- if (runtime.approvals && !adapterMethod(runtime.approvals, "requestApproval"))
336
- throw new Error("Runtime approvals must implement ApprovalAdapter.requestApproval().");
337
- if (runtime.sandbox && !adapterMethod(runtime.sandbox, "execute"))
338
- throw new Error("Runtime sandbox must implement SandboxAdapter.execute().");
339
- if (runtime.subRuns && !adapterMethod(runtime.subRuns, "execute"))
340
- throw new Error("Runtime subRuns must implement SubRunAdapter.execute().");
341
- if (runtime.summarizer && !adapterMethod(runtime.summarizer, "summarize"))
342
- throw new Error("Runtime summarizer must implement ContextSummarizerAdapter.summarize().");
343
- if (runtime.workspaces &&
344
- !adapterMethod(runtime.workspaces, "resolveWorkspace")) {
345
- throw new Error("Runtime workspaces must implement WorkspaceProvider.resolveWorkspace().");
346
- }
347
- if (runtime.runSandbox &&
348
- (!adapterMethod(runtime.runSandbox, "open") ||
349
- !adapterMethod(runtime.runSandbox, "validate") ||
350
- !adapterMethod(runtime.runSandbox, "tools"))) {
351
- throw new Error("Runtime runSandbox must implement RunSandboxProvider.tools(), validate(), and open().");
352
- }
353
- if (runtime.sandboxProvider &&
354
- (!adapterMethod(runtime.sandboxProvider, "create") ||
355
- !adapterMethod(runtime.sandboxProvider, "execute") ||
356
- !adapterMethod(runtime.sandboxProvider, "terminate"))) {
357
- throw new Error("Runtime sandboxProvider must implement the SandboxProvider lifecycle methods.");
358
- }
359
- if (runtime.eventSinks &&
360
- (!Array.isArray(runtime.eventSinks) ||
361
- runtime.eventSinks.some((sink) => !adapterMethod(sink, "emit")))) {
362
- throw new Error("Runtime eventSinks must be an array of EventSink values.");
363
- }
364
- if (runtime.stepExecutors &&
365
- (!Array.isArray(runtime.stepExecutors) ||
366
- runtime.stepExecutors.some((executor) => !executor ||
367
- typeof executor !== "object" ||
368
- typeof executor.type !== "string" ||
369
- !adapterMethod(executor, "execute")))) {
370
- throw new Error("Runtime stepExecutors must implement StepExecutor.");
371
- }
372
- return runtime;
373
- };
374
- const normalizeRuntime = (runtime) => ({
375
- ...(runtime.shutdown ? { shutdown: runtime.shutdown } : {}),
376
- ...((runtime.runStore ?? runtime.store)
377
- ? { runStore: runtime.runStore ?? runtime.store }
378
- : {}),
379
- ...((runtime.artifactStore ?? runtime.artifacts)
380
- ? { artifactStore: runtime.artifactStore ?? runtime.artifacts }
381
- : {}),
382
- ...((runtime.model ?? runtime.modelAdapter)
383
- ? { model: runtime.model ?? runtime.modelAdapter }
384
- : {}),
385
- ...((runtime.tools ?? runtime.toolAdapter)
386
- ? { tools: runtime.tools ?? runtime.toolAdapter }
387
- : {}),
388
- ...((runtime.connectionCredentials ?? runtime.credentialProvider)
389
- ? {
390
- connectionCredentials: runtime.connectionCredentials ?? runtime.credentialProvider,
391
- }
392
- : {}),
393
- ...((runtime.approvals ?? runtime.approvalAdapter)
394
- ? { approvals: runtime.approvals ?? runtime.approvalAdapter }
395
- : {}),
396
- ...((runtime.sandbox ?? runtime.sandboxAdapter)
397
- ? { sandbox: runtime.sandbox ?? runtime.sandboxAdapter }
398
- : {}),
399
- ...((runtime.subRuns ?? runtime.subRunAdapter)
400
- ? { subRuns: runtime.subRuns ?? runtime.subRunAdapter }
401
- : {}),
402
- ...((runtime.workspaces ?? runtime.workspaceProvider)
403
- ? { workspaces: runtime.workspaces ?? runtime.workspaceProvider }
404
- : {}),
405
- ...((runtime.runSandbox ?? runtime.runSandboxProvider)
406
- ? { runSandbox: runtime.runSandbox ?? runtime.runSandboxProvider }
407
- : {}),
408
- ...(runtime.sandboxProvider
409
- ? { sandboxProvider: runtime.sandboxProvider }
410
- : {}),
411
- ...(runtime.policies
412
- ? { policies: executionPoliciesSchema.parse(runtime.policies) }
413
- : {}),
414
- ...(runtime.enforcedPolicies
415
- ? {
416
- enforcedPolicies: executionPoliciesSchema.parse(runtime.enforcedPolicies),
417
- }
418
- : {}),
419
- ...(runtime.summarizer ? { summarizer: runtime.summarizer } : {}),
420
- ...((runtime.eventSinks?.length ?? 0) > 0 || runtime.eventSink
421
- ? {
422
- eventSinks: [
423
- ...(runtime.eventSinks ?? []),
424
- ...(runtime.eventSink ? [runtime.eventSink] : []),
425
- ],
426
- }
427
- : {}),
428
- ...((runtime.stepExecutors?.length ?? 0) > 0 ||
429
- (runtime.executors?.length ?? 0) > 0
430
- ? { stepExecutors: runtime.stepExecutors ?? runtime.executors }
431
- : {}),
432
- });
433
- const defaultStepExecutors = (allowUnsafeWebhooks) => [
434
- new PromptStepExecutor(),
435
- new LoopStepExecutor(),
436
- ...(allowUnsafeWebhooks
437
- ? [new WebhookStepExecutor({ allowUnsafeDestinations: true })]
438
- : []),
439
- new ApprovalStepExecutor(),
440
- new CodeStepExecutor(),
441
- new SubRunStepExecutor(),
442
- ];
443
- const resolveStepExecutors = (runtime, options = {}) => {
444
- const byType = new Map(defaultStepExecutors(options.allowUnsafeWebhooks === true).map((executor) => [executor.type, executor]));
445
- for (const executor of runtime.stepExecutors ?? [])
446
- byType.set(executor.type, executor);
447
- return [...byType.values()];
448
- };
449
- const loadRuntime = async (modulePath, context) => {
450
- if (!modulePath)
451
- return {};
452
- const absolutePath = path.resolve(modulePath);
453
- let imported;
454
- try {
455
- imported = (await import(pathToFileURL(absolutePath).href));
456
- }
457
- catch (error) {
458
- throw new Error(`Could not load runtime module ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`);
459
- }
460
- const staticRuntime = imported.default ?? imported.runtime ?? imported;
461
- const composedRuntime = imported.createRuntime
462
- ? await imported.createRuntime(context)
463
- : normalizeRuntime(staticRuntime);
464
- if (!composedRuntime || typeof composedRuntime !== "object") {
465
- throw new Error(`Runtime module ${absolutePath} did not export a runtime object.`);
466
- }
467
- const runtime = !composedRuntime.runStore && imported.createRunStore
468
- ? { ...composedRuntime, runStore: await imported.createRunStore(context) }
469
- : composedRuntime;
470
- return validateRuntime(runtime);
471
- };
472
- const loadRuntimeStore = async (modulePath, context) => {
473
- if (!modulePath)
474
- return undefined;
475
- const absolutePath = path.resolve(modulePath);
476
- let imported;
477
- try {
478
- imported = (await import(pathToFileURL(absolutePath).href));
479
- }
480
- catch (error) {
481
- throw new Error(`Could not load runtime module ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`);
482
- }
483
- const staticRuntime = imported.default ?? imported.runtime ?? imported;
484
- const store = imported.createRunStore
485
- ? await imported.createRunStore(context)
486
- : (staticRuntime.runStore ?? staticRuntime.store);
487
- if (store &&
488
- (!adapterMethod(store, "createRun") ||
489
- !adapterMethod(store, "loadRun") ||
490
- !adapterMethod(store, "saveCheckpoint"))) {
491
- throw new Error("Runtime runStore must implement the RunStore lifecycle methods.");
492
- }
493
- return store;
494
- };
495
- const defaultConfigNames = [
496
- "agent-runtime.config.yaml",
497
- "agent-runtime.config.yml",
498
- "agent-runtime.config.json",
499
- ];
500
- const resolveConfig = async (requested, searchDirectory = process.cwd()) => {
501
- if (requested)
502
- return loadAgentRuntimeConfig(requested);
503
- for (const candidate of defaultConfigNames) {
504
- const absolute = path.resolve(searchDirectory, candidate);
505
- try {
506
- await access(absolute);
507
- return await loadAgentRuntimeConfig(absolute);
508
- }
509
- catch (error) {
510
- if (error.code !== "ENOENT")
511
- throw error;
512
- }
513
- }
514
- return emptyAgentRuntimeConfig();
515
- };
516
- /** Host-supplied workspace and sandbox adapters take precedence over configuration. */
517
- const workspaceCompositionOptions = (...runtimes) => {
518
- const options = {};
519
- for (const runtime of runtimes) {
520
- if (runtime.workspaces && !options.provider)
521
- options.provider = runtime.workspaces;
522
- if (runtime.runSandbox && !options.runSandbox)
523
- options.runSandbox = runtime.runSandbox;
524
- if (runtime.sandboxProvider && !options.sandboxProvider)
525
- options.sandboxProvider = runtime.sandboxProvider;
526
- }
527
- return options;
528
- };
529
- const mergeRuntimes = (configured, moduleRuntime) => validateRuntime({
530
- ...configured,
531
- ...moduleRuntime,
532
- ...(configured.messages || moduleRuntime.messages
533
- ? { messages: { ...configured.messages, ...moduleRuntime.messages } }
534
- : {}),
535
- ...((configured.eventSinks?.length ?? 0) > 0 ||
536
- (moduleRuntime.eventSinks?.length ?? 0) > 0
537
- ? {
538
- eventSinks: [
539
- ...(configured.eventSinks ?? []),
540
- ...(moduleRuntime.eventSinks ?? []),
541
- ],
542
- }
543
- : {}),
544
- });
545
334
  const sensitiveKey = /(?:authorization|cookie|credential|password|secret|token|api[-_]?key)/iu;
546
335
  const redactValue = (value, key = "") => {
547
336
  if (sensitiveKey.test(key))
@@ -650,8 +439,24 @@ class CliStreamingEventSink {
650
439
  return `✓ run completed (${event.runId})`;
651
440
  case "run.failed":
652
441
  return `✗ run failed (${event.runId})`;
653
- case "run.suspended":
442
+ case "run.suspended": {
443
+ const details = event.data?.details != null &&
444
+ typeof event.data.details === "object" &&
445
+ !Array.isArray(event.data.details)
446
+ ? event.data.details
447
+ : {};
448
+ if (event.data?.kind === "awaiting-host" && details.cause === "limit")
449
+ return `Ⅱ run blocked (${event.runId}): reached ${String(details.limit)} (${String(details.used)} of ${String(details.value)}); grant a higher limit with agent-runtime resume ${event.runId} --limits <file>`;
450
+ if (event.data?.kind === "awaiting-host") {
451
+ const error = details.error != null &&
452
+ typeof details.error === "object" &&
453
+ !Array.isArray(details.error)
454
+ ? details.error
455
+ : {};
456
+ return `Ⅱ run blocked (${event.runId}): ${String(error.code ?? "error")}: ${String(error.message ?? "")}; fix the cause, then agent-runtime resume ${event.runId}`;
457
+ }
654
458
  return `Ⅱ run suspended (${event.runId}): ${String(event.data?.reason ?? "awaiting input")}; resume with agent-runtime resume ${event.runId}`;
459
+ }
655
460
  case "run.interrupted":
656
461
  return `↯ run interrupted (${event.runId}): ${String(event.data?.reason ?? "interrupted")}; resume with agent-runtime resume ${event.runId}`;
657
462
  case "step.failed":
@@ -674,15 +479,28 @@ class CliStreamingEventSink {
674
479
  this.#io.stderr(`${label}\n`);
675
480
  }
676
481
  }
677
- /** The run's message options with the prompt package's history compactor. */
678
- const withHistoryCompactor = (options) => ({
679
- compactor: new PromptMessageHistoryCompactor(),
680
- ...options,
681
- });
682
482
  /**
683
483
  * Read `--messages`: a JSON or YAML array of messages, or `{ messages,
684
484
  * signature }` as written by `--messages-out`.
685
485
  */
486
+ /** Run limits to grant, from a JSON or YAML file (`--limits`). */
487
+ const readLimitsFile = async (file) => {
488
+ const source = await readFile(file, "utf8");
489
+ let value;
490
+ try {
491
+ value = file.endsWith(".json")
492
+ ? JSON.parse(source)
493
+ : parseYamlDocument(source);
494
+ }
495
+ catch (error) {
496
+ throw new Error(`Could not parse run limits ${file}: ${error instanceof Error ? error.message : String(error)}`);
497
+ }
498
+ const parsed = runLimitsSchema.safeParse(value);
499
+ if (!parsed.success) {
500
+ throw new Error(`Run limits in ${file} are invalid: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "limits"}: ${issue.message}`).join("; ")}`);
501
+ }
502
+ return parsed.data;
503
+ };
686
504
  const readMessagesFile = async (file) => {
687
505
  const source = await readFile(file, "utf8");
688
506
  let value;
@@ -720,8 +538,11 @@ const executionOptions = new Set([
720
538
  "format",
721
539
  "show-reasoning",
722
540
  "max-total-tokens",
541
+ "limits",
542
+ "from",
543
+ "list",
723
544
  ]);
724
- const executionFlags = new Set(["stream", "show-reasoning"]);
545
+ const executionFlags = new Set(["stream", "show-reasoning", "list"]);
725
546
  const execute = async (command, args, io, signal) => {
726
547
  const parsed = parseOptions(args, executionOptions, executionFlags);
727
548
  const target = requireOnePositional(parsed, command === "run"
@@ -729,6 +550,14 @@ const execute = async (command, args, io, signal) => {
729
550
  : command === "run-manifest"
730
551
  ? "agent run manifest path"
731
552
  : "run id");
553
+ if (command !== "restart" &&
554
+ (parsed.options.has("from") || parsed.options.has("list"))) {
555
+ throw new Error("--from and --list are only valid with the restart command.");
556
+ }
557
+ if (command === "restart" &&
558
+ (parsed.options.has("variables") || parsed.options.has("messages"))) {
559
+ throw new Error("A restarted run takes its state and history from the step it restarts from; --variables and --messages are not valid with restart.");
560
+ }
732
561
  if (command === "resume" && parsed.options.has("run-id")) {
733
562
  throw new Error("--run-id is only valid with the run command.");
734
563
  }
@@ -747,8 +576,9 @@ const execute = async (command, args, io, signal) => {
747
576
  if (command === "run-manifest" &&
748
577
  (parsed.options.has("variables") ||
749
578
  parsed.options.has("run-id") ||
750
- parsed.options.has("max-total-tokens"))) {
751
- throw new Error("--variables, --run-id, and --max-total-tokens cannot be combined with an agent run manifest; declare them in the agent run manifest.");
579
+ parsed.options.has("max-total-tokens") ||
580
+ parsed.options.has("limits"))) {
581
+ throw new Error("--variables, --run-id, --max-total-tokens, and --limits cannot be combined with an agent run manifest; declare them in the agent run manifest or the agent manifest.");
752
582
  }
753
583
  const agentRunManifestFile = command === "run-manifest" ? path.resolve(target) : undefined;
754
584
  const agentRunManifestSource = agentRunManifestFile
@@ -767,10 +597,11 @@ const execute = async (command, args, io, signal) => {
767
597
  const runId = command === "resume"
768
598
  ? target
769
599
  : (agentRunManifest?.runId ?? parsed.options.get("run-id"));
600
+ const sourceRunId = command === "restart" ? target : undefined;
770
601
  const maxTotalTokens = positiveSafeIntegerOption(parsed, "max-total-tokens");
771
602
  const runtimeModulePath = parsed.options.get("runtime-module");
772
- const runtimeStore = command === "resume"
773
- ? await loadRuntimeStore(runtimeModulePath, {
603
+ const runtimeStore = command === "resume" || command === "restart"
604
+ ? await loadHostRunStore(runtimeModulePath, {
774
605
  runId: target,
775
606
  storeDirectory,
776
607
  storeDriver: resolvedStore.driver,
@@ -782,6 +613,9 @@ const execute = async (command, args, io, signal) => {
782
613
  const variableOverrides = command === "run" && parsed.options.has("variables")
783
614
  ? parseAgentVariableOverrides(JSON.parse(await readFile(path.resolve(parsed.options.get("variables")), "utf8")))
784
615
  : undefined;
616
+ const grantedLimits = parsed.options.has("limits")
617
+ ? await readLimitsFile(path.resolve(parsed.options.get("limits")))
618
+ : undefined;
785
619
  const suppliedMessages = command === "run" && parsed.options.has("messages")
786
620
  ? await readMessagesFile(path.resolve(parsed.options.get("messages")))
787
621
  : undefined;
@@ -804,6 +638,41 @@ const execute = async (command, args, io, signal) => {
804
638
  throw new Error(`Run not found: ${target}`);
805
639
  manifest = record.manifest;
806
640
  }
641
+ // restart: choose the step checkpoint to start the new run from.
642
+ let seed;
643
+ if (sourceRunId) {
644
+ if (!store.listCheckpoints || !store.loadCheckpoint) {
645
+ throw new Error("This run store cannot list checkpoints, so runs cannot be restarted from a step.");
646
+ }
647
+ const points = await store.listCheckpoints(sourceRunId, {
648
+ boundaries: true,
649
+ });
650
+ if (parsed.options.has("list")) {
651
+ io.stdout(points.length === 0
652
+ ? `No restart points for run ${sourceRunId}.\n`
653
+ : `${points
654
+ .map((point) => `${String(point.sequence).padStart(6)} ${point.boundary?.executionKey ?? point.boundary?.stepPath ?? ""} ${point.createdAt}`)
655
+ .join("\n")}\n`);
656
+ return;
657
+ }
658
+ const from = parsed.options.get("from");
659
+ const chosen = from
660
+ ? [...points]
661
+ .reverse()
662
+ .find((point) => point.boundary?.executionKey === from ||
663
+ point.boundary?.stepPath === from ||
664
+ String(point.sequence) === from)
665
+ : points.at(-1);
666
+ if (!chosen) {
667
+ throw new Error(from
668
+ ? `Run ${sourceRunId} has no restart point matching ${from}; list them with agent-runtime restart ${sourceRunId} --list.`
669
+ : `Run ${sourceRunId} has no completed step to restart from.`);
670
+ }
671
+ seed =
672
+ (await store.loadCheckpoint(sourceRunId, chosen.sequence)) ?? undefined;
673
+ if (!seed)
674
+ throw new Error(`Checkpoint ${chosen.sequence} is no longer retained.`);
675
+ }
807
676
  const eventsOption = parsed.options.get("events");
808
677
  const eventFile = eventsOption === "none"
809
678
  ? undefined
@@ -821,21 +690,13 @@ const execute = async (command, args, io, signal) => {
821
690
  ...(eventFile ? { eventFile } : {}),
822
691
  ...(artifactDirectory ? { artifactDirectory } : {}),
823
692
  };
824
- const loadedModuleRuntime = await loadRuntime(runtimeModulePath, context);
693
+ const loadedModuleRuntime = await loadHostRuntime(runtimeModulePath, context);
825
694
  shutdown = loadedModuleRuntime.shutdown;
826
695
  const moduleRuntime = runtimeStore
827
- ? validateRuntime({ ...loadedModuleRuntime, runStore: runtimeStore })
696
+ ? validateHostRuntime({ ...loadedModuleRuntime, runStore: runtimeStore })
828
697
  : loadedModuleRuntime;
829
- const config = await resolveConfig(parsed.options.get("config"), configSearchDirectory);
830
- const configuredRuntime = composeRuntime(manifest, config, {}, {
831
- model: !moduleRuntime.model,
832
- tools: !moduleRuntime.tools,
833
- ...(moduleRuntime.connectionCredentials
834
- ? { connectionCredentials: moduleRuntime.connectionCredentials }
835
- : {}),
836
- workspaceOptions: workspaceCompositionOptions(moduleRuntime),
837
- });
838
- const runtime = mergeRuntimes(configuredRuntime, moduleRuntime);
698
+ const config = await resolveAgentRuntimeConfig(parsed.options.get("config"), configSearchDirectory);
699
+ const runtime = composeHostRuntime(manifest, config, [moduleRuntime]);
839
700
  const jsonlSink = eventFile ? new JsonlEventSink(eventFile) : undefined;
840
701
  const requestedFormat = parsed.options.get("format") ??
841
702
  (parsed.options.has("stream") ? "pretty" : "json");
@@ -847,7 +708,9 @@ const execute = async (command, args, io, signal) => {
847
708
  ? undefined
848
709
  : new CliStreamingEventSink(io, outputFormat, parsed.options.has("show-reasoning"));
849
710
  const warnedSinks = new Set();
850
- const runner = new AgentRuntime({
711
+ const runner = new AgentRuntime(hostRuntimeDependencies(runtime, {
712
+ // The operator runs manifests they chose on their own machine.
713
+ trust: "local-operator",
851
714
  onEventSinkError(_error, _event, sink) {
852
715
  if (warnedSinks.has(sink))
853
716
  return;
@@ -855,35 +718,16 @@ const execute = async (command, args, io, signal) => {
855
718
  io.stderr(`Warning: event delivery failed for ${sink instanceof SafeLocalEventSink ? `local log ${eventFile}` : sink.constructor.name}. Check permissions and available disk space. Execution continues.\n`);
856
719
  },
857
720
  runStore: runtime.runStore ?? store,
858
- ...(agentManifestSource ? { agentManifestSource } : {}),
859
- stepExecutors: resolveStepExecutors(runtime, {
860
- allowUnsafeWebhooks: true,
861
- }),
862
- conditionEvaluator: new JexlConditionEvaluator(),
721
+ agentManifestSource,
863
722
  eventSinks: [
864
723
  ...(jsonlSink ? [new SafeLocalEventSink(jsonlSink)] : []),
865
724
  ...(streamingSink ? [streamingSink] : []),
866
- ...(runtime.eventSinks ?? []),
867
725
  ],
868
- ...(runtime.model ? { model: runtime.model } : {}),
869
- ...(runtime.tools ? { tools: runtime.tools } : {}),
870
- ...(runtime.approvals ? { approvals: runtime.approvals } : {}),
871
- ...(runtime.sandbox ? { sandbox: runtime.sandbox } : {}),
872
- ...(runtime.subRuns ? { subRuns: runtime.subRuns } : {}),
873
- ...(runtime.workspaces ? { workspaces: runtime.workspaces } : {}),
874
- ...(runtime.runSandbox ? { runSandbox: runtime.runSandbox } : {}),
875
- ...(runtime.policies ? { policies: runtime.policies } : {}),
876
- ...(runtime.enforcedPolicies
877
- ? { enforcedPolicies: runtime.enforcedPolicies }
878
- : {}),
879
- ...(runtime.summarizer ? { summarizer: runtime.summarizer } : {}),
880
- messages: withHistoryCompactor(runtime.messages),
881
- ...(runtime.artifactStore
882
- ? { artifacts: runtime.artifactStore }
883
- : artifactDirectory
884
- ? { artifacts: new FileArtifactStore(artifactDirectory) }
885
- : {}),
886
- });
726
+ artifacts: runtime.artifactStore ??
727
+ (artifactDirectory
728
+ ? new FileArtifactStore(artifactDirectory)
729
+ : undefined),
730
+ }));
887
731
  try {
888
732
  const result = await runner.run(command === "run-manifest" && agentRunManifest
889
733
  ? {
@@ -903,6 +747,8 @@ const execute = async (command, args, io, signal) => {
903
747
  : {}),
904
748
  ...(messagesScope != null ? { messagesScope } : {}),
905
749
  ...(maxTotalTokens ? { budget: { maxTotalTokens } } : {}),
750
+ ...(grantedLimits ? { limits: grantedLimits } : {}),
751
+ ...(seed ? { seed } : {}),
906
752
  ...(signal ? { signal } : {}),
907
753
  ...(command === "resume" ? { resume: true } : {}),
908
754
  });
@@ -1027,8 +873,8 @@ export const executeWorkerInvocation = async (invocation, options) => {
1027
873
  throw new Error("Worker request runtimeReference requires a host resolveRuntimeReference callback.");
1028
874
  })()
1029
875
  : undefined;
1030
- const moduleRuntime = await loadRuntime(runtimeReference, context);
1031
- const hostRuntime = validateRuntime(options.runtime ?? {});
876
+ const moduleRuntime = await loadHostRuntime(runtimeReference, context);
877
+ const hostRuntime = validateHostRuntime(options.runtime ?? {});
1032
878
  let requestSuppliedConfiguration = false;
1033
879
  const config = options.configFile
1034
880
  ? await loadAgentRuntimeConfig(options.configFile)
@@ -1045,40 +891,22 @@ export const executeWorkerInvocation = async (invocation, options) => {
1045
891
  : (() => {
1046
892
  throw new Error("Worker request configReference requires a host resolveConfigReference callback.");
1047
893
  })()
1048
- : await resolveConfig(undefined, process.cwd());
894
+ : await resolveAgentRuntimeConfig(undefined, process.cwd());
1049
895
  if (requestSuppliedConfiguration) {
1050
896
  assertSafeInlineWorkerConfiguration(config);
1051
897
  }
1052
- const configuredRuntime = composeRuntime(manifest, config, requestSuppliedConfiguration
1053
- ? { environment: options.environment ?? {} }
1054
- : options.environment
1055
- ? { environment: options.environment }
1056
- : {}, {
1057
- model: !moduleRuntime.model && !hostRuntime.model,
1058
- tools: !moduleRuntime.tools && !hostRuntime.tools,
1059
- workspaceOptions: {
1060
- ...options.workspaceOptions,
1061
- ...workspaceCompositionOptions(hostRuntime, moduleRuntime),
1062
- },
898
+ const runtime = composeHostRuntime(manifest, config, [moduleRuntime, hostRuntime], {
899
+ ...(requestSuppliedConfiguration
900
+ ? { environment: options.environment ?? {} }
901
+ : options.environment
902
+ ? { environment: options.environment }
903
+ : {}),
1063
904
  ...(options.modelPolicy ? { modelPolicy: options.modelPolicy } : {}),
1064
- ...(options.toolOptions ||
1065
- hostRuntime.connectionCredentials ||
1066
- moduleRuntime.connectionCredentials
1067
- ? {
1068
- toolOptions: {
1069
- ...options.toolOptions,
1070
- ...((hostRuntime.connectionCredentials ??
1071
- moduleRuntime.connectionCredentials)
1072
- ? {
1073
- credentialProvider: hostRuntime.connectionCredentials ??
1074
- moduleRuntime.connectionCredentials,
1075
- }
1076
- : {}),
1077
- },
1078
- }
905
+ ...(options.toolOptions ? { toolOptions: options.toolOptions } : {}),
906
+ ...(options.workspaceOptions
907
+ ? { workspaceOptions: options.workspaceOptions }
1079
908
  : {}),
1080
909
  });
1081
- const runtime = mergeRuntimes(mergeRuntimes(configuredRuntime, moduleRuntime), hostRuntime);
1082
910
  const store = runtime.runStore ??
1083
911
  (storeDriver === "sqlite"
1084
912
  ? new (await import("@clearideas/agent-runtime-store-sqlite")).SqliteRunStore(storeLocation)
@@ -1120,37 +948,16 @@ export const executeWorkerInvocation = async (invocation, options) => {
1120
948
  await store.saveCheckpoint(importedCheckpoint);
1121
949
  }
1122
950
  }
1123
- const runner = new AgentRuntime({
951
+ const runner = new AgentRuntime(hostRuntimeDependencies(runtime, {
952
+ // Webhook execution is host-supplied in worker mode so destination
953
+ // policy cannot be bypassed by a remote manifest.
954
+ trust: "untrusted-request",
1124
955
  runStore: store,
1125
- // Webhook execution is host-supplied in worker mode so destination policy
1126
- // cannot be bypassed by a remote manifest.
1127
- stepExecutors: resolveStepExecutors(runtime),
1128
- conditionEvaluator: new JexlConditionEvaluator(),
1129
- eventSinks: [
1130
- new PortableWorkerEventSink(options.onMessage),
1131
- ...(runtime.eventSinks ?? []),
1132
- ],
1133
- ...(runtime.model ? { model: runtime.model } : {}),
1134
- ...(runtime.tools ? { tools: runtime.tools } : {}),
1135
- ...(runtime.approvals ? { approvals: runtime.approvals } : {}),
1136
- ...(runtime.sandbox ? { sandbox: runtime.sandbox } : {}),
1137
- ...(runtime.subRuns ? { subRuns: runtime.subRuns } : {}),
1138
- ...(runtime.workspaces ? { workspaces: runtime.workspaces } : {}),
1139
- ...(runtime.runSandbox ? { runSandbox: runtime.runSandbox } : {}),
1140
- ...(runtime.policies ? { policies: runtime.policies } : {}),
1141
- ...(runtime.enforcedPolicies
1142
- ? { enforcedPolicies: runtime.enforcedPolicies }
1143
- : {}),
1144
- ...(runtime.summarizer ? { summarizer: runtime.summarizer } : {}),
1145
- messages: withHistoryCompactor(runtime.messages),
956
+ eventSinks: [new PortableWorkerEventSink(options.onMessage)],
1146
957
  artifacts,
1147
- ...(options.maxParallelSteps
1148
- ? { maxParallelSteps: options.maxParallelSteps }
1149
- : {}),
1150
- ...(options.eventSinkFailurePolicy
1151
- ? { eventSinkFailurePolicy: options.eventSinkFailurePolicy }
1152
- : {}),
1153
- });
958
+ maxParallelSteps: options.maxParallelSteps,
959
+ eventSinkFailurePolicy: options.eventSinkFailurePolicy,
960
+ }));
1154
961
  return await runner.run({
1155
962
  manifest,
1156
963
  ...(request.runId ? { runId: request.runId } : {}),
@@ -1166,6 +973,7 @@ export const executeWorkerInvocation = async (invocation, options) => {
1166
973
  : {}),
1167
974
  ...(request.execution ? { execution: request.execution } : {}),
1168
975
  ...(request.budget ? { budget: request.budget } : {}),
976
+ ...(request.limits ? { limits: request.limits } : {}),
1169
977
  ...(options.signal ? { signal: options.signal } : {}),
1170
978
  ...(invocation.action === "resume"
1171
979
  ? {
@@ -1242,6 +1050,139 @@ const worker = async (args, io, signal) => {
1242
1050
  return false;
1243
1051
  }
1244
1052
  };
1053
+ const serveOptionNames = new Set([
1054
+ "server-config",
1055
+ "no-server-config",
1056
+ "served-model-name",
1057
+ "config",
1058
+ "runtime-config",
1059
+ "runtime-module",
1060
+ "host",
1061
+ "port",
1062
+ "api-key-env",
1063
+ "allow-unauthenticated",
1064
+ "input",
1065
+ "output",
1066
+ "stream-mode",
1067
+ "progress",
1068
+ "store-driver",
1069
+ "store",
1070
+ "ledger",
1071
+ "on-unrecognized",
1072
+ "client-tools",
1073
+ "max-concurrent-runs",
1074
+ "request-timeout",
1075
+ "warmup",
1076
+ "check",
1077
+ ]);
1078
+ const serveFlags = new Set([
1079
+ "no-server-config",
1080
+ "allow-unauthenticated",
1081
+ "warmup",
1082
+ "check",
1083
+ ]);
1084
+ const INPUT_SOURCES = new Set([
1085
+ "last-user",
1086
+ "transcript",
1087
+ "system",
1088
+ "json",
1089
+ "client",
1090
+ ]);
1091
+ const oneOf = (parsed, name, values) => {
1092
+ const value = parsed.options.get(name);
1093
+ if (value === undefined)
1094
+ return undefined;
1095
+ if (!values.includes(value))
1096
+ throw new Error(`--${name} must be one of ${values.join(", ")}.`);
1097
+ return value;
1098
+ };
1099
+ /** Parse `agent-runtime serve` arguments into server options. */
1100
+ export const parseServeArguments = (args) => {
1101
+ const parsed = parseOptions(args, serveOptionNames, serveFlags, new Set(["input"]));
1102
+ if (parsed.positional.length > 1)
1103
+ throw new Error("Serve one manifest, or use --server-config for several.");
1104
+ if (parsed.options.has("config") && parsed.options.has("runtime-config"))
1105
+ throw new Error("--runtime-config is an alias of --config; use one.");
1106
+ const manifest = parsed.positional[0];
1107
+ const input = {};
1108
+ for (const entry of parsed.repeated.get("input") ?? []) {
1109
+ const separator = entry.indexOf("=");
1110
+ const variable = entry.slice(0, separator);
1111
+ const source = entry.slice(separator + 1);
1112
+ if (separator <= 0 || !INPUT_SOURCES.has(source)) {
1113
+ throw new Error(`--input expects <variable>=<source> with source last-user, transcript, system, json, or client; got ${JSON.stringify(entry)}.`);
1114
+ }
1115
+ if (input[variable])
1116
+ throw new Error(`--input maps ${variable} twice.`);
1117
+ input[variable] = source;
1118
+ }
1119
+ const port = parsed.options.get("port");
1120
+ const portNumber = port === undefined ? undefined : Number(port);
1121
+ if (portNumber !== undefined &&
1122
+ (!Number.isInteger(portNumber) || portNumber < 0 || portNumber > 65_535))
1123
+ throw new Error("--port must be an integer from 0 to 65535.");
1124
+ const runtimeConfig = parsed.options.get("config") ?? parsed.options.get("runtime-config");
1125
+ const streamMode = oneOf(parsed, "stream-mode", [
1126
+ "auto",
1127
+ "live",
1128
+ "committed",
1129
+ ]);
1130
+ const progress = oneOf(parsed, "progress", ["none", "status"]);
1131
+ const storeDriver = oneOf(parsed, "store-driver", [
1132
+ "memory",
1133
+ "sqlite",
1134
+ ]);
1135
+ const onUnrecognized = oneOf(parsed, "on-unrecognized", [
1136
+ "unsigned",
1137
+ "reject",
1138
+ "restart",
1139
+ ]);
1140
+ const clientTools = oneOf(parsed, "client-tools", [
1141
+ "ignore",
1142
+ "reject",
1143
+ ]);
1144
+ const maxConcurrentRuns = positiveSafeIntegerOption(parsed, "max-concurrent-runs");
1145
+ const requestTimeoutMs = positiveSafeIntegerOption(parsed, "request-timeout");
1146
+ if (storeDriver === "sqlite" && !parsed.options.has("store"))
1147
+ throw new Error("--store-driver sqlite requires --store <path>.");
1148
+ const value = (name) => parsed.options.get(name);
1149
+ return {
1150
+ ...(manifest ? { manifest } : {}),
1151
+ ...(value("server-config")
1152
+ ? { serverConfig: value("server-config") }
1153
+ : {}),
1154
+ ...(parsed.options.has("no-server-config") ? { noServerConfig: true } : {}),
1155
+ ...(value("served-model-name")
1156
+ ? { servedModelName: value("served-model-name") }
1157
+ : {}),
1158
+ ...(runtimeConfig ? { runtimeConfig } : {}),
1159
+ ...(value("runtime-module")
1160
+ ? { runtimeModule: value("runtime-module") }
1161
+ : {}),
1162
+ ...(value("host") ? { host: value("host") } : {}),
1163
+ ...(portNumber !== undefined ? { port: portNumber } : {}),
1164
+ ...(value("api-key-env") ? { apiKeyEnv: value("api-key-env") } : {}),
1165
+ ...(parsed.options.has("allow-unauthenticated")
1166
+ ? { allowUnauthenticated: true }
1167
+ : {}),
1168
+ ...(Object.keys(input).length > 0 ? { input } : {}),
1169
+ ...(value("output") ? { output: value("output") } : {}),
1170
+ ...(streamMode ? { streamMode } : {}),
1171
+ ...(progress ? { progress } : {}),
1172
+ ...(storeDriver ? { storeDriver } : {}),
1173
+ ...(value("store") ? { store: value("store") } : {}),
1174
+ ...(value("ledger") ? { ledger: value("ledger") } : {}),
1175
+ ...(onUnrecognized ? { onUnrecognized } : {}),
1176
+ ...(clientTools ? { clientTools } : {}),
1177
+ ...(maxConcurrentRuns ? { maxConcurrentRuns } : {}),
1178
+ ...(requestTimeoutMs ? { requestTimeoutMs } : {}),
1179
+ ...(parsed.options.has("warmup") ? { warmup: true } : {}),
1180
+ ...(parsed.options.has("check") ? { check: true } : {}),
1181
+ };
1182
+ };
1183
+ const serve = async (args, io, signal) => {
1184
+ await runServe(parseServeArguments(args), io, signal);
1185
+ };
1245
1186
  const examples = async (args, io, signal) => {
1246
1187
  const [subcommand, name, ...remaining] = args;
1247
1188
  if (subcommand === "list") {
@@ -1291,11 +1232,14 @@ export const runCli = async (args, io = defaultIo, options = {}) => {
1291
1232
  await examples(commandArgs, io, options.signal);
1292
1233
  else if (command === "run" ||
1293
1234
  command === "run-manifest" ||
1294
- command === "resume") {
1235
+ command === "resume" ||
1236
+ command === "restart") {
1295
1237
  await execute(command, commandArgs, io, options.signal);
1296
1238
  }
1297
1239
  else if (command === "worker")
1298
1240
  return (await worker(commandArgs, io, options.signal)) ? 0 : 1;
1241
+ else if (command === "serve")
1242
+ await serve(commandArgs, io, options.signal);
1299
1243
  else {
1300
1244
  io.stderr(`Unknown command: ${command}\n\n${usage}`);
1301
1245
  return 2;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clearideas/agent-runtime-cli",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Standalone CLI for validating, running, resuming, and inspecting declarative agents.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Clear Ideas Incorporated",
@@ -40,17 +40,13 @@
40
40
  "postpack": "node ../../scripts/cleanup-package-license.mjs"
41
41
  },
42
42
  "dependencies": {
43
- "@clearideas/agent-runtime-condition-jexl": "0.8.0",
44
- "@clearideas/agent-runtime-config": "0.8.0",
45
- "@clearideas/agent-runtime-contracts": "0.8.0",
46
- "@clearideas/agent-runtime-core": "0.8.0",
47
- "@clearideas/agent-runtime-execution": "0.8.0",
48
- "@clearideas/agent-runtime-sandbox": "0.8.0",
49
- "@clearideas/agent-runtime-step-loop": "0.8.0",
50
- "@clearideas/agent-runtime-step-prompt": "0.8.0",
51
- "@clearideas/agent-runtime-step-standard": "0.8.0",
52
- "@clearideas/agent-runtime-store-local": "0.8.0",
53
- "@clearideas/agent-runtime-store-sqlite": "0.8.0",
43
+ "@clearideas/agent-runtime-config": "0.10.0",
44
+ "@clearideas/agent-runtime-contracts": "0.10.0",
45
+ "@clearideas/agent-runtime-core": "0.10.0",
46
+ "@clearideas/agent-runtime-execution": "0.10.0",
47
+ "@clearideas/agent-runtime-server": "0.10.0",
48
+ "@clearideas/agent-runtime-store-local": "0.10.0",
49
+ "@clearideas/agent-runtime-store-sqlite": "0.10.0",
54
50
  "yaml": "^2.9.1"
55
51
  },
56
52
  "devDependencies": {