@aaac/runtime 0.1.16 → 0.1.18

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.d.ts CHANGED
@@ -745,6 +745,101 @@ interface GuardStatusResult {
745
745
  */
746
746
  declare function guardStatus(opts?: GuardStatusOptions): Promise<GuardStatusResult>;
747
747
 
748
+ /**
749
+ * Prompt Executor — natural language routing via LLM tool selection.
750
+ *
751
+ * Converts component operations into tool descriptions, sends them to an LLM
752
+ * for routing, and dispatches the selected operation through the existing
753
+ * component binding.
754
+ */
755
+
756
+ interface OperationToolDef {
757
+ name: string;
758
+ description: string;
759
+ inputSchema: Record<string, unknown>;
760
+ }
761
+ interface PromptResult {
762
+ selectedOperation: string;
763
+ mappedInput: Record<string, unknown>;
764
+ output?: unknown;
765
+ dryRun?: boolean;
766
+ model?: string;
767
+ }
768
+ interface PromptExecuteOptions {
769
+ dryRun?: boolean;
770
+ adapter: string;
771
+ model?: string;
772
+ }
773
+ /**
774
+ * Convert non-handler, non-prompt operations from ComponentIR into tool definitions
775
+ * for LLM routing.
776
+ */
777
+ declare function operationsToTools(ir: ComponentIR): OperationToolDef[];
778
+ /**
779
+ * Parse the LLM router response to extract selected operation and mapped input.
780
+ */
781
+ declare function parseRouterResponse(response: string, validNames: string[]): {
782
+ selectedOperation: string;
783
+ mappedInput: Record<string, unknown>;
784
+ };
785
+ /**
786
+ * Execute a natural language prompt by routing to the appropriate operation.
787
+ */
788
+ declare function executePrompt(message: string, ir: ComponentIR, binding: RuntimeBinding, ctx: AaacInvocationContext, opts: PromptExecuteOptions): Promise<PromptResult>;
789
+
790
+ /**
791
+ * Toolchain Checker — runs check commands defined in toolchain-contracts
792
+ * and returns structured pass/fail results.
793
+ *
794
+ * Each toolchain may declare a `checks` map (checkType → shell command).
795
+ * This module iterates all checks, executes them via subprocess, and
796
+ * returns a ToolchainCheckResult[].
797
+ *
798
+ * For "drift" check types, a manifest-based fast path is available:
799
+ * if a .toolchain-manifest.json exists and the toolchain_id matches,
800
+ * the command execution can be skipped when the source hash is current.
801
+ */
802
+
803
+ declare const ToolchainManifestSchema: z.ZodObject<{
804
+ schema: z.ZodString;
805
+ toolchain_id: z.ZodString;
806
+ generated_at: z.ZodString;
807
+ source_hash: z.ZodString;
808
+ output_hash: z.ZodString;
809
+ source_globs: z.ZodOptional<z.ZodArray<z.ZodString>>;
810
+ output_globs: z.ZodOptional<z.ZodArray<z.ZodString>>;
811
+ files: z.ZodOptional<z.ZodArray<z.ZodObject<{
812
+ path: z.ZodString;
813
+ hash: z.ZodString;
814
+ }, z.core.$strip>>>;
815
+ }, z.core.$strip>;
816
+ type ToolchainManifest = z.infer<typeof ToolchainManifestSchema>;
817
+ interface ToolchainCheckResult {
818
+ toolchainId: string;
819
+ checkType: string;
820
+ status: "pass" | "fail" | "skip" | "error";
821
+ action: "block" | "warn" | "shadow";
822
+ message?: string;
823
+ durationMs?: number;
824
+ }
825
+ interface RunToolchainChecksOptions {
826
+ /** Absolute path to toolchain-contracts YAML */
827
+ toolchainsPath: string;
828
+ /** Absolute path to artifact-contracts YAML (optional, for manifest fast path) */
829
+ artifactsPath?: string;
830
+ /** Working directory for subprocess execution */
831
+ cwd?: string;
832
+ /** Filter: only run these check types */
833
+ checkTypes?: string[];
834
+ /** Filter: only run checks for these toolchain IDs */
835
+ toolchainFilter?: string[];
836
+ /** Policy-resolved action per check type. Key = check type, value = action. Special key "_default" for fallback. */
837
+ checkTypeActions?: Record<string, "block" | "warn" | "shadow">;
838
+ /** Default action when no policy match */
839
+ defaultAction?: "block" | "warn" | "shadow";
840
+ }
841
+ declare function runToolchainChecks(options: RunToolchainChecksOptions): Promise<ToolchainCheckResult[]>;
842
+
748
843
  /**
749
844
  * @aaac/runtime — public API
750
845
  *
@@ -753,4 +848,4 @@ declare function guardStatus(opts?: GuardStatusOptions): Promise<GuardStatusResu
753
848
  /** Package version string. */
754
849
  declare const version: string;
755
850
 
756
- export { type AaacInvocationContext, type AaacObserver, type AaacPolicy, type AaacRuntime, AgentContractLike, AgentLogWriter, type AgentLogWriterOptions, type AgentPlugin, ArtifactBindingConfig, type ArtifactResolveOptions, type ArtifactResolveResult, type ComponentScope, type CreateAdapterOptions, type CreateComponentScopeOptions, type CreateProjectRuntimeOptions, DelegateStep, type DslContext, DslValidationError, type EvaluateGuardrailOptions, type EvaluateGuardrailResult, type ExecuteOptions, type ExecuteTaskOptions, type ExecuteWorkflowOptions, FileMemoryStore, type GuardStatusOptions, type GuardStatusResult, GuardrailCheckResult, GuardrailHooks, type GuardrailListEntry, type GuardrailResult, GuardrailRuleData, HandoffInput, HookResponse, LibraryToolDefinition, LibraryToolRegistry, type ListGuardrailsOptions, type ListGuardrailsResult, type LoadDslOptions, MemoryRef, MemoryStore, type MemoryStoreEntry, type NavigationContext, type NavigationContextOptions, ObserverEmitFn, type OperationHandler, type OperationMemoryRefConfig, PROJECT_CONFIG_FILENAME, type PermissionMode, type PluginLoadResult, PluginRegistry, type ProcessEditOptions, type ProcessTaskOptions, type ProcessWorkflowOptions, type ProgressSink, type ProgressSinkOptions, type ProjectRuntime, type PromptBuilderArgs, PromptBuilderOptions, type RequiredEntities, type ResolvedAdapterSelection, ResolvedComponent, ResolvedToolchain, type RunLogEvent, type Runtime, type RuntimeBinding, type RuntimeConfig, SdkAdapter, type SdkFunctionTool, StepCompleteEvent, StepResult, TaskContext, TaskContractLike, type TaskHookContext, TaskOutcome, TaskRunResult, WorkflowBuilder, type WorkflowHookContext, WorkflowRegistries, WorkflowResult, buildGuardrailRulesFromDsl, buildNavigationContext, buildRegistriesFromDsl, buildSdkFunctionTools, createAdapter, createComponentScope, createProgressSink, createProjectRuntime, createRuntime, createRuntimeBinding, emitProcessEdit, emitProcessTaskClose, emitProcessTaskOpen, emitProcessWorkflowClose, emitProcessWorkflowOpen, evaluateGuardrail, executeTask, executeWorkflow, findProjectConfig, guardStatus, jsonSchemaToZod, listGuardrails, loadDslContext, loadPlugins, loadPluginsFromDirectory, loadPluginsFromPaths, pluginRegistry, resolveArtifacts, version };
851
+ export { type AaacInvocationContext, type AaacObserver, type AaacPolicy, type AaacRuntime, AgentContractLike, AgentLogWriter, type AgentLogWriterOptions, type AgentPlugin, ArtifactBindingConfig, type ArtifactResolveOptions, type ArtifactResolveResult, type ComponentScope, type CreateAdapterOptions, type CreateComponentScopeOptions, type CreateProjectRuntimeOptions, DelegateStep, type DslContext, DslValidationError, type EvaluateGuardrailOptions, type EvaluateGuardrailResult, type ExecuteOptions, type ExecuteTaskOptions, type ExecuteWorkflowOptions, FileMemoryStore, type GuardStatusOptions, type GuardStatusResult, GuardrailCheckResult, GuardrailHooks, type GuardrailListEntry, type GuardrailResult, GuardrailRuleData, HandoffInput, HookResponse, LibraryToolDefinition, LibraryToolRegistry, type ListGuardrailsOptions, type ListGuardrailsResult, type LoadDslOptions, MemoryRef, MemoryStore, type MemoryStoreEntry, type NavigationContext, type NavigationContextOptions, ObserverEmitFn, type OperationHandler, type OperationMemoryRefConfig, type OperationToolDef, PROJECT_CONFIG_FILENAME, type PermissionMode, type PluginLoadResult, PluginRegistry, type ProcessEditOptions, type ProcessTaskOptions, type ProcessWorkflowOptions, type ProgressSink, type ProgressSinkOptions, type ProjectRuntime, type PromptBuilderArgs, PromptBuilderOptions, type PromptExecuteOptions, type PromptResult, type RequiredEntities, type ResolvedAdapterSelection, ResolvedComponent, ResolvedToolchain, type RunLogEvent, type RunToolchainChecksOptions, type Runtime, type RuntimeBinding, type RuntimeConfig, SdkAdapter, type SdkFunctionTool, StepCompleteEvent, StepResult, TaskContext, TaskContractLike, type TaskHookContext, TaskOutcome, TaskRunResult, type ToolchainCheckResult, type ToolchainManifest, ToolchainManifestSchema, WorkflowBuilder, type WorkflowHookContext, WorkflowRegistries, WorkflowResult, buildGuardrailRulesFromDsl, buildNavigationContext, buildRegistriesFromDsl, buildSdkFunctionTools, createAdapter, createComponentScope, createProgressSink, createProjectRuntime, createRuntime, createRuntimeBinding, emitProcessEdit, emitProcessTaskClose, emitProcessTaskOpen, emitProcessWorkflowClose, emitProcessWorkflowOpen, evaluateGuardrail, executePrompt, executeTask, executeWorkflow, findProjectConfig, guardStatus, jsonSchemaToZod, listGuardrails, loadDslContext, loadPlugins, loadPluginsFromDirectory, loadPluginsFromPaths, operationsToTools, parseRouterResponse, pluginRegistry, resolveArtifacts, runToolchainChecks, version };
package/dist/index.js CHANGED
@@ -2946,8 +2946,8 @@ async function buildNavigationContext(options) {
2946
2946
  dsl = options.embeddedDsl;
2947
2947
  }
2948
2948
  } else if (options.projectDslPath) {
2949
- const { resolve: resolve4 } = await import("agent-contracts");
2950
- const result = await resolve4(options.projectDslPath);
2949
+ const { resolve: resolve5 } = await import("agent-contracts");
2950
+ const result = await resolve5(options.projectDslPath);
2951
2951
  dsl = result.data;
2952
2952
  } else {
2953
2953
  throw new Error("buildNavigationContext requires embeddedDsl or projectDslPath");
@@ -3154,6 +3154,243 @@ async function guardStatus(opts = {}) {
3154
3154
  };
3155
3155
  }
