@clearideas/agent-runtime-cli 0.4.3 → 0.6.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 CHANGED
@@ -15,6 +15,7 @@ The CLI stores run state and events locally by default.
15
15
  ```sh
16
16
  npx agent-runtime validate ./agent.yaml
17
17
  npx agent-runtime config validate ./agent-runtime.config.yaml
18
+ npx agent-runtime connections inspect ./agent-runtime.config.yaml --format yaml
18
19
  npx agent-runtime run ./agent.yaml --config ./agent-runtime.config.yaml --store ./.agent-runtime
19
20
  npx agent-runtime run ./agent.yaml --max-total-tokens 100000 --store ./.agent-runtime
20
21
  npx agent-runtime resume run_123 --max-total-tokens 150000 --store ./.agent-runtime
@@ -47,7 +48,9 @@ The Ollama configuration uses its OpenAI-compatible endpoint at
47
48
  The CLI automatically loads `agent-runtime.config.yaml`, `agent-runtime.config.yml`,
48
49
  or `agent-runtime.config.json` beside the agent manifest.
49
50
  Use `--config` to select another file. The CLI configures built-in providers,
50
- model profiles, and MCP connections without a JavaScript runtime module.
51
+ model profiles, MCP connections, host workspaces, and the run sandbox
52
+ (`sandbox.driver: bubblewrap` or `docker`) without a JavaScript runtime
53
+ module.
51
54
 
52
55
  ```yaml
53
56
  version: "1.0"
@@ -103,6 +106,16 @@ Configuration files contain secret references, not secret values. Native
103
106
  provider drivers use their conventional environment variables by default.
104
107
  An agent cannot elevate a connection beyond the host-configured mode.
105
108
 
109
+ MCP tool descriptions and schemas are supplied by the server and reach the
110
+ model. To pin the definitions you reviewed, run
111
+ `connections inspect <config> --format yaml`, check the printed tools, and
112
+ paste the `toolIntegrity` block into the connection. Discovery then refuses a
113
+ changed or unpinned tool before any model sees it (`onFailure: fail`, the
114
+ default) or drops only that tool (`onFailure: exclude`). The default JSON
115
+ format includes full tool metadata, digests, and `verified`, `mismatch`, or
116
+ `unpinned` status. Use `--connection <name>` for one connection and
117
+ `--runtime-module` to supply `connectionCredentials` for OAuth connections.
118
+
106
119
  ## Local storage and output
107
120
 
108
121
  Runs persist state beneath `.agent-runtime` and events in
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import type { AgentManifest, RunResult } from "@clearideas/agent-runtime-contracts";
2
- import { type ArtifactStore, type ApprovalAdapter, type ConnectionCredentialProvider, type EventSink, type ModelAdapter, type RunStore, type SandboxAdapter, type StepExecutor, type SubRunAdapter, type ToolAdapter } from "@clearideas/agent-runtime-core";
2
+ import { type ArtifactStore, type ApprovalAdapter, type ConnectionCredentialProvider, type EventSink, type ModelAdapter, type RunSandboxProvider, type RunStore, type SandboxAdapter, type StepExecutor, type SubRunAdapter, type ToolAdapter, type WorkspaceProvider } from "@clearideas/agent-runtime-core";
3
+ import type { SandboxProvider } from "@clearideas/agent-runtime-sandbox";
3
4
  import { type ExecutionRequest, type WorkerInvocation, type WorkerMessage } from "@clearideas/agent-runtime-execution";
4
- import { type AgentRuntimeConfig, type ConfiguredMcpToolAdapterOptions, type ModelAuthorizationPolicy } from "@clearideas/agent-runtime-config";
5
+ import { type AgentRuntimeConfig, type ConfiguredMcpToolAdapterOptions, type ModelAuthorizationPolicy, type WorkspaceCompositionOptions } from "@clearideas/agent-runtime-config";
5
6
  export interface CliIo {
6
7
  stdout: (text: string) => void;
7
8
  stderr: (text: string) => void;
@@ -9,6 +10,8 @@ export interface CliIo {
9
10
  export type CliStoreDriver = "file" | "sqlite";
10
11
  /** Adapters a local runtime module may contribute to CLI execution. */
11
12
  export interface CliRuntime {
13
+ /** Called once after execution, including failed setup. Own only module-created resources. */
14
+ shutdown?: () => void | Promise<void>;
12
15
  runStore?: RunStore;
13
16
  artifactStore?: ArtifactStore;
14
17
  model?: ModelAdapter;
@@ -17,6 +20,12 @@ export interface CliRuntime {
17
20
  approvals?: ApprovalAdapter;
18
21
  sandbox?: SandboxAdapter;
19
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;
20
29
  eventSinks?: EventSink[];
21
30
  stepExecutors?: StepExecutor[];
22
31
  }
@@ -39,6 +48,8 @@ export interface CliRuntimeModule extends CliRuntime {
39
48
  approvalAdapter?: ApprovalAdapter;
40
49
  sandboxAdapter?: SandboxAdapter;
41
50
  subRunAdapter?: SubRunAdapter;
51
+ workspaceProvider?: WorkspaceProvider;
52
+ runSandboxProvider?: RunSandboxProvider;
42
53
  eventSink?: EventSink;
43
54
  executors?: StepExecutor[];
44
55
  }
@@ -73,6 +84,8 @@ export interface PortableWorkerOptions {
73
84
  modelPolicy?: ModelAuthorizationPolicy;
74
85
  /** Host policy and credentials applied to configured MCP adapters. */
75
86
  toolOptions?: ConfiguredMcpToolAdapterOptions;
87
+ /** Host policy, hooks, and providers applied to configured workspaces and the run sandbox. */
88
+ workspaceOptions?: WorkspaceCompositionOptions;
76
89
  /** Host-supplied adapters for embedded workers such as managed compute runtimes. */
77
90
  runtime?: CliRuntime;
78
91
  eventSinkFailurePolicy?: "continue" | "fail-run";
package/dist/index.js CHANGED
@@ -5,11 +5,12 @@ import { JexlConditionEvaluator } from "@clearideas/agent-runtime-condition-jexl
5
5
  import { parseAgentVariableOverrides } from "@clearideas/agent-runtime-contracts";
6
6
  import { AgentRuntime, } from "@clearideas/agent-runtime-core";
7
7
  import { EXECUTION_PROTOCOL_VERSION, parseWorkerInvocation, serializeWorkerMessage, } from "@clearideas/agent-runtime-execution";
8
- import { composeRuntime, emptyAgentRuntimeConfig, loadAgentRuntimeConfig, parseAgentRuntimeConfig, validateRuntimeConfiguration, } from "@clearideas/agent-runtime-config";
8
+ import { composeRuntime, discoverMcpConnectionTools, emptyAgentRuntimeConfig, loadAgentRuntimeConfig, parseAgentRuntimeConfig, validateRuntimeConfiguration, } from "@clearideas/agent-runtime-config";
9
9
  import { LoopStepExecutor } from "@clearideas/agent-runtime-step-loop";
10
10
  import { PromptStepExecutor } from "@clearideas/agent-runtime-step-prompt";
11
11
  import { ApprovalStepExecutor, CodeStepExecutor, SubRunStepExecutor, WebhookStepExecutor, } from "@clearideas/agent-runtime-step-standard";
12
12
  import { FileArtifactStore, FileAgentManifestSource, FileAgentRunManifestSource, FileRunStore, JsonlEventSink, } from "@clearideas/agent-runtime-store-local";
13
+ import { Document as YamlDocument, YAMLMap, isPair, isScalar } from "yaml";
13
14
  const defaultIo = {
14
15
  stdout: (text) => process.stdout.write(text),
15
16
  stderr: (text) => process.stderr.write(text),
@@ -19,6 +20,7 @@ const usage = `Clear Ideas Agent Runtime
19
20
  Usage:
20
21
  agent-runtime validate <manifest.json|manifest.yaml> [--config <config.yaml>]
21
22
  agent-runtime config validate <config.json|config.yaml>
23
+ agent-runtime connections inspect <config.json|config.yaml> [--connection <name>] [--runtime-module <local-js-file>] [--format <json|yaml>]
22
24
  agent-runtime run <manifest.json|manifest.yaml> [--variables <overrides.json>] [--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]
23
25
  agent-runtime run-manifest <run.json|run.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
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]
@@ -67,11 +69,16 @@ const resolveCliStoreLocation = (parsed, workerMode = false) => {
67
69
  };
68
70
  const resolveCliStore = async (parsed) => {
69
71
  const resolved = resolveCliStoreLocation(parsed);
72
+ const store = resolved.driver === "sqlite"
73
+ ? new (await import("@clearideas/agent-runtime-store-sqlite")).SqliteRunStore(resolved.location)
74
+ : new FileRunStore(resolved.location);
70
75
  return {
71
76
  ...resolved,
72
- store: resolved.driver === "sqlite"
73
- ? new (await import("@clearideas/agent-runtime-store-sqlite")).SqliteRunStore(resolved.location)
74
- : new FileRunStore(resolved.location),
77
+ store,
78
+ close: () => {
79
+ if ("close" in store)
80
+ store.close();
81
+ },
75
82
  };
76
83
  };
77
84
  const parseOptions = (args, allowed, flags = new Set()) => {
@@ -144,23 +151,130 @@ const validateConfig = async (args, io) => {
144
151
  providerCount: Object.keys(config.providers).length,
145
152
  modelCount: Object.keys(config.models).length,
146
153
  connectionCount: Object.keys(config.connections).length,
154
+ workspaceCount: Object.keys(config.workspaces ?? {}).length,
155
+ ...(config.sandbox ? { sandbox: config.sandbox.driver } : {}),
156
+ }, null, 2)}\n`);
157
+ };
158
+ const firstLine = (value) => value?.split(/\r?\n/u)[0]?.trim().slice(0, 100);
159
+ /** Renders a paste-ready toolIntegrity block with tool descriptions as comments. */
160
+ const toolIntegrityYaml = (discovered) => {
161
+ const document = new YamlDocument({
162
+ connections: Object.fromEntries(Object.entries(discovered).map(([name, tools]) => [
163
+ name,
164
+ {
165
+ toolIntegrity: {
166
+ digests: Object.fromEntries(tools
167
+ .filter((tool) => tool.allowed)
168
+ .map((tool) => [tool.name, tool.digest])),
169
+ },
170
+ },
171
+ ])),
172
+ });
173
+ for (const [name, tools] of Object.entries(discovered)) {
174
+ const digests = document.getIn([
175
+ "connections",
176
+ name,
177
+ "toolIntegrity",
178
+ "digests",
179
+ ]);
180
+ if (!(digests instanceof YAMLMap))
181
+ continue;
182
+ for (const item of digests.items) {
183
+ if (!isPair(item))
184
+ continue;
185
+ const key = item.key;
186
+ if (!isScalar(key))
187
+ continue;
188
+ const tool = tools.find((candidate) => candidate.name === key.value);
189
+ const summary = firstLine(tool?.description ?? tool?.title);
190
+ if (summary)
191
+ key.commentBefore = ` ${summary}`;
192
+ }
193
+ }
194
+ return document.toString({ lineWidth: 0 });
195
+ };
196
+ const inspectConnections = async (args, io) => {
197
+ const [subcommand, ...subcommandArgs] = args;
198
+ if (subcommand !== "inspect")
199
+ throw new Error("Expected connections inspect <Agent Runtime config path>.");
200
+ const parsed = parseOptions(subcommandArgs, new Set(["connection", "runtime-module", "format"]));
201
+ const file = path.resolve(requireOnePositional(parsed, "Agent Runtime config path"));
202
+ const format = parsed.options.get("format") ?? "json";
203
+ if (format !== "json" && format !== "yaml")
204
+ throw new Error("--format must be json or yaml.");
205
+ const config = await loadAgentRuntimeConfig(file);
206
+ const requested = parsed.options.get("connection");
207
+ const names = requested ? [requested] : Object.keys(config.connections);
208
+ for (const name of names) {
209
+ if (!config.connections[name])
210
+ throw new Error(`Unknown connection "${name}".`);
211
+ }
212
+ const runtimeModulePath = parsed.options.get("runtime-module");
213
+ const moduleRuntime = await loadRuntime(runtimeModulePath, {
214
+ manifest: {
215
+ schemaVersion: "1.0",
216
+ connections: names.map((ref) => ({ ref })),
217
+ steps: [],
218
+ },
219
+ storeDirectory: resolveCliStoreLocation(parsed).baseDirectory,
220
+ });
221
+ let shutdownError;
222
+ const discovered = {};
223
+ try {
224
+ for (const name of names) {
225
+ discovered[name] = await discoverMcpConnectionTools(config, name, {}, moduleRuntime.connectionCredentials
226
+ ? { credentialProvider: moduleRuntime.connectionCredentials }
227
+ : {});
228
+ }
229
+ }
230
+ finally {
231
+ try {
232
+ await moduleRuntime.shutdown?.();
233
+ }
234
+ catch (error) {
235
+ shutdownError = error;
236
+ }
237
+ }
238
+ if (shutdownError)
239
+ throw shutdownError;
240
+ if (format === "yaml") {
241
+ io.stdout(toolIntegrityYaml(discovered));
242
+ return;
243
+ }
244
+ io.stdout(`${JSON.stringify({
245
+ connections: Object.fromEntries(Object.entries(discovered).map(([name, tools]) => [
246
+ name,
247
+ {
248
+ tools,
249
+ toolIntegrity: {
250
+ digests: Object.fromEntries(tools
251
+ .filter((tool) => tool.allowed)
252
+ .map((tool) => [tool.name, tool.digest])),
253
+ },
254
+ },
255
+ ])),
147
256
  }, null, 2)}\n`);
148
257
  };
149
258
  const inspect = async (args, io) => {
150
259
  const parsed = parseOptions(args, new Set(["store", "store-driver", "runtime-module"]));
151
260
  const runId = requireOnePositional(parsed, "run id");
152
261
  const resolved = await resolveCliStore(parsed);
153
- const store = (await loadRuntimeStore(parsed.options.get("runtime-module"), {
154
- runId,
155
- storeDirectory: resolved.baseDirectory,
156
- storeDriver: resolved.driver,
157
- storeLocation: resolved.location,
158
- })) ?? resolved.store;
159
- const run = await store.loadRun(runId);
160
- if (!run)
161
- throw new Error(`Run not found: ${runId}`);
162
- const checkpoint = await store.loadLatestCheckpoint(runId);
163
- io.stdout(`${JSON.stringify({ run, checkpoint }, null, 2)}\n`);
262
+ try {
263
+ const store = (await loadRuntimeStore(parsed.options.get("runtime-module"), {
264
+ runId,
265
+ storeDirectory: resolved.baseDirectory,
266
+ storeDriver: resolved.driver,
267
+ storeLocation: resolved.location,
268
+ })) ?? resolved.store;
269
+ const run = await store.loadRun(runId);
270
+ if (!run)
271
+ throw new Error(`Run not found: ${runId}`);
272
+ const checkpoint = await store.loadLatestCheckpoint(runId);
273
+ io.stdout(`${JSON.stringify({ run, checkpoint }, null, 2)}\n`);
274
+ }
275
+ finally {
276
+ resolved.close();
277
+ }
164
278
  };
165
279
  const events = async (args, io) => {
166
280
  const parsed = parseOptions(args, new Set(["run", "type", "tail"]));
@@ -194,6 +308,8 @@ const adapterMethod = (value, name) => value != null &&
194
308
  typeof value === "object" &&
195
309
  typeof value[name] === "function";
196
310
  const validateRuntime = (runtime) => {
311
+ if (runtime.shutdown !== undefined && typeof runtime.shutdown !== "function")
312
+ throw new Error("Runtime shutdown must be a function.");
197
313
  if (runtime.runStore &&
198
314
  (!adapterMethod(runtime.runStore, "createRun") ||
199
315
  !adapterMethod(runtime.runStore, "loadRun") ||
@@ -222,6 +338,22 @@ const validateRuntime = (runtime) => {
222
338
  throw new Error("Runtime sandbox must implement SandboxAdapter.execute().");
223
339
  if (runtime.subRuns && !adapterMethod(runtime.subRuns, "execute"))
224
340
  throw new Error("Runtime subRuns must implement SubRunAdapter.execute().");
341
+ if (runtime.workspaces &&
342
+ !adapterMethod(runtime.workspaces, "resolveWorkspace")) {
343
+ throw new Error("Runtime workspaces must implement WorkspaceProvider.resolveWorkspace().");
344
+ }
345
+ if (runtime.runSandbox &&
346
+ (!adapterMethod(runtime.runSandbox, "open") ||
347
+ !adapterMethod(runtime.runSandbox, "validate") ||
348
+ !adapterMethod(runtime.runSandbox, "tools"))) {
349
+ throw new Error("Runtime runSandbox must implement RunSandboxProvider.tools(), validate(), and open().");
350
+ }
351
+ if (runtime.sandboxProvider &&
352
+ (!adapterMethod(runtime.sandboxProvider, "create") ||
353
+ !adapterMethod(runtime.sandboxProvider, "execute") ||
354
+ !adapterMethod(runtime.sandboxProvider, "terminate"))) {
355
+ throw new Error("Runtime sandboxProvider must implement the SandboxProvider lifecycle methods.");
356
+ }
225
357
  if (runtime.eventSinks &&
226
358
  (!Array.isArray(runtime.eventSinks) ||
227
359
  runtime.eventSinks.some((sink) => !adapterMethod(sink, "emit")))) {
@@ -238,6 +370,7 @@ const validateRuntime = (runtime) => {
238
370
  return runtime;
239
371
  };
240
372
  const normalizeRuntime = (runtime) => ({
373
+ ...(runtime.shutdown ? { shutdown: runtime.shutdown } : {}),
241
374
  ...((runtime.runStore ?? runtime.store)
242
375
  ? { runStore: runtime.runStore ?? runtime.store }
243
376
  : {}),
@@ -264,6 +397,15 @@ const normalizeRuntime = (runtime) => ({
264
397
  ...((runtime.subRuns ?? runtime.subRunAdapter)
265
398
  ? { subRuns: runtime.subRuns ?? runtime.subRunAdapter }
266
399
  : {}),
400
+ ...((runtime.workspaces ?? runtime.workspaceProvider)
401
+ ? { workspaces: runtime.workspaces ?? runtime.workspaceProvider }
402
+ : {}),
403
+ ...((runtime.runSandbox ?? runtime.runSandboxProvider)
404
+ ? { runSandbox: runtime.runSandbox ?? runtime.runSandboxProvider }
405
+ : {}),
406
+ ...(runtime.sandboxProvider
407
+ ? { sandboxProvider: runtime.sandboxProvider }
408
+ : {}),
267
409
  ...((runtime.eventSinks?.length ?? 0) > 0 || runtime.eventSink
268
410
  ? {
269
411
  eventSinks: [
@@ -360,6 +502,19 @@ const resolveConfig = async (requested, searchDirectory = process.cwd()) => {
360
502
  }
361
503
  return emptyAgentRuntimeConfig();
362
504
  };
505
+ /** Host-supplied workspace and sandbox adapters take precedence over configuration. */
506
+ const workspaceCompositionOptions = (...runtimes) => {
507
+ const options = {};
508
+ for (const runtime of runtimes) {
509
+ if (runtime.workspaces && !options.provider)
510
+ options.provider = runtime.workspaces;
511
+ if (runtime.runSandbox && !options.runSandbox)
512
+ options.runSandbox = runtime.runSandbox;
513
+ if (runtime.sandboxProvider && !options.sandboxProvider)
514
+ options.sandboxProvider = runtime.sandboxProvider;
515
+ }
516
+ return options;
517
+ };
363
518
  const mergeRuntimes = (configured, moduleRuntime) => validateRuntime({
364
519
  ...configured,
365
520
  ...moduleRuntime,
@@ -481,6 +636,10 @@ class CliStreamingEventSink {
481
636
  return `✓ run completed (${event.runId})`;
482
637
  case "run.failed":
483
638
  return `✗ run failed (${event.runId})`;
639
+ case "run.suspended":
640
+ return `Ⅱ run suspended (${event.runId}): ${String(event.data?.reason ?? "awaiting input")}; resume with agent-runtime resume ${event.runId}`;
641
+ case "webhook.retry.scheduled":
642
+ return ` webhook retry: ${String(event.data?.reason ?? "transient failure")}, waiting ${String(event.data?.delayMs ?? "unknown")}ms`;
484
643
  case "run.cancelled":
485
644
  return `■ run cancelled (${event.runId})`;
486
645
  default:
@@ -536,145 +695,175 @@ const execute = async (command, args, io, signal) => {
536
695
  ? new FileAgentManifestSource(path.dirname(agentRunManifestFile))
537
696
  : undefined;
538
697
  const resolvedStore = await resolveCliStore(parsed);
539
- const storeDirectory = resolvedStore.baseDirectory;
540
- const runId = command === "resume"
541
- ? target
542
- : (agentRunManifest?.runId ?? parsed.options.get("run-id"));
543
- const maxTotalTokens = positiveSafeIntegerOption(parsed, "max-total-tokens");
544
- const runtimeModulePath = parsed.options.get("runtime-module");
545
- const runtimeStore = command === "resume"
546
- ? await loadRuntimeStore(runtimeModulePath, {
547
- runId: target,
698
+ let shutdown;
699
+ try {
700
+ const storeDirectory = resolvedStore.baseDirectory;
701
+ const runId = command === "resume"
702
+ ? target
703
+ : (agentRunManifest?.runId ?? parsed.options.get("run-id"));
704
+ const maxTotalTokens = positiveSafeIntegerOption(parsed, "max-total-tokens");
705
+ const runtimeModulePath = parsed.options.get("runtime-module");
706
+ const runtimeStore = command === "resume"
707
+ ? await loadRuntimeStore(runtimeModulePath, {
708
+ runId: target,
709
+ storeDirectory,
710
+ storeDriver: resolvedStore.driver,
711
+ storeLocation: resolvedStore.location,
712
+ })
713
+ : undefined;
714
+ const store = runtimeStore ?? resolvedStore.store;
715
+ let manifest;
716
+ const variableOverrides = command === "run" && parsed.options.has("variables")
717
+ ? parseAgentVariableOverrides(JSON.parse(await readFile(path.resolve(parsed.options.get("variables")), "utf8")))
718
+ : undefined;
719
+ let configSearchDirectory = process.cwd();
720
+ if (command === "run") {
721
+ const manifestFile = path.resolve(target);
722
+ configSearchDirectory = path.dirname(manifestFile);
723
+ manifest = await new FileAgentManifestSource(path.dirname(manifestFile), path.basename(manifestFile)).loadManifest();
724
+ }
725
+ else if (command === "run-manifest" &&
726
+ agentRunManifest &&
727
+ agentManifestSource) {
728
+ configSearchDirectory = path.dirname(agentRunManifestFile);
729
+ manifest = await agentManifestSource.loadManifest(agentRunManifest.agent.ref);
730
+ }
731
+ else {
732
+ const record = await store.loadRun(target);
733
+ if (!record)
734
+ throw new Error(`Run not found: ${target}`);
735
+ manifest = record.manifest;
736
+ }
737
+ const eventsOption = parsed.options.get("events");
738
+ const eventFile = eventsOption === "none"
739
+ ? undefined
740
+ : path.resolve(eventsOption ?? path.join(storeDirectory, "events.jsonl"));
741
+ const artifactsOption = parsed.options.get("artifacts");
742
+ const artifactDirectory = artifactsOption === "none"
743
+ ? undefined
744
+ : path.resolve(artifactsOption ?? storeDirectory);
745
+ const context = {
746
+ manifest,
747
+ ...(runId ? { runId } : {}),
548
748
  storeDirectory,
549
749
  storeDriver: resolvedStore.driver,
550
750
  storeLocation: resolvedStore.location,
551
- })
552
- : undefined;
553
- const store = runtimeStore ?? resolvedStore.store;
554
- let manifest;
555
- const variableOverrides = command === "run" && parsed.options.has("variables")
556
- ? parseAgentVariableOverrides(JSON.parse(await readFile(path.resolve(parsed.options.get("variables")), "utf8")))
557
- : undefined;
558
- let configSearchDirectory = process.cwd();
559
- if (command === "run") {
560
- const manifestFile = path.resolve(target);
561
- configSearchDirectory = path.dirname(manifestFile);
562
- manifest = await new FileAgentManifestSource(path.dirname(manifestFile), path.basename(manifestFile)).loadManifest();
563
- }
564
- else if (command === "run-manifest" &&
565
- agentRunManifest &&
566
- agentManifestSource) {
567
- configSearchDirectory = path.dirname(agentRunManifestFile);
568
- manifest = await agentManifestSource.loadManifest(agentRunManifest.agent.ref);
569
- }
570
- else {
571
- const record = await store.loadRun(target);
572
- if (!record)
573
- throw new Error(`Run not found: ${target}`);
574
- manifest = record.manifest;
575
- }
576
- const eventsOption = parsed.options.get("events");
577
- const eventFile = eventsOption === "none"
578
- ? undefined
579
- : path.resolve(eventsOption ?? path.join(storeDirectory, "events.jsonl"));
580
- const artifactsOption = parsed.options.get("artifacts");
581
- const artifactDirectory = artifactsOption === "none"
582
- ? undefined
583
- : path.resolve(artifactsOption ?? storeDirectory);
584
- const context = {
585
- manifest,
586
- ...(runId ? { runId } : {}),
587
- storeDirectory,
588
- storeDriver: resolvedStore.driver,
589
- storeLocation: resolvedStore.location,
590
- ...(eventFile ? { eventFile } : {}),
591
- ...(artifactDirectory ? { artifactDirectory } : {}),
592
- };
593
- const loadedModuleRuntime = await loadRuntime(runtimeModulePath, context);
594
- const moduleRuntime = runtimeStore
595
- ? validateRuntime({ ...loadedModuleRuntime, runStore: runtimeStore })
596
- : loadedModuleRuntime;
597
- const config = await resolveConfig(parsed.options.get("config"), configSearchDirectory);
598
- const configuredRuntime = composeRuntime(manifest, config, {}, {
599
- model: !moduleRuntime.model,
600
- tools: !moduleRuntime.tools,
601
- ...(moduleRuntime.connectionCredentials
602
- ? { connectionCredentials: moduleRuntime.connectionCredentials }
603
- : {}),
604
- });
605
- const runtime = mergeRuntimes(configuredRuntime, moduleRuntime);
606
- const jsonlSink = eventFile ? new JsonlEventSink(eventFile) : undefined;
607
- const requestedFormat = parsed.options.get("format") ??
608
- (parsed.options.has("stream") ? "pretty" : "json");
609
- if (!["json", "pretty", "ndjson"].includes(requestedFormat)) {
610
- throw new Error("--format must be json, pretty, or ndjson.");
611
- }
612
- const outputFormat = requestedFormat;
613
- const streamingSink = outputFormat === "json"
614
- ? undefined
615
- : new CliStreamingEventSink(io, outputFormat, parsed.options.has("show-reasoning"));
616
- const runner = new AgentRuntime({
617
- runStore: runtime.runStore ?? store,
618
- ...(agentManifestSource ? { agentManifestSource } : {}),
619
- stepExecutors: resolveStepExecutors(runtime, { allowUnsafeWebhooks: true }),
620
- conditionEvaluator: new JexlConditionEvaluator(),
621
- eventSinks: [
622
- ...(jsonlSink ? [new SafeLocalEventSink(jsonlSink)] : []),
623
- ...(streamingSink ? [streamingSink] : []),
624
- ...(runtime.eventSinks ?? []),
625
- ],
626
- ...(runtime.model ? { model: runtime.model } : {}),
627
- ...(runtime.tools ? { tools: runtime.tools } : {}),
628
- ...(runtime.approvals ? { approvals: runtime.approvals } : {}),
629
- ...(runtime.sandbox ? { sandbox: runtime.sandbox } : {}),
630
- ...(runtime.subRuns ? { subRuns: runtime.subRuns } : {}),
631
- ...(runtime.artifactStore
632
- ? { artifacts: runtime.artifactStore }
633
- : artifactDirectory
634
- ? { artifacts: new FileArtifactStore(artifactDirectory) }
751
+ ...(eventFile ? { eventFile } : {}),
752
+ ...(artifactDirectory ? { artifactDirectory } : {}),
753
+ };
754
+ const loadedModuleRuntime = await loadRuntime(runtimeModulePath, context);
755
+ shutdown = loadedModuleRuntime.shutdown;
756
+ const moduleRuntime = runtimeStore
757
+ ? validateRuntime({ ...loadedModuleRuntime, runStore: runtimeStore })
758
+ : loadedModuleRuntime;
759
+ const config = await resolveConfig(parsed.options.get("config"), configSearchDirectory);
760
+ const configuredRuntime = composeRuntime(manifest, config, {}, {
761
+ model: !moduleRuntime.model,
762
+ tools: !moduleRuntime.tools,
763
+ ...(moduleRuntime.connectionCredentials
764
+ ? { connectionCredentials: moduleRuntime.connectionCredentials }
635
765
  : {}),
636
- });
637
- try {
638
- const result = await runner.run(command === "run-manifest" && agentRunManifest
639
- ? {
640
- agentRunManifest,
641
- ...(signal ? { signal } : {}),
766
+ workspaceOptions: workspaceCompositionOptions(moduleRuntime),
767
+ });
768
+ const runtime = mergeRuntimes(configuredRuntime, moduleRuntime);
769
+ const jsonlSink = eventFile ? new JsonlEventSink(eventFile) : undefined;
770
+ const requestedFormat = parsed.options.get("format") ??
771
+ (parsed.options.has("stream") ? "pretty" : "json");
772
+ if (!["json", "pretty", "ndjson"].includes(requestedFormat)) {
773
+ throw new Error("--format must be json, pretty, or ndjson.");
774
+ }
775
+ const outputFormat = requestedFormat;
776
+ const streamingSink = outputFormat === "json"
777
+ ? undefined
778
+ : new CliStreamingEventSink(io, outputFormat, parsed.options.has("show-reasoning"));
779
+ const warnedSinks = new Set();
780
+ const runner = new AgentRuntime({
781
+ onEventSinkError(_error, _event, sink) {
782
+ if (warnedSinks.has(sink))
783
+ return;
784
+ warnedSinks.add(sink);
785
+ 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`);
786
+ },
787
+ runStore: runtime.runStore ?? store,
788
+ ...(agentManifestSource ? { agentManifestSource } : {}),
789
+ stepExecutors: resolveStepExecutors(runtime, {
790
+ allowUnsafeWebhooks: true,
791
+ }),
792
+ conditionEvaluator: new JexlConditionEvaluator(),
793
+ eventSinks: [
794
+ ...(jsonlSink ? [new SafeLocalEventSink(jsonlSink)] : []),
795
+ ...(streamingSink ? [streamingSink] : []),
796
+ ...(runtime.eventSinks ?? []),
797
+ ],
798
+ ...(runtime.model ? { model: runtime.model } : {}),
799
+ ...(runtime.tools ? { tools: runtime.tools } : {}),
800
+ ...(runtime.approvals ? { approvals: runtime.approvals } : {}),
801
+ ...(runtime.sandbox ? { sandbox: runtime.sandbox } : {}),
802
+ ...(runtime.subRuns ? { subRuns: runtime.subRuns } : {}),
803
+ ...(runtime.workspaces ? { workspaces: runtime.workspaces } : {}),
804
+ ...(runtime.runSandbox ? { runSandbox: runtime.runSandbox } : {}),
805
+ ...(runtime.artifactStore
806
+ ? { artifacts: runtime.artifactStore }
807
+ : artifactDirectory
808
+ ? { artifacts: new FileArtifactStore(artifactDirectory) }
809
+ : {}),
810
+ });
811
+ try {
812
+ const result = await runner.run(command === "run-manifest" && agentRunManifest
813
+ ? {
814
+ agentRunManifest,
815
+ ...(signal ? { signal } : {}),
816
+ }
817
+ : {
818
+ manifest,
819
+ ...(runId ? { runId } : {}),
820
+ ...(variableOverrides ? { variables: variableOverrides } : {}),
821
+ ...(maxTotalTokens ? { budget: { maxTotalTokens } } : {}),
822
+ ...(signal ? { signal } : {}),
823
+ ...(command === "resume" ? { resume: true } : {}),
824
+ });
825
+ // Deliberately exclude variables, transcript and model output. They may
826
+ // contain secrets; inspect is an explicit command for persisted details.
827
+ if (outputFormat === "ndjson") {
828
+ io.stdout(`${JSON.stringify({
829
+ type: "result",
830
+ result,
831
+ })}\n`);
832
+ }
833
+ else if (outputFormat === "pretty") {
834
+ if (streamingSink?.streamedText)
835
+ io.stdout("\n");
836
+ else if (result.output !== undefined) {
837
+ io.stdout(`${typeof result.output === "string" ? result.output : JSON.stringify(result.output, null, 2)}\n`);
838
+ }
839
+ io.stderr(`run ${result.runId}: ${result.stepResults.length} step(s), ${result.artifacts.length} artifact(s)\n`);
642
840
  }
643
- : {
644
- manifest,
645
- ...(runId ? { runId } : {}),
646
- ...(variableOverrides ? { variables: variableOverrides } : {}),
647
- ...(maxTotalTokens ? { budget: { maxTotalTokens } } : {}),
648
- ...(signal ? { signal } : {}),
649
- ...(command === "resume" ? { resume: true } : {}),
650
- });
651
- // Deliberately exclude variables, transcript and model output. They may
652
- // contain secrets; inspect is an explicit command for persisted details.
653
- if (outputFormat === "ndjson") {
654
- io.stdout(`${JSON.stringify({
655
- type: "result",
656
- result,
657
- })}\n`);
658
- }
659
- else if (outputFormat === "pretty") {
660
- if (streamingSink?.streamedText)
661
- io.stdout("\n");
662
- else if (result.output !== undefined) {
663
- io.stdout(`${typeof result.output === "string" ? result.output : JSON.stringify(result.output, null, 2)}\n`);
841
+ else {
842
+ io.stdout(`${JSON.stringify({
843
+ runId: result.runId,
844
+ status: "completed",
845
+ stepCount: result.stepResults.length,
846
+ artifactCount: result.artifacts.length,
847
+ }, null, 2)}\n`);
664
848
  }
665
- io.stderr(`run ${result.runId}: ${result.stepResults.length} step(s), ${result.artifacts.length} artifact(s)\n`);
666
849
  }
667
- else {
668
- io.stdout(`${JSON.stringify({
669
- runId: result.runId,
670
- status: "completed",
671
- stepCount: result.stepResults.length,
672
- artifactCount: result.artifacts.length,
673
- }, null, 2)}\n`);
850
+ finally {
851
+ await jsonlSink?.flush();
674
852
  }
675
853
  }
676
854
  finally {
677
- await jsonlSink?.flush();
855
+ try {
856
+ await shutdown?.();
857
+ }
858
+ catch {
859
+ io.stderr("Warning: runtime shutdown failed. Check adapter cleanup.\n");
860
+ }
861
+ try {
862
+ resolvedStore.close();
863
+ }
864
+ catch {
865
+ io.stderr("Warning: local store cleanup failed.\n");
866
+ }
678
867
  }
679
868
  };
680
869
  const assertSafeInlineWorkerConfiguration = (config) => {
@@ -685,6 +874,9 @@ const assertSafeInlineWorkerConfiguration = (config) => {
685
874
  if (Object.keys(config.connections).length > 0) {
686
875
  throw new Error("Inline worker configuration cannot define MCP connections; use a trusted configReference.");
687
876
  }
877
+ if (Object.keys(config.workspaces ?? {}).length > 0 || config.sandbox) {
878
+ throw new Error("Inline worker configuration cannot define workspaces or a sandbox; use a trusted configReference.");
879
+ }
688
880
  };
689
881
  const MAXIMUM_WORKER_INPUT_BYTES = 16 * 1024 * 1024;
690
882
  class PortableWorkerEventSink {
@@ -756,6 +948,10 @@ export const executeWorkerInvocation = async (invocation, options) => {
756
948
  : {}, {
757
949
  model: !moduleRuntime.model && !hostRuntime.model,
758
950
  tools: !moduleRuntime.tools && !hostRuntime.tools,
951
+ workspaceOptions: {
952
+ ...options.workspaceOptions,
953
+ ...workspaceCompositionOptions(hostRuntime, moduleRuntime),
954
+ },
759
955
  ...(options.modelPolicy ? { modelPolicy: options.modelPolicy } : {}),
760
956
  ...(options.toolOptions ||
761
957
  hostRuntime.connectionCredentials ||
@@ -779,81 +975,92 @@ export const executeWorkerInvocation = async (invocation, options) => {
779
975
  (storeDriver === "sqlite"
780
976
  ? new (await import("@clearideas/agent-runtime-store-sqlite")).SqliteRunStore(storeLocation)
781
977
  : new FileRunStore(storeLocation));
782
- const artifacts = runtime.artifactStore ?? new FileArtifactStore(storeDirectory);
783
- if (invocation.action === "resume" &&
784
- "checkpoint" in request &&
785
- request.checkpoint) {
786
- const existing = await store.loadRun(request.runId);
787
- if (!existing) {
788
- const checkpointAttempt = request.checkpoint.attempt ?? request.attempt - 1;
789
- const importedCheckpoint = {
790
- ...request.checkpoint,
791
- ...(request.checkpoint.sequence === 1
792
- ? {}
793
- : {
794
- id: `${request.checkpoint.id}:imported`,
795
- sequence: 1,
796
- metadata: {
797
- ...(request.checkpoint.metadata ?? {}),
798
- importedCheckpointId: request.checkpoint.id,
799
- importedCheckpointSequence: request.checkpoint.sequence,
800
- },
801
- }),
802
- };
803
- await store.createRun({
804
- runId: request.runId,
805
- manifest,
806
- status: "suspended",
807
- attempt: checkpointAttempt,
808
- state: structuredClone(importedCheckpoint.state),
809
- createdAt: importedCheckpoint.createdAt,
810
- updatedAt: importedCheckpoint.createdAt,
811
- });
812
- // A transferred checkpoint is a complete snapshot, not a partial log.
813
- // Rebase its local sequence when the destination store has no history;
814
- // preserve the source cursor in metadata for audit/debugging.
815
- await store.saveCheckpoint(importedCheckpoint);
816
- }
817
- }
818
- const runner = new AgentRuntime({
819
- runStore: store,
820
- // Webhook execution is host-supplied in worker mode so destination policy
821
- // cannot be bypassed by a remote manifest.
822
- stepExecutors: resolveStepExecutors(runtime),
823
- conditionEvaluator: new JexlConditionEvaluator(),
824
- eventSinks: [
825
- new PortableWorkerEventSink(options.onMessage),
826
- ...(runtime.eventSinks ?? []),
827
- ],
828
- ...(runtime.model ? { model: runtime.model } : {}),
829
- ...(runtime.tools ? { tools: runtime.tools } : {}),
830
- ...(runtime.approvals ? { approvals: runtime.approvals } : {}),
831
- ...(runtime.sandbox ? { sandbox: runtime.sandbox } : {}),
832
- ...(runtime.subRuns ? { subRuns: runtime.subRuns } : {}),
833
- artifacts,
834
- ...(options.maxParallelSteps
835
- ? { maxParallelSteps: options.maxParallelSteps }
836
- : {}),
837
- ...(options.eventSinkFailurePolicy
838
- ? { eventSinkFailurePolicy: options.eventSinkFailurePolicy }
839
- : {}),
840
- });
841
- return runner.run({
842
- manifest,
843
- ...(request.runId ? { runId: request.runId } : {}),
844
- ...(invocationVariables ? { variables: invocationVariables } : {}),
845
- ...(request.execution ? { execution: request.execution } : {}),
846
- ...(request.budget ? { budget: request.budget } : {}),
847
- ...(options.signal ? { signal: options.signal } : {}),
848
- ...(invocation.action === "resume"
849
- ? {
850
- resume: true,
851
- ...("allowRunningTakeover" in request && request.allowRunningTakeover
852
- ? { allowRunningTakeover: true }
853
- : {}),
978
+ try {
979
+ const artifacts = runtime.artifactStore ?? new FileArtifactStore(storeDirectory);
980
+ if (invocation.action === "resume" &&
981
+ "checkpoint" in request &&
982
+ request.checkpoint) {
983
+ const existing = await store.loadRun(request.runId);
984
+ if (!existing) {
985
+ const checkpointAttempt = request.checkpoint.attempt ?? request.attempt - 1;
986
+ const importedCheckpoint = {
987
+ ...request.checkpoint,
988
+ ...(request.checkpoint.sequence === 1
989
+ ? {}
990
+ : {
991
+ id: `${request.checkpoint.id}:imported`,
992
+ sequence: 1,
993
+ metadata: {
994
+ ...(request.checkpoint.metadata ?? {}),
995
+ importedCheckpointId: request.checkpoint.id,
996
+ importedCheckpointSequence: request.checkpoint.sequence,
997
+ },
998
+ }),
999
+ };
1000
+ await store.createRun({
1001
+ runId: request.runId,
1002
+ manifest,
1003
+ status: "suspended",
1004
+ attempt: checkpointAttempt,
1005
+ state: structuredClone(importedCheckpoint.state),
1006
+ createdAt: importedCheckpoint.createdAt,
1007
+ updatedAt: importedCheckpoint.createdAt,
1008
+ });
1009
+ // A transferred checkpoint is a complete snapshot, not a partial log.
1010
+ // Rebase its local sequence when the destination store has no history;
1011
+ // preserve the source cursor in metadata for audit/debugging.
1012
+ await store.saveCheckpoint(importedCheckpoint);
854
1013
  }
855
- : {}),
856
- });
1014
+ }
1015
+ const runner = new AgentRuntime({
1016
+ runStore: store,
1017
+ // Webhook execution is host-supplied in worker mode so destination policy
1018
+ // cannot be bypassed by a remote manifest.
1019
+ stepExecutors: resolveStepExecutors(runtime),
1020
+ conditionEvaluator: new JexlConditionEvaluator(),
1021
+ eventSinks: [
1022
+ new PortableWorkerEventSink(options.onMessage),
1023
+ ...(runtime.eventSinks ?? []),
1024
+ ],
1025
+ ...(runtime.model ? { model: runtime.model } : {}),
1026
+ ...(runtime.tools ? { tools: runtime.tools } : {}),
1027
+ ...(runtime.approvals ? { approvals: runtime.approvals } : {}),
1028
+ ...(runtime.sandbox ? { sandbox: runtime.sandbox } : {}),
1029
+ ...(runtime.subRuns ? { subRuns: runtime.subRuns } : {}),
1030
+ ...(runtime.workspaces ? { workspaces: runtime.workspaces } : {}),
1031
+ ...(runtime.runSandbox ? { runSandbox: runtime.runSandbox } : {}),
1032
+ artifacts,
1033
+ ...(options.maxParallelSteps
1034
+ ? { maxParallelSteps: options.maxParallelSteps }
1035
+ : {}),
1036
+ ...(options.eventSinkFailurePolicy
1037
+ ? { eventSinkFailurePolicy: options.eventSinkFailurePolicy }
1038
+ : {}),
1039
+ });
1040
+ return await runner.run({
1041
+ manifest,
1042
+ ...(request.runId ? { runId: request.runId } : {}),
1043
+ ...(invocationVariables ? { variables: invocationVariables } : {}),
1044
+ ...(request.execution ? { execution: request.execution } : {}),
1045
+ ...(request.budget ? { budget: request.budget } : {}),
1046
+ ...(options.signal ? { signal: options.signal } : {}),
1047
+ ...(invocation.action === "resume"
1048
+ ? {
1049
+ resume: true,
1050
+ ...("allowRunningTakeover" in request &&
1051
+ request.allowRunningTakeover
1052
+ ? { allowRunningTakeover: true }
1053
+ : {}),
1054
+ }
1055
+ : {}),
1056
+ });
1057
+ }
1058
+ finally {
1059
+ if (!runtime.runStore &&
1060
+ "close" in store &&
1061
+ typeof store.close === "function")
1062
+ store.close();
1063
+ }
857
1064
  };
858
1065
  const readStandardInput = async () => {
859
1066
  process.stdin.setEncoding("utf8");
@@ -951,6 +1158,8 @@ export const runCli = async (args, io = defaultIo, options = {}) => {
951
1158
  await validateManifest(commandArgs, io);
952
1159
  else if (command === "config")
953
1160
  await validateConfig(commandArgs, io);
1161
+ else if (command === "connections")
1162
+ await inspectConnections(commandArgs, io);
954
1163
  else if (command === "inspect")
955
1164
  await inspect(commandArgs, io);
956
1165
  else if (command === "events")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clearideas/agent-runtime-cli",
3
- "version": "0.4.3",
3
+ "version": "0.6.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,16 +40,18 @@
40
40
  "postpack": "node ../../scripts/cleanup-package-license.mjs"
41
41
  },
42
42
  "dependencies": {
43
- "@clearideas/agent-runtime-condition-jexl": "0.4.3",
44
- "@clearideas/agent-runtime-config": "0.4.3",
45
- "@clearideas/agent-runtime-contracts": "0.4.3",
46
- "@clearideas/agent-runtime-core": "0.4.3",
47
- "@clearideas/agent-runtime-execution": "0.4.3",
48
- "@clearideas/agent-runtime-step-loop": "0.4.3",
49
- "@clearideas/agent-runtime-step-prompt": "0.4.3",
50
- "@clearideas/agent-runtime-step-standard": "0.4.3",
51
- "@clearideas/agent-runtime-store-local": "0.4.3",
52
- "@clearideas/agent-runtime-store-sqlite": "0.4.3"
43
+ "@clearideas/agent-runtime-condition-jexl": "0.6.0",
44
+ "@clearideas/agent-runtime-config": "0.6.0",
45
+ "@clearideas/agent-runtime-contracts": "0.6.0",
46
+ "@clearideas/agent-runtime-core": "0.6.0",
47
+ "@clearideas/agent-runtime-execution": "0.6.0",
48
+ "@clearideas/agent-runtime-sandbox": "0.6.0",
49
+ "@clearideas/agent-runtime-step-loop": "0.6.0",
50
+ "@clearideas/agent-runtime-step-prompt": "0.6.0",
51
+ "@clearideas/agent-runtime-step-standard": "0.6.0",
52
+ "@clearideas/agent-runtime-store-local": "0.6.0",
53
+ "@clearideas/agent-runtime-store-sqlite": "0.6.0",
54
+ "yaml": "^2.9.1"
53
55
  },
54
56
  "devDependencies": {
55
57
  "@types/node": "^26.4.0",