@clearideas/agent-runtime-cli 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,942 @@
1
+ import { access, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { JexlConditionEvaluator } from "@clearideas/agent-runtime-condition-jexl";
5
+ import { parseAgentVariableOverrides } from "@clearideas/agent-runtime-contracts";
6
+ import { AgentRuntime, } from "@clearideas/agent-runtime-core";
7
+ import { EXECUTION_PROTOCOL_VERSION, parseWorkerInvocation, serializeWorkerMessage, } from "@clearideas/agent-runtime-execution";
8
+ import { composeRuntime, emptyAgentRuntimeConfig, loadAgentRuntimeConfig, parseAgentRuntimeConfig, validateRuntimeConfiguration, } from "@clearideas/agent-runtime-config";
9
+ import { LoopStepExecutor } from "@clearideas/agent-runtime-step-loop";
10
+ import { PromptStepExecutor } from "@clearideas/agent-runtime-step-prompt";
11
+ import { ApprovalStepExecutor, CodeStepExecutor, SubRunStepExecutor, WebhookStepExecutor, } from "@clearideas/agent-runtime-step-standard";
12
+ import { FileArtifactStore, FileAgentManifestSource, FileAgentRunManifestSource, FileRunStore, JsonlEventSink, } from "@clearideas/agent-runtime-store-local";
13
+ const defaultIo = {
14
+ stdout: (text) => process.stdout.write(text),
15
+ stderr: (text) => process.stderr.write(text),
16
+ };
17
+ const usage = `Clear Ideas Agent Runtime
18
+
19
+ Usage:
20
+ agent-runtime validate <manifest.json|manifest.yaml> [--config <config.yaml>]
21
+ agent-runtime config validate <config.json|config.yaml>
22
+ agent-runtime run <manifest.json|manifest.yaml> [--variables <overrides.json>] [--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
+ 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
+ agent-runtime resume <run-id> [--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]
25
+ agent-runtime inspect <run-id> [--store <path>] [--store-driver <file|sqlite>] [--runtime-module <local-js-file>]
26
+ agent-runtime events <events.jsonl> [--run <run-id>] [--type <event-type>] [--tail <count>]
27
+ agent-runtime examples list
28
+ agent-runtime examples show <variables|conditions|loops>
29
+ agent-runtime examples run <variables|conditions|loops> [run options]
30
+ agent-runtime worker [--store <path>] [--store-driver <file|sqlite>] [--config <config.yaml>] [--runtime-module <local-js-file>]
31
+ `;
32
+ const packageDirectory = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
33
+ const bundledExamplesDirectory = path.join(packageDirectory, "examples");
34
+ const exampleCatalog = {
35
+ variables: {
36
+ file: "variables.agent.yaml",
37
+ description: "Variables, nested values, system prompts, and step outputs.",
38
+ },
39
+ conditions: {
40
+ file: "conditions.agent.yaml",
41
+ description: "Conditional step execution using variables and prior outputs.",
42
+ },
43
+ loops: {
44
+ file: "loops.agent.yaml",
45
+ description: "A filtered collection loop with scoped item variables.",
46
+ },
47
+ };
48
+ const isExampleName = (value) => value in exampleCatalog;
49
+ const resolveCliStoreLocation = (parsed, workerMode = false) => {
50
+ const requestedDriver = parsed.options.get("store-driver") ?? "file";
51
+ if (requestedDriver !== "file" && requestedDriver !== "sqlite") {
52
+ throw new Error("--store-driver must be file or sqlite.");
53
+ }
54
+ const driver = requestedDriver;
55
+ const defaultLocation = workerMode
56
+ ? ".agent-runtime-worker"
57
+ : ".agent-runtime";
58
+ const location = path.resolve(parsed.options.get("store") ??
59
+ (driver === "sqlite"
60
+ ? path.join(defaultLocation, "runs.sqlite")
61
+ : defaultLocation));
62
+ return {
63
+ driver,
64
+ location,
65
+ baseDirectory: driver === "sqlite" ? path.dirname(location) : location,
66
+ };
67
+ };
68
+ const resolveCliStore = async (parsed) => {
69
+ const resolved = resolveCliStoreLocation(parsed);
70
+ return {
71
+ ...resolved,
72
+ store: resolved.driver === "sqlite"
73
+ ? new (await import("@clearideas/agent-runtime-store-sqlite")).SqliteRunStore(resolved.location)
74
+ : new FileRunStore(resolved.location),
75
+ };
76
+ };
77
+ const parseOptions = (args, allowed, flags = new Set()) => {
78
+ const positional = [];
79
+ const options = new Map();
80
+ for (let index = 0; index < args.length; index += 1) {
81
+ const value = args[index];
82
+ if (!value.startsWith("--")) {
83
+ positional.push(value);
84
+ continue;
85
+ }
86
+ const name = value.slice(2);
87
+ if (!allowed.has(name))
88
+ throw new Error(`Unknown option: ${value}`);
89
+ if (flags.has(name)) {
90
+ if (options.has(name))
91
+ throw new Error(`Option ${value} may only be provided once.`);
92
+ options.set(name, "true");
93
+ continue;
94
+ }
95
+ const optionValue = args[index + 1];
96
+ if (!optionValue || optionValue.startsWith("--"))
97
+ throw new Error(`Option ${value} requires a value.`);
98
+ if (options.has(name))
99
+ throw new Error(`Option ${value} may only be provided once.`);
100
+ options.set(name, optionValue);
101
+ index += 1;
102
+ }
103
+ return { positional, options };
104
+ };
105
+ const requireOnePositional = (parsed, label) => {
106
+ if (parsed.positional.length !== 1)
107
+ throw new Error(`Expected exactly one ${label}.`);
108
+ return parsed.positional[0];
109
+ };
110
+ const validateManifest = async (args, io) => {
111
+ const parsed = parseOptions(args, new Set(["config"]));
112
+ const file = path.resolve(requireOnePositional(parsed, "manifest path"));
113
+ const manifest = await new FileAgentManifestSource(path.dirname(file), path.basename(file)).loadManifest();
114
+ const configFile = parsed.options.get("config");
115
+ if (configFile)
116
+ validateRuntimeConfiguration(manifest, await loadAgentRuntimeConfig(configFile));
117
+ io.stdout(`${JSON.stringify({
118
+ valid: true,
119
+ schemaVersion: manifest.schemaVersion,
120
+ ...(manifest.id ? { id: manifest.id } : {}),
121
+ ...(manifest.name ? { name: manifest.name } : {}),
122
+ stepCount: manifest.steps.length,
123
+ }, null, 2)}\n`);
124
+ };
125
+ const validateConfig = async (args, io) => {
126
+ const [subcommand, ...subcommandArgs] = args;
127
+ if (subcommand !== "validate")
128
+ throw new Error("Expected config validate <Agent Runtime config path>.");
129
+ const file = path.resolve(requireOnePositional(parseOptions(subcommandArgs, new Set()), "Agent Runtime config path"));
130
+ const config = await loadAgentRuntimeConfig(file);
131
+ io.stdout(`${JSON.stringify({
132
+ valid: true,
133
+ version: config.version,
134
+ providerCount: Object.keys(config.providers).length,
135
+ modelCount: Object.keys(config.models).length,
136
+ connectionCount: Object.keys(config.connections).length,
137
+ }, null, 2)}\n`);
138
+ };
139
+ const inspect = async (args, io) => {
140
+ const parsed = parseOptions(args, new Set(["store", "store-driver", "runtime-module"]));
141
+ const runId = requireOnePositional(parsed, "run id");
142
+ const resolved = await resolveCliStore(parsed);
143
+ const store = (await loadRuntimeStore(parsed.options.get("runtime-module"), {
144
+ runId,
145
+ storeDirectory: resolved.baseDirectory,
146
+ storeDriver: resolved.driver,
147
+ storeLocation: resolved.location,
148
+ })) ?? resolved.store;
149
+ const run = await store.loadRun(runId);
150
+ if (!run)
151
+ throw new Error(`Run not found: ${runId}`);
152
+ const checkpoint = await store.loadLatestCheckpoint(runId);
153
+ io.stdout(`${JSON.stringify({ run, checkpoint }, null, 2)}\n`);
154
+ };
155
+ const events = async (args, io) => {
156
+ const parsed = parseOptions(args, new Set(["run", "type", "tail"]));
157
+ const file = path.resolve(requireOnePositional(parsed, "event file"));
158
+ const lines = (await readFile(file, "utf8")).split(/\r?\n/u).filter(Boolean);
159
+ let selected = lines.map((line, index) => {
160
+ try {
161
+ return JSON.parse(line);
162
+ }
163
+ catch {
164
+ throw new Error(`Invalid JSON on event line ${index + 1}.`);
165
+ }
166
+ });
167
+ const runId = parsed.options.get("run");
168
+ const eventType = parsed.options.get("type");
169
+ if (runId)
170
+ selected = selected.filter((event) => event.runId === runId);
171
+ if (eventType)
172
+ selected = selected.filter((event) => event.type === eventType);
173
+ const tailText = parsed.options.get("tail");
174
+ if (tailText) {
175
+ const count = Number(tailText);
176
+ if (!Number.isSafeInteger(count) || count < 0)
177
+ throw new Error("--tail must be a non-negative integer.");
178
+ selected = count === 0 ? [] : selected.slice(-count);
179
+ }
180
+ for (const event of selected)
181
+ io.stdout(`${JSON.stringify(event)}\n`);
182
+ };
183
+ const adapterMethod = (value, name) => value != null &&
184
+ typeof value === "object" &&
185
+ typeof value[name] === "function";
186
+ const validateRuntime = (runtime) => {
187
+ if (runtime.runStore &&
188
+ (!adapterMethod(runtime.runStore, "createRun") ||
189
+ !adapterMethod(runtime.runStore, "loadRun") ||
190
+ !adapterMethod(runtime.runStore, "saveCheckpoint"))) {
191
+ throw new Error("Runtime runStore must implement the RunStore lifecycle methods.");
192
+ }
193
+ if (runtime.artifactStore &&
194
+ (!adapterMethod(runtime.artifactStore, "put") ||
195
+ !adapterMethod(runtime.artifactStore, "get"))) {
196
+ throw new Error("Runtime artifactStore must implement ArtifactStore.put() and get().");
197
+ }
198
+ if (runtime.model && !adapterMethod(runtime.model, "generate"))
199
+ throw new Error("Runtime model must implement ModelAdapter.generate().");
200
+ if (runtime.tools &&
201
+ (!adapterMethod(runtime.tools, "listTools") ||
202
+ !adapterMethod(runtime.tools, "executeTool"))) {
203
+ throw new Error("Runtime tools must implement ToolAdapter.listTools() and executeTool().");
204
+ }
205
+ if (runtime.connectionCredentials &&
206
+ !adapterMethod(runtime.connectionCredentials, "getCredential")) {
207
+ throw new Error("Runtime connectionCredentials must implement ConnectionCredentialProvider.getCredential().");
208
+ }
209
+ if (runtime.approvals && !adapterMethod(runtime.approvals, "requestApproval"))
210
+ throw new Error("Runtime approvals must implement ApprovalAdapter.requestApproval().");
211
+ if (runtime.sandbox && !adapterMethod(runtime.sandbox, "execute"))
212
+ throw new Error("Runtime sandbox must implement SandboxAdapter.execute().");
213
+ if (runtime.subRuns && !adapterMethod(runtime.subRuns, "execute"))
214
+ throw new Error("Runtime subRuns must implement SubRunAdapter.execute().");
215
+ if (runtime.eventSinks &&
216
+ (!Array.isArray(runtime.eventSinks) ||
217
+ runtime.eventSinks.some((sink) => !adapterMethod(sink, "emit")))) {
218
+ throw new Error("Runtime eventSinks must be an array of EventSink values.");
219
+ }
220
+ if (runtime.stepExecutors &&
221
+ (!Array.isArray(runtime.stepExecutors) ||
222
+ runtime.stepExecutors.some((executor) => !executor ||
223
+ typeof executor !== "object" ||
224
+ typeof executor.type !== "string" ||
225
+ !adapterMethod(executor, "execute")))) {
226
+ throw new Error("Runtime stepExecutors must implement StepExecutor.");
227
+ }
228
+ return runtime;
229
+ };
230
+ const normalizeRuntime = (runtime) => ({
231
+ ...((runtime.runStore ?? runtime.store)
232
+ ? { runStore: runtime.runStore ?? runtime.store }
233
+ : {}),
234
+ ...((runtime.artifactStore ?? runtime.artifacts)
235
+ ? { artifactStore: runtime.artifactStore ?? runtime.artifacts }
236
+ : {}),
237
+ ...((runtime.model ?? runtime.modelAdapter)
238
+ ? { model: runtime.model ?? runtime.modelAdapter }
239
+ : {}),
240
+ ...((runtime.tools ?? runtime.toolAdapter)
241
+ ? { tools: runtime.tools ?? runtime.toolAdapter }
242
+ : {}),
243
+ ...((runtime.connectionCredentials ?? runtime.credentialProvider)
244
+ ? {
245
+ connectionCredentials: runtime.connectionCredentials ?? runtime.credentialProvider,
246
+ }
247
+ : {}),
248
+ ...((runtime.approvals ?? runtime.approvalAdapter)
249
+ ? { approvals: runtime.approvals ?? runtime.approvalAdapter }
250
+ : {}),
251
+ ...((runtime.sandbox ?? runtime.sandboxAdapter)
252
+ ? { sandbox: runtime.sandbox ?? runtime.sandboxAdapter }
253
+ : {}),
254
+ ...((runtime.subRuns ?? runtime.subRunAdapter)
255
+ ? { subRuns: runtime.subRuns ?? runtime.subRunAdapter }
256
+ : {}),
257
+ ...((runtime.eventSinks?.length ?? 0) > 0 || runtime.eventSink
258
+ ? {
259
+ eventSinks: [
260
+ ...(runtime.eventSinks ?? []),
261
+ ...(runtime.eventSink ? [runtime.eventSink] : []),
262
+ ],
263
+ }
264
+ : {}),
265
+ ...((runtime.stepExecutors?.length ?? 0) > 0 ||
266
+ (runtime.executors?.length ?? 0) > 0
267
+ ? { stepExecutors: runtime.stepExecutors ?? runtime.executors }
268
+ : {}),
269
+ });
270
+ const defaultStepExecutors = (allowUnsafeWebhooks) => [
271
+ new PromptStepExecutor(),
272
+ new LoopStepExecutor(),
273
+ ...(allowUnsafeWebhooks
274
+ ? [new WebhookStepExecutor({ allowUnsafeDestinations: true })]
275
+ : []),
276
+ new ApprovalStepExecutor(),
277
+ new CodeStepExecutor(),
278
+ new SubRunStepExecutor(),
279
+ ];
280
+ const resolveStepExecutors = (runtime, options = {}) => {
281
+ const byType = new Map(defaultStepExecutors(options.allowUnsafeWebhooks === true).map((executor) => [executor.type, executor]));
282
+ for (const executor of runtime.stepExecutors ?? [])
283
+ byType.set(executor.type, executor);
284
+ return [...byType.values()];
285
+ };
286
+ const loadRuntime = async (modulePath, context) => {
287
+ if (!modulePath)
288
+ return {};
289
+ const absolutePath = path.resolve(modulePath);
290
+ let imported;
291
+ try {
292
+ imported = (await import(pathToFileURL(absolutePath).href));
293
+ }
294
+ catch (error) {
295
+ throw new Error(`Could not load runtime module ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`);
296
+ }
297
+ const staticRuntime = imported.default ?? imported.runtime ?? imported;
298
+ const composedRuntime = imported.createRuntime
299
+ ? await imported.createRuntime(context)
300
+ : normalizeRuntime(staticRuntime);
301
+ if (!composedRuntime || typeof composedRuntime !== "object") {
302
+ throw new Error(`Runtime module ${absolutePath} did not export a runtime object.`);
303
+ }
304
+ const runtime = !composedRuntime.runStore && imported.createRunStore
305
+ ? { ...composedRuntime, runStore: await imported.createRunStore(context) }
306
+ : composedRuntime;
307
+ return validateRuntime(runtime);
308
+ };
309
+ const loadRuntimeStore = async (modulePath, context) => {
310
+ if (!modulePath)
311
+ return undefined;
312
+ const absolutePath = path.resolve(modulePath);
313
+ let imported;
314
+ try {
315
+ imported = (await import(pathToFileURL(absolutePath).href));
316
+ }
317
+ catch (error) {
318
+ throw new Error(`Could not load runtime module ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`);
319
+ }
320
+ const staticRuntime = imported.default ?? imported.runtime ?? imported;
321
+ const store = imported.createRunStore
322
+ ? await imported.createRunStore(context)
323
+ : (staticRuntime.runStore ?? staticRuntime.store);
324
+ if (store &&
325
+ (!adapterMethod(store, "createRun") ||
326
+ !adapterMethod(store, "loadRun") ||
327
+ !adapterMethod(store, "saveCheckpoint"))) {
328
+ throw new Error("Runtime runStore must implement the RunStore lifecycle methods.");
329
+ }
330
+ return store;
331
+ };
332
+ const defaultConfigNames = [
333
+ "agent-runtime.config.yaml",
334
+ "agent-runtime.config.yml",
335
+ "agent-runtime.config.json",
336
+ ];
337
+ const resolveConfig = async (requested, searchDirectory = process.cwd()) => {
338
+ if (requested)
339
+ return loadAgentRuntimeConfig(requested);
340
+ for (const candidate of defaultConfigNames) {
341
+ const absolute = path.resolve(searchDirectory, candidate);
342
+ try {
343
+ await access(absolute);
344
+ return await loadAgentRuntimeConfig(absolute);
345
+ }
346
+ catch (error) {
347
+ if (error.code !== "ENOENT")
348
+ throw error;
349
+ }
350
+ }
351
+ return emptyAgentRuntimeConfig();
352
+ };
353
+ const mergeRuntimes = (configured, moduleRuntime) => validateRuntime({
354
+ ...configured,
355
+ ...moduleRuntime,
356
+ ...((configured.eventSinks?.length ?? 0) > 0 ||
357
+ (moduleRuntime.eventSinks?.length ?? 0) > 0
358
+ ? {
359
+ eventSinks: [
360
+ ...(configured.eventSinks ?? []),
361
+ ...(moduleRuntime.eventSinks ?? []),
362
+ ],
363
+ }
364
+ : {}),
365
+ });
366
+ const sensitiveKey = /(?:authorization|cookie|credential|password|secret|token|api[-_]?key)/iu;
367
+ const redactValue = (value, key = "") => {
368
+ if (sensitiveKey.test(key))
369
+ return "[REDACTED]";
370
+ if (Array.isArray(value))
371
+ return value.map((item) => redactValue(item));
372
+ if (value && typeof value === "object") {
373
+ return Object.fromEntries(Object.entries(value).map(([childKey, childValue]) => [
374
+ childKey,
375
+ redactValue(childValue, childKey),
376
+ ]));
377
+ }
378
+ return value;
379
+ };
380
+ /**
381
+ * Local lifecycle logs exclude transient model content and common secret
382
+ * fields. A host-supplied event sink is trusted code and receives raw events.
383
+ */
384
+ class SafeLocalEventSink {
385
+ #delegate;
386
+ constructor(delegate) {
387
+ this.#delegate = delegate;
388
+ }
389
+ emit(event) {
390
+ if (event.type === "model.text.delta" ||
391
+ event.type === "model.reasoning.delta") {
392
+ return;
393
+ }
394
+ let data = event.data ? redactValue(event.data) : undefined;
395
+ if ((event.type === "run.failed" || event.type === "step.failed") &&
396
+ data?.error) {
397
+ const error = data.error;
398
+ data = {
399
+ ...data,
400
+ error: error && typeof error === "object" && !Array.isArray(error)
401
+ ? {
402
+ ...("code" in error ? { code: error.code } : {}),
403
+ ...("retryable" in error ? { retryable: error.retryable } : {}),
404
+ }
405
+ : "[REDACTED]",
406
+ };
407
+ }
408
+ return this.#delegate.emit({
409
+ ...event,
410
+ ...(data ? { data } : {}),
411
+ });
412
+ }
413
+ }
414
+ class CliStreamingEventSink {
415
+ #io;
416
+ #format;
417
+ #showReasoning;
418
+ #streamedText = false;
419
+ constructor(io, format, showReasoning) {
420
+ this.#io = io;
421
+ this.#format = format;
422
+ this.#showReasoning = showReasoning;
423
+ }
424
+ get streamedText() {
425
+ return this.#streamedText;
426
+ }
427
+ emit(event) {
428
+ if (this.#format === "ndjson") {
429
+ this.#io.stdout(`${JSON.stringify({ type: "event", event })}\n`);
430
+ return;
431
+ }
432
+ if (event.type === "model.text.delta") {
433
+ const delta = typeof event.data?.delta === "string" ? event.data.delta : "";
434
+ if (delta) {
435
+ this.#streamedText = true;
436
+ this.#io.stdout(delta);
437
+ }
438
+ return;
439
+ }
440
+ if (event.type === "model.reasoning.delta") {
441
+ if (!this.#showReasoning)
442
+ return;
443
+ const delta = typeof event.data?.delta === "string" ? event.data.delta : "";
444
+ if (delta)
445
+ this.#io.stderr(` reasoning: ${delta}`);
446
+ return;
447
+ }
448
+ const label = (() => {
449
+ switch (event.type) {
450
+ case "run.started":
451
+ return `● run started (${event.runId})`;
452
+ case "run.resumed":
453
+ return `● run resumed (${event.runId})`;
454
+ case "step.started":
455
+ return `● step started${event.stepId ? `: ${event.stepId}` : ""}`;
456
+ case "step.skipped":
457
+ return `○ step skipped${event.stepId ? `: ${event.stepId}` : ""}`;
458
+ case "step.completed":
459
+ return `✓ step completed${event.stepId ? `: ${event.stepId}` : ""}`;
460
+ case "model.started":
461
+ return ` model: ${String(event.data?.model ?? "unknown")}`;
462
+ case "model.tool.started":
463
+ return ` tool started: ${String(event.data?.toolName ?? "unknown")}`;
464
+ case "model.tool.completed":
465
+ return ` tool completed: ${String(event.data?.toolName ?? "unknown")}`;
466
+ case "checkpoint.saved":
467
+ return ` checkpoint saved: ${String(event.data?.nextStepIndex ?? "")}`.trimEnd();
468
+ case "artifact.created":
469
+ return ` artifact created: ${String(event.data?.name ?? event.data?.artifactId ?? "")}`.trimEnd();
470
+ case "run.completed":
471
+ return `✓ run completed (${event.runId})`;
472
+ case "run.failed":
473
+ return `✗ run failed (${event.runId})`;
474
+ case "run.cancelled":
475
+ return `■ run cancelled (${event.runId})`;
476
+ default:
477
+ return undefined;
478
+ }
479
+ })();
480
+ if (label)
481
+ this.#io.stderr(`${label}\n`);
482
+ }
483
+ }
484
+ const executionOptions = new Set([
485
+ "config",
486
+ "variables",
487
+ "run-id",
488
+ "store",
489
+ "store-driver",
490
+ "events",
491
+ "artifacts",
492
+ "runtime-module",
493
+ "stream",
494
+ "format",
495
+ "show-reasoning",
496
+ ]);
497
+ const executionFlags = new Set(["stream", "show-reasoning"]);
498
+ const execute = async (command, args, io, signal) => {
499
+ const parsed = parseOptions(args, executionOptions, executionFlags);
500
+ const target = requireOnePositional(parsed, command === "run"
501
+ ? "agent manifest path"
502
+ : command === "run-manifest"
503
+ ? "agent run manifest path"
504
+ : "run id");
505
+ if (command === "resume" && parsed.options.has("run-id")) {
506
+ throw new Error("--run-id is only valid with the run command.");
507
+ }
508
+ if (command === "resume" && parsed.options.has("variables")) {
509
+ throw new Error("--variables is only valid with the run command.");
510
+ }
511
+ if (command === "run-manifest" &&
512
+ (parsed.options.has("variables") || parsed.options.has("run-id"))) {
513
+ throw new Error("--variables and --run-id cannot be combined with an agent run manifest; declare them in the agent run manifest.");
514
+ }
515
+ const agentRunManifestFile = command === "run-manifest" ? path.resolve(target) : undefined;
516
+ const agentRunManifestSource = agentRunManifestFile
517
+ ? new FileAgentRunManifestSource(path.dirname(agentRunManifestFile), path.basename(agentRunManifestFile))
518
+ : undefined;
519
+ const agentRunManifest = agentRunManifestSource
520
+ ? await agentRunManifestSource.loadAgentRunManifest()
521
+ : undefined;
522
+ const agentManifestSource = agentRunManifestFile
523
+ ? new FileAgentManifestSource(path.dirname(agentRunManifestFile))
524
+ : undefined;
525
+ const resolvedStore = await resolveCliStore(parsed);
526
+ const storeDirectory = resolvedStore.baseDirectory;
527
+ const runId = command === "resume"
528
+ ? target
529
+ : (agentRunManifest?.runId ?? parsed.options.get("run-id"));
530
+ const runtimeModulePath = parsed.options.get("runtime-module");
531
+ const runtimeStore = command === "resume"
532
+ ? await loadRuntimeStore(runtimeModulePath, {
533
+ runId: target,
534
+ storeDirectory,
535
+ storeDriver: resolvedStore.driver,
536
+ storeLocation: resolvedStore.location,
537
+ })
538
+ : undefined;
539
+ const store = runtimeStore ?? resolvedStore.store;
540
+ let manifest;
541
+ const variableOverrides = command === "run" && parsed.options.has("variables")
542
+ ? parseAgentVariableOverrides(JSON.parse(await readFile(path.resolve(parsed.options.get("variables")), "utf8")))
543
+ : undefined;
544
+ let configSearchDirectory = process.cwd();
545
+ if (command === "run") {
546
+ const manifestFile = path.resolve(target);
547
+ configSearchDirectory = path.dirname(manifestFile);
548
+ manifest = await new FileAgentManifestSource(path.dirname(manifestFile), path.basename(manifestFile)).loadManifest();
549
+ }
550
+ else if (command === "run-manifest" &&
551
+ agentRunManifest &&
552
+ agentManifestSource) {
553
+ configSearchDirectory = path.dirname(agentRunManifestFile);
554
+ manifest = await agentManifestSource.loadManifest(agentRunManifest.agent.ref);
555
+ }
556
+ else {
557
+ const record = await store.loadRun(target);
558
+ if (!record)
559
+ throw new Error(`Run not found: ${target}`);
560
+ manifest = record.manifest;
561
+ }
562
+ const eventsOption = parsed.options.get("events");
563
+ const eventFile = eventsOption === "none"
564
+ ? undefined
565
+ : path.resolve(eventsOption ?? path.join(storeDirectory, "events.jsonl"));
566
+ const artifactsOption = parsed.options.get("artifacts");
567
+ const artifactDirectory = artifactsOption === "none"
568
+ ? undefined
569
+ : path.resolve(artifactsOption ?? storeDirectory);
570
+ const context = {
571
+ manifest,
572
+ ...(runId ? { runId } : {}),
573
+ storeDirectory,
574
+ storeDriver: resolvedStore.driver,
575
+ storeLocation: resolvedStore.location,
576
+ ...(eventFile ? { eventFile } : {}),
577
+ ...(artifactDirectory ? { artifactDirectory } : {}),
578
+ };
579
+ const loadedModuleRuntime = await loadRuntime(runtimeModulePath, context);
580
+ const moduleRuntime = runtimeStore
581
+ ? validateRuntime({ ...loadedModuleRuntime, runStore: runtimeStore })
582
+ : loadedModuleRuntime;
583
+ const config = await resolveConfig(parsed.options.get("config"), configSearchDirectory);
584
+ const configuredRuntime = composeRuntime(manifest, config, {}, {
585
+ model: !moduleRuntime.model,
586
+ tools: !moduleRuntime.tools,
587
+ ...(moduleRuntime.connectionCredentials
588
+ ? { connectionCredentials: moduleRuntime.connectionCredentials }
589
+ : {}),
590
+ });
591
+ const runtime = mergeRuntimes(configuredRuntime, moduleRuntime);
592
+ const jsonlSink = eventFile ? new JsonlEventSink(eventFile) : undefined;
593
+ const requestedFormat = parsed.options.get("format") ??
594
+ (parsed.options.has("stream") ? "pretty" : "json");
595
+ if (!["json", "pretty", "ndjson"].includes(requestedFormat)) {
596
+ throw new Error("--format must be json, pretty, or ndjson.");
597
+ }
598
+ const outputFormat = requestedFormat;
599
+ const streamingSink = outputFormat === "json"
600
+ ? undefined
601
+ : new CliStreamingEventSink(io, outputFormat, parsed.options.has("show-reasoning"));
602
+ const runner = new AgentRuntime({
603
+ runStore: runtime.runStore ?? store,
604
+ ...(agentManifestSource ? { agentManifestSource } : {}),
605
+ stepExecutors: resolveStepExecutors(runtime, { allowUnsafeWebhooks: true }),
606
+ conditionEvaluator: new JexlConditionEvaluator(),
607
+ eventSinks: [
608
+ ...(jsonlSink ? [new SafeLocalEventSink(jsonlSink)] : []),
609
+ ...(streamingSink ? [streamingSink] : []),
610
+ ...(runtime.eventSinks ?? []),
611
+ ],
612
+ ...(runtime.model ? { model: runtime.model } : {}),
613
+ ...(runtime.tools ? { tools: runtime.tools } : {}),
614
+ ...(runtime.approvals ? { approvals: runtime.approvals } : {}),
615
+ ...(runtime.sandbox ? { sandbox: runtime.sandbox } : {}),
616
+ ...(runtime.subRuns ? { subRuns: runtime.subRuns } : {}),
617
+ ...(runtime.artifactStore
618
+ ? { artifacts: runtime.artifactStore }
619
+ : artifactDirectory
620
+ ? { artifacts: new FileArtifactStore(artifactDirectory) }
621
+ : {}),
622
+ });
623
+ try {
624
+ const result = await runner.run(command === "run-manifest" && agentRunManifest
625
+ ? {
626
+ agentRunManifest,
627
+ ...(signal ? { signal } : {}),
628
+ }
629
+ : {
630
+ manifest,
631
+ ...(runId ? { runId } : {}),
632
+ ...(variableOverrides ? { variables: variableOverrides } : {}),
633
+ ...(signal ? { signal } : {}),
634
+ ...(command === "resume" ? { resume: true } : {}),
635
+ });
636
+ // Deliberately exclude variables, transcript and model output. They may
637
+ // contain secrets; inspect is an explicit command for persisted details.
638
+ if (outputFormat === "ndjson") {
639
+ io.stdout(`${JSON.stringify({
640
+ type: "result",
641
+ result,
642
+ })}\n`);
643
+ }
644
+ else if (outputFormat === "pretty") {
645
+ if (streamingSink?.streamedText)
646
+ io.stdout("\n");
647
+ else if (result.output !== undefined) {
648
+ io.stdout(`${typeof result.output === "string" ? result.output : JSON.stringify(result.output, null, 2)}\n`);
649
+ }
650
+ io.stderr(`run ${result.runId}: ${result.stepResults.length} step(s), ${result.artifacts.length} artifact(s)\n`);
651
+ }
652
+ else {
653
+ io.stdout(`${JSON.stringify({
654
+ runId: result.runId,
655
+ status: "completed",
656
+ stepCount: result.stepResults.length,
657
+ artifactCount: result.artifacts.length,
658
+ }, null, 2)}\n`);
659
+ }
660
+ }
661
+ finally {
662
+ await jsonlSink?.flush();
663
+ }
664
+ };
665
+ class PortableWorkerEventSink {
666
+ #onMessage;
667
+ constructor(onMessage) {
668
+ this.#onMessage = onMessage;
669
+ }
670
+ emit(event) {
671
+ return this.#onMessage({
672
+ protocolVersion: EXECUTION_PROTOCOL_VERSION,
673
+ type: "event",
674
+ event,
675
+ });
676
+ }
677
+ }
678
+ /** Runs one provider-neutral worker invocation in the current process. */
679
+ export const executeWorkerInvocation = async (invocation, options) => {
680
+ const request = invocation.request;
681
+ const invocationVariables = invocation.action === "run"
682
+ ? request.variables
683
+ : undefined;
684
+ const manifest = request.manifest;
685
+ const storeLocation = path.resolve(options.storeDirectory);
686
+ const storeDriver = options.storeDriver ?? "file";
687
+ const storeDirectory = storeDriver === "sqlite" ? path.dirname(storeLocation) : storeLocation;
688
+ const context = {
689
+ manifest,
690
+ ...(request.runId ? { runId: request.runId } : {}),
691
+ storeDirectory,
692
+ storeDriver,
693
+ storeLocation,
694
+ artifactDirectory: storeDirectory,
695
+ };
696
+ const runtimeReference = options.runtimeModule
697
+ ? options.runtimeModule
698
+ : request.runtimeReference
699
+ ? options.resolveRuntimeReference
700
+ ? await options.resolveRuntimeReference(request.runtimeReference, request)
701
+ : (() => {
702
+ throw new Error("Worker request runtimeReference requires a host resolveRuntimeReference callback.");
703
+ })()
704
+ : undefined;
705
+ const moduleRuntime = await loadRuntime(runtimeReference, context);
706
+ const hostRuntime = validateRuntime(options.runtime ?? {});
707
+ let requestSuppliedConfiguration = false;
708
+ const config = options.configFile
709
+ ? await loadAgentRuntimeConfig(options.configFile)
710
+ : request.configuration
711
+ ? options.allowRequestConfiguration === true
712
+ ? ((requestSuppliedConfiguration = true),
713
+ parseAgentRuntimeConfig(request.configuration))
714
+ : (() => {
715
+ throw new Error("Worker request configuration requires allowRequestConfiguration and an explicit environment allowlist.");
716
+ })()
717
+ : request.configReference
718
+ ? options.resolveConfigReference
719
+ ? await options.resolveConfigReference(request.configReference, request)
720
+ : (() => {
721
+ throw new Error("Worker request configReference requires a host resolveConfigReference callback.");
722
+ })()
723
+ : await resolveConfig(undefined, process.cwd());
724
+ const configuredRuntime = composeRuntime(manifest, config, requestSuppliedConfiguration
725
+ ? { environment: options.environment ?? {} }
726
+ : options.environment
727
+ ? { environment: options.environment }
728
+ : {}, {
729
+ model: !moduleRuntime.model && !hostRuntime.model,
730
+ tools: !moduleRuntime.tools && !hostRuntime.tools,
731
+ ...(options.modelPolicy ? { modelPolicy: options.modelPolicy } : {}),
732
+ ...(options.toolOptions ||
733
+ hostRuntime.connectionCredentials ||
734
+ moduleRuntime.connectionCredentials
735
+ ? {
736
+ toolOptions: {
737
+ ...options.toolOptions,
738
+ ...((hostRuntime.connectionCredentials ??
739
+ moduleRuntime.connectionCredentials)
740
+ ? {
741
+ credentialProvider: hostRuntime.connectionCredentials ??
742
+ moduleRuntime.connectionCredentials,
743
+ }
744
+ : {}),
745
+ },
746
+ }
747
+ : {}),
748
+ });
749
+ const runtime = mergeRuntimes(mergeRuntimes(configuredRuntime, moduleRuntime), hostRuntime);
750
+ const store = runtime.runStore ??
751
+ (storeDriver === "sqlite"
752
+ ? new (await import("@clearideas/agent-runtime-store-sqlite")).SqliteRunStore(storeLocation)
753
+ : new FileRunStore(storeLocation));
754
+ const artifacts = runtime.artifactStore ?? new FileArtifactStore(storeDirectory);
755
+ if (invocation.action === "resume" &&
756
+ "checkpoint" in request &&
757
+ request.checkpoint) {
758
+ const existing = await store.loadRun(request.runId);
759
+ if (!existing) {
760
+ const checkpointAttempt = request.checkpoint.attempt ?? request.attempt - 1;
761
+ const importedCheckpoint = {
762
+ ...request.checkpoint,
763
+ ...(request.checkpoint.sequence === 1
764
+ ? {}
765
+ : {
766
+ id: `${request.checkpoint.id}:imported`,
767
+ sequence: 1,
768
+ metadata: {
769
+ ...(request.checkpoint.metadata ?? {}),
770
+ importedCheckpointId: request.checkpoint.id,
771
+ importedCheckpointSequence: request.checkpoint.sequence,
772
+ },
773
+ }),
774
+ };
775
+ await store.createRun({
776
+ runId: request.runId,
777
+ manifest,
778
+ status: "suspended",
779
+ attempt: checkpointAttempt,
780
+ state: structuredClone(importedCheckpoint.state),
781
+ createdAt: importedCheckpoint.createdAt,
782
+ updatedAt: importedCheckpoint.createdAt,
783
+ });
784
+ // A transferred checkpoint is a complete snapshot, not a partial log.
785
+ // Rebase its local sequence when the destination store has no history;
786
+ // preserve the source cursor in metadata for audit/debugging.
787
+ await store.saveCheckpoint(importedCheckpoint);
788
+ }
789
+ }
790
+ const runner = new AgentRuntime({
791
+ runStore: store,
792
+ // Webhook execution is host-supplied in worker mode so destination policy
793
+ // cannot be bypassed by a remote manifest.
794
+ stepExecutors: resolveStepExecutors(runtime),
795
+ conditionEvaluator: new JexlConditionEvaluator(),
796
+ eventSinks: [
797
+ new PortableWorkerEventSink(options.onMessage),
798
+ ...(runtime.eventSinks ?? []),
799
+ ],
800
+ ...(runtime.model ? { model: runtime.model } : {}),
801
+ ...(runtime.tools ? { tools: runtime.tools } : {}),
802
+ ...(runtime.approvals ? { approvals: runtime.approvals } : {}),
803
+ ...(runtime.sandbox ? { sandbox: runtime.sandbox } : {}),
804
+ ...(runtime.subRuns ? { subRuns: runtime.subRuns } : {}),
805
+ artifacts,
806
+ ...(options.maxParallelSteps
807
+ ? { maxParallelSteps: options.maxParallelSteps }
808
+ : {}),
809
+ ...(options.eventSinkFailurePolicy
810
+ ? { eventSinkFailurePolicy: options.eventSinkFailurePolicy }
811
+ : {}),
812
+ });
813
+ return runner.run({
814
+ manifest,
815
+ ...(request.runId ? { runId: request.runId } : {}),
816
+ ...(invocationVariables ? { variables: invocationVariables } : {}),
817
+ ...(request.execution ? { execution: request.execution } : {}),
818
+ ...(options.signal ? { signal: options.signal } : {}),
819
+ ...(invocation.action === "resume"
820
+ ? {
821
+ resume: true,
822
+ ...("allowRunningTakeover" in request && request.allowRunningTakeover
823
+ ? { allowRunningTakeover: true }
824
+ : {}),
825
+ }
826
+ : {}),
827
+ });
828
+ };
829
+ const readStandardInput = async () => {
830
+ process.stdin.setEncoding("utf8");
831
+ let source = "";
832
+ for await (const chunk of process.stdin)
833
+ source += chunk;
834
+ return source;
835
+ };
836
+ const worker = async (args, io, signal) => {
837
+ const parsed = parseOptions(args, new Set(["store", "store-driver", "config", "runtime-module"]));
838
+ if (parsed.positional.length > 0)
839
+ throw new Error("The worker command reads its invocation from stdin.");
840
+ const onMessage = (message) => io.stdout(serializeWorkerMessage(message));
841
+ try {
842
+ const resolvedStore = resolveCliStoreLocation(parsed, true);
843
+ const invocation = parseWorkerInvocation((await readStandardInput()).trim());
844
+ await onMessage({
845
+ protocolVersion: EXECUTION_PROTOCOL_VERSION,
846
+ type: "ready",
847
+ });
848
+ const result = await executeWorkerInvocation(invocation, {
849
+ storeDirectory: resolvedStore.location,
850
+ storeDriver: resolvedStore.driver,
851
+ ...(parsed.options.get("config")
852
+ ? { configFile: parsed.options.get("config") }
853
+ : {}),
854
+ ...(parsed.options.get("runtime-module")
855
+ ? { runtimeModule: parsed.options.get("runtime-module") }
856
+ : {}),
857
+ ...(signal ? { signal } : {}),
858
+ onMessage,
859
+ });
860
+ await onMessage({
861
+ protocolVersion: EXECUTION_PROTOCOL_VERSION,
862
+ type: "result",
863
+ result,
864
+ });
865
+ return true;
866
+ }
867
+ catch (error) {
868
+ await onMessage({
869
+ protocolVersion: EXECUTION_PROTOCOL_VERSION,
870
+ type: "error",
871
+ error: {
872
+ code: "WORKER_EXECUTION_FAILED",
873
+ message: error instanceof Error ? error.message : String(error),
874
+ retryable: false,
875
+ },
876
+ });
877
+ return false;
878
+ }
879
+ };
880
+ const examples = async (args, io, signal) => {
881
+ const [subcommand, name, ...remaining] = args;
882
+ if (subcommand === "list") {
883
+ if (name || remaining.length > 0)
884
+ throw new Error("The examples list command takes no arguments.");
885
+ for (const [exampleName, example] of Object.entries(exampleCatalog)) {
886
+ io.stdout(`${exampleName.padEnd(12)} ${example.description}\n`);
887
+ }
888
+ return;
889
+ }
890
+ if (subcommand !== "show" && subcommand !== "run") {
891
+ throw new Error("Expected examples list, examples show <name>, or examples run <name>.");
892
+ }
893
+ if (!name || !isExampleName(name)) {
894
+ throw new Error(`Unknown example: ${name ?? "(missing)"}. Choose variables, conditions, or loops.`);
895
+ }
896
+ const manifestFile = path.join(bundledExamplesDirectory, exampleCatalog[name].file);
897
+ if (subcommand === "show") {
898
+ if (remaining.length > 0)
899
+ throw new Error("The examples show command takes exactly one name.");
900
+ io.stdout(await readFile(manifestFile, "utf8"));
901
+ return;
902
+ }
903
+ await execute("run", [manifestFile, ...remaining], io, signal);
904
+ };
905
+ export const runCli = async (args, io = defaultIo, options = {}) => {
906
+ const [command, ...commandArgs] = args;
907
+ if (!command ||
908
+ command === "help" ||
909
+ command === "--help" ||
910
+ command === "-h") {
911
+ io.stdout(usage);
912
+ return 0;
913
+ }
914
+ try {
915
+ if (command === "validate")
916
+ await validateManifest(commandArgs, io);
917
+ else if (command === "config")
918
+ await validateConfig(commandArgs, io);
919
+ else if (command === "inspect")
920
+ await inspect(commandArgs, io);
921
+ else if (command === "events")
922
+ await events(commandArgs, io);
923
+ else if (command === "examples")
924
+ await examples(commandArgs, io, options.signal);
925
+ else if (command === "run" ||
926
+ command === "run-manifest" ||
927
+ command === "resume") {
928
+ await execute(command, commandArgs, io, options.signal);
929
+ }
930
+ else if (command === "worker")
931
+ return (await worker(commandArgs, io, options.signal)) ? 0 : 1;
932
+ else {
933
+ io.stderr(`Unknown command: ${command}\n\n${usage}`);
934
+ return 2;
935
+ }
936
+ return 0;
937
+ }
938
+ catch (error) {
939
+ io.stderr(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
940
+ return 1;
941
+ }
942
+ };