3156
3156
 
3157
+ // src/lib/prompt-executor.ts
3158
+ import * as YAML5 from "yaml";
3159
+ function unwrapInputSchema(input) {
3160
+ if (!input) {
3161
+ return { type: "object", properties: {} };
3162
+ }
3163
+ if ("schema" in input && input.schema && typeof input.schema === "object") {
3164
+ return input.schema;
3165
+ }
3166
+ if ("$ref" in input) {
3167
+ return { type: "object", properties: {} };
3168
+ }
3169
+ return input;
3170
+ }
3171
+ function operationsToTools(ir) {
3172
+ return Object.entries(ir.operations).filter(([name, op]) => name !== "prompt" && !op.handler).map(([name, op]) => ({
3173
+ name,
3174
+ description: op.description,
3175
+ inputSchema: unwrapInputSchema(op.input)
3176
+ }));
3177
+ }
3178
+ function buildRouterPrompt(componentId, tools, message) {
3179
+ const toolDescriptions = tools.map((t) => {
3180
+ const schema = JSON.stringify(t.inputSchema, null, 2);
3181
+ return `### ${t.name}
3182
+ ${t.description}
3183
+ Input schema:
3184
+ \`\`\`json
3185
+ ${schema}
3186
+ \`\`\``;
3187
+ }).join("\n\n");
3188
+ return [
3189
+ `You are an operation router for the "${componentId}" CLI.`,
3190
+ `Understand the user request and call the appropriate operation.`,
3191
+ `Always select exactly one operation. Extract parameters from the user message.`,
3192
+ ``,
3193
+ `## Available Operations`,
3194
+ ``,
3195
+ toolDescriptions,
3196
+ ``,
3197
+ `## Response Format`,
3198
+ ``,
3199
+ `Respond with ONLY the following YAML:`,
3200
+ ``,
3201
+ "```yaml",
3202
+ `operation: <operation_name>`,
3203
+ `input:`,
3204
+ ` <key>: <value>`,
3205
+ "```",
3206
+ ``,
3207
+ `## User Request`,
3208
+ ``,
3209
+ message
3210
+ ].join("\n");
3211
+ }
3212
+ function parseRouterResponse(response, validNames) {
3213
+ const yamlMatch = response.match(/```(?:yaml)?\n([\s\S]*?)```/);
3214
+ const content = yamlMatch ? yamlMatch[1].trim() : response.trim();
3215
+ let parsed;
3216
+ try {
3217
+ parsed = YAML5.parse(content);
3218
+ } catch {
3219
+ const jsonMatch = response.match(/\{[\s\S]*"operation"[\s\S]*\}/);
3220
+ if (jsonMatch) {
3221
+ try {
3222
+ parsed = JSON.parse(jsonMatch[0]);
3223
+ } catch {
3224
+ }
3225
+ }
3226
+ }
3227
+ if (parsed?.operation && typeof parsed.operation === "string") {
3228
+ if (!validNames.includes(parsed.operation)) {
3229
+ throw new Error(
3230
+ `Router selected unknown operation "${parsed.operation}". Available: ${validNames.join(", ")}`
3231
+ );
3232
+ }
3233
+ return {
3234
+ selectedOperation: parsed.operation,
3235
+ mappedInput: parsed.input ?? {}
3236
+ };
3237
+ }
3238
+ throw new Error(
3239
+ `Could not parse operation routing from LLM response. Expected YAML with "operation" and "input" fields.
3240
+ Response:
3241
+ ${response.slice(0, 500)}`
3242
+ );
3243
+ }
3244
+ async function executePrompt(message, ir, binding, ctx, opts) {
3245
+ const tools = operationsToTools(ir);
3246
+ if (tools.length < 2) {
3247
+ throw new Error(
3248
+ `prompt command requires at least 2 routable operations, found ${tools.length}`
3249
+ );
3250
+ }
3251
+ const prompt = buildRouterPrompt(ir.info.id, tools, message);
3252
+ const adapter = await createAdapter(opts.adapter, { model: opts.model });
3253
+ const response = await adapter.send(prompt, { readonly: true });
3254
+ const { selectedOperation, mappedInput } = parseRouterResponse(
3255
+ response,
3256
+ tools.map((t) => t.name)
3257
+ );
3258
+ if (opts.dryRun) {
3259
+ return {
3260
+ selectedOperation,
3261
+ mappedInput,
3262
+ dryRun: true,
3263
+ model: opts.model
3264
+ };
3265
+ }
3266
+ const output = await binding.execute(selectedOperation, {}, mappedInput, ctx);
3267
+ return { selectedOperation, mappedInput, output };
3268
+ }
3269
+
3270
+ // src/lib/toolchain-checker.ts
3271
+ import { execFile } from "child_process";
3272
+ import { readFile as readFile7 } from "fs/promises";
3273
+ import { existsSync as existsSync3 } from "fs";
3274
+ import { resolve as resolve4 } from "path";
3275
+ import { promisify } from "util";
3276
+ import { z as z2 } from "zod";
3277
+ import { parseToolchainFile } from "@aaac/toolchain";
3278
+ var execFileAsync = promisify(execFile);
3279
+ var SUBPROCESS_TIMEOUT_MS = 3e4;
3280
+ var MANIFEST_FILENAME = ".toolchain-manifest.json";
3281
+ var ToolchainManifestSchema = z2.object({
3282
+ schema: z2.string(),
3283
+ toolchain_id: z2.string(),
3284
+ generated_at: z2.string(),
3285
+ source_hash: z2.string(),
3286
+ output_hash: z2.string(),
3287
+ source_globs: z2.array(z2.string()).optional(),
3288
+ output_globs: z2.array(z2.string()).optional(),
3289
+ files: z2.array(
3290
+ z2.object({
3291
+ path: z2.string(),
3292
+ hash: z2.string()
3293
+ })
3294
+ ).optional()
3295
+ });
3296
+ function resolveAction(checkType, checkTypeActions, defaultAction) {
3297
+ if (checkTypeActions?.[checkType]) return checkTypeActions[checkType];
3298
+ if (checkTypeActions?.["_default"]) return checkTypeActions["_default"];
3299
+ return defaultAction ?? "warn";
3300
+ }
3301
+ async function tryManifestFastPath(toolchainId, cwd) {
3302
+ const manifestPath = resolve4(cwd, MANIFEST_FILENAME);
3303
+ if (!existsSync3(manifestPath)) return null;
3304
+ try {
3305
+ const raw = await readFile7(manifestPath, "utf-8");
3306
+ const parsed = ToolchainManifestSchema.parse(JSON.parse(raw));
3307
+ if (parsed.toolchain_id !== toolchainId) return null;
3308
+ return {
3309
+ toolchainId,
3310
+ checkType: "drift",
3311
+ status: "pass",
3312
+ action: "warn",
3313
+ message: `Manifest fast path: ${MANIFEST_FILENAME} found, toolchain_id matches`,
3314
+ durationMs: 0
3315
+ };
3316
+ } catch {
3317
+ return null;
3318
+ }
3319
+ }
3320
+ async function executeCheck(command, cwd) {
3321
+ try {
3322
+ const { stdout, stderr } = await execFileAsync("sh", ["-c", command], {
3323
+ cwd,
3324
+ timeout: SUBPROCESS_TIMEOUT_MS
3325
+ });
3326
+ return { exitCode: 0, stdout, stderr };
3327
+ } catch (err) {
3328
+ const execErr = err;
3329
+ if (execErr.killed) {
3330
+ throw new Error(`Command timed out after ${SUBPROCESS_TIMEOUT_MS}ms: ${command}`);
3331
+ }
3332
+ const exitCode = typeof execErr.code === "number" ? execErr.code : 1;
3333
+ return {
3334
+ exitCode,
3335
+ stdout: execErr.stdout ?? "",
3336
+ stderr: execErr.stderr ?? ""
3337
+ };
3338
+ }
3339
+ }
3340
+ async function runToolchainChecks(options) {
3341
+ const {
3342
+ toolchainsPath,
3343
+ cwd: workingDir,
3344
+ checkTypes,
3345
+ toolchainFilter,
3346
+ checkTypeActions,
3347
+ defaultAction
3348
+ } = options;
3349
+ const cwd = workingDir ?? process.cwd();
3350
+ const contracts = await parseToolchainFile(toolchainsPath);
3351
+ const results = [];
3352
+ for (const [toolchainId, toolchain] of Object.entries(contracts.toolchains)) {
3353
+ if (!toolchain.checks) continue;
3354
+ if (toolchainFilter && !toolchainFilter.includes(toolchainId)) continue;
3355
+ for (const [checkType, command] of Object.entries(toolchain.checks)) {
3356
+ if (checkTypes && !checkTypes.includes(checkType)) continue;
3357
+ const action = resolveAction(checkType, checkTypeActions, defaultAction);
3358
+ const start = performance.now();
3359
+ if (checkType === "drift" && options.artifactsPath) {
3360
+ const fastResult = await tryManifestFastPath(toolchainId, cwd);
3361
+ if (fastResult) {
3362
+ fastResult.action = action;
3363
+ results.push(fastResult);
3364
+ continue;
3365
+ }
3366
+ }
3367
+ try {
3368
+ const { exitCode, stderr } = await executeCheck(command, cwd);
3369
+ const durationMs = Math.round(performance.now() - start);
3370
+ results.push({
3371
+ toolchainId,
3372
+ checkType,
3373
+ status: exitCode === 0 ? "pass" : "fail",
3374
+ action,
3375
+ message: exitCode === 0 ? void 0 : stderr.trim() || `exit code ${exitCode}`,
3376
+ durationMs
3377
+ });
3378
+ } catch (err) {
3379
+ const durationMs = Math.round(performance.now() - start);
3380
+ results.push({
3381
+ toolchainId,
3382
+ checkType,
3383
+ status: "error",
3384
+ action,
3385
+ message: err.message,
3386
+ durationMs
3387
+ });
3388
+ }
3389
+ }
3390
+ }
3391
+ return results;
3392
+ }
3393
+
3157
3394
  // src/index.ts
3158
3395
  var require2 = createRequire(import.meta.url);
3159
3396
  var pkg = require2("../package.json");
@@ -3166,6 +3403,7 @@ export {
3166
3403
  InMemoryStore,
3167
3404
  PROJECT_CONFIG_FILENAME,
3168
3405
  PluginRegistry,
3406
+ ToolchainManifestSchema,
3169
3407
  WorkflowBuilder,
3170
3408
  buildCandidateAgents,
3171
3409
  buildGateEvaluationPrompt,
@@ -3205,6 +3443,7 @@ export {
3205
3443
  emitToolchainClose,
3206
3444
  emitToolchainOpen,
3207
3445
  evaluateGuardrail,
3446
+ executePrompt,
3208
3447
  executeTask,
3209
3448
  executeWorkflow,
3210
3449
  extractStructuredResult,
@@ -3222,11 +3461,14 @@ export {
3222
3461
  loadPlugins,
3223
3462
  loadPluginsFromDirectory,
3224
3463
  loadPluginsFromPaths,
3464
+ operationsToTools,
3225
3465
  parseGateEvaluationResponse,
3466
+ parseRouterResponse,
3226
3467
  pluginRegistry,
3227
3468
  renderAgentSystemPrompt,
3228
3469
  resolveArtifacts,
3229
3470
  runTask,
3471
+ runToolchainChecks,
3230
3472
  runWorkflow,
3231
3473
  version,
3232
3474
  zodSchemaToPromptDescription,