@aaac/runtime 0.1.55 → 0.2.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.
Files changed (71) hide show
  1. package/README.md +6 -11
  2. package/dist/adapters/adk-sdk.d.ts +3 -3
  3. package/dist/adapters/adk-sdk.js +6 -8
  4. package/dist/adapters/adk-sdk.js.map +1 -1
  5. package/dist/adapters/claude-agent-sdk.d.ts +3 -3
  6. package/dist/adapters/claude-agent-sdk.js +22 -23
  7. package/dist/adapters/claude-agent-sdk.js.map +1 -1
  8. package/dist/adapters/mock.d.ts +2 -3
  9. package/dist/adapters/openai-agents-sdk.d.ts +3 -3
  10. package/dist/adapters/openai-agents-sdk.js +6 -5
  11. package/dist/adapters/openai-agents-sdk.js.map +1 -1
  12. package/dist/chunk-2INQL5TG.js +298 -0
  13. package/dist/chunk-2INQL5TG.js.map +1 -0
  14. package/dist/chunk-3CLWG72V.js +47 -0
  15. package/dist/chunk-3CLWG72V.js.map +1 -0
  16. package/dist/chunk-3DDB34BU.js +237 -0
  17. package/dist/chunk-3DDB34BU.js.map +1 -0
  18. package/dist/chunk-ABXDSTUV.js +685 -0
  19. package/dist/chunk-ABXDSTUV.js.map +1 -0
  20. package/dist/{chunk-3H3PVPPF.js → chunk-F5R46S7I.js} +151 -204
  21. package/dist/chunk-F5R46S7I.js.map +1 -0
  22. package/dist/chunk-FKAI54OM.js +234 -0
  23. package/dist/chunk-FKAI54OM.js.map +1 -0
  24. package/dist/chunk-KTVMMG33.js +1111 -0
  25. package/dist/chunk-KTVMMG33.js.map +1 -0
  26. package/dist/chunk-MSVIEEGR.js +269 -0
  27. package/dist/chunk-MSVIEEGR.js.map +1 -0
  28. package/dist/chunk-VJXGCWSZ.js +36 -0
  29. package/dist/chunk-VJXGCWSZ.js.map +1 -0
  30. package/dist/claude-bundles/full.js +311 -309
  31. package/dist/claude-bundles/lean.js +6 -6
  32. package/dist/claude-bundles/prompt.js +17 -0
  33. package/dist/generator/index.d.ts +2 -2
  34. package/dist/generator/index.js +8 -7
  35. package/dist/guardrail-hooks-CB23nhZV.d.ts +202 -0
  36. package/dist/hook-protocol-CFnNudiV.d.ts +96 -0
  37. package/dist/hooks-lite-CoWWnCRH.d.ts +428 -0
  38. package/dist/index-BlSepCSZ.d.ts +296 -0
  39. package/dist/index.d.ts +785 -105
  40. package/dist/index.js +2189 -634
  41. package/dist/index.js.map +1 -1
  42. package/dist/lib/claude-native/hooks-lite.d.ts +3 -26
  43. package/dist/lib/claude-native/hooks-lite.js +18 -36
  44. package/dist/lib/claude-native/hooks-prompt.d.ts +5 -0
  45. package/dist/lib/claude-native/hooks-prompt.js +33 -0
  46. package/dist/lib/claude-native/hooks-prompt.js.map +1 -0
  47. package/dist/lib/claude-native/index.d.ts +56 -214
  48. package/dist/lib/claude-native/index.js +79 -280
  49. package/dist/lib/claude-native/index.js.map +1 -1
  50. package/dist/{navigation-context-D_E1NIUf.d.ts → navigation-context-B-RpUg3_.d.ts} +1 -1
  51. package/dist/navigation-index-prompt-CbrS5laO.d.ts +43 -0
  52. package/dist/{task-runner-DfIEorkU.d.ts → task-runner-GWoI7_71.d.ts} +100 -493
  53. package/dist/workspace-user-prompt-submit-D11Iu0zO.d.ts +269 -0
  54. package/package.json +15 -6
  55. package/dist/chunk-3H3PVPPF.js.map +0 -1
  56. package/dist/chunk-DBM5XN67.js +0 -354
  57. package/dist/chunk-DBM5XN67.js.map +0 -1
  58. package/dist/chunk-KXGUWBGK.js +0 -370
  59. package/dist/chunk-KXGUWBGK.js.map +0 -1
  60. package/dist/chunk-LDCQZPDG.js +0 -11
  61. package/dist/chunk-LDCQZPDG.js.map +0 -1
  62. package/dist/chunk-N4KNGDYY.js +0 -1963
  63. package/dist/chunk-N4KNGDYY.js.map +0 -1
  64. package/dist/chunk-NMX4C6LC.js +0 -332
  65. package/dist/chunk-NMX4C6LC.js.map +0 -1
  66. package/dist/chunk-QVH5KKBR.js +0 -374
  67. package/dist/chunk-QVH5KKBR.js.map +0 -1
  68. package/dist/context-DKkamYX_.d.ts +0 -31
  69. package/dist/guardrail-hooks-slK-z0Dz.d.ts +0 -83
  70. package/dist/index-LqEvaRk-.d.ts +0 -299
  71. package/dist/workspace-pre-tool-use-C6nidc0q.d.ts +0 -333
package/dist/index.js CHANGED
@@ -1,50 +1,31 @@
1
- import {
2
- buildSdkFunctionTools
3
- } from "./chunk-DBM5XN67.js";
4
1
  import {
5
2
  BoundResolver,
6
3
  DslValidationError,
7
- buildCandidateAgents,
4
+ buildAgentRegistry,
8
5
  buildNavigationContext,
9
6
  buildPerAgentGuardrails,
10
7
  buildRegistriesFromDsl,
11
- buildRetryFollowUp,
12
- buildSplitTaskPrompt,
13
- buildTaskPrompt,
14
- collectAnalyzerToolIds,
15
- computeCostUsd,
16
- createAnalyzerBridge,
17
8
  deriveToolchainsForAgents,
18
- emitProcessEdit,
19
- emitProcessTaskClose,
20
- emitProcessTaskOpen,
21
- emitProcessWorkflowClose,
22
- emitProcessWorkflowOpen,
23
- extractStructuredResult,
24
9
  getEffectiveGuardrailIds,
25
10
  getGuardrailRulesForAgent,
26
11
  guardrailContextToRuleData,
27
- isContextPack,
28
- isFileEditTool,
29
- isNavigationIndex,
30
12
  loadDslContext,
31
- renderAgentSystemPrompt,
32
- renderAnalyzerExplorationMandatePrompt,
33
- renderContextPackPrompt,
34
- renderNavigationIndexPrompt,
35
13
  resolveArtifacts,
36
14
  resolveGuardrailContext,
37
- runTask,
38
- shouldInjectAnalyzerExplorationMandate,
39
- zodSchemaToPromptDescription,
40
- zodSchemaToYamlExample
41
- } from "./chunk-N4KNGDYY.js";
15
+ resolveNavigationDsl,
16
+ resolveNavigationSources
17
+ } from "./chunk-ABXDSTUV.js";
42
18
  import {
43
19
  jsonSchemaToZod
44
20
  } from "./chunk-ET6TGQRT.js";
21
+ import {
22
+ toolGrantForAgent
23
+ } from "./chunk-VJXGCWSZ.js";
45
24
  import {
46
25
  OBSERVABILITY_ENV_VARS,
47
26
  buildObservabilityEnv,
27
+ buildSdkFunctionTools,
28
+ createAnalyzerBridge,
48
29
  createExecutionEnvelope,
49
30
  emitIterationClose,
50
31
  emitIterationMetric,
@@ -59,26 +40,28 @@ import {
59
40
  emitToolExecOpen,
60
41
  emitToolchainClose,
61
42
  emitToolchainOpen,
43
+ isContextPack,
44
+ renderContextPackPrompt,
62
45
  serializeObserverEmit
63
- } from "./chunk-KXGUWBGK.js";
46
+ } from "./chunk-KTVMMG33.js";
64
47
  import {
65
48
  PROJECT_CONFIG_FILENAME,
66
49
  loadProjectConfig,
67
50
  loadWorkspaceMembers
68
- } from "./chunk-3H3PVPPF.js";
51
+ } from "./chunk-F5R46S7I.js";
69
52
  import {
70
- guardrailCacheKey
71
- } from "./chunk-LDCQZPDG.js";
53
+ isNavigationIndex,
54
+ renderNavigationIndexPrompt
55
+ } from "./chunk-3CLWG72V.js";
72
56
  import {
73
- PluginRegistry,
57
+ UNRESOLVED_GUARDRAIL_ACTION,
74
58
  createGuardrailHooks,
75
- createGuardrailHooksForAgent,
76
59
  createGuardrailHooksFromRules,
77
60
  getBlockingViolations,
78
61
  getWarnings,
79
62
  hasBlockingViolation,
80
- pluginRegistry
81
- } from "./chunk-NMX4C6LC.js";
63
+ toolTargetPath
64
+ } from "./chunk-MSVIEEGR.js";
82
65
  import {
83
66
  __commonJS,
84
67
  __require,
@@ -1520,7 +1503,7 @@ var require_parser = __commonJS({
1520
1503
  parseError: function parseError(str, hash) {
1521
1504
  throw new Error(str);
1522
1505
  },
1523
- parse: function parse4(input) {
1506
+ parse: function parse5(input) {
1524
1507
  var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
1525
1508
  this.lexer.setInput(input);
1526
1509
  this.lexer.yy = this.yy;
@@ -2433,7 +2416,7 @@ var require_base2 = __commonJS({
2433
2416
  "use strict";
2434
2417
  exports.__esModule = true;
2435
2418
  exports.parseWithoutProcessing = parseWithoutProcessing;
2436
- exports.parse = parse4;
2419
+ exports.parse = parse5;
2437
2420
  function _interopRequireWildcard(obj) {
2438
2421
  if (obj && obj.__esModule) {
2439
2422
  return obj;
@@ -2475,7 +2458,7 @@ var require_base2 = __commonJS({
2475
2458
  var ast = _parser2["default"].parse(input);
2476
2459
  return ast;
2477
2460
  }
2478
- function parse4(input, options) {
2461
+ function parse5(input, options) {
2479
2462
  var ast = parseWithoutProcessing(input, options);
2480
2463
  var strip = new _whitespaceControl2["default"](options);
2481
2464
  return strip.accept(ast);
@@ -5979,203 +5962,1347 @@ var require_lib = __commonJS({
5979
5962
  // src/index.ts
5980
5963
  import { createRequire } from "module";
5981
5964
 
5982
- // src/lib/toolchain-checker.ts
5983
- import { execFile } from "child_process";
5984
- import { readFile } from "fs/promises";
5985
- import { existsSync } from "fs";
5986
- import { resolve } from "path";
5987
- import { promisify } from "util";
5965
+ // src/lib/task-runner.ts
5988
5966
  import { z } from "zod";
5989
- import { parseToolchainFile } from "@aaac/toolchain";
5990
- var execFileAsync = promisify(execFile);
5991
- var SUBPROCESS_TIMEOUT_MS = 3e4;
5992
- var MANIFEST_FILENAME = ".toolchain-manifest.json";
5993
- var ToolchainManifestSchema = z.object({
5994
- schema: z.string(),
5995
- toolchain_id: z.string(),
5996
- generated_at: z.string(),
5997
- source_hash: z.string(),
5998
- output_hash: z.string(),
5999
- source_globs: z.array(z.string()).optional(),
6000
- output_globs: z.array(z.string()).optional(),
6001
- files: z.array(
6002
- z.object({
6003
- path: z.string(),
6004
- hash: z.string()
6005
- })
6006
- ).optional()
6007
- });
6008
- function resolveAction(checkType, checkTypeActions, defaultAction) {
6009
- if (checkTypeActions?.[checkType]) return checkTypeActions[checkType];
6010
- if (checkTypeActions?.["_default"]) return checkTypeActions["_default"];
6011
- return defaultAction ?? "warn";
5967
+ import * as yaml from "yaml";
5968
+
5969
+ // src/lib/plugin.ts
5970
+ function toCheckResult(result) {
5971
+ return {
5972
+ guardrail_id: result.guardrail_id,
5973
+ passed: !result.matched,
5974
+ action: result.action,
5975
+ message: result.matched ? result.message : ""
5976
+ };
6012
5977
  }
6013
- async function tryManifestFastPath(toolchainId, cwd) {
6014
- const manifestPath = resolve(cwd, MANIFEST_FILENAME);
6015
- if (!existsSync(manifestPath)) return null;
6016
- try {
6017
- const raw = await readFile(manifestPath, "utf-8");
6018
- const parsed = ToolchainManifestSchema.parse(JSON.parse(raw));
6019
- if (parsed.toolchain_id !== toolchainId) return null;
6020
- return {
6021
- toolchainId,
6022
- checkType: "drift",
6023
- status: "pass",
6024
- action: "warn",
6025
- message: `Manifest fast path: ${MANIFEST_FILENAME} found, toolchain_id matches`,
6026
- durationMs: 0
6027
- };
6028
- } catch {
5978
+ var PluginRegistry = class {
5979
+ plugins = [];
5980
+ register(plugin) {
5981
+ if (this.plugins.some((p) => p.id === plugin.id)) {
5982
+ throw new Error(`Plugin "${plugin.id}" is already registered`);
5983
+ }
5984
+ this.plugins.push(plugin);
5985
+ }
5986
+ getAll() {
5987
+ return this.plugins;
5988
+ }
5989
+ async runBeforeTask(taskId, context) {
5990
+ let ctx = context;
5991
+ for (const plugin of this.plugins) {
5992
+ if (!plugin.beforeTask || ctx === null) continue;
5993
+ ctx = await plugin.beforeTask(taskId, ctx);
5994
+ }
5995
+ return ctx;
5996
+ }
5997
+ async runAfterTask(taskId, outcome) {
5998
+ let result = outcome;
5999
+ for (const plugin of this.plugins) {
6000
+ if (!plugin.afterTask) continue;
6001
+ result = await plugin.afterTask(taskId, result);
6002
+ }
6003
+ return result;
6004
+ }
6005
+ applyContextEnhancers(taskId, context) {
6006
+ let ctx = context;
6007
+ for (const plugin of this.plugins) {
6008
+ if (!plugin.contextEnhancer) continue;
6009
+ ctx = plugin.contextEnhancer(taskId, ctx);
6010
+ }
6011
+ return ctx;
6012
+ }
6013
+ /**
6014
+ * Try plugin promptBuilder hooks. Returns custom prompt if any plugin provides one,
6015
+ * or null to use the default buildTaskPrompt.
6016
+ */
6017
+ applyPromptBuilder(args) {
6018
+ for (const plugin of this.plugins) {
6019
+ if (!plugin.promptBuilder) continue;
6020
+ const result = plugin.promptBuilder(args);
6021
+ if (result !== null) return result;
6022
+ }
6029
6023
  return null;
6030
6024
  }
6031
- }
6032
- async function executeCheck(command, cwd, observabilityIds) {
6033
- const env = observabilityIds ? buildObservabilityEnv(observabilityIds) : void 0;
6034
- try {
6035
- const { stdout, stderr } = await execFileAsync("sh", ["-c", command], {
6036
- cwd,
6037
- timeout: SUBPROCESS_TIMEOUT_MS,
6038
- ...env ? { env } : {}
6039
- });
6040
- return { exitCode: 0, stdout, stderr };
6041
- } catch (err) {
6042
- const execErr = err;
6043
- if (execErr.killed) {
6044
- throw new Error(`Command timed out after ${SUBPROCESS_TIMEOUT_MS}ms: ${command}`);
6025
+ applyPromptEnhancers(taskId, prompt, context) {
6026
+ let enhanced = prompt;
6027
+ for (const plugin of this.plugins) {
6028
+ if (!plugin.promptEnhancer) continue;
6029
+ enhanced = plugin.promptEnhancer(taskId, enhanced, context);
6045
6030
  }
6046
- const exitCode = typeof execErr.code === "number" ? execErr.code : 1;
6031
+ return enhanced;
6032
+ }
6033
+ evaluateCommandGuardrails(command) {
6034
+ const results = [];
6035
+ for (const plugin of this.plugins) {
6036
+ if (!plugin.customGuardrails?.evaluateCommand) continue;
6037
+ results.push(...plugin.customGuardrails.evaluateCommand(command));
6038
+ }
6039
+ return results;
6040
+ }
6041
+ evaluateFilePathGuardrails(filePath) {
6042
+ const results = [];
6043
+ for (const plugin of this.plugins) {
6044
+ if (!plugin.customGuardrails?.evaluateFilePath) continue;
6045
+ results.push(...plugin.customGuardrails.evaluateFilePath(filePath));
6046
+ }
6047
+ return results;
6048
+ }
6049
+ evaluateFileContentGuardrails(filePath, content) {
6050
+ const results = [];
6051
+ for (const plugin of this.plugins) {
6052
+ if (!plugin.customGuardrails?.evaluateFileContent) continue;
6053
+ results.push(...plugin.customGuardrails.evaluateFileContent(filePath, content));
6054
+ }
6055
+ return results;
6056
+ }
6057
+ /**
6058
+ * Whether `guardrailChecks()` would supply anything.
6059
+ *
6060
+ * The execution layer has to know this BEFORE it builds hooks, because it
6061
+ * decides whether hooks exist at all and the source it gets back is three
6062
+ * closures either way, indistinguishable from an empty one. It gated on the
6063
+ * resolved rules instead, so a project whose ONLY guardrails came from a
6064
+ * plugin got no hooks and its plugin was consulted nowhere (#332).
6065
+ *
6066
+ * The question is asked of the three EVALUATORS, not of `customGuardrails`
6067
+ * itself, because that is what the three aggregators above ask: each skips a
6068
+ * plugin whose own method is absent, so `customGuardrails: {}` — legal under
6069
+ * the type — contributes to no check. Answering `true` for it would report a
6070
+ * source that grades nothing, and the execution layer would give a project
6071
+ * one adapter per agent to carry hooks with nothing in them.
6072
+ *
6073
+ * Answering it belongs here for the same reason `guardrailChecks` does: the
6074
+ * shape of `AgentPlugin.customGuardrails` is this module's to know, and it is
6075
+ * read nowhere else.
6076
+ */
6077
+ hasGuardrails() {
6078
+ return this.plugins.some(
6079
+ ({ customGuardrails: g }) => Boolean(g?.evaluateCommand) || Boolean(g?.evaluateFilePath) || Boolean(g?.evaluateFileContent)
6080
+ );
6081
+ }
6082
+ /**
6083
+ * These plugins' `customGuardrails`, as a check source `createGuardrailHooks`
6084
+ * takes alongside the rules a software binding resolved.
6085
+ *
6086
+ * The evaluator used to reach for the `pluginRegistry` singleton itself. That
6087
+ * is an ambient dependency pointing the wrong way — a shared leaf module
6088
+ * reaching up into an application-level registry — and it had a measurable
6089
+ * price, because `guardrail-hooks` is on the LEAN graph: a class gets no
6090
+ * per-method tree-shaking, so the whole registry, task and workflow hooks
6091
+ * included, was 1,481 B of the 12,496 B `check-artifact-edit` parses on every
6092
+ * single tool call (#331). Handing the source in reverses the edge (this
6093
+ * module knows the evaluator's shape; the evaluator knows nothing of plugins)
6094
+ * and takes the class off that graph entirely.
6095
+ *
6096
+ * WHO passes it is the whole design, so it is stated here rather than left to
6097
+ * be inferred from call sites:
6098
+ *
6099
+ * - The EXECUTION layer does — `execute.ts`, for the hooks it hands each
6100
+ * agent's adapter. That is the process `loadPlugins` ran in
6101
+ * (`project-runtime.ts` → `plugin-loader.ts`), and plugin guardrails guard
6102
+ * what this runtime itself executes, exactly like every other
6103
+ * `AgentPlugin` hook, all of which the task and workflow runners consume.
6104
+ * - The HOOK routes do NOT — the two Claude Code PreToolUse bins and
6105
+ * `guard evaluate`. Those answer "may this editor do this?", and they have
6106
+ * to answer it identically or a project's rule means one thing in a Claude
6107
+ * Code session and another under `guard evaluate` (#316). Two of the three
6108
+ * CANNOT consult plugins at any price: they run on the lean bundle, which
6109
+ * deliberately excludes the project-manifest resolver, so the `plugins:`
6110
+ * list that `loadPlugins` needs is unreachable there — the shipped lean
6111
+ * bundle contains neither this class nor any `loadPlugins` or `register`
6112
+ * caller, so those processes hold no registry to consult at all. Feeding
6113
+ * the third one a source the other two structurally lack is what would
6114
+ * split the verdict; passing none keeps the three equal by construction
6115
+ * instead of by the accident of no project declaring a plugin.
6116
+ *
6117
+ * The closures consult `this.plugins` when a check runs, not when the source
6118
+ * is built. That is not a promise that a plugin registering later is picked
6119
+ * up: the caller asks `hasGuardrails()` first and never comes back for the
6120
+ * source when the answer was no, so a registration after that point reaches
6121
+ * no hooks. What holds instead is the order — `loadPlugins` runs once, while
6122
+ * `createProjectRuntime` builds the runtime, before anything can execute.
6123
+ */
6124
+ guardrailChecks() {
6047
6125
  return {
6048
- exitCode,
6049
- stdout: execErr.stdout ?? "",
6050
- stderr: execErr.stderr ?? ""
6126
+ checkCommand: (command) => this.evaluateCommandGuardrails(command).map(toCheckResult),
6127
+ checkFilePath: (filePath) => this.evaluateFilePathGuardrails(filePath).map(toCheckResult),
6128
+ checkContent: (filePath, content) => this.evaluateFileContentGuardrails(filePath, content).map(toCheckResult)
6051
6129
  };
6052
6130
  }
6053
- }
6054
- async function runToolchainChecks(options) {
6055
- const {
6056
- toolchainsPath,
6057
- cwd: workingDir,
6058
- checkTypes,
6059
- toolchainFilter,
6060
- checkTypeActions,
6061
- defaultAction,
6062
- observer,
6063
- parentSpanId,
6064
- componentId,
6065
- observabilityIds
6066
- } = options;
6067
- const cwd = workingDir ?? process.cwd();
6068
- const contracts = await parseToolchainFile(toolchainsPath);
6069
- const results = [];
6070
- for (const [toolchainId, toolchain] of Object.entries(contracts.toolchains)) {
6071
- if (!toolchain.checks) continue;
6072
- if (toolchainFilter && !toolchainFilter.includes(toolchainId)) continue;
6073
- for (const [checkType, command] of Object.entries(toolchain.checks)) {
6074
- if (checkTypes && !checkTypes.includes(checkType)) continue;
6075
- const action = resolveAction(checkType, checkTypeActions, defaultAction);
6076
- const start = performance.now();
6077
- const spanId = emitToolchainOpen(
6078
- observer,
6079
- parentSpanId,
6080
- toolchainId,
6081
- checkType,
6082
- [],
6083
- componentId
6084
- );
6085
- let result;
6086
- const fastResult = checkType === "drift" && options.artifactsPath ? await tryManifestFastPath(toolchainId, cwd) : null;
6087
- if (fastResult) {
6088
- fastResult.action = action;
6089
- result = fastResult;
6090
- } else {
6091
- try {
6092
- const { exitCode, stderr } = await executeCheck(command, cwd, observabilityIds);
6093
- const durationMs = Math.round(performance.now() - start);
6094
- result = {
6095
- toolchainId,
6096
- checkType,
6097
- status: exitCode === 0 ? "pass" : "fail",
6098
- action,
6099
- message: exitCode === 0 ? void 0 : stderr.trim() || `exit code ${exitCode}`,
6100
- durationMs
6101
- };
6102
- } catch (err) {
6103
- const durationMs = Math.round(performance.now() - start);
6104
- result = {
6105
- toolchainId,
6106
- checkType,
6107
- status: "error",
6108
- action,
6109
- message: err.message,
6110
- durationMs
6111
- };
6112
- }
6113
- }
6114
- results.push(result);
6115
- emitToolchainClose(
6116
- observer,
6117
- spanId ?? "",
6118
- toolchainId,
6119
- checkType,
6120
- result.durationMs ?? Math.round(performance.now() - start),
6121
- result.status === "pass" ? "success" : "failure",
6122
- result.status === "pass" ? void 0 : result.message
6123
- );
6131
+ async runBeforeWorkflow(workflowId, userRequest) {
6132
+ for (const plugin of this.plugins) {
6133
+ if (!plugin.beforeWorkflow) continue;
6134
+ await plugin.beforeWorkflow(workflowId, userRequest);
6124
6135
  }
6125
6136
  }
6126
- return results;
6127
- }
6137
+ async runAfterWorkflow(workflowId, result) {
6138
+ for (const plugin of this.plugins) {
6139
+ if (!plugin.afterWorkflow) continue;
6140
+ await plugin.afterWorkflow(workflowId, result);
6141
+ }
6142
+ }
6143
+ };
6144
+ var pluginRegistry = new PluginRegistry();
6128
6145
 
6129
- // src/lib/workflow-input.ts
6130
- var WORKFLOW_INPUT_STEP_ID = "workflow-input";
6131
- function buildWorkflowInputOutput(userRequest, handoff) {
6132
- return {
6133
- user_request: userRequest,
6134
- ...handoff ? {
6135
- handoff: {
6136
- type: handoff.type,
6137
- ...handoff.version !== void 0 ? { version: handoff.version } : {},
6138
- payload: handoff.payload
6139
- }
6140
- } : {}
6141
- };
6142
- }
6143
- function stepDependsOnWorkflowInput(dependsOn) {
6144
- return dependsOn?.includes(WORKFLOW_INPUT_STEP_ID) ?? false;
6145
- }
6146
- function formatWorkflowInputContext(output) {
6147
- return `
6146
+ // src/lib/candidate-agents.ts
6147
+ function renderAgentSystemPrompt(agent) {
6148
+ const sections = [];
6149
+ sections.push(`# Role: ${agent.role_name}
6148
6150
 
6149
- --- Step: ${WORKFLOW_INPUT_STEP_ID} ---
6150
- ${JSON.stringify(output, null, 2)}`;
6151
+ ${agent.purpose}`);
6152
+ if (agent.responsibilities.length > 0) {
6153
+ sections.push(
6154
+ `## Responsibilities
6155
+
6156
+ ${agent.responsibilities.map((r) => `- ${r}`).join("\n")}`
6157
+ );
6158
+ }
6159
+ if (agent.constraints.length > 0) {
6160
+ sections.push(
6161
+ `## Constraints
6162
+
6163
+ ${agent.constraints.map((c) => `- ${c}`).join("\n")}`
6164
+ );
6165
+ }
6166
+ if (agent.rules && agent.rules.length > 0) {
6167
+ const ruleLines = agent.rules.map(
6168
+ (r) => `- **${r.id}** [${r.severity}]: ${r.description}`
6169
+ );
6170
+ sections.push(`## Rules
6171
+
6172
+ ${ruleLines.join("\n")}`);
6173
+ }
6174
+ if (agent.anti_patterns && agent.anti_patterns.length > 0) {
6175
+ sections.push(
6176
+ `## Anti-patterns
6177
+
6178
+ ${agent.anti_patterns.map((a) => `- ${a}`).join("\n")}`
6179
+ );
6180
+ }
6181
+ if (agent.escalation_criteria && agent.escalation_criteria.length > 0) {
6182
+ const lines = agent.escalation_criteria.map((e) => `- **${e.condition}** \u2192 ${e.action}`);
6183
+ sections.push(`## Escalation Criteria
6184
+
6185
+ ${lines.join("\n")}`);
6186
+ }
6187
+ const canDecide = agent.authority?.can_decide ?? [];
6188
+ const cannotDecide = agent.authority?.cannot_decide ?? [];
6189
+ if (canDecide.length > 0 || cannotDecide.length > 0) {
6190
+ const lines = [];
6191
+ if (canDecide.length > 0) lines.push(`- **Can decide**: ${canDecide.join(", ")}`);
6192
+ if (cannotDecide.length > 0) lines.push(`- **Cannot decide**: ${cannotDecide.join(", ")}`);
6193
+ sections.push(`## Authority Boundaries
6194
+
6195
+ ${lines.join("\n")}`);
6196
+ }
6197
+ if (agent.audit_checklist && agent.audit_checklist.length > 0) {
6198
+ const groups = agent.audit_checklist.map(
6199
+ (group) => `### ${group.section}
6200
+
6201
+ ${group.checks.map((c) => `- [ ] ${c}`).join("\n")}`
6202
+ );
6203
+ sections.push(`## Audit Checklist
6204
+
6205
+ ${groups.join("\n\n")}`);
6206
+ }
6207
+ for (const section of agent.sections ?? []) {
6208
+ sections.push(`## ${section.title}
6209
+
6210
+ ${section.content}`);
6211
+ }
6212
+ return sections.join("\n\n");
6213
+ }
6214
+ function deriveDescription(purpose) {
6215
+ const firstLine = purpose.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
6216
+ const sentenceEnd = firstLine.search(/[.!?](\s|$)/);
6217
+ if (sentenceEnd !== -1) {
6218
+ return firstLine.slice(0, sentenceEnd + 1).trim();
6219
+ }
6220
+ return firstLine;
6221
+ }
6222
+ function buildCandidateAgents(agentRegistry, opts) {
6223
+ const entryId = opts?.entryAgentId;
6224
+ const allowed = opts?.allowedAgentIds;
6225
+ const allowSet = allowed ? new Set(allowed) : void 0;
6226
+ const candidates = [];
6227
+ for (const [id, agent] of Object.entries(agentRegistry)) {
6228
+ if (id === entryId) continue;
6229
+ if (allowSet && !allowSet.has(id)) continue;
6230
+ const agentTools = opts?.toolsByAgent?.get(id) ?? [];
6231
+ candidates.push({
6232
+ name: id,
6233
+ description: deriveDescription(agent.purpose),
6234
+ prompt: renderAgentSystemPrompt(agent),
6235
+ ...agentTools.length > 0 ? { tools: agentTools } : {}
6236
+ });
6237
+ }
6238
+ return candidates;
6151
6239
  }
6152
6240
 
6153
- // src/lib/workflow-runner.ts
6154
- function isAdapterFactory(v) {
6155
- return typeof v === "function" && !("send" in v);
6241
+ // src/lib/model-pricing.ts
6242
+ function normalizeModelId(model) {
6243
+ return model.trim().toLowerCase();
6244
+ }
6245
+ var PRICING_TABLE = {
6246
+ // Anthropic Claude
6247
+ "claude-opus-4-6": { inputPerMillion: 15, outputPerMillion: 75 },
6248
+ "claude-opus-4": { inputPerMillion: 15, outputPerMillion: 75 },
6249
+ "claude-sonnet-4": { inputPerMillion: 3, outputPerMillion: 15 },
6250
+ "claude-sonnet-4-6": { inputPerMillion: 3, outputPerMillion: 15 },
6251
+ "claude-haiku-4": { inputPerMillion: 0.8, outputPerMillion: 4 },
6252
+ // OpenAI GPT
6253
+ "gpt-5.5": { inputPerMillion: 2.5, outputPerMillion: 10 },
6254
+ "gpt-5.3-codex": { inputPerMillion: 2.5, outputPerMillion: 10 },
6255
+ "gpt-4.1": { inputPerMillion: 2, outputPerMillion: 8 },
6256
+ "gpt-4o": { inputPerMillion: 2.5, outputPerMillion: 10 },
6257
+ "gpt-4o-mini": { inputPerMillion: 0.15, outputPerMillion: 0.6 },
6258
+ // Google Gemini
6259
+ "gemini-2.5-pro": { inputPerMillion: 1.25, outputPerMillion: 10 },
6260
+ "gemini-2.5-flash": { inputPerMillion: 0.15, outputPerMillion: 0.6 },
6261
+ "gemini-2.0-flash": { inputPerMillion: 0.1, outputPerMillion: 0.4 }
6262
+ };
6263
+ function resolveModelPricing(model) {
6264
+ if (!model) return void 0;
6265
+ const key = normalizeModelId(model);
6266
+ if (PRICING_TABLE[key]) return PRICING_TABLE[key];
6267
+ for (const [known, pricing] of Object.entries(PRICING_TABLE)) {
6268
+ if (key.startsWith(known)) return pricing;
6269
+ }
6270
+ return void 0;
6271
+ }
6272
+ function computeCostUsd(model, inputTokens, outputTokens) {
6273
+ const pricing = resolveModelPricing(model);
6274
+ if (!pricing) return void 0;
6275
+ if (inputTokens <= 0 && outputTokens <= 0) return void 0;
6276
+ const cost = (inputTokens * pricing.inputPerMillion + outputTokens * pricing.outputPerMillion) / 1e6;
6277
+ return Math.round(cost * 1e6) / 1e6;
6156
6278
  }
6157
- function resolveAdapter(adapterOrFactory) {
6158
- if (isAdapterFactory(adapterOrFactory)) {
6159
- const result = adapterOrFactory();
6160
- if (result && typeof result.then === "function") {
6161
- throw new Error("ModelAwareSdkAdapterFactory returned a Promise for the default adapter. Use a synchronous factory or pre-resolve the default adapter.");
6162
- }
6163
- return { adapter: result, factory: adapterOrFactory };
6279
+
6280
+ // src/lib/process-axis-bridge.ts
6281
+ import { generateId } from "@aaac/observability";
6282
+ function attrs(base) {
6283
+ const out = {};
6284
+ for (const [k, v] of Object.entries(base)) {
6285
+ if (v !== void 0 && v !== "") out[k] = v;
6164
6286
  }
6165
- return { adapter: adapterOrFactory, factory: void 0 };
6287
+ return out;
6166
6288
  }
6167
- function resolveInvocation(invocation) {
6168
- let userRequest;
6169
- if (invocation.handoff) {
6170
- const h = invocation.handoff;
6171
- userRequest = invocation.user_request ? invocation.user_request : typeof h.payload === "string" ? h.payload : JSON.stringify(h.payload, null, 2);
6172
- } else {
6173
- userRequest = invocation.user_request ?? "";
6174
- }
6175
- const ctx = invocation.context;
6176
- const variables = { ...ctx?.variables };
6177
- if (ctx?.cwd) variables.cwd = ctx.cwd;
6178
- if (ctx?.environment) variables.environment = ctx.environment;
6289
+ var FILE_EDIT_TOOL_NAMES = /* @__PURE__ */ new Set([
6290
+ "write",
6291
+ "edit",
6292
+ "multiedit",
6293
+ "multi_edit",
6294
+ "notebookedit",
6295
+ "notebook_edit"
6296
+ ]);
6297
+ function isFileEditTool(toolName) {
6298
+ if (!toolName) return false;
6299
+ return FILE_EDIT_TOOL_NAMES.has(toolName.toLowerCase());
6300
+ }
6301
+ function emitProcessWorkflowOpen(options) {
6302
+ if (!options.observer) return void 0;
6303
+ const spanId = generateId();
6304
+ options.observer({
6305
+ source: "aaac-runtime",
6306
+ eventType: "process.workflow",
6307
+ lifecycle: "open",
6308
+ spanId,
6309
+ parentSpanId: options.parentSpanId,
6310
+ attributes: attrs({
6311
+ axis: "process",
6312
+ "agent.session_id": options.sessionId,
6313
+ "workflow.id": options.workflowId
6314
+ })
6315
+ });
6316
+ return spanId;
6317
+ }
6318
+ function emitProcessWorkflowClose(spanId, options) {
6319
+ if (!options.observer) return;
6320
+ options.observer({
6321
+ source: "aaac-runtime",
6322
+ eventType: "process.workflow",
6323
+ lifecycle: "close",
6324
+ spanId,
6325
+ attributes: attrs({
6326
+ axis: "process",
6327
+ "workflow.status": options.status,
6328
+ ...options.durationMs !== void 0 ? { "workflow.duration_ms": options.durationMs } : {}
6329
+ })
6330
+ });
6331
+ }
6332
+ function emitProcessTaskOpen(options) {
6333
+ if (!options.observer) return void 0;
6334
+ const spanId = generateId();
6335
+ options.observer({
6336
+ source: "aaac-runtime",
6337
+ eventType: "process.task",
6338
+ lifecycle: "open",
6339
+ spanId,
6340
+ parentSpanId: options.parentSpanId,
6341
+ attributes: attrs({
6342
+ axis: "process",
6343
+ "agent.session_id": options.sessionId,
6344
+ "task.id": options.taskId,
6345
+ "task.type": "implement",
6346
+ "task.target_agent": options.targetAgent
6347
+ })
6348
+ });
6349
+ return spanId;
6350
+ }
6351
+ function emitProcessTaskClose(spanId, options) {
6352
+ if (!options.observer) return;
6353
+ options.observer({
6354
+ source: "aaac-runtime",
6355
+ eventType: "process.task",
6356
+ lifecycle: "close",
6357
+ spanId,
6358
+ attributes: attrs({
6359
+ axis: "process",
6360
+ "task.status": options.status,
6361
+ ...options.durationMs !== void 0 ? { "task.duration_ms": options.durationMs } : {}
6362
+ })
6363
+ });
6364
+ }
6365
+ function emitProcessEdit(options) {
6366
+ if (!options.observer) return void 0;
6367
+ const spanId = generateId();
6368
+ options.observer({
6369
+ source: "aaac-runtime",
6370
+ eventType: "process.edit",
6371
+ lifecycle: "instant",
6372
+ spanId,
6373
+ parentSpanId: options.parentSpanId,
6374
+ attributes: attrs({
6375
+ axis: "process",
6376
+ "agent.session_id": options.sessionId,
6377
+ "edit.path": options.filePath,
6378
+ "edit.artifact_id": options.artifactId
6379
+ })
6380
+ });
6381
+ return spanId;
6382
+ }
6383
+
6384
+ // src/lib/task-runner.ts
6385
+ function getZodChecks(schema) {
6386
+ const def = schema._def;
6387
+ return def?.checks ?? [];
6388
+ }
6389
+ function extractZodConstraints(schema) {
6390
+ const inner = unwrapOptional(schema);
6391
+ const parts = [];
6392
+ if (inner instanceof z.ZodString) {
6393
+ const str = inner;
6394
+ if (str.minLength != null) parts.push(`min: ${str.minLength}`);
6395
+ if (str.maxLength != null) parts.push(`max: ${str.maxLength}`);
6396
+ for (const check of getZodChecks(inner)) {
6397
+ if (check.kind === "min") parts.push(`min: ${check.value}`);
6398
+ if (check.kind === "max") parts.push(`max: ${check.value}`);
6399
+ if (check.kind === "regex" && check.regex) parts.push(`regex: ${check.regex}`);
6400
+ const def = check._zod?.def;
6401
+ if (def?.format === "regex" && def.pattern instanceof RegExp) {
6402
+ parts.push(`regex: ${def.pattern}`);
6403
+ }
6404
+ }
6405
+ } else if (inner instanceof z.ZodNumber) {
6406
+ let hasInt = false;
6407
+ for (const check of getZodChecks(inner)) {
6408
+ if (check.kind === "int") hasInt = true;
6409
+ if (check.kind === "min") parts.push(`min: ${check.value}`);
6410
+ if (check.kind === "max") parts.push(`max: ${check.value}`);
6411
+ if (check.isInt) hasInt = true;
6412
+ const def = check._zod?.def;
6413
+ if (def?.check === "number_format" && def.format === "safeint") hasInt = true;
6414
+ if (def?.check === "greater_than") parts.push(`min: ${def.value}`);
6415
+ if (def?.check === "less_than") parts.push(`max: ${def.value}`);
6416
+ }
6417
+ if (hasInt) parts.unshift("int");
6418
+ } else if (inner instanceof z.ZodArray) {
6419
+ for (const check of getZodChecks(inner)) {
6420
+ if (check.kind === "min") parts.push(`min: ${check.value}`);
6421
+ if (check.kind === "max") parts.push(`max: ${check.value}`);
6422
+ const def = check._zod?.def;
6423
+ if (def?.check === "min_length") parts.push(`min: ${def.minimum}`);
6424
+ if (def?.check === "max_length") parts.push(`max: ${def.maximum}`);
6425
+ }
6426
+ }
6427
+ return parts.length > 0 ? parts.join(", ") : void 0;
6428
+ }
6429
+ function zodTypeToString(schema) {
6430
+ if (schema instanceof z.ZodString) return "string";
6431
+ if (schema instanceof z.ZodNumber) return "number";
6432
+ if (schema instanceof z.ZodBoolean) return "boolean";
6433
+ if (schema instanceof z.ZodEnum) return `enum(${schema.options.join(", ")})`;
6434
+ if (schema instanceof z.ZodLiteral) return `"${String(schema._def.values[0])}"`;
6435
+ if (schema instanceof z.ZodArray) {
6436
+ const element = schema._def.element;
6437
+ const inner = zodTypeToString(element);
6438
+ return `${inner}[]`;
6439
+ }
6440
+ if (schema instanceof z.ZodObject) return "object";
6441
+ if (schema instanceof z.ZodOptional) {
6442
+ return zodTypeToString(schema._def.innerType);
6443
+ }
6444
+ if (schema instanceof z.ZodRecord) return "Record<string, unknown>";
6445
+ return "unknown";
6446
+ }
6447
+ function unwrapOptional(schema) {
6448
+ if (schema instanceof z.ZodOptional) {
6449
+ return schema._def.innerType;
6450
+ }
6451
+ return schema;
6452
+ }
6453
+ function getArrayElement(schema) {
6454
+ const inner = unwrapOptional(schema);
6455
+ if (inner instanceof z.ZodArray) {
6456
+ return inner._def.element;
6457
+ }
6458
+ return null;
6459
+ }
6460
+ function extractFieldDescriptors(schema) {
6461
+ let shape = null;
6462
+ if (schema instanceof z.ZodObject) {
6463
+ shape = schema.shape;
6464
+ }
6465
+ if (!shape) return null;
6466
+ return Object.entries(shape).map(([name, field]) => {
6467
+ const isOptional = field instanceof z.ZodOptional;
6468
+ const innerField = isOptional ? field._def.innerType : field;
6469
+ const description = innerField.description ?? field.description;
6470
+ return {
6471
+ name,
6472
+ type: zodTypeToString(field),
6473
+ required: !isOptional,
6474
+ description,
6475
+ constraints: extractZodConstraints(innerField)
6476
+ };
6477
+ });
6478
+ }
6479
+ function zodSchemaToPromptDescription(schema) {
6480
+ const tables = [];
6481
+ collectFieldTables(schema, "", tables);
6482
+ return tables.join("\n\n");
6483
+ }
6484
+ function collectFieldTables(schema, pathPrefix, tables) {
6485
+ const fields = extractFieldDescriptors(schema);
6486
+ if (!fields || fields.length === 0) return;
6487
+ const title = pathPrefix ? `**${pathPrefix}**
6488
+
6489
+ ` : "";
6490
+ const header = "| Field | Type | Required | Constraints | Description |";
6491
+ const sep = "|-------|------|----------|-------------|-------------|";
6492
+ const rows = fields.map(
6493
+ (f) => `| ${f.name} | ${f.type} | ${f.required ? "Yes" : "No"} | ${f.constraints ?? ""} | ${f.description ?? ""} |`
6494
+ );
6495
+ tables.push(`${title}${[header, sep, ...rows].join("\n")}`);
6496
+ const shape = schema instanceof z.ZodObject ? schema.shape : null;
6497
+ if (!shape) return;
6498
+ for (const f of fields) {
6499
+ const rawField = shape[f.name];
6500
+ const inner = unwrapOptional(rawField);
6501
+ if (inner instanceof z.ZodObject) {
6502
+ collectFieldTables(inner, pathPrefix ? `${pathPrefix}.${f.name}` : f.name, tables);
6503
+ } else if (inner instanceof z.ZodArray) {
6504
+ const element = inner._def.element;
6505
+ if (element instanceof z.ZodObject) {
6506
+ collectFieldTables(element, pathPrefix ? `${pathPrefix}.${f.name}[]` : `${f.name}[]`, tables);
6507
+ }
6508
+ }
6509
+ }
6510
+ }
6511
+ function zodSchemaToYamlExample(schema, maxDepth = 3) {
6512
+ return renderYamlObject(schema, 0, maxDepth);
6513
+ }
6514
+ function renderYamlObject(schema, indent, maxDepth) {
6515
+ const fields = extractFieldDescriptors(schema);
6516
+ if (!fields || fields.length === 0) return "";
6517
+ const prefix = " ".repeat(indent);
6518
+ const lines = [];
6519
+ for (const f of fields) {
6520
+ const shape = schema instanceof z.ZodObject ? schema.shape : null;
6521
+ const rawField = shape?.[f.name];
6522
+ if (f.type.endsWith("[]")) {
6523
+ lines.push(`${prefix}${f.name}:`);
6524
+ const element = rawField ? getArrayElement(rawField) : null;
6525
+ if (element && element instanceof z.ZodObject && indent < maxDepth) {
6526
+ const nested = renderYamlObject(element, indent + 2, maxDepth);
6527
+ if (nested) {
6528
+ const basePrefix = " ".repeat(indent + 2);
6529
+ const nestedLines = nested.split("\n");
6530
+ lines.push(`${prefix} - ${nestedLines[0].slice(basePrefix.length)}`);
6531
+ for (let i = 1; i < nestedLines.length; i++) {
6532
+ lines.push(`${prefix} ${nestedLines[i].slice(basePrefix.length)}`);
6533
+ }
6534
+ } else {
6535
+ lines.push(`${prefix} - key: "value"`);
6536
+ }
6537
+ } else if (f.type === "string[]") {
6538
+ lines.push(`${prefix} - "example"`);
6539
+ } else {
6540
+ lines.push(`${prefix} - key: "value"`);
6541
+ }
6542
+ } else if (f.type === "object" && indent < maxDepth) {
6543
+ const inner = rawField ? unwrapOptional(rawField) : null;
6544
+ if (inner && inner instanceof z.ZodObject) {
6545
+ lines.push(`${prefix}${f.name}:`);
6546
+ const nested = renderYamlObject(inner, indent + 1, maxDepth);
6547
+ if (nested) {
6548
+ lines.push(nested);
6549
+ } else {
6550
+ lines.push(`${prefix} key: "value"`);
6551
+ }
6552
+ } else {
6553
+ lines.push(`${prefix}${f.name}:`);
6554
+ lines.push(`${prefix} key: "value"`);
6555
+ }
6556
+ } else if (f.type === "string") {
6557
+ lines.push(`${prefix}${f.name}: "..."`);
6558
+ } else if (f.type === "number") {
6559
+ lines.push(`${prefix}${f.name}: 0`);
6560
+ } else if (f.type === "boolean") {
6561
+ lines.push(`${prefix}${f.name}: false`);
6562
+ } else if (f.type.startsWith("enum(")) {
6563
+ const enumVals = f.type.slice(5, -1).split(", ");
6564
+ lines.push(`${prefix}${f.name}: "${enumVals[0]}"`);
6565
+ } else {
6566
+ lines.push(`${prefix}${f.name}: "..."`);
6567
+ }
6568
+ }
6569
+ return lines.join("\n");
6570
+ }
6571
+ function collectAnalyzerToolIds(registry) {
6572
+ if (!registry) return [];
6573
+ return registry.getAll().map((def) => def.toolId).filter((id) => id.startsWith("analyzer."));
6574
+ }
6575
+ function shouldInjectAnalyzerExplorationMandate(context) {
6576
+ return isNavigationIndex(context.variables?.navigationIndex);
6577
+ }
6578
+ function renderAnalyzerExplorationMandatePrompt(toolIds) {
6579
+ const tools = toolIds.length > 0 ? toolIds.map((id) => `- \`${id}\``).join("\n") : "- `analyzer.getContextMap`\n- `analyzer.analyzeImpact`\n- `analyzer.generateContextPack`\n- `analyzer.buildCallGraph`";
6580
+ return [
6581
+ "## Codebase Exploration Protocol (Level 2)",
6582
+ "",
6583
+ "A Project Navigation Index is provided in the user prompt. When you need to",
6584
+ "investigate the codebase (locate affected files, trace dependencies, or scope",
6585
+ "changes), you MUST use the analyzer MCP tools **before** ad-hoc Read/Grep/Glob:",
6586
+ "",
6587
+ "1. Use the navigation index to pick candidate artifacts and path patterns.",
6588
+ "2. Call `analyzer.getContextMap` with your `instruction` and `candidates[]`.",
6589
+ "3. Review suggestedReadTargets / suggestedEditTargets / suggestedValidationTargets.",
6590
+ "4. Call `analyzer.analyzeImpact` when you need a flat impact report.",
6591
+ "5. Use Read/Grep/Glob only for gaps the analyzer output did not cover.",
6592
+ "",
6593
+ "Available analyzer tools:",
6594
+ tools
6595
+ ].join("\n");
6596
+ }
6597
+ function buildSplitTaskPrompt(agent, task, context, options) {
6598
+ const system = [];
6599
+ system.push(renderAgentSystemPrompt(agent));
6600
+ if (options?.analyzerExploration?.toolIds.length && shouldInjectAnalyzerExplorationMandate(context)) {
6601
+ system.push(
6602
+ renderAnalyzerExplorationMandatePrompt(options.analyzerExploration.toolIds)
6603
+ );
6604
+ }
6605
+ system.push(`## Task: ${task.id}
6606
+
6607
+ ${task.description}`);
6608
+ if (task.completion_criteria.length > 0) {
6609
+ system.push(
6610
+ `## Completion Criteria
6611
+
6612
+ ${task.completion_criteria.map((c) => `- ${c}`).join("\n")}`
6613
+ );
6614
+ }
6615
+ const handoffId = task.result_handoff;
6616
+ const schema = options?.handoffSchemas?.[handoffId];
6617
+ let outputSection = `## Required Output Format
6618
+
6619
+ Return your result as a YAML block matching the "${handoffId}" schema.`;
6620
+ if (schema) {
6621
+ const fieldTable = zodSchemaToPromptDescription(schema);
6622
+ if (fieldTable) {
6623
+ outputSection += `
6624
+
6625
+ ${fieldTable}`;
6626
+ }
6627
+ const yamlExample = zodSchemaToYamlExample(schema);
6628
+ if (yamlExample) {
6629
+ outputSection += `
6630
+
6631
+ Example:
6632
+
6633
+ \`\`\`yaml
6634
+ ${yamlExample}
6635
+ \`\`\``;
6636
+ }
6637
+ } else {
6638
+ outputSection += ` Include all required fields.`;
6639
+ }
6640
+ system.push(outputSection);
6641
+ if (options?.retry) {
6642
+ const r = options.retry;
6643
+ let recoverySection = `## Recovery Instructions
6644
+
6645
+ If the task fails due to: "${r.condition}"
6646
+ \u2192 Apply the recovery approach from task "${r.fix_task}"`;
6647
+ if (r.revalidate_task) {
6648
+ recoverySection += `
6649
+ \u2192 Then revalidate using task "${r.revalidate_task}"`;
6650
+ }
6651
+ system.push(recoverySection);
6652
+ }
6653
+ const userSections = [];
6654
+ userSections.push(`## User Request
6655
+
6656
+ ${context.user_request}`);
6657
+ if (context.handoff_input) {
6658
+ const hi = context.handoff_input;
6659
+ const payloadStr = typeof hi.payload === "string" ? hi.payload : yaml.stringify(hi.payload);
6660
+ userSections.push(`## Handoff Input (${hi.type})
6661
+
6662
+ \`\`\`yaml
6663
+ ${payloadStr}\`\`\``);
6664
+ }
6665
+ if (context.prior_context) {
6666
+ userSections.push(`## Prior Context
6667
+
6668
+ ${context.prior_context}`);
6669
+ }
6670
+ if (context.relevant_paths && context.relevant_paths.length > 0) {
6671
+ userSections.push(
6672
+ `## Relevant Files
6673
+
6674
+ ${context.relevant_paths.map((p) => `- ${p}`).join("\n")}`
6675
+ );
6676
+ }
6677
+ if (context.acceptance_criteria && context.acceptance_criteria.length > 0) {
6678
+ userSections.push(
6679
+ `## Acceptance Criteria
6680
+
6681
+ ${context.acceptance_criteria.map((c) => `- ${c}`).join("\n")}`
6682
+ );
6683
+ }
6684
+ if (context.variables && Object.keys(context.variables).length > 0) {
6685
+ const contextPack = context.variables.analyzerContextPack;
6686
+ if (isContextPack(contextPack)) {
6687
+ userSections.push(renderContextPackPrompt(contextPack));
6688
+ }
6689
+ const navigationIndex = context.variables.navigationIndex;
6690
+ if (isNavigationIndex(navigationIndex)) {
6691
+ userSections.push(renderNavigationIndexPrompt(navigationIndex));
6692
+ }
6693
+ const otherVars = Object.entries(context.variables).filter(
6694
+ ([k]) => k !== "analyzerContextPack" && k !== "navigationIndex"
6695
+ );
6696
+ if (otherVars.length > 0) {
6697
+ const varLines = otherVars.map(([k, v]) => `- ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join("\n");
6698
+ userSections.push(`## Context Variables
6699
+
6700
+ ${varLines}`);
6701
+ }
6702
+ }
6703
+ return {
6704
+ system,
6705
+ user: userSections.join("\n\n---\n\n")
6706
+ };
6707
+ }
6708
+ function joinSplitPrompt(split) {
6709
+ return [...split.system, split.user].join("\n\n---\n\n");
6710
+ }
6711
+ function buildTaskPrompt(agent, task, context, options) {
6712
+ return joinSplitPrompt(buildSplitTaskPrompt(agent, task, context, options));
6713
+ }
6714
+ function extractStructuredResult(raw) {
6715
+ const yamlMatch = raw.match(/```ya?ml\n([\s\S]*?)```/);
6716
+ if (yamlMatch) {
6717
+ try {
6718
+ return yaml.parse(yamlMatch[1]);
6719
+ } catch {
6720
+ }
6721
+ }
6722
+ const jsonMatch = raw.match(/```json\n([\s\S]*?)```/);
6723
+ if (jsonMatch) {
6724
+ try {
6725
+ return JSON.parse(jsonMatch[1]);
6726
+ } catch {
6727
+ }
6728
+ }
6729
+ try {
6730
+ return JSON.parse(raw);
6731
+ } catch {
6732
+ }
6733
+ return null;
6734
+ }
6735
+ function validateOutput(fullOutput, task, schemas) {
6736
+ if (!fullOutput.trim()) {
6737
+ return { status: "error", message: "Agent returned empty output" };
6738
+ }
6739
+ const parsed = extractStructuredResult(fullOutput);
6740
+ if (!parsed) {
6741
+ return {
6742
+ status: "validation_error",
6743
+ errors: new z.ZodError([{ code: "custom", message: "Could not extract structured result from agent output", path: [] }]),
6744
+ raw: fullOutput
6745
+ };
6746
+ }
6747
+ const schema = schemas[task.result_handoff];
6748
+ if (!schema) {
6749
+ return { status: "success", data: parsed, raw: fullOutput };
6750
+ }
6751
+ const validation = schema.safeParse(parsed);
6752
+ if (!validation.success) {
6753
+ return { status: "validation_error", errors: validation.error, raw: fullOutput };
6754
+ }
6755
+ const data = validation.data;
6756
+ if (data.escalation_needed === true) {
6757
+ return {
6758
+ status: "escalation",
6759
+ reason: data.escalation_reasons ?? "Agent requested escalation",
6760
+ raw: fullOutput
6761
+ };
6762
+ }
6763
+ return { status: "success", data: validation.data, raw: fullOutput };
6764
+ }
6765
+ function attachMemoryRef(outcome, adapter) {
6766
+ if (outcome.status !== "success") return outcome;
6767
+ const ref = adapter.getLastMemoryRef?.();
6768
+ if (!ref) return outcome;
6769
+ return { ...outcome, memoryRef: ref };
6770
+ }
6771
+ function buildRetryFollowUp(task, lastOutcome, options) {
6772
+ const sections = [];
6773
+ sections.push(
6774
+ "Your previous response could not be validated. The task work itself is fine \u2014 please re-output only the structured result block in the correct format."
6775
+ );
6776
+ if (lastOutcome.status === "validation_error") {
6777
+ sections.push(`Validation errors:
6778
+ ${lastOutcome.errors.message}`);
6779
+ } else if (lastOutcome.status === "error") {
6780
+ sections.push(`Error: ${lastOutcome.message}`);
6781
+ }
6782
+ const handoffId = task.result_handoff;
6783
+ const schema = options?.handoffSchemas?.[handoffId];
6784
+ let formatSection = `Required format: Return your result as a YAML block matching the "${handoffId}" schema.`;
6785
+ if (schema) {
6786
+ const fieldTable = zodSchemaToPromptDescription(schema);
6787
+ if (fieldTable) {
6788
+ formatSection += `
6789
+
6790
+ ${fieldTable}`;
6791
+ }
6792
+ const yamlExample = zodSchemaToYamlExample(schema);
6793
+ if (yamlExample) {
6794
+ formatSection += `
6795
+
6796
+ Example:
6797
+
6798
+ \`\`\`yaml
6799
+ ${yamlExample}
6800
+ \`\`\``;
6801
+ }
6802
+ } else {
6803
+ formatSection += ` Include all required fields.`;
6804
+ }
6805
+ sections.push(formatSection);
6806
+ return sections.join("\n\n");
6807
+ }
6808
+ function defaultDecideRetryStrategy(outcome, _counts) {
6809
+ if (outcome.status === "validation_error") {
6810
+ return "follow_up";
6811
+ }
6812
+ if (outcome.status === "error") {
6813
+ if (outcome.message === "Agent returned empty output") return "retry";
6814
+ return "abort";
6815
+ }
6816
+ return "abort";
6817
+ }
6818
+ function summarizeToolInput(input) {
6819
+ if (!input) return "";
6820
+ const path = toolTargetPath(input);
6821
+ if (path) return ` \u2014 ${path}`;
6822
+ const cmd = input.command ?? input.cmd;
6823
+ if (typeof cmd === "string") return ` \u2014 ${cmd.length > 80 ? cmd.slice(0, 77) + "..." : cmd}`;
6824
+ const query = input.query ?? input.search ?? input.pattern;
6825
+ if (typeof query === "string") return ` \u2014 "${query}"`;
6826
+ return "";
6827
+ }
6828
+ function timestamp() {
6829
+ return (/* @__PURE__ */ new Date()).toISOString();
6830
+ }
6831
+ function formatProgressPrefix(event, taskId, agentId) {
6832
+ const ts = timestamp();
6833
+ const sid = event.session_id ? event.session_id.slice(0, 8) : "-";
6834
+ const agent = agentId ?? "-";
6835
+ return `[${ts},${sid},${agent},${taskId}]`;
6836
+ }
6837
+ function formatProgressEvent(event, taskId, agentId) {
6838
+ const prefix = formatProgressPrefix(event, taskId, agentId);
6839
+ switch (event.type) {
6840
+ case "tool_use":
6841
+ return `${prefix} \u2699 ${event.tool_name ?? "tool"}${summarizeToolInput(event.input)}
6842
+ `;
6843
+ case "tool_result":
6844
+ return "";
6845
+ case "text": {
6846
+ if (!event.message) return "";
6847
+ const trimmed = event.message.trim();
6848
+ if (!trimmed) return "";
6849
+ const firstLine = trimmed.split("\n")[0];
6850
+ const preview = firstLine.length > 120 ? firstLine.slice(0, 117) + "..." : firstLine;
6851
+ return `${prefix} \u{1F4AD} ${preview}
6852
+ `;
6853
+ }
6854
+ case "status":
6855
+ return event.message ? `${prefix} \u25CF ${event.message}
6856
+ ` : "";
6857
+ default:
6858
+ return "";
6859
+ }
6860
+ }
6861
+ async function runTask(adapter, taskId, context, options) {
6862
+ const taskReg = options?.taskRegistry ?? {};
6863
+ const agentReg = options?.agentRegistry ?? {};
6864
+ const schemas = options?.handoffSchemas ?? {};
6865
+ const task = taskReg[taskId];
6866
+ if (!task) return { outcome: { status: "error", message: `Unknown task: ${taskId}` }, follow_ups_used: 0, retries_used: 0 };
6867
+ const agentContract = agentReg[task.target_agent];
6868
+ if (!agentContract) return { outcome: { status: "error", message: `Unknown agent: ${task.target_agent}` }, follow_ups_used: 0, retries_used: 0 };
6869
+ const taskEnvelope = createExecutionEnvelope({
6870
+ taskInstanceId: taskId,
6871
+ componentId: agentContract.id,
6872
+ fromAgent: agentContract.id,
6873
+ parentRunId: options?.parentSpanId,
6874
+ // correlates to agent.session run_id
6875
+ adapter: options?.envelopeAdapter,
6876
+ model: options?.envelopeModel
6877
+ });
6878
+ const modifiedContext = await pluginRegistry.runBeforeTask(taskId, context);
6879
+ if (modifiedContext === null) {
6880
+ return { outcome: { status: "error", message: `Task "${taskId}" skipped by plugin` }, follow_ups_used: 0, retries_used: 0 };
6881
+ }
6882
+ const enrichedContext = pluginRegistry.applyContextEnhancers(taskId, modifiedContext);
6883
+ const analyzerToolIds = collectAnalyzerToolIds(options?.libraryTools);
6884
+ const promptOpts = {
6885
+ handoffSchemas: schemas,
6886
+ retry: options?.retry,
6887
+ ...analyzerToolIds.length > 0 && shouldInjectAnalyzerExplorationMandate(enrichedContext) ? { analyzerExploration: { toolIds: analyzerToolIds } } : {}
6888
+ };
6889
+ const builderArgs = { agent: agentContract, task, context: enrichedContext, options: promptOpts };
6890
+ let prompt;
6891
+ let splitPrompt;
6892
+ const pluginPrompt = pluginRegistry.applyPromptBuilder(builderArgs);
6893
+ if (pluginPrompt) {
6894
+ prompt = pluginPrompt;
6895
+ } else {
6896
+ const split = buildSplitTaskPrompt(agentContract, task, enrichedContext, promptOpts);
6897
+ splitPrompt = split;
6898
+ prompt = joinSplitPrompt(split);
6899
+ }
6900
+ const enhancedPrompt = pluginRegistry.applyPromptEnhancers(taskId, prompt, enrichedContext);
6901
+ if (enhancedPrompt !== prompt) {
6902
+ splitPrompt = void 0;
6903
+ prompt = enhancedPrompt;
6904
+ }
6905
+ const isReadonly = agentContract.mode === "read-only";
6906
+ const allowDynamicWorkflow = task.allow_dynamic_workflow ?? false;
6907
+ const candidateAgents = Object.keys(agentReg).length > 0 ? buildCandidateAgents(agentReg, {
6908
+ entryAgentId: agentContract.id,
6909
+ allowedAgentIds: agentContract.can_invoke_agents,
6910
+ toolsByAgent: options?.toolsByAgent
6911
+ }) : [];
6912
+ const agents = candidateAgents.length > 0 ? candidateAgents : void 0;
6913
+ const maxFollowUps = options?.maxFollowUps ?? 2;
6914
+ const maxRetries = options?.maxRetries ?? 0;
6915
+ const decide = options?.decideRetryStrategy ?? defaultDecideRetryStrategy;
6916
+ const taskExecStart = Date.now();
6917
+ const effectiveSessionId = options?.sessionId ?? options?.parentSpanId ?? taskEnvelope.run_id;
6918
+ let processTaskSpanId;
6919
+ const emittedEditPaths = /* @__PURE__ */ new Set();
6920
+ const onProgress = options?.progressOutput || options?.observer ? (event) => {
6921
+ if (options?.progressOutput) {
6922
+ const line = formatProgressEvent(event, taskId, agentContract.id);
6923
+ if (line) options.progressOutput.write(line);
6924
+ }
6925
+ if (options?.observer && event.type === "tool_use" && isFileEditTool(event.tool_name)) {
6926
+ const p = toolTargetPath(event.input);
6927
+ if (p && !emittedEditPaths.has(p)) {
6928
+ emittedEditPaths.add(p);
6929
+ emitProcessEdit({
6930
+ filePath: p,
6931
+ sessionId: effectiveSessionId,
6932
+ observer: options.observer
6933
+ });
6934
+ }
6935
+ }
6936
+ } : void 0;
6937
+ let followUpsUsed = 0;
6938
+ let retriesUsed = 0;
6939
+ let memoryRef = enrichedContext.memoryRef;
6940
+ if (memoryRef && adapter.isCompatible && !adapter.isCompatible(memoryRef.compat)) {
6941
+ console.warn(
6942
+ `Memory ref compat mismatch: ${memoryRef.compat} is not compatible with this adapter`
6943
+ );
6944
+ memoryRef = void 0;
6945
+ }
6946
+ const subagentSpanId = emitSubagentOpen(
6947
+ options?.observer,
6948
+ taskEnvelope,
6949
+ options?.parentSpanId,
6950
+ taskId,
6951
+ agentContract.role_name,
6952
+ effectiveSessionId
6953
+ );
6954
+ processTaskSpanId = emitProcessTaskOpen({
6955
+ taskId,
6956
+ targetAgent: task.target_agent,
6957
+ sessionId: effectiveSessionId,
6958
+ parentSpanId: subagentSpanId ?? options?.parentSpanId,
6959
+ observer: options?.observer
6960
+ });
6961
+ let closeStatus = "error";
6962
+ let closeCause;
6963
+ let spanClosed = false;
6964
+ const closeSubagentSpan = () => {
6965
+ if (spanClosed) return;
6966
+ spanClosed = true;
6967
+ const durationMs = Date.now() - taskExecStart;
6968
+ const lastTokenUsage = adapter.getLastTokenUsage?.();
6969
+ taskEnvelope.execution_metadata = {
6970
+ ...taskEnvelope.execution_metadata ?? {},
6971
+ duration_ms: durationMs,
6972
+ ...lastTokenUsage ? {
6973
+ token_usage: {
6974
+ input_tokens: lastTokenUsage.inputTokens,
6975
+ output_tokens: lastTokenUsage.outputTokens,
6976
+ ...lastTokenUsage.totalTokens !== void 0 ? { total_tokens: lastTokenUsage.totalTokens } : {},
6977
+ ...lastTokenUsage.cacheReadTokens !== void 0 ? { cache_read_input_tokens: lastTokenUsage.cacheReadTokens } : {},
6978
+ ...lastTokenUsage.cacheCreationTokens !== void 0 ? { cache_creation_input_tokens: lastTokenUsage.cacheCreationTokens } : {}
6979
+ }
6980
+ } : {}
6981
+ };
6982
+ if (lastTokenUsage) {
6983
+ const costUsd = computeCostUsd(
6984
+ taskEnvelope.model,
6985
+ lastTokenUsage.inputTokens,
6986
+ lastTokenUsage.outputTokens
6987
+ );
6988
+ if (costUsd !== void 0) {
6989
+ taskEnvelope.execution_metadata = {
6990
+ ...taskEnvelope.execution_metadata,
6991
+ cost_usd: costUsd
6992
+ };
6993
+ }
6994
+ }
6995
+ emitSubagentClose(
6996
+ options?.observer,
6997
+ subagentSpanId ?? taskEnvelope.run_id,
6998
+ taskEnvelope,
6999
+ durationMs,
7000
+ closeStatus,
7001
+ agentContract.role_name,
7002
+ closeCause,
7003
+ effectiveSessionId
7004
+ );
7005
+ if (processTaskSpanId) {
7006
+ emitProcessTaskClose(processTaskSpanId, {
7007
+ status: closeStatus,
7008
+ durationMs,
7009
+ observer: options?.observer
7010
+ });
7011
+ }
7012
+ };
7013
+ try {
7014
+ let fullOutput;
7015
+ try {
7016
+ if (adapter.sendExecution) {
7017
+ fullOutput = await adapter.sendExecution({
7018
+ agentId: agentContract.id,
7019
+ taskId,
7020
+ prompt,
7021
+ handoff: schemas[task.result_handoff] ? { type: task.result_handoff, payload: void 0 } : void 0,
7022
+ schema: schemas[task.result_handoff] ? {
7023
+ handoffType: task.result_handoff,
7024
+ zodSchema: schemas[task.result_handoff],
7025
+ promptDescription: zodSchemaToPromptDescription(schemas[task.result_handoff])
7026
+ } : void 0,
7027
+ context: enrichedContext,
7028
+ memoryRef,
7029
+ splitPrompt,
7030
+ agents,
7031
+ options: { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId, maxFollowUps, attempt: 0 }
7032
+ });
7033
+ } else {
7034
+ fullOutput = await adapter.send(prompt, { readonly: isReadonly, onProgress, splitPrompt, agents, allowDynamicWorkflow, libraryTools: options?.libraryTools, observer: options?.observer, parentSpanId: subagentSpanId, sessionId: effectiveSessionId });
7035
+ }
7036
+ } catch (err) {
7037
+ closeStatus = "error";
7038
+ closeCause = `SDK error: ${err.message}`;
7039
+ return { outcome: { status: "error", message: closeCause }, follow_ups_used: 0, retries_used: 0 };
7040
+ }
7041
+ let outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
7042
+ outcome = await pluginRegistry.runAfterTask(taskId, outcome);
7043
+ while (outcome.status === "validation_error" || outcome.status === "error") {
7044
+ const decision = await decide(outcome, { followUps: followUpsUsed, retries: retriesUsed });
7045
+ if (decision === "abort") break;
7046
+ let effectiveDecision = decision;
7047
+ if (effectiveDecision === "follow_up" && followUpsUsed >= maxFollowUps) {
7048
+ effectiveDecision = "retry";
7049
+ }
7050
+ if (effectiveDecision === "retry" && retriesUsed >= maxRetries) {
7051
+ break;
7052
+ }
7053
+ if (effectiveDecision === "follow_up") {
7054
+ followUpsUsed++;
7055
+ const followUpPrompt = buildRetryFollowUp(task, outcome, promptOpts);
7056
+ try {
7057
+ if (adapter.followUp) {
7058
+ fullOutput = await adapter.followUp(followUpPrompt);
7059
+ } else {
7060
+ const retryContext = {
7061
+ ...modifiedContext,
7062
+ prior_context: (modifiedContext.prior_context ?? "") + `
7063
+
7064
+ --- FollowUp ${followUpsUsed} ---
7065
+ ${followUpPrompt}`
7066
+ };
7067
+ let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext, promptOpts);
7068
+ retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
7069
+ fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
7070
+ }
7071
+ } catch (err) {
7072
+ outcome = { status: "error", message: `SDK error on followUp ${followUpsUsed}: ${err.message}` };
7073
+ continue;
7074
+ }
7075
+ } else {
7076
+ retriesUsed++;
7077
+ const retryContext = {
7078
+ ...modifiedContext,
7079
+ prior_context: (modifiedContext.prior_context ?? "") + `
7080
+
7081
+ --- Full Retry ${retriesUsed} ---
7082
+ Previous attempt failed: ` + (outcome.status === "validation_error" ? `Validation errors: ${outcome.errors.message}` : outcome.status === "error" ? outcome.message : "unknown") + `
7083
+ Please re-execute the entire task.`
7084
+ };
7085
+ let retryFullPrompt = buildTaskPrompt(agentContract, task, retryContext);
7086
+ retryFullPrompt = pluginRegistry.applyPromptEnhancers(taskId, retryFullPrompt, retryContext);
7087
+ try {
7088
+ fullOutput = await adapter.send(retryFullPrompt, { readonly: isReadonly, agents });
7089
+ } catch (err) {
7090
+ outcome = { status: "error", message: `SDK error on retry ${retriesUsed}: ${err.message}` };
7091
+ continue;
7092
+ }
7093
+ }
7094
+ outcome = attachMemoryRef(validateOutput(fullOutput, task, schemas), adapter);
7095
+ outcome = await pluginRegistry.runAfterTask(taskId, outcome);
7096
+ }
7097
+ closeStatus = outcome.status;
7098
+ const finalTokenUsage = adapter.getLastTokenUsage?.() ?? void 0;
7099
+ return { outcome, follow_ups_used: followUpsUsed, retries_used: retriesUsed, tokenUsage: finalTokenUsage };
7100
+ } catch (err) {
7101
+ closeStatus = "error";
7102
+ closeCause = err.message;
7103
+ throw err;
7104
+ } finally {
7105
+ closeSubagentSpan();
7106
+ }
7107
+ }
7108
+
7109
+ // src/lib/toolchain-checker.ts
7110
+ import { execFile } from "child_process";
7111
+ import { readFile } from "fs/promises";
7112
+ import { existsSync } from "fs";
7113
+ import { resolve } from "path";
7114
+ import { promisify } from "util";
7115
+ import { z as z2 } from "zod";
7116
+ import { parseToolchainFile } from "@aaac/toolchain";
7117
+ var execFileAsync = promisify(execFile);
7118
+ var SUBPROCESS_TIMEOUT_MS = 3e4;
7119
+ var MANIFEST_FILENAME = ".toolchain-manifest.json";
7120
+ var ToolchainManifestSchema = z2.object({
7121
+ schema: z2.string(),
7122
+ toolchain_id: z2.string(),
7123
+ generated_at: z2.string(),
7124
+ source_hash: z2.string(),
7125
+ output_hash: z2.string(),
7126
+ source_globs: z2.array(z2.string()).optional(),
7127
+ output_globs: z2.array(z2.string()).optional(),
7128
+ files: z2.array(
7129
+ z2.object({
7130
+ path: z2.string(),
7131
+ hash: z2.string()
7132
+ })
7133
+ ).optional()
7134
+ });
7135
+ function resolveAction(checkType, checkTypeActions, defaultAction) {
7136
+ if (checkTypeActions?.[checkType]) return checkTypeActions[checkType];
7137
+ if (checkTypeActions?.["_default"]) return checkTypeActions["_default"];
7138
+ return defaultAction ?? "warn";
7139
+ }
7140
+ async function tryManifestFastPath(toolchainId, cwd) {
7141
+ const manifestPath = resolve(cwd, MANIFEST_FILENAME);
7142
+ if (!existsSync(manifestPath)) return null;
7143
+ try {
7144
+ const raw = await readFile(manifestPath, "utf-8");
7145
+ const parsed = ToolchainManifestSchema.parse(JSON.parse(raw));
7146
+ if (parsed.toolchain_id !== toolchainId) return null;
7147
+ return {
7148
+ toolchainId,
7149
+ checkType: "drift",
7150
+ status: "pass",
7151
+ action: "warn",
7152
+ message: `Manifest fast path: ${MANIFEST_FILENAME} found, toolchain_id matches`,
7153
+ durationMs: 0
7154
+ };
7155
+ } catch {
7156
+ return null;
7157
+ }
7158
+ }
7159
+ async function executeCheck(command, cwd, observabilityIds) {
7160
+ const env = observabilityIds ? buildObservabilityEnv(observabilityIds) : void 0;
7161
+ try {
7162
+ const { stdout, stderr } = await execFileAsync("sh", ["-c", command], {
7163
+ cwd,
7164
+ timeout: SUBPROCESS_TIMEOUT_MS,
7165
+ ...env ? { env } : {}
7166
+ });
7167
+ return { exitCode: 0, stdout, stderr };
7168
+ } catch (err) {
7169
+ const execErr = err;
7170
+ if (execErr.killed) {
7171
+ throw new Error(`Command timed out after ${SUBPROCESS_TIMEOUT_MS}ms: ${command}`);
7172
+ }
7173
+ const exitCode = typeof execErr.code === "number" ? execErr.code : 1;
7174
+ return {
7175
+ exitCode,
7176
+ stdout: execErr.stdout ?? "",
7177
+ stderr: execErr.stderr ?? ""
7178
+ };
7179
+ }
7180
+ }
7181
+ async function runToolchainChecks(options) {
7182
+ const {
7183
+ toolchainsPath,
7184
+ cwd: workingDir,
7185
+ checkTypes,
7186
+ toolchainFilter,
7187
+ checkTypeActions,
7188
+ defaultAction,
7189
+ observer,
7190
+ parentSpanId,
7191
+ componentId,
7192
+ observabilityIds
7193
+ } = options;
7194
+ const cwd = workingDir ?? process.cwd();
7195
+ const contracts = await parseToolchainFile(toolchainsPath);
7196
+ const results = [];
7197
+ for (const [toolchainId, toolchain] of Object.entries(contracts.toolchains)) {
7198
+ if (!toolchain.checks) continue;
7199
+ if (toolchainFilter && !toolchainFilter.includes(toolchainId)) continue;
7200
+ for (const [checkType, command] of Object.entries(toolchain.checks)) {
7201
+ if (checkTypes && !checkTypes.includes(checkType)) continue;
7202
+ const action = resolveAction(checkType, checkTypeActions, defaultAction);
7203
+ const start = performance.now();
7204
+ const spanId = emitToolchainOpen(
7205
+ observer,
7206
+ parentSpanId,
7207
+ toolchainId,
7208
+ checkType,
7209
+ [],
7210
+ componentId
7211
+ );
7212
+ let result;
7213
+ const fastResult = checkType === "drift" && options.artifactsPath ? await tryManifestFastPath(toolchainId, cwd) : null;
7214
+ if (fastResult) {
7215
+ fastResult.action = action;
7216
+ result = fastResult;
7217
+ } else {
7218
+ try {
7219
+ const { exitCode, stderr } = await executeCheck(command, cwd, observabilityIds);
7220
+ const durationMs = Math.round(performance.now() - start);
7221
+ result = {
7222
+ toolchainId,
7223
+ checkType,
7224
+ status: exitCode === 0 ? "pass" : "fail",
7225
+ action,
7226
+ message: exitCode === 0 ? void 0 : stderr.trim() || `exit code ${exitCode}`,
7227
+ durationMs
7228
+ };
7229
+ } catch (err) {
7230
+ const durationMs = Math.round(performance.now() - start);
7231
+ result = {
7232
+ toolchainId,
7233
+ checkType,
7234
+ status: "error",
7235
+ action,
7236
+ message: err.message,
7237
+ durationMs
7238
+ };
7239
+ }
7240
+ }
7241
+ results.push(result);
7242
+ emitToolchainClose(
7243
+ observer,
7244
+ spanId ?? "",
7245
+ toolchainId,
7246
+ checkType,
7247
+ result.durationMs ?? Math.round(performance.now() - start),
7248
+ result.status === "pass" ? "success" : "failure",
7249
+ result.status === "pass" ? void 0 : result.message
7250
+ );
7251
+ }
7252
+ }
7253
+ return results;
7254
+ }
7255
+
7256
+ // src/lib/workflow-input.ts
7257
+ var WORKFLOW_INPUT_STEP_ID = "workflow-input";
7258
+ function buildWorkflowInputOutput(userRequest, handoff) {
7259
+ return {
7260
+ user_request: userRequest,
7261
+ ...handoff ? {
7262
+ handoff: {
7263
+ type: handoff.type,
7264
+ ...handoff.version !== void 0 ? { version: handoff.version } : {},
7265
+ payload: handoff.payload
7266
+ }
7267
+ } : {}
7268
+ };
7269
+ }
7270
+ function stepDependsOnWorkflowInput(dependsOn) {
7271
+ return dependsOn?.includes(WORKFLOW_INPUT_STEP_ID) ?? false;
7272
+ }
7273
+ function formatWorkflowInputContext(output) {
7274
+ return `
7275
+
7276
+ --- Step: ${WORKFLOW_INPUT_STEP_ID} ---
7277
+ ${JSON.stringify(output, null, 2)}`;
7278
+ }
7279
+
7280
+ // src/lib/workflow-runner.ts
7281
+ function isAdapterFactory(v) {
7282
+ return typeof v === "function" && !("send" in v);
7283
+ }
7284
+ function resolveAdapter(adapterOrFactory) {
7285
+ if (isAdapterFactory(adapterOrFactory)) {
7286
+ const result = adapterOrFactory();
7287
+ if (result && typeof result.then === "function") {
7288
+ throw new Error("ModelAwareSdkAdapterFactory returned a Promise for the default adapter. Use a synchronous factory or pre-resolve the default adapter.");
7289
+ }
7290
+ return { adapter: result, factory: adapterOrFactory };
7291
+ }
7292
+ return { adapter: adapterOrFactory, factory: void 0 };
7293
+ }
7294
+ function resolveInvocation(invocation) {
7295
+ let userRequest;
7296
+ if (invocation.handoff) {
7297
+ const h = invocation.handoff;
7298
+ userRequest = invocation.user_request ? invocation.user_request : typeof h.payload === "string" ? h.payload : JSON.stringify(h.payload, null, 2);
7299
+ } else {
7300
+ userRequest = invocation.user_request ?? "";
7301
+ }
7302
+ const ctx = invocation.context;
7303
+ const variables = { ...ctx?.variables };
7304
+ if (ctx?.cwd) variables.cwd = ctx.cwd;
7305
+ if (ctx?.environment) variables.environment = ctx.environment;
6179
7306
  if (ctx?.artifacts) variables.artifacts = ctx.artifacts;
6180
7307
  return {
6181
7308
  workflowId: invocation.workflow,
@@ -6191,6 +7318,7 @@ function resolveInvocation(invocation) {
6191
7318
  observer: invocation.observer,
6192
7319
  toolchain: invocation.toolchain,
6193
7320
  libraryTools: invocation.libraryTools,
7321
+ toolsByAgent: invocation.toolsByAgent,
6194
7322
  resolveModelMeta: invocation.resolveModelMeta,
6195
7323
  perAgentAdapters: invocation.perAgentAdapters
6196
7324
  }
@@ -6375,6 +7503,7 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
6375
7503
  parentSpanId: iterationSpanId ?? sessionSpanId,
6376
7504
  sessionId: sessionSpanId ?? sessionEnvelope.run_id,
6377
7505
  libraryTools: options.libraryTools,
7506
+ toolsByAgent: options.toolsByAgent,
6378
7507
  envelopeAdapter: envelopeMeta?.adapter,
6379
7508
  envelopeModel: envelopeMeta?.model
6380
7509
  });
@@ -6442,6 +7571,7 @@ async function runWorkflow(adapterOrFactory, workflowIdOrInvocation, optionsOrRe
6442
7571
  parentSpanId: sessionSpanId,
6443
7572
  sessionId: sessionSpanId ?? sessionEnvelope.run_id,
6444
7573
  libraryTools: options.libraryTools,
7574
+ toolsByAgent: options.toolsByAgent,
6445
7575
  envelopeAdapter: envelopeMeta?.adapter,
6446
7576
  envelopeModel: envelopeMeta?.model
6447
7577
  });
@@ -6888,19 +8018,10 @@ var WorkflowBuilder = class {
6888
8018
 
6889
8019
  // src/lib/plugin-loader.ts
6890
8020
  import { existsSync as existsSync2 } from "fs";
6891
- import { readdir } from "fs/promises";
6892
- import { resolve as resolve2, join } from "path";
6893
- var PLUGIN_EXTENSIONS = [".ts", ".js", ".mts", ".mjs"];
8021
+ import { resolve as resolve2 } from "path";
6894
8022
  function isPluginLike(obj) {
6895
8023
  return typeof obj === "object" && obj !== null && typeof obj.id === "string";
6896
8024
  }
6897
- async function scanDirectory(dir) {
6898
- if (!existsSync2(dir)) return [];
6899
- const entries = await readdir(dir, { withFileTypes: true });
6900
- return entries.filter(
6901
- (e) => e.isFile() && PLUGIN_EXTENSIONS.some((ext) => e.name.endsWith(ext)) && !e.name.startsWith("_") && !e.name.endsWith(".d.ts") && !e.name.endsWith(".test.ts") && !e.name.endsWith(".spec.ts")
6902
- ).map((e) => resolve2(dir, e.name));
6903
- }
6904
8025
  async function loadPluginModule(modulePath) {
6905
8026
  const mod = await import(new URL(`file://${modulePath}`).href);
6906
8027
  let count = 0;
@@ -6915,59 +8036,32 @@ async function loadPluginModule(modulePath) {
6915
8036
  }
6916
8037
  return count;
6917
8038
  }
6918
- async function loadPluginsFromPaths(paths, baseDir) {
6919
- const result = { loaded: 0, files: [], errors: [] };
8039
+ async function loadPlugins(paths, baseDir) {
8040
+ const result = { loaded: 0, files: [] };
6920
8041
  for (const p of paths) {
6921
8042
  const absPath2 = resolve2(baseDir, p);
6922
8043
  if (!existsSync2(absPath2)) {
6923
- result.errors.push({ file: p, error: `File not found: ${absPath2}` });
6924
- continue;
8044
+ throw new Error(
8045
+ `Plugin not found: ${absPath2} (declared by the project manifest's \`plugins:\`).`
8046
+ );
6925
8047
  }
6926
8048
  try {
6927
- const count = await loadPluginModule(absPath2);
6928
- result.loaded += count;
8049
+ result.loaded += await loadPluginModule(absPath2);
6929
8050
  result.files.push(absPath2);
6930
8051
  } catch (err) {
6931
- result.errors.push({
6932
- file: p,
6933
- error: err.message
6934
- });
6935
- }
6936
- }
6937
- return result;
6938
- }
6939
- async function loadPluginsFromDirectory(dir) {
6940
- const result = { loaded: 0, files: [], errors: [] };
6941
- const candidates = await scanDirectory(dir);
6942
- for (const filePath of candidates) {
6943
- try {
6944
- const count = await loadPluginModule(filePath);
6945
- result.loaded += count;
6946
- result.files.push(filePath);
6947
- } catch (err) {
6948
- result.errors.push({
6949
- file: filePath,
6950
- error: err.message
6951
- });
8052
+ throw new Error(
8053
+ `Failed to load plugin ${absPath2} (declared by the project manifest's \`plugins:\`): ${err.message}`
8054
+ );
6952
8055
  }
6953
8056
  }
6954
8057
  return result;
6955
8058
  }
6956
- async function loadPlugins(options) {
6957
- if (options.pluginPaths && options.pluginPaths.length > 0) {
6958
- return loadPluginsFromPaths(options.pluginPaths, options.projectDir);
6959
- }
6960
- const conventionDir = join(options.projectDir, "src", "plugins");
6961
- return loadPluginsFromDirectory(conventionDir);
6962
- }
6963
8059
 
6964
8060
  // src/lib/model-resolver.ts
6965
8061
  var ENV_PREFIX = "AGENT_RUNTIME_MODEL";
6966
- var CLASS_ENV_KEYS = {
6967
- fast: `${ENV_PREFIX}_FAST`,
6968
- standard: `${ENV_PREFIX}_STANDARD`,
6969
- thinking: `${ENV_PREFIX}_THINKING`
6970
- };
8062
+ function classEnvKey(modelClass) {
8063
+ return `${ENV_PREFIX}_${modelClass.toUpperCase()}`;
8064
+ }
6971
8065
  function parseEnvValue(value, fallbackAdapter) {
6972
8066
  const colonIdx = value.indexOf(":");
6973
8067
  if (colonIdx === -1) {
@@ -6986,7 +8080,7 @@ function createModelResolver(options) {
6986
8080
  model: options.fallbackModel
6987
8081
  };
6988
8082
  if (!modelClass) return fallback;
6989
- const classEnv = env[CLASS_ENV_KEYS[modelClass]];
8083
+ const classEnv = env[classEnvKey(modelClass)];
6990
8084
  if (classEnv) {
6991
8085
  const parsed = parseEnvValue(classEnv, options.fallbackAdapter);
6992
8086
  return options.pinnedAdapter ? { adapter: options.pinnedAdapter, model: parsed.model } : parsed;
@@ -7010,7 +8104,8 @@ function createModelResolver(options) {
7010
8104
 
7011
8105
  // src/lib/progress-sink.ts
7012
8106
  import { openSync, writeSync, closeSync, mkdirSync } from "fs";
7013
- import { dirname, join as join2, basename, extname } from "path";
8107
+ import { dirname, join, basename, extname } from "path";
8108
+ import { pathSegmentForId } from "@aaac/contracts";
7014
8109
  function resolveFilePath(base, naming, label) {
7015
8110
  if (naming === "single") return base;
7016
8111
  const dir = dirname(base);
@@ -7019,12 +8114,12 @@ function resolveFilePath(base, naming, label) {
7019
8114
  const now = /* @__PURE__ */ new Date();
7020
8115
  if (naming === "daily") {
7021
8116
  const date = now.toISOString().slice(0, 10);
7022
- return join2(dir, `${stem}-${date}${ext}`);
8117
+ return join(dir, `${stem}-${date}${ext}`);
7023
8118
  }
7024
8119
  const pad = (n) => String(n).padStart(2, "0");
7025
8120
  const ts = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}T${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
7026
- const suffix = label ? `-${label}` : "";
7027
- return join2(dir, `${stem}-${ts}${suffix}${ext}`);
8121
+ const suffix = label ? `-${pathSegmentForId("progress-log label", label)}` : "";
8122
+ return join(dir, `${stem}-${ts}${suffix}${ext}`);
7028
8123
  }
7029
8124
  function createProgressSink(options) {
7030
8125
  const useStderr = options.stderr ?? false;
@@ -7074,10 +8169,14 @@ var InMemoryStore = class {
7074
8169
 
7075
8170
  // src/lib/file-memory-store.ts
7076
8171
  import { mkdir, readFile as readFile2, unlink, writeFile } from "fs/promises";
7077
- import { join as join3 } from "path";
8172
+ import { join as join2 } from "path";
8173
+ import { pathSegmentForId as pathSegmentForId2 } from "@aaac/contracts";
7078
8174
  function resolveFilePath2(baseDir, ref) {
7079
8175
  const runId = ref.parent_run_id ?? "unknown";
7080
- return join3(baseDir, `${runId}_${ref.id}.json`);
8176
+ return join2(
8177
+ baseDir,
8178
+ `${pathSegmentForId2("memory ref parent_run_id", runId)}_${pathSegmentForId2("memory ref id", ref.id)}.json`
8179
+ );
7081
8180
  }
7082
8181
  var FileMemoryStore = class {
7083
8182
  baseDir;
@@ -7115,32 +8214,75 @@ var FileMemoryStore = class {
7115
8214
  };
7116
8215
 
7117
8216
  // src/lib/agent-log-writer.ts
7118
- import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, stat, unlink as unlink2, writeFile as writeFile2, appendFile } from "fs/promises";
7119
- import { join as join4 } from "path";
8217
+ import { mkdir as mkdir2, readFile as readFile3, readdir, stat, unlink as unlink2, writeFile as writeFile2, appendFile } from "fs/promises";
8218
+ import { join as join3 } from "path";
8219
+ import { pathSegmentForId as pathSegmentForId3 } from "@aaac/contracts";
8220
+ var RUN_LOG_EVENT_TYPES = [
8221
+ "operation_start",
8222
+ "operation_end",
8223
+ "operation_error",
8224
+ "workflow_start",
8225
+ "workflow_end",
8226
+ "task_start",
8227
+ "task_end",
8228
+ "handoff"
8229
+ ];
8230
+ var optionalString = (value) => value === void 0 || typeof value === "string";
8231
+ function isRunLogEvent(value) {
8232
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
8233
+ const event = value;
8234
+ return typeof event.timestamp === "string" && RUN_LOG_EVENT_TYPES.includes(event.type) && typeof event.runId === "string" && optionalString(event.operationName) && optionalString(event.agentId) && (event.durationMs === void 0 || typeof event.durationMs === "number") && optionalString(event.error);
8235
+ }
7120
8236
  var AgentLogWriter = class {
7121
8237
  baseDir;
7122
8238
  memoryStore;
7123
8239
  constructor(options) {
7124
8240
  this.baseDir = options?.baseDir ?? ".agent-logs";
7125
8241
  this.memoryStore = new FileMemoryStore({
7126
- baseDir: join4(this.baseDir, "memories")
8242
+ baseDir: join3(this.baseDir, "memories")
7127
8243
  });
7128
8244
  }
7129
8245
  getMemoryStore() {
7130
8246
  return this.memoryStore;
7131
8247
  }
8248
+ /**
8249
+ * Where one run's event log lives. The writer and the reader must agree on
8250
+ * the name, so both derive it here rather than each spelling it out — and
8251
+ * with it, the check that keeps a run id inside `baseDir`.
8252
+ */
8253
+ runLogPath(runId) {
8254
+ return join3(this.baseDir, "runs", `${pathSegmentForId3("run id", runId)}.jsonl`);
8255
+ }
8256
+ /** Where one run's handoff payload lives. Shared by the writer and reader. */
8257
+ handoffPath(runId, step) {
8258
+ return join3(
8259
+ this.baseDir,
8260
+ "handoffs",
8261
+ `${pathSegmentForId3("run id", runId)}_${pathSegmentForId3("handoff step", step)}.json`
8262
+ );
8263
+ }
7132
8264
  async writeRunEvent(runId, event) {
7133
- const runsDir = join4(this.baseDir, "runs");
7134
- await mkdir2(runsDir, { recursive: true });
7135
- const filePath = join4(runsDir, `${runId}.jsonl`);
8265
+ const filePath = this.runLogPath(runId);
8266
+ await mkdir2(join3(this.baseDir, "runs"), { recursive: true });
7136
8267
  await appendFile(filePath, `${JSON.stringify(event)}
7137
8268
  `, "utf-8");
7138
8269
  }
7139
8270
  async readRunLog(runId) {
7140
- const filePath = join4(this.baseDir, "runs", `${runId}.jsonl`);
8271
+ const filePath = this.runLogPath(runId);
7141
8272
  try {
7142
8273
  const raw = await readFile3(filePath, "utf-8");
7143
- return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
8274
+ const events = [];
8275
+ for (const line of raw.split("\n")) {
8276
+ if (line.trim().length === 0) continue;
8277
+ let parsed;
8278
+ try {
8279
+ parsed = JSON.parse(line);
8280
+ } catch {
8281
+ continue;
8282
+ }
8283
+ if (isRunLogEvent(parsed)) events.push(parsed);
8284
+ }
8285
+ return events;
7144
8286
  } catch (error) {
7145
8287
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
7146
8288
  return [];
@@ -7149,13 +8291,12 @@ var AgentLogWriter = class {
7149
8291
  }
7150
8292
  }
7151
8293
  async writeHandoff(runId, step, data) {
7152
- const handoffsDir = join4(this.baseDir, "handoffs");
7153
- await mkdir2(handoffsDir, { recursive: true });
7154
- const filePath = join4(handoffsDir, `${runId}_${step}.json`);
8294
+ const filePath = this.handoffPath(runId, step);
8295
+ await mkdir2(join3(this.baseDir, "handoffs"), { recursive: true });
7155
8296
  await writeFile2(filePath, JSON.stringify(data, null, 2), "utf-8");
7156
8297
  }
7157
8298
  async readHandoff(runId, step) {
7158
- const filePath = join4(this.baseDir, "handoffs", `${runId}_${step}.json`);
8299
+ const filePath = this.handoffPath(runId, step);
7159
8300
  try {
7160
8301
  const raw = await readFile3(filePath, "utf-8");
7161
8302
  return JSON.parse(raw);
@@ -7171,10 +8312,10 @@ var AgentLogWriter = class {
7171
8312
  let deleted = 0;
7172
8313
  const subdirs = ["memories", "runs", "handoffs"];
7173
8314
  for (const subdir of subdirs) {
7174
- const dirPath = join4(this.baseDir, subdir);
8315
+ const dirPath = join3(this.baseDir, subdir);
7175
8316
  let entries;
7176
8317
  try {
7177
- entries = await readdir2(dirPath);
8318
+ entries = await readdir(dirPath);
7178
8319
  } catch (error) {
7179
8320
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
7180
8321
  continue;
@@ -7182,7 +8323,7 @@ var AgentLogWriter = class {
7182
8323
  throw error;
7183
8324
  }
7184
8325
  for (const entry of entries) {
7185
- const filePath = join4(dirPath, entry);
8326
+ const filePath = join3(dirPath, entry);
7186
8327
  const fileStat = await stat(filePath);
7187
8328
  if (fileStat.mtimeMs < cutoff) {
7188
8329
  await unlink2(filePath);
@@ -7343,20 +8484,123 @@ async function createAdapter(name, options) {
7343
8484
  );
7344
8485
  }
7345
8486
  }
7346
- function throwMissingPackageError(adapter, err) {
7347
- const cause = err;
7348
- if (cause?.message?.includes("Cannot find package")) {
7349
- const pkg2 = ADAPTER_PACKAGES[adapter];
7350
- throw new Error(
7351
- `Adapter "${adapter}" requires package "${pkg2}" which is not installed.
7352
- Install it with: npm install ${pkg2}`
7353
- );
8487
+ function throwMissingPackageError(adapter, err) {
8488
+ const message = err instanceof Error ? err.message : String(err);
8489
+ if (message.includes("Cannot find package")) {
8490
+ const pkg2 = ADAPTER_PACKAGES[adapter];
8491
+ throw new Error(
8492
+ `Adapter "${adapter}" requires package "${pkg2}" which is not installed.
8493
+ Install it with: npm install ${pkg2}`
8494
+ );
8495
+ }
8496
+ throw err;
8497
+ }
8498
+
8499
+ // src/lib/execute.ts
8500
+ import { resolve as resolve3 } from "path";
8501
+
8502
+ // src/component-scope.ts
8503
+ var DEFAULT_COMPONENT_ID = "default";
8504
+ var UnresolvedScopeDeclarationError = class extends Error {
8505
+ componentId;
8506
+ unresolved;
8507
+ operationNames;
8508
+ toolIds;
8509
+ constructor(componentId, unresolved, operationNames, toolIds) {
8510
+ super(
8511
+ `Declarations do not resolve against component "${componentId}":
8512
+ ` + unresolved.map((u) => ` - ${u}`).join("\n") + `
8513
+ Component operations: ${operationNames.join(", ")}
8514
+ Tool ids: ${toolIds.join(", ")}`
8515
+ );
8516
+ this.name = "UnresolvedScopeDeclarationError";
8517
+ this.componentId = componentId;
8518
+ this.unresolved = unresolved;
8519
+ this.operationNames = operationNames;
8520
+ this.toolIds = toolIds;
8521
+ }
8522
+ };
8523
+ function buildToolsByAgent(dsl, resolved, componentIR) {
8524
+ const operationNames = new Set(Object.keys(componentIR?.operations ?? {}));
8525
+ const toolsByAgent = /* @__PURE__ */ new Map();
8526
+ const tools = dsl?.tools ?? {};
8527
+ const toolIds = /* @__PURE__ */ new Set([
8528
+ ...Object.keys(tools),
8529
+ ...Object.keys(resolved?.toolchains ?? {})
8530
+ ]);
8531
+ const unresolved = [];
8532
+ for (const [toolId, tool] of Object.entries(tools)) {
8533
+ for (const agentId of tool.invokable_by ?? []) {
8534
+ appendToolForAgent(toolsByAgent, agentId, toolId);
8535
+ }
8536
+ }
8537
+ const agents = dsl?.agents ?? {};
8538
+ for (const [agentId, agent] of Object.entries(agents)) {
8539
+ for (const toolId of agent.can_execute_tools ?? []) {
8540
+ if (toolIds.has(toolId)) {
8541
+ appendToolForAgent(toolsByAgent, agentId, toolId);
8542
+ } else {
8543
+ unresolved.push(`${agentId}.can_execute_tools: ${toolId}`);
8544
+ }
8545
+ }
8546
+ }
8547
+ if (resolved?.toolchainsByAgent) {
8548
+ for (const [agentId, toolchains] of resolved.toolchainsByAgent) {
8549
+ for (const tc of toolchains) {
8550
+ appendToolForAgent(toolsByAgent, agentId, tc.id);
8551
+ if (!componentIR || tc.componentId !== componentIR.info.id) continue;
8552
+ for (const op of tc.operations ?? []) {
8553
+ if (operationNames.has(op)) {
8554
+ appendToolForAgent(toolsByAgent, agentId, op);
8555
+ } else {
8556
+ unresolved.push(`${tc.id}.operations: ${op}`);
8557
+ }
8558
+ }
8559
+ }
8560
+ }
8561
+ }
8562
+ if (unresolved.length > 0) {
8563
+ throw new UnresolvedScopeDeclarationError(
8564
+ componentIR?.info.id ?? resolved?.id ?? DEFAULT_COMPONENT_ID,
8565
+ [...new Set(unresolved)].sort(),
8566
+ [...operationNames].sort(),
8567
+ [...toolIds].sort()
8568
+ );
8569
+ }
8570
+ return toolsByAgent;
8571
+ }
8572
+ function appendToolForAgent(toolsByAgent, agentId, toolName) {
8573
+ const existing = toolsByAgent.get(agentId) ?? [];
8574
+ if (existing.includes(toolName)) {
8575
+ return;
8576
+ }
8577
+ toolsByAgent.set(agentId, [...existing, toolName]);
8578
+ }
8579
+ function buildGuardrailsByAgent(resolved) {
8580
+ const guardrailsByAgent = /* @__PURE__ */ new Map();
8581
+ if (!resolved) {
8582
+ return guardrailsByAgent;
8583
+ }
8584
+ for (const agentId of resolved.guardrails.perAgent.keys()) {
8585
+ const rules = getGuardrailRulesForAgent(resolved, agentId);
8586
+ if (rules) {
8587
+ guardrailsByAgent.set(agentId, rules);
8588
+ }
7354
8589
  }
7355
- throw cause;
8590
+ return guardrailsByAgent;
8591
+ }
8592
+ function createComponentScope(options = {}) {
8593
+ const resolved = options.resolvedComponent;
8594
+ const componentIR = options.component?.ir;
8595
+ return {
8596
+ componentId: componentIR?.info.id ?? resolved?.id ?? DEFAULT_COMPONENT_ID,
8597
+ ...options.component ? { componentIR: options.component.ir, binding: options.component.binding } : {},
8598
+ toolsByAgent: buildToolsByAgent(options.dsl, resolved, componentIR),
8599
+ guardrailsByAgent: buildGuardrailsByAgent(resolved),
8600
+ ...options.libraryTools ? { libraryTools: options.libraryTools } : {},
8601
+ ...resolved?.toolchainsByAgent ? { toolchainsByAgent: resolved.toolchainsByAgent } : {}
8602
+ };
7356
8603
  }
7357
-
7358
- // src/lib/execute.ts
7359
- import { resolve as resolve3 } from "path";
7360
8604
 
7361
8605
  // src/lib/model-aware-adapter.ts
7362
8606
  function cacheKey(resolved, agentId) {
@@ -7421,8 +8665,18 @@ async function createModelAwareAdapterSetup(options) {
7421
8665
  }
7422
8666
 
7423
8667
  // src/lib/execute.ts
8668
+ function createExecutionProgressSink(invocationId, progressLog) {
8669
+ if (!progressLog) return createProgressSink({ stderr: true });
8670
+ const { destination, file, naming } = progressLog;
8671
+ const wantsFile = destination === "file" || destination === "both";
8672
+ return createProgressSink({
8673
+ stderr: destination === "stderr" || destination === "both",
8674
+ // The schema requires `file` whenever destination selects file output.
8675
+ ...wantsFile && file ? { file: resolve3(file), naming, label: invocationId } : {}
8676
+ });
8677
+ }
7424
8678
  async function resolveExecutionContext(options, requiredEntities) {
7425
- const useBoundResolver = options.resolvedComponent || options.bindingPaths && options.bindingPaths.length > 0 || options.artifactBinding;
8679
+ const useBoundResolver = options.resolvedComponent || options.bindingPaths && options.bindingPaths.length > 0 || options.artifactBinding || options.toolchain;
7426
8680
  if (useBoundResolver) {
7427
8681
  let baseDsl = options.dsl;
7428
8682
  if (!options.resolvedComponent && options.projectDslPath) {
@@ -7433,41 +8687,50 @@ async function resolveExecutionContext(options, requiredEntities) {
7433
8687
  baseDsl = merged.dsl;
7434
8688
  }
7435
8689
  const component = options.resolvedComponent ?? await new BoundResolver().resolve({
7436
- id: options.componentId ?? "default",
8690
+ // The component the binding named is this run's identity, so it is also
8691
+ // what the resolver is keyed on: two components resolved in one process
8692
+ // are two entries, not one shared "default".
8693
+ id: options.component?.ir.info.id ?? options.componentId ?? DEFAULT_COMPONENT_ID,
7437
8694
  embeddedDsl: baseDsl,
7438
8695
  bindingPaths: options.bindingPaths,
7439
8696
  activeGuardrailPolicy: options.activeGuardrailPolicy,
7440
8697
  artifactBinding: options.artifactBinding,
7441
- paths: options.paths
8698
+ paths: options.paths,
8699
+ toolchainContractsPath: options.toolchain?.toolchainsPath
7442
8700
  });
7443
- if (requiredEntities) {
7444
- const ctx2 = await loadDslContext({
7445
- embeddedDsl: component.dsl,
7446
- requiredEntities
7447
- });
7448
- return { registries: ctx2.registries, dsl: component.dsl, resolvedComponent: component };
7449
- }
7450
- return {
7451
- registries: component.registries,
7452
- dsl: component.dsl,
7453
- resolvedComponent: component
7454
- };
8701
+ const registries = requiredEntities ? (await loadDslContext({ embeddedDsl: component.dsl, requiredEntities })).registries : component.registries;
8702
+ return scopeExecution(options, registries, component.dsl, component);
7455
8703
  }
7456
8704
  const ctx = await loadDslContext({
7457
8705
  embeddedDsl: options.dsl,
7458
8706
  projectDslPath: options.projectDslPath,
7459
8707
  requiredEntities
7460
8708
  });
7461
- return { registries: ctx.registries, dsl: ctx.dsl };
8709
+ return scopeExecution(options, ctx.registries, ctx.dsl);
8710
+ }
8711
+ async function scopeExecution(options, registries, dsl, resolvedComponent) {
8712
+ const navigationIndex = (await buildNavigationContextSafely(dsl))?.navigationIndex;
8713
+ const scope = createComponentScope({
8714
+ component: options.component,
8715
+ dsl,
8716
+ resolvedComponent,
8717
+ libraryTools: buildAnalyzerToolRegistry({
8718
+ navigationIndex,
8719
+ artifactPatterns: deriveArtifactPatterns(navigationIndex)
8720
+ })
8721
+ });
8722
+ return { registries, dsl, navigationIndex, scope };
7462
8723
  }
7463
8724
  function createAgentGuardrailHooks(execCtx) {
7464
- const component = execCtx.resolvedComponent;
7465
- if (!component || component.guardrails.perAgent.size === 0) return void 0;
8725
+ const guardrailsByAgent = execCtx.scope.guardrailsByAgent;
8726
+ const pluginSources = pluginRegistry.hasGuardrails() ? [pluginRegistry.guardrailChecks()] : [];
8727
+ if (pluginSources.length === 0 && guardrailsByAgent.size === 0) return void 0;
8728
+ const pluginOnlyHooks = pluginSources.length > 0 ? createGuardrailHooks(...pluginSources) : void 0;
7466
8729
  const cache = /* @__PURE__ */ new Map();
7467
8730
  return (agentId) => {
7468
8731
  if (cache.has(agentId)) return cache.get(agentId);
7469
- const rules = getGuardrailRulesForAgent(component, agentId);
7470
- const hooks = rules && (rules.commandRules.length > 0 || rules.fileRules.length > 0 || rules.contentRules.length > 0) ? createGuardrailHooksFromRules(rules) : void 0;
8732
+ const rules = guardrailsByAgent.get(agentId);
8733
+ const hooks = rules ? createGuardrailHooksFromRules(rules, ...pluginSources) : pluginOnlyHooks;
7471
8734
  cache.set(agentId, hooks);
7472
8735
  return hooks;
7473
8736
  };
@@ -7500,10 +8763,10 @@ function deriveArtifactPatterns(navigationIndex) {
7500
8763
  }
7501
8764
  return patterns;
7502
8765
  }
7503
- async function buildNavigationContextSafely(execCtx) {
7504
- if (!execCtx.dsl) return void 0;
8766
+ async function buildNavigationContextSafely(dsl) {
8767
+ if (!dsl) return void 0;
7505
8768
  try {
7506
- return await buildNavigationContext({ embeddedDsl: execCtx.dsl });
8769
+ return await buildNavigationContext({ embeddedDsl: dsl });
7507
8770
  } catch {
7508
8771
  return void 0;
7509
8772
  }
@@ -7524,17 +8787,10 @@ async function executeTask(taskId, options) {
7524
8787
  });
7525
8788
  const resolved = modelResolver.resolve(modelClass);
7526
8789
  const adapter = await resolveTaskAdapter(modelClass);
7527
- const progressSink = createProgressSink(
7528
- options.logFile ? { stderr: true, file: resolve3(options.logFile), naming: "single" } : { stderr: true }
7529
- );
7530
- const navContext = await buildNavigationContextSafely(execCtx);
7531
- const analyzerTools = buildAnalyzerToolRegistry({
7532
- navigationIndex: navContext?.navigationIndex,
7533
- artifactPatterns: deriveArtifactPatterns(navContext?.navigationIndex)
7534
- });
8790
+ const progressSink = createExecutionProgressSink(taskId, options.progressLog);
7535
8791
  const taskContext = { user_request: options.request };
7536
- if (navContext?.navigationIndex) {
7537
- taskContext.variables = { navigationIndex: navContext.navigationIndex };
8792
+ if (execCtx.navigationIndex) {
8793
+ taskContext.variables = { navigationIndex: execCtx.navigationIndex };
7538
8794
  }
7539
8795
  try {
7540
8796
  if (options.hooks?.beforeTask) {
@@ -7545,7 +8801,8 @@ async function executeTask(taskId, options) {
7545
8801
  maxRetries: options.maxRetries ?? 0,
7546
8802
  progressOutput: progressSink,
7547
8803
  observer: options.observer,
7548
- libraryTools: analyzerTools,
8804
+ libraryTools: execCtx.scope.libraryTools,
8805
+ toolsByAgent: execCtx.scope.toolsByAgent,
7549
8806
  envelopeAdapter: resolved.adapter,
7550
8807
  envelopeModel: resolved.model,
7551
8808
  ...execCtx.registries
@@ -7570,19 +8827,12 @@ async function executeWorkflow(workflowId, options) {
7570
8827
  pinAdapter: options.pinAdapter,
7571
8828
  guardrailHooksForAgent
7572
8829
  });
7573
- const progressSink = createProgressSink(
7574
- options.logFile ? { stderr: true, file: resolve3(options.logFile), naming: "single" } : { stderr: true }
7575
- );
7576
- const navContext = await buildNavigationContextSafely(execCtx);
7577
- const analyzerTools = buildAnalyzerToolRegistry({
7578
- navigationIndex: navContext?.navigationIndex,
7579
- artifactPatterns: deriveArtifactPatterns(navContext?.navigationIndex)
7580
- });
7581
- const workflowContext = navContext?.navigationIndex ? {
8830
+ const progressSink = createExecutionProgressSink(workflowId, options.progressLog);
8831
+ const workflowContext = execCtx.navigationIndex ? {
7582
8832
  ...options.context,
7583
8833
  variables: {
7584
8834
  ...options.context?.variables,
7585
- navigationIndex: navContext.navigationIndex
8835
+ navigationIndex: execCtx.navigationIndex
7586
8836
  }
7587
8837
  } : options.context;
7588
8838
  try {
@@ -7596,7 +8846,8 @@ async function executeWorkflow(workflowId, options) {
7596
8846
  progressOutput: progressSink,
7597
8847
  observer: options.observer,
7598
8848
  toolchain: options.toolchain,
7599
- libraryTools: analyzerTools,
8849
+ libraryTools: execCtx.scope.libraryTools,
8850
+ toolsByAgent: execCtx.scope.toolsByAgent,
7600
8851
  resolveModelMeta: (modelClass) => modelResolver.resolve(modelClass),
7601
8852
  perAgentAdapters: Boolean(guardrailHooksForAgent),
7602
8853
  runtime: {
@@ -7627,7 +8878,7 @@ var DEFAULT_MEMORY_COMPAT = "aaac/0.1";
7627
8878
  function getMemoryRefConfig(op) {
7628
8879
  return op.memoryRef;
7629
8880
  }
7630
- function attachMemoryRef(result, memoryRef) {
8881
+ function attachMemoryRef2(result, memoryRef) {
7631
8882
  if (result !== null && typeof result === "object" && !Array.isArray(result)) {
7632
8883
  return { ...result, _memoryRef: memoryRef };
7633
8884
  }
@@ -7635,7 +8886,7 @@ function attachMemoryRef(result, memoryRef) {
7635
8886
  }
7636
8887
  function createRuntimeBinding(component, handlers) {
7637
8888
  const operations = component.operations;
7638
- return {
8889
+ const binding = {
7639
8890
  getOperationNames() {
7640
8891
  return Object.keys(operations);
7641
8892
  },
@@ -7649,7 +8900,11 @@ function createRuntimeBinding(component, handlers) {
7649
8900
  }
7650
8901
  const memoryConfig = getMemoryRefConfig(op);
7651
8902
  const runId = ctx.runId ?? ctx.parentRunId ?? randomUUID();
7652
- const execCtx = { ...ctx, runId };
8903
+ const execCtx = {
8904
+ ...ctx,
8905
+ runId,
8906
+ component: { ir: component, binding }
8907
+ };
7653
8908
  if (ctx.memoryRef && ctx.memoryStore) {
7654
8909
  const stored = await ctx.memoryStore.load(ctx.memoryRef);
7655
8910
  if (stored !== null) {
@@ -7693,7 +8948,7 @@ function createRuntimeBinding(component, handlers) {
7693
8948
  memoryRef: newMemoryRef
7694
8949
  };
7695
8950
  await ctx.memoryStore.save(newMemoryRef, entry);
7696
- finalResult = attachMemoryRef(result, newMemoryRef);
8951
+ finalResult = attachMemoryRef2(result, newMemoryRef);
7697
8952
  }
7698
8953
  ctx.observer?.onOperationEnd?.(operationName, finalResult);
7699
8954
  if (ctx.logWriter) {
@@ -7724,6 +8979,7 @@ function createRuntimeBinding(component, handlers) {
7724
8979
  }
7725
8980
  }
7726
8981
  };
8982
+ return binding;
7727
8983
  }
7728
8984
  async function dispatchOperation(operationName, op, options, input, ctx, handlers) {
7729
8985
  if (op.agentWorkflow) {
@@ -7780,6 +9036,7 @@ async function createProjectRuntime(options) {
7780
9036
  );
7781
9037
  }
7782
9038
  const projectDslPath = config.dslDeclared ? config.dslPath : void 0;
9039
+ await loadPlugins(config.plugins, dirname2(configPath));
7783
9040
  let observer;
7784
9041
  let observerSink;
7785
9042
  let observerClosed = false;
@@ -7831,12 +9088,16 @@ async function createProjectRuntime(options) {
7831
9088
  maxFollowUps: config.recovery.max_follow_ups,
7832
9089
  maxRetries: config.recovery.max_retries,
7833
9090
  modelMapping: config.model_mapping,
9091
+ progressLog: config.logging.progress_log,
7834
9092
  observer,
7835
- // Toolchain.execution observation: only when BOTH in-process observability
7836
- // is wired AND project.yaml declares `toolchains`. Observation is non-
7837
- // destructive (records spans; never gates the workflow) and a no-op when
7838
- // either is absent (AC4 regression safety). Consumed only by executeWorkflow.
7839
- toolchain: observer && config.toolchainsPath ? {
9093
+ // The manifest's `toolchains:`, for every consumer of it on the execution
9094
+ // path — `BoundResolver` derives each agent's toolchains from it (#336),
9095
+ // and `runWorkflow` runs the declared `checks` as a post-run observation
9096
+ // pass. Gating this on `observer` would have made the derivation depend on
9097
+ // whether observability happens to be configured; the observation pass
9098
+ // gates itself on `observer` where it is run (workflow-runner.ts), which
9099
+ // is the only consumer that needs the gate.
9100
+ toolchain: config.toolchainsPath ? {
7840
9101
  toolchainsPath: config.toolchainsPath,
7841
9102
  artifactsPath: config.artifactsPath,
7842
9103
  cwd
@@ -7844,10 +9105,11 @@ async function createProjectRuntime(options) {
7844
9105
  };
7845
9106
  }
7846
9107
  const runtime = {
7847
- async runWorkflow(workflowId, _options, input, _ctx) {
9108
+ async runWorkflow(workflowId, _options, input, ctx) {
7848
9109
  try {
7849
9110
  return await executeWorkflow(workflowId, {
7850
9111
  ...sharedExecuteOptions(),
9112
+ component: ctx?.component,
7851
9113
  request: serializeRequest(input),
7852
9114
  autoApproveGates: options.autoApproveGates ?? true
7853
9115
  });
@@ -7855,10 +9117,11 @@ async function createProjectRuntime(options) {
7855
9117
  closeObserver();
7856
9118
  }
7857
9119
  },
7858
- async runTask(taskId, _options, input, _ctx) {
9120
+ async runTask(taskId, _options, input, ctx) {
7859
9121
  try {
7860
9122
  return await executeTask(taskId, {
7861
9123
  ...sharedExecuteOptions(),
9124
+ component: ctx?.component,
7862
9125
  request: serializeRequest(input)
7863
9126
  });
7864
9127
  } finally {
@@ -7877,99 +9140,22 @@ async function createProjectRuntime(options) {
7877
9140
  };
7878
9141
  }
7879
9142
 
7880
- // src/component-scope.ts
7881
- function buildToolsByAgent(componentIR, resolved) {
7882
- const operationNames = new Set(Object.keys(componentIR.operations));
7883
- const toolsByAgent = /* @__PURE__ */ new Map();
7884
- if (!resolved) {
7885
- return toolsByAgent;
7886
- }
7887
- const dsl = resolved.dsl;
7888
- const tools = dsl.tools ?? {};
7889
- for (const tool of Object.values(tools)) {
7890
- const command = tool.command;
7891
- if (!command || !operationNames.has(command)) {
7892
- continue;
7893
- }
7894
- for (const agentId of tool.invokable_by ?? []) {
7895
- appendToolForAgent(toolsByAgent, agentId, command);
7896
- }
7897
- }
7898
- const agents = dsl.agents ?? {};
7899
- for (const [agentId, agent] of Object.entries(agents)) {
7900
- for (const toolName of agent.can_execute_tools ?? []) {
7901
- if (operationNames.has(toolName)) {
7902
- appendToolForAgent(toolsByAgent, agentId, toolName);
7903
- }
7904
- }
7905
- }
7906
- if (resolved.toolchainsByAgent) {
7907
- for (const [agentId, toolchains] of resolved.toolchainsByAgent) {
7908
- for (const tc of toolchains) {
7909
- if (tc.operations) {
7910
- for (const op of tc.operations) {
7911
- if (operationNames.has(op)) {
7912
- appendToolForAgent(toolsByAgent, agentId, op);
7913
- }
7914
- }
7915
- }
7916
- }
7917
- }
7918
- }
7919
- return toolsByAgent;
7920
- }
7921
- function appendToolForAgent(toolsByAgent, agentId, operationName) {
7922
- const existing = toolsByAgent.get(agentId) ?? [];
7923
- if (existing.includes(operationName)) {
7924
- return;
7925
- }
7926
- toolsByAgent.set(agentId, [...existing, operationName]);
7927
- }
7928
- function buildGuardrailsByAgent(resolved) {
7929
- const guardrailsByAgent = /* @__PURE__ */ new Map();
7930
- if (!resolved) {
7931
- return guardrailsByAgent;
7932
- }
7933
- for (const [agentId, rules] of resolved.guardrails.perAgent) {
7934
- guardrailsByAgent.set(agentId, [rules]);
7935
- }
7936
- return guardrailsByAgent;
7937
- }
7938
- function buildLibraryTools(defs) {
7939
- if (!defs || defs.length === 0) {
7940
- return void 0;
7941
- }
7942
- const registry = createLibraryToolRegistry();
7943
- for (const def of defs) {
7944
- registry.register(def);
7945
- }
7946
- return registry;
7947
- }
7948
- function createComponentScope(componentIR, binding, options) {
7949
- const resolved = options?.resolvedComponent;
7950
- return {
7951
- componentId: componentIR.info.id,
7952
- componentIR,
7953
- binding,
7954
- toolsByAgent: buildToolsByAgent(componentIR, resolved),
7955
- guardrailsByAgent: buildGuardrailsByAgent(resolved),
7956
- libraryTools: buildLibraryTools(options?.libraryToolDefs),
7957
- ...resolved?.toolchainsByAgent ? { toolchainsByAgent: resolved.toolchainsByAgent } : {}
7958
- };
7959
- }
7960
-
7961
9143
  // src/lib/guard-commands.ts
7962
- import { readFile as readFile4, readdir as readdir3 } from "fs/promises";
9144
+ import { readFile as readFile4, readdir as readdir2 } from "fs/promises";
7963
9145
  import "yaml";
7964
9146
  async function evaluateGuardrail(opts) {
7965
- let hookInput;
9147
+ let document;
7966
9148
  try {
7967
- hookInput = JSON.parse(opts.hookJson);
9149
+ document = JSON.parse(opts.hookJson);
7968
9150
  } catch (cause) {
7969
9151
  throw new Error(
7970
9152
  `Invalid hook JSON: input must be valid JSON. ${cause.message}`
7971
9153
  );
7972
9154
  }
9155
+ if (typeof document !== "object" || document === null || Array.isArray(document)) {
9156
+ throw new Error("Invalid hook JSON: input must be a JSON object.");
9157
+ }
9158
+ const hookInput = document;
7973
9159
  const guardrailCtx = await resolveGuardrailContext(
7974
9160
  opts.dsl,
7975
9161
  opts.bindingPaths,
@@ -7991,7 +9177,7 @@ async function evaluateGuardrail(opts) {
7991
9177
  checks = hooks.runChecks({ command: shellCommand });
7992
9178
  } else if (toolName !== void 0 || toolInput !== void 0) {
7993
9179
  response = hooks.preToolUse({ tool_name: toolName, tool_input: toolInput });
7994
- const checkFilePath = toolInput?.file_path ?? toolInput?.path ?? "";
9180
+ const checkFilePath = toolTargetPath(toolInput);
7995
9181
  if (checkFilePath) {
7996
9182
  checks = hooks.runChecks({ filePath: checkFilePath });
7997
9183
  }
@@ -8021,7 +9207,8 @@ async function listGuardrails(opts) {
8021
9207
  );
8022
9208
  return {
8023
9209
  policy: opts.activeGuardrailPolicy,
8024
- entries
9210
+ entries,
9211
+ diagnostics: guardrailCtx.diagnostics
8025
9212
  };
8026
9213
  }
8027
9214
  async function guardStatus(opts = {}) {
@@ -8030,7 +9217,7 @@ async function guardStatus(opts = {}) {
8030
9217
  const limit = opts.limit ?? 10;
8031
9218
  let files = [];
8032
9219
  try {
8033
- files = await readdir3(runsDir);
9220
+ files = await readdir2(runsDir);
8034
9221
  } catch (err) {
8035
9222
  const code = err.code;
8036
9223
  if (code === "ENOENT") {
@@ -8078,34 +9265,40 @@ async function guardStatus(opts = {}) {
8078
9265
  }
8079
9266
 
8080
9267
  // src/lib/claude-materialize/config.ts
8081
- import { z as z2 } from "zod";
8082
- var ClaudeCommandsEmitSchema = z2.object({
9268
+ import { z as z3 } from "zod";
9269
+ var ClaudeCommandsEmitSchema = z3.object({
8083
9270
  /**
8084
9271
  * Project-root-relative output path with a required `{name}` placeholder.
8085
9272
  * Defaults to `.claude/commands/aidev/{name}.md` (resolved in materialize.ts
8086
9273
  * against DEFAULT_COMMAND_OUTPUT so the default lives with the renderer).
8087
9274
  */
8088
- output: z2.string().optional(),
9275
+ output: z3.string().optional(),
8089
9276
  /**
8090
9277
  * Project-root-relative path to a custom Handlebars template. When omitted,
8091
9278
  * the bundled default template (command-render.ts) is used.
8092
9279
  */
8093
- template: z2.string().optional()
9280
+ template: z3.string().optional()
8094
9281
  }).strip();
8095
- var ClaudeCommandsToggle = z2.union([z2.boolean(), ClaudeCommandsEmitSchema]).optional().transform((v) => {
9282
+ var ClaudeCommandsToggle = z3.union([z3.boolean(), ClaudeCommandsEmitSchema]).optional().transform((v) => {
8096
9283
  if (v === void 0 || v === false) return void 0;
8097
9284
  if (v === true) return {};
8098
9285
  return v;
8099
9286
  });
8100
- var ClaudeEmitSchema = z2.object({
9287
+ var ClaudeEmitSchema = z3.object({
8101
9288
  /** When true, materialize `<output_dir>/workflows/<id>.js` per workflow. */
8102
- workflows: z2.boolean().default(false),
9289
+ workflows: z3.boolean().default(false),
8103
9290
  /** When set, materialize one slash-command file per workflow (#249). */
8104
- commands: ClaudeCommandsToggle
9291
+ commands: ClaudeCommandsToggle,
9292
+ /**
9293
+ * When true, materialize `<output_dir>/agents/<id>.md` per DSL agent, so
9294
+ * DSL-declared agents are real Claude Code subagents (#272). In a workspace
9295
+ * every member's agents are merged into the single root directory.
9296
+ */
9297
+ agents: z3.boolean().default(false)
8105
9298
  }).strip();
8106
- var ClaudeConfigSchema = z2.object({
9299
+ var ClaudeConfigSchema = z3.object({
8107
9300
  /** Root directory for Claude artifacts (relative to the project root). */
8108
- output_dir: z2.string().default(".claude"),
9301
+ output_dir: z3.string().default(".claude"),
8109
9302
  /**
8110
9303
  * Agents DSL path (relative to the project root) baked into the generated
8111
9304
  * nav hook bins as the FALLBACK for a project root with no `project.yaml`
@@ -8113,19 +9306,19 @@ var ClaudeConfigSchema = z2.object({
8113
9306
  * the hooks resolve `agents:` and `artifacts:` from it at hook runtime
8114
9307
  * (#260), so this value is not consulted.
8115
9308
  */
8116
- config_path: z2.string().default("./agent-contracts.yaml"),
9309
+ config_path: z3.string().default("./agent-contracts.yaml"),
8117
9310
  /**
8118
9311
  * Additive-artifact emission toggles. Defaults keep the historical
8119
9312
  * behavior (no workflow scripts) so existing output is byte-preserved.
8120
9313
  */
8121
- emit: ClaudeEmitSchema.default({ workflows: false, commands: void 0 }),
9314
+ emit: ClaudeEmitSchema.default({ workflows: false, commands: void 0, agents: false }),
8122
9315
  /**
8123
9316
  * Command wired into guardrail hooks (e.g. "dev-team guard evaluate").
8124
9317
  * Reserved for future hook integration; validated for config parity.
8125
9318
  */
8126
- guard_command: z2.string().optional(),
9319
+ guard_command: z3.string().optional(),
8127
9320
  /** Override component id; defaults to `dsl.system.id`. */
8128
- component_id: z2.string().optional()
9321
+ component_id: z3.string().optional()
8129
9322
  }).strip();
8130
9323
  function parseClaudeConfig(raw) {
8131
9324
  return ClaudeConfigSchema.parse(raw ?? {});
@@ -8133,6 +9326,59 @@ function parseClaudeConfig(raw) {
8133
9326
 
8134
9327
  // src/lib/claude-materialize/workflow-render.ts
8135
9328
  import { resolveSchemaRefs } from "agent-contracts";
9329
+ import { pathSegmentForId as pathSegmentForId4 } from "@aaac/contracts";
9330
+
9331
+ // src/lib/claude-materialize/dsl-sources.ts
9332
+ import { existsSync as existsSync4 } from "fs";
9333
+ import { join as join4, resolve as resolve5 } from "path";
9334
+ function originLabel(source) {
9335
+ return source.member ?? "project";
9336
+ }
9337
+ async function workspaceMembersForProject(root) {
9338
+ const manifestPath = join4(root, PROJECT_CONFIG_FILENAME);
9339
+ if (!existsSync4(manifestPath)) return [];
9340
+ const members = await loadWorkspaceMembers(manifestPath);
9341
+ return members.map((m) => ({
9342
+ name: m.name,
9343
+ path: m.path,
9344
+ cacheKey: m.cacheKey
9345
+ }));
9346
+ }
9347
+ async function resolveDslSources(root, embeddedDsl, config) {
9348
+ const members = await workspaceMembersForProject(root);
9349
+ const roots = members.length > 0 ? members.map((m) => ({ member: m.name, root: resolve5(root, m.path) })) : [{ root }];
9350
+ return Promise.all(
9351
+ roots.map(async ({ member, root: projectRoot }) => {
9352
+ const { navigationOptions } = await resolveNavigationSources({
9353
+ projectRoot,
9354
+ embeddedDsl,
9355
+ dslPath: config.config_path
9356
+ });
9357
+ const dsl = await resolveNavigationDsl(navigationOptions);
9358
+ return member === void 0 ? { dsl } : { member, dsl };
9359
+ })
9360
+ );
9361
+ }
9362
+ function mergeSourceFiles(rendered, conflict) {
9363
+ const merged = /* @__PURE__ */ new Map();
9364
+ for (const { origin, files } of rendered) {
9365
+ for (const file of files) {
9366
+ const existing = merged.get(file.path);
9367
+ if (existing === void 0) {
9368
+ merged.set(file.path, { file, origin });
9369
+ continue;
9370
+ }
9371
+ if (existing.file.content !== file.content) {
9372
+ throw conflict(
9373
+ `"${file.path}" is generated differently by "${existing.origin}" and "${origin}"; Claude Code reads this directory from the harness root only, so it can hold just one version of the file. Align the two definitions, or rename one of them in the DSL.`
9374
+ );
9375
+ }
9376
+ }
9377
+ }
9378
+ return [...merged.values()].map((entry) => entry.file);
9379
+ }
9380
+
9381
+ // src/lib/claude-materialize/workflow-render.ts
8136
9382
  var GENERATED_MARKER = "// Auto-generated by @aaac/runtime claude-materialize (#235). Do not edit; run `claude sync` instead.";
8137
9383
  var MODEL_CLASS_MAP = {
8138
9384
  fast: { model: "haiku" },
@@ -8219,7 +9465,7 @@ function computeWaves(steps, deps) {
8219
9465
  return waves;
8220
9466
  }
8221
9467
  function renderDelegatePrompt(agent, task, step) {
8222
- const userRequest = (step.instruction ?? step.description ?? "").trim() || "Perform the task described above.";
9468
+ const userRequest = (step["x-instruction"] ?? step.description ?? "").trim() || "Perform the task described above.";
8223
9469
  return buildTaskPrompt(agent, task, { user_request: userRequest });
8224
9470
  }
8225
9471
  var PRIOR_CONTEXT_PREFIX = "\n\n---\n\n## Prior Context\n";
@@ -8238,18 +9484,6 @@ function resolveHandoffSchema(task, handoffTypes, components) {
8238
9484
  if (!ht?.schema) return void 0;
8239
9485
  return resolveSchemaRefs(ht.schema, components);
8240
9486
  }
8241
- function toAgentContract(id, raw) {
8242
- const rawMode = raw.mode ?? "read-only";
8243
- return {
8244
- id,
8245
- role_name: raw.role_name ?? id,
8246
- purpose: raw.purpose ?? "",
8247
- mode: rawMode === "read-write" ? "read-write" : "read-only",
8248
- responsibilities: raw.responsibilities ?? [],
8249
- constraints: raw.constraints ?? [],
8250
- rules: raw.rules ?? []
8251
- };
8252
- }
8253
9487
  function toTaskContract(id, raw) {
8254
9488
  return {
8255
9489
  id,
@@ -8261,10 +9495,8 @@ function toTaskContract(id, raw) {
8261
9495
  };
8262
9496
  }
8263
9497
  function buildRegistries(dsl) {
8264
- const rawAgents = dsl.agents ?? {};
8265
9498
  const rawTasks = dsl.tasks ?? {};
8266
- const agents = {};
8267
- for (const [id, a] of Object.entries(rawAgents)) agents[id] = toAgentContract(id, a);
9499
+ const agents = buildAgentRegistry(dsl);
8268
9500
  const tasks = {};
8269
9501
  for (const [id, t] of Object.entries(rawTasks)) tasks[id] = toTaskContract(id, t);
8270
9502
  const componentsRoot = dsl.components ?? {};
@@ -8596,19 +9828,46 @@ export const meta = ${metaLiteral}
8596
9828
  ${topLevelBody}
8597
9829
  `;
8598
9830
  }
8599
- function renderWorkflowFiles(dsl, outputDir) {
8600
- const workflows = dsl.workflow ?? {};
8601
- const root = outputDir.replace(/\/+$/, "");
8602
- const files = [];
8603
- for (const [id, wf] of Object.entries(workflows)) {
8604
- const content = renderWorkflowScript(id, wf, dsl);
8605
- files.push({ path: `${root}/workflows/${id}.js`, content });
8606
- }
8607
- return files;
9831
+ function renderWorkflowFiles(sources, outputDir) {
9832
+ const dir = workflowsDirFor(outputDir);
9833
+ return mergeSourceFiles(
9834
+ sources.map((source) => ({
9835
+ origin: originLabel(source),
9836
+ files: Object.entries(
9837
+ source.dsl.workflow ?? {}
9838
+ ).map(([id, wf]) => ({
9839
+ path: `${dir}/${pathSegmentForId4("workflow id", id)}${WORKFLOW_FILE_EXT}`,
9840
+ content: renderWorkflowScript(id, wf, source.dsl)
9841
+ }))
9842
+ })),
9843
+ (message) => new WorkflowCodegenError(message)
9844
+ );
9845
+ }
9846
+ var WORKFLOW_FILE_EXT = ".js";
9847
+ function workflowsDirFor(outputDir) {
9848
+ return `${outputDir.replace(/\/+$/, "")}/workflows`;
8608
9849
  }
8609
9850
 
8610
9851
  // src/lib/claude-materialize/command-render.ts
8611
9852
  var import_handlebars = __toESM(require_lib(), 1);
9853
+ import { pathSegmentForId as pathSegmentForId5 } from "@aaac/contracts";
9854
+
9855
+ // src/lib/claude-materialize/frontmatter.ts
9856
+ function yamlScalar(value) {
9857
+ const str = value === void 0 || value === null ? "" : String(value);
9858
+ return JSON.stringify(str);
9859
+ }
9860
+ function renderFrontmatter(fields) {
9861
+ const lines = ["---"];
9862
+ for (const [key, value] of fields) {
9863
+ if (value === void 0) continue;
9864
+ lines.push(`${key}: ${value}`);
9865
+ }
9866
+ lines.push("---");
9867
+ return lines.join("\n") + "\n";
9868
+ }
9869
+
9870
+ // src/lib/claude-materialize/command-render.ts
8612
9871
  var CommandCodegenError = class extends Error {
8613
9872
  constructor(message) {
8614
9873
  super(message);
@@ -8628,10 +9887,7 @@ argument-hint: <request>
8628
9887
  $ARGUMENTS
8629
9888
  `;
8630
9889
  var hb = import_handlebars.default.create();
8631
- hb.registerHelper("yaml", (value) => {
8632
- const str = value === void 0 || value === null ? "" : String(value);
8633
- return new import_handlebars.default.SafeString(JSON.stringify(str));
8634
- });
9890
+ hb.registerHelper("yaml", (value) => new import_handlebars.default.SafeString(yamlScalar(value)));
8635
9891
  function buildCommandContext(name, wf) {
8636
9892
  if (!name) {
8637
9893
  throw new CommandCodegenError("Workflow has an empty name; cannot generate a command file.");
@@ -8641,15 +9897,9 @@ function buildCommandContext(name, wf) {
8641
9897
  return { name, description, whenToUse, trigger: whenToUse };
8642
9898
  }
8643
9899
  function substituteName(outputTemplate, name) {
8644
- return outputTemplate.split(NAME_PLACEHOLDER).join(name);
9900
+ return outputTemplate.split(NAME_PLACEHOLDER).join(pathSegmentForId5("workflow id", name));
8645
9901
  }
8646
- function renderCommandFiles(dsl, outputTemplate, templateSource) {
8647
- if (!outputTemplate.includes(NAME_PLACEHOLDER)) {
8648
- throw new CommandCodegenError(
8649
- `Command output path "${outputTemplate}" is missing the required per-workflow placeholder "${NAME_PLACEHOLDER}"; every workflow would collide on one path.`
8650
- );
8651
- }
8652
- const render = hb.compile(templateSource, { noEscape: true });
9902
+ function renderOneDsl(dsl, outputTemplate, render) {
8653
9903
  const workflows = dsl.workflow ?? {};
8654
9904
  const files = [];
8655
9905
  const seenPaths = /* @__PURE__ */ new Set();
@@ -8666,32 +9916,167 @@ function renderCommandFiles(dsl, outputTemplate, templateSource) {
8666
9916
  }
8667
9917
  return files;
8668
9918
  }
9919
+ function renderCommandFiles(sources, outputTemplate, templateSource) {
9920
+ if (!outputTemplate.includes(NAME_PLACEHOLDER)) {
9921
+ throw new CommandCodegenError(
9922
+ `Command output path "${outputTemplate}" is missing the required per-workflow placeholder "${NAME_PLACEHOLDER}"; every workflow would collide on one path.`
9923
+ );
9924
+ }
9925
+ const render = hb.compile(templateSource, { noEscape: true });
9926
+ return mergeSourceFiles(
9927
+ sources.map((source) => ({
9928
+ origin: originLabel(source),
9929
+ files: renderOneDsl(source.dsl, outputTemplate, render)
9930
+ })),
9931
+ (message) => new CommandCodegenError(message)
9932
+ );
9933
+ }
9934
+
9935
+ // src/lib/claude-materialize/agent-render.ts
9936
+ import { pathSegmentForId as pathSegmentForId6 } from "@aaac/contracts";
9937
+ var AgentCodegenError = class extends Error {
9938
+ constructor(message) {
9939
+ super(message);
9940
+ this.name = "AgentCodegenError";
9941
+ }
9942
+ };
9943
+ var AGENTS_SUBDIR = "agents";
9944
+ var AGENT_FILE_EXT = ".md";
9945
+ var AGENT_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
9946
+ var GENERATED_MARKER2 = "<!-- Auto-generated from the agent-contracts DSL. Do not edit; run `claude sync`. -->";
9947
+ function agentsDirFor(outputDir) {
9948
+ return `${outputDir.replace(/\/+$/, "")}/${AGENTS_SUBDIR}`;
9949
+ }
9950
+ function canonicalize(value) {
9951
+ if (Array.isArray(value)) return value.map(canonicalize);
9952
+ if (value !== null && typeof value === "object") {
9953
+ const source = value;
9954
+ const out = {};
9955
+ for (const key of Object.keys(source).sort()) {
9956
+ out[key] = canonicalize(source[key]);
9957
+ }
9958
+ return out;
9959
+ }
9960
+ return value;
9961
+ }
9962
+ function listSection(title, items) {
9963
+ if (!items || items.length === 0) return void 0;
9964
+ return `## ${title}
9965
+
9966
+ ${items.map((i) => `- ${i}`).join("\n")}`;
9967
+ }
9968
+ function permissionSections(agent) {
9969
+ return [
9970
+ `## Mode
9971
+
9972
+ ${agent.mode}`,
9973
+ listSection("Readable Artifacts", agent.can_read_artifacts),
9974
+ listSection("Writable Artifacts", agent.can_write_artifacts),
9975
+ listSection("Executable Tools", agent.can_execute_tools),
9976
+ listSection("Invokable Agents", agent.can_invoke_agents),
9977
+ listSection("Returnable Handoffs", agent.can_return_handoffs),
9978
+ listSection("Performable Validations", agent.can_perform_validations)
9979
+ ].filter((s) => s !== void 0);
9980
+ }
9981
+ function agentDescription(agent) {
9982
+ const purpose = agent.purpose.replace(/\s+/g, " ").trim();
9983
+ if (!purpose) return agent.role_name;
9984
+ return `${agent.role_name} \u2014 ${purpose}`;
9985
+ }
9986
+ function renderAgentBody(agent) {
9987
+ return [renderAgentSystemPrompt(agent), ...permissionSections(agent)].join("\n\n").replace(/\s+$/, "");
9988
+ }
9989
+ function renderAgentFile(name, agent) {
9990
+ const frontmatter = renderFrontmatter([
9991
+ // `name` is validated against AGENT_NAME_PATTERN, so it is always a plain
9992
+ // YAML scalar and needs no quoting. `description` is arbitrary DSL prose.
9993
+ ["name", name],
9994
+ ["description", yamlScalar(agentDescription(agent))],
9995
+ // The Claude Code tool grant follows the contract, never the DSL tool ids.
9996
+ ["tools", toolGrantForAgent(agent).join(", ")]
9997
+ ]);
9998
+ const body = [GENERATED_MARKER2, renderAgentBody(agent)].join("\n\n");
9999
+ return `${frontmatter}
10000
+ ${body}
10001
+ `;
10002
+ }
10003
+ function isEntryAgent(agent) {
10004
+ return agent.dispatch_only === true;
10005
+ }
10006
+ function mergeAgents(sources, dir) {
10007
+ const merged = /* @__PURE__ */ new Map();
10008
+ for (const source of sources) {
10009
+ const rawAgents = source.dsl.agents ?? {};
10010
+ const registry = buildAgentRegistry(source.dsl);
10011
+ for (const [name, agent] of Object.entries(registry)) {
10012
+ const identity = JSON.stringify(canonicalize(rawAgents[name]));
10013
+ const existing = merged.get(name);
10014
+ if (existing && existing.identity !== identity) {
10015
+ throw new AgentCodegenError(
10016
+ `Agent "${name}" is defined differently by "${existing.origin}" and "${originLabel(source)}"; Claude Code keys subagents by frontmatter \`name\`, so ${dir}/ can hold only one definition of it \u2014 including which surface it is materialized to. Align the two definitions, or rename one of them in the DSL.`
10017
+ );
10018
+ }
10019
+ if (!existing) {
10020
+ merged.set(name, { agent, identity, origin: originLabel(source) });
10021
+ }
10022
+ }
10023
+ }
10024
+ return merged;
10025
+ }
10026
+ function renderAgentFiles(sources, outputDir) {
10027
+ const dir = agentsDirFor(outputDir);
10028
+ const files = [];
10029
+ for (const [name, { agent, origin }] of mergeAgents(sources, dir)) {
10030
+ if (isEntryAgent(agent)) continue;
10031
+ if (!AGENT_NAME_PATTERN.test(name)) {
10032
+ throw new AgentCodegenError(
10033
+ `Agent id "${name}" (${origin}) is not a valid Claude Code subagent name; names must match ${AGENT_NAME_PATTERN.source} (lowercase letters, digits and hyphens).`
10034
+ );
10035
+ }
10036
+ files.push({
10037
+ path: `${dir}/${pathSegmentForId6("agent id", name)}${AGENT_FILE_EXT}`,
10038
+ content: renderAgentFile(name, agent)
10039
+ });
10040
+ }
10041
+ return files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
10042
+ }
10043
+ function renderEntryAgentPrompt(sources, outputDir) {
10044
+ const entries = [...mergeAgents(sources, agentsDirFor(outputDir))].filter(([, { agent }]) => isEntryAgent(agent)).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
10045
+ if (entries.length === 0) return void 0;
10046
+ return entries.map(([, { agent }]) => renderAgentBody(agent)).join("\n\n");
10047
+ }
8669
10048
 
8670
10049
  // src/lib/claude-materialize/materialize.ts
8671
- import { existsSync as existsSync4 } from "fs";
8672
- import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
8673
- import { dirname as dirname5, join as join7, resolve as resolve5 } from "path";
10050
+ import { existsSync as existsSync5 } from "fs";
10051
+ import { chmod, mkdir as mkdir3, readFile as readFile5, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
10052
+ import { dirname as dirname5, join as join7, resolve as resolve6 } from "path";
8674
10053
  import {
8675
- claudeGenerator
10054
+ claudeGenerator,
10055
+ generatedFileRelPath,
10056
+ isOwnedByExtension,
10057
+ orphanGeneratedFiles
8676
10058
  } from "@aaac/contracts";
8677
10059
 
8678
10060
  // src/lib/claude-materialize/bundle-bins.ts
10061
+ import {
10062
+ isHookBinChunk
10063
+ } from "@aaac/contracts";
8679
10064
  import { createHash } from "crypto";
8680
10065
  import { readFileSync as readFileSync2 } from "fs";
8681
- import { dirname as dirname4, join as join6, parse as parse2 } from "path";
10066
+ import { dirname as dirname4, join as join6, parse as parse3 } from "path";
8682
10067
  import { fileURLToPath as fileURLToPath2 } from "url";
8683
10068
 
8684
10069
  // src/lib/claude-materialize/claude-bundle-assets.ts
8685
10070
  import { readFileSync } from "fs";
8686
- import { dirname as dirname3, join as join5, parse } from "path";
10071
+ import { dirname as dirname3, join as join5, parse as parse2 } from "path";
8687
10072
  import { fileURLToPath } from "url";
8688
10073
  function resolveRuntimeDistDir() {
8689
10074
  let dir = dirname3(fileURLToPath(import.meta.url));
8690
- const root = parse(dir).root;
10075
+ const root = parse2(dir).root;
8691
10076
  while (true) {
8692
10077
  try {
8693
- const pkg2 = JSON.parse(readFileSync(join5(dir, "package.json"), "utf8"));
8694
- if (pkg2.name === "@aaac/runtime") {
10078
+ const manifest = JSON.parse(readFileSync(join5(dir, "package.json"), "utf8"));
10079
+ if (typeof manifest === "object" && manifest !== null && manifest.name === "@aaac/runtime") {
8695
10080
  return join5(dir, "dist", "claude-bundles");
8696
10081
  }
8697
10082
  } catch {
@@ -8713,14 +10098,18 @@ function loadPrebuiltBundle(kind) {
8713
10098
  }
8714
10099
 
8715
10100
  // src/lib/claude-materialize/bundle-bins.ts
8716
- var RUNTIME_GLOBAL = "__aaac_runtime";
10101
+ var HOOK_BIN_DIR = ".claude/bin";
10102
+ var BUNDLE_KINDS = ["lean", "prompt", "full"];
8717
10103
  function resolveRuntimeVersion() {
8718
10104
  let dir = dirname4(fileURLToPath2(import.meta.url));
8719
- const root = parse2(dir).root;
10105
+ const root = parse3(dir).root;
8720
10106
  while (true) {
8721
10107
  try {
8722
- const pkg2 = JSON.parse(readFileSync2(join6(dir, "package.json"), "utf8"));
8723
- if (pkg2.name === "@aaac/runtime" && pkg2.version) return pkg2.version;
10108
+ const manifest = JSON.parse(readFileSync2(join6(dir, "package.json"), "utf8"));
10109
+ if (typeof manifest === "object" && manifest !== null) {
10110
+ const pkg2 = manifest;
10111
+ if (pkg2.name === "@aaac/runtime" && typeof pkg2.version === "string") return pkg2.version;
10112
+ }
8724
10113
  } catch {
8725
10114
  }
8726
10115
  if (dir === root) break;
@@ -8739,45 +10128,88 @@ function readPrebuiltBundle(kind) {
8739
10128
  }
8740
10129
  var MARKER_PREFIX = "//__aaac_bundle__:";
8741
10130
  function isHookBin(targetDir, path) {
8742
- return targetDir === ".claude/bin" && !path.includes("/");
8743
- }
8744
- function bundleKindFor(source) {
8745
- return /@aaac\/runtime\/claude-native\/hooks-lite/.test(source) ? "lean" : "full";
10131
+ return targetDir === HOOK_BIN_DIR && !path.includes("/");
8746
10132
  }
8747
- function extractRuntimeImport(source) {
8748
- const re = /import\s*\{([^}]*)\}\s*from\s*["']@aaac\/runtime\/claude-native(?:\/hooks-lite)?["'];?/;
8749
- const match = source.match(re);
8750
- if (!match) {
10133
+ var RUNTIME_IMPORT_RE = /(import\s*\{[^}]*\}\s*from\s*)["']@aaac\/runtime\/claude-native(?:\/(hooks-lite|hooks-prompt))?["']/g;
10134
+ function requireRuntimeImport(source) {
10135
+ const matches = [...source.matchAll(RUNTIME_IMPORT_RE)];
10136
+ if (matches.length !== 1) {
8751
10137
  throw new Error(
8752
- "Could not find the @aaac/runtime/claude-native import in the generated hook bin."
10138
+ `A generated hook bin must import @aaac/runtime/claude-native exactly once; found ${matches.length}${matches.length > 0 ? `: ${matches.map((m) => JSON.stringify(m[0])).join(", ")}` : ""}. Only one can be repointed at the shared chunk; any other would ship as a bare specifier that needs node_modules at hook runtime.`
8753
10139
  );
8754
10140
  }
8755
- const names = match[1].split(",").map((s) => s.trim()).filter((s) => s.length > 0);
8756
- return { statement: match[0], names };
10141
+ return matches[0];
10142
+ }
10143
+ var KIND_BY_SUBPATH = {
10144
+ "hooks-lite": "lean",
10145
+ "hooks-prompt": "prompt"
10146
+ };
10147
+ function bundleKindFor(source) {
10148
+ const subpath = requireRuntimeImport(source)[2];
10149
+ return subpath ? KIND_BY_SUBPATH[subpath] : "full";
10150
+ }
10151
+ var RUNTIME_CHUNK_FILE = {
10152
+ lean: "_aaac-runtime-lean.mjs",
10153
+ prompt: "_aaac-runtime-prompt.mjs",
10154
+ full: "_aaac-runtime-full.mjs"
10155
+ };
10156
+ function chunkFileName(kind) {
10157
+ return RUNTIME_CHUNK_FILE[kind];
8757
10158
  }
8758
- function assembleHookBin(source) {
8759
- const kind = bundleKindFor(source);
8760
- const bundle = readPrebuiltBundle(kind);
10159
+ function withMarker(bodyWithoutMarker) {
10160
+ const firstNl = bodyWithoutMarker.indexOf("\n");
10161
+ return bodyWithoutMarker.slice(0, firstNl + 1) + markerFor(bodyWithoutMarker) + "\n" + bodyWithoutMarker.slice(firstNl + 1);
10162
+ }
10163
+ function assembleHookBin(source, kind) {
8761
10164
  const withoutShebang = source.replace(/^#![^\n]*\n/, "");
8762
- const { statement, names } = extractRuntimeImport(withoutShebang);
8763
- const rebind = `const { ${names.join(", ")} } = ${RUNTIME_GLOBAL};`;
8764
- const binBody = withoutShebang.replace(statement, rebind);
8765
- const requireShim = [
8766
- "import { createRequire as __aaacCreateRequire } from 'node:module';",
8767
- "const require = __aaacCreateRequire(import.meta.url);",
8768
- "const __aaacImportMetaUrl = import.meta.url;",
8769
- "const __aaacImportMetaResolve = (s) => import.meta.resolve(s);"
8770
- ].join("\n");
8771
- const bodyWithoutMarker = [
8772
- "#!/usr/bin/env node",
8773
- "// Auto-generated by @aaac/runtime claude sync (#241). Do not edit \u2014 self-contained bundle.",
8774
- requireShim,
8775
- bundle.trimEnd(),
8776
- binBody.trimStart()
8777
- ].join("\n");
8778
- const marker = markerFor(bodyWithoutMarker);
8779
- const shebangEnd = bodyWithoutMarker.indexOf("\n");
8780
- return bodyWithoutMarker.slice(0, shebangEnd + 1) + marker + "\n" + bodyWithoutMarker.slice(shebangEnd + 1);
10165
+ const match = requireRuntimeImport(withoutShebang);
10166
+ const binBody = withoutShebang.replace(
10167
+ match[0],
10168
+ () => `${match[1]}"./${chunkFileName(kind)}"`
10169
+ );
10170
+ return withMarker(
10171
+ [
10172
+ "#!/usr/bin/env node",
10173
+ "// Auto-generated by @aaac/runtime claude sync (#241). Do not edit \u2014 self-contained bundle.",
10174
+ binBody.trimStart()
10175
+ ].join("\n")
10176
+ );
10177
+ }
10178
+ function assembleRuntimeChunk(kind) {
10179
+ return withMarker(
10180
+ [
10181
+ `// Auto-generated by @aaac/runtime claude sync (#278). Do not edit \u2014 shared ${kind} runtime chunk.`,
10182
+ readPrebuiltBundle(kind).trimEnd(),
10183
+ ""
10184
+ ].join("\n")
10185
+ );
10186
+ }
10187
+ function withAssembledHookBins(files) {
10188
+ const out = [];
10189
+ const needed = /* @__PURE__ */ new Set();
10190
+ for (const file of files) {
10191
+ if (!isHookBin(file.targetDir, file.path)) {
10192
+ out.push(file);
10193
+ continue;
10194
+ }
10195
+ if (isHookBinChunk(file.path)) {
10196
+ out.push({ ...file, content: withMarker(file.content) });
10197
+ continue;
10198
+ }
10199
+ const kind = bundleKindFor(file.content);
10200
+ needed.add(kind);
10201
+ out.push({ ...file, content: assembleHookBin(file.content, kind) });
10202
+ }
10203
+ for (const kind of BUNDLE_KINDS) {
10204
+ if (!needed.has(kind)) continue;
10205
+ out.push({
10206
+ path: chunkFileName(kind),
10207
+ content: assembleRuntimeChunk(kind),
10208
+ overwrite: true,
10209
+ targetDir: HOOK_BIN_DIR
10210
+ });
10211
+ }
10212
+ return out;
8781
10213
  }
8782
10214
  function markerFor(fullFileMinusMarker) {
8783
10215
  const hash = createHash("sha256").update(fullFileMinusMarker).digest("hex").slice(0, 16);
@@ -8790,10 +10222,6 @@ function readBundleMarker(content) {
8790
10222
  const line = content.slice(nl + 1, secondNl === -1 ? void 0 : secondNl);
8791
10223
  return line.startsWith(MARKER_PREFIX) ? line : void 0;
8792
10224
  }
8793
- function expectedBundleMarker(source) {
8794
- const assembled = assembleHookBin(source);
8795
- return readBundleMarker(assembled) ?? "";
8796
- }
8797
10225
  function recomputeMarkerFromDisk(content) {
8798
10226
  const nl = content.indexOf("\n");
8799
10227
  if (nl === -1) return void 0;
@@ -8801,10 +10229,9 @@ function recomputeMarkerFromDisk(content) {
8801
10229
  if (secondNl === -1) return void 0;
8802
10230
  const markerLine = content.slice(nl + 1, secondNl);
8803
10231
  if (!markerLine.startsWith(MARKER_PREFIX)) return void 0;
8804
- const shebang = content.slice(0, nl + 1);
10232
+ const firstLine = content.slice(0, nl + 1);
8805
10233
  const rest = content.slice(secondNl + 1);
8806
- const bodyWithoutMarker = shebang + rest;
8807
- return markerFor(bodyWithoutMarker);
10234
+ return markerFor(firstLine + rest);
8808
10235
  }
8809
10236
 
8810
10237
  // src/lib/claude-materialize/settings-merge.ts
@@ -8821,14 +10248,34 @@ function commandsInEntry(entry) {
8821
10248
  const c = commandOf(entry);
8822
10249
  return c === void 0 ? [] : [c];
8823
10250
  }
10251
+ function isCommandHook(value) {
10252
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
10253
+ const hook = value;
10254
+ return (hook.type === void 0 || typeof hook.type === "string") && (hook.command === void 0 || typeof hook.command === "string");
10255
+ }
10256
+ function isHookEntry(value) {
10257
+ if (!isCommandHook(value)) return false;
10258
+ const entry = value;
10259
+ return (entry.matcher === void 0 || typeof entry.matcher === "string") && (entry.hooks === void 0 || Array.isArray(entry.hooks) && entry.hooks.every(isCommandHook));
10260
+ }
10261
+ function isClaudeSettings(value) {
10262
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
10263
+ const settings = value;
10264
+ if (settings.hooks === void 0) return true;
10265
+ if (typeof settings.hooks !== "object" || settings.hooks === null) return false;
10266
+ return Object.values(settings.hooks).every(
10267
+ (entries) => Array.isArray(entries) && entries.every(isHookEntry)
10268
+ );
10269
+ }
8824
10270
  function parseSettings(raw) {
8825
10271
  if (!raw || !raw.trim()) return {};
10272
+ let parsed;
8826
10273
  try {
8827
- const parsed = JSON.parse(raw);
8828
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
10274
+ parsed = JSON.parse(raw);
8829
10275
  } catch {
8830
10276
  return {};
8831
10277
  }
10278
+ return isClaudeSettings(parsed) ? parsed : {};
8832
10279
  }
8833
10280
  function serializeSettings(settings) {
8834
10281
  return JSON.stringify(settings, null, 2) + "\n";
@@ -8916,42 +10363,32 @@ function buildComponentIR(dsl, config) {
8916
10363
  operations: {}
8917
10364
  };
8918
10365
  }
8919
- function relPath(file) {
8920
- if (file.targetDir && file.targetDir !== ".") {
8921
- return join7(file.targetDir, file.path);
8922
- }
8923
- return file.path;
8924
- }
8925
10366
  function absPath(root, file) {
8926
- return join7(root, relPath(file));
10367
+ return join7(root, generatedFileRelPath(file));
8927
10368
  }
8928
10369
  async function readIfExists(path) {
8929
- if (!existsSync4(path)) return void 0;
10370
+ if (!existsSync5(path)) return void 0;
8930
10371
  return readFile5(path, "utf8");
8931
10372
  }
8932
- async function workspaceMembersForProject(root) {
8933
- const manifestPath = join7(root, PROJECT_CONFIG_FILENAME);
8934
- if (!existsSync4(manifestPath)) return [];
8935
- const members = await loadWorkspaceMembers(manifestPath);
8936
- return members.map((m) => ({
8937
- name: m.name,
8938
- path: m.path,
8939
- cacheKey: m.cacheKey,
8940
- guardrailCacheKey: guardrailCacheKey(m.cacheKey)
8941
- }));
8942
- }
8943
- async function renderFiles(root, dsl, config) {
10373
+ async function renderFiles(root, dsl, config, entryAgentPrompt) {
8944
10374
  const ir = buildComponentIR(dsl, config);
8945
10375
  const members = await workspaceMembersForProject(root);
8946
10376
  const workspaceOptions = members.length > 0 ? { members } : void 0;
8947
- return claudeGenerator.generate(ir, {
8948
- outputDir: "",
8949
- componentPath: "",
8950
- // Bake the resolved DSL into the nav hook bins so a consumer project DSL
8951
- // that `extends: /$embedded/` resolves at hook runtime (#255 follow-up).
8952
- resolvedDslData: dsl,
8953
- workspace: workspaceOptions
8954
- });
10377
+ return withAssembledHookBins(
10378
+ claudeGenerator.generate(ir, {
10379
+ outputDir: "",
10380
+ componentPath: "",
10381
+ // Bake the resolved DSL into the nav hook bins so a consumer project DSL
10382
+ // that `extends: /$embedded/` resolves at hook runtime (#255 follow-up).
10383
+ resolvedDslData: dsl,
10384
+ workspace: workspaceOptions,
10385
+ // The other half of the agent render: a dispatch-only agent has no
10386
+ // subagent file, so the CLAUDE.md block is where its prompt reaches
10387
+ // Claude (#345). Resolved by the caller from the SAME merge that produced
10388
+ // the subagent files.
10389
+ entryAgentPrompt
10390
+ })
10391
+ );
8955
10392
  }
8956
10393
  function mergeClaudeMdBlock(existing, block) {
8957
10394
  const normalizedBlock = block.trimStart();
@@ -9025,93 +10462,205 @@ function checkContent(file, existing) {
9025
10462
  if (existing !== file.content) return "changed";
9026
10463
  return null;
9027
10464
  }
9028
- function workflowFiles(dsl, config) {
10465
+ function workflowFiles(sources, config) {
9029
10466
  if (!config.emit.workflows) return [];
9030
- return renderWorkflowFiles(dsl, config.output_dir);
10467
+ return renderWorkflowFiles(sources, config.output_dir);
9031
10468
  }
9032
- async function commandFiles(dsl, config, root) {
10469
+ function commandOutputTemplate(config) {
10470
+ const commands = config.emit.commands;
10471
+ if (!commands) return void 0;
10472
+ return commands.output ?? DEFAULT_COMMAND_OUTPUT;
10473
+ }
10474
+ async function commandFiles(sources, config, root) {
9033
10475
  const commands = config.emit.commands;
9034
10476
  if (!commands) return [];
9035
- const outputTemplate = commands.output ?? DEFAULT_COMMAND_OUTPUT;
10477
+ const outputTemplate = commandOutputTemplate(config);
9036
10478
  let templateSource = DEFAULT_COMMAND_TEMPLATE;
9037
10479
  if (commands.template) {
9038
- const templatePath = resolve5(root, commands.template);
10480
+ const templatePath = resolve6(root, commands.template);
9039
10481
  templateSource = await readFile5(templatePath, "utf8");
9040
10482
  }
9041
- return renderCommandFiles(dsl, outputTemplate, templateSource);
10483
+ return renderCommandFiles(sources, outputTemplate, templateSource);
10484
+ }
10485
+ function agentFiles(sources, config) {
10486
+ if (!config.emit.agents) return [];
10487
+ return renderAgentFiles(sources, config.output_dir);
10488
+ }
10489
+ function entryAgentPromptFor(sources, config) {
10490
+ if (!config.emit.agents) return void 0;
10491
+ return renderEntryAgentPrompt(sources, config.output_dir);
10492
+ }
10493
+ async function isOwnedHookBinFile(_name, absPath2) {
10494
+ const content = await readIfExists(absPath2).catch(() => void 0);
10495
+ return content !== void 0 && readBundleMarker(content) !== void 0;
10496
+ }
10497
+ function templateDir(outputTemplate) {
10498
+ const slash = outputTemplate.lastIndexOf("/");
10499
+ return slash === -1 ? "." : outputTemplate.slice(0, slash);
10500
+ }
10501
+ function templateExt(outputTemplate) {
10502
+ const base = outputTemplate.slice(outputTemplate.lastIndexOf("/") + 1);
10503
+ const dot = base.lastIndexOf(".");
10504
+ return dot <= 0 ? "" : base.slice(dot);
10505
+ }
10506
+ async function orphanFiles(root, config, rendered, workflows, commands, agents) {
10507
+ const orphans = await orphanGeneratedFiles(
10508
+ root,
10509
+ HOOK_BIN_DIR,
10510
+ rendered.filter((f) => isHookBin(f.targetDir, f.path)).map(generatedFileRelPath),
10511
+ isOwnedHookBinFile
10512
+ );
10513
+ if (config.emit.workflows) {
10514
+ orphans.push(
10515
+ ...await orphanGeneratedFiles(
10516
+ root,
10517
+ workflowsDirFor(config.output_dir),
10518
+ workflows.map((f) => f.path),
10519
+ isOwnedByExtension(WORKFLOW_FILE_EXT)
10520
+ )
10521
+ );
10522
+ }
10523
+ const commandTemplate = commandOutputTemplate(config);
10524
+ if (commandTemplate) {
10525
+ orphans.push(
10526
+ ...await orphanGeneratedFiles(
10527
+ root,
10528
+ templateDir(commandTemplate),
10529
+ commands.map((f) => f.path),
10530
+ isOwnedByExtension(templateExt(commandTemplate))
10531
+ )
10532
+ );
10533
+ }
10534
+ if (config.emit.agents) {
10535
+ orphans.push(
10536
+ ...await orphanGeneratedFiles(
10537
+ root,
10538
+ agentsDirFor(config.output_dir),
10539
+ agents.map((f) => f.path),
10540
+ isOwnedByExtension(AGENT_FILE_EXT)
10541
+ )
10542
+ );
10543
+ }
10544
+ return orphans;
9042
10545
  }
9043
10546
  function actionForOverwrite(existing, next) {
9044
10547
  if (existing === void 0) return "created";
9045
10548
  return existing === next ? "unchanged" : "updated";
9046
10549
  }
10550
+ var EXECUTABLE_MODE = 493;
10551
+ var OWNER_EXEC_BIT = 64;
10552
+ async function execBitMissing(abs) {
10553
+ try {
10554
+ const { mode } = await stat2(abs);
10555
+ return (mode & OWNER_EXEC_BIT) === 0;
10556
+ } catch {
10557
+ return false;
10558
+ }
10559
+ }
10560
+ async function writeArtifact(opts) {
10561
+ const modeOnly = opts.action === "unchanged" && opts.executable && await execBitMissing(opts.abs);
10562
+ const action = modeOnly ? "updated" : opts.action;
10563
+ if (action === "unchanged" || opts.dryRun) return action;
10564
+ if (!modeOnly) {
10565
+ await mkdir3(dirname5(opts.abs), { recursive: true });
10566
+ await writeFile3(opts.abs, opts.content(), "utf8");
10567
+ }
10568
+ if (opts.executable) await chmod(opts.abs, EXECUTABLE_MODE);
10569
+ return action;
10570
+ }
10571
+ function checkHookBin(file, existing) {
10572
+ if (existing === void 0) return "missing";
10573
+ const stored = readBundleMarker(existing);
10574
+ const expected = readBundleMarker(file.content);
10575
+ const onDisk = recomputeMarkerFromDisk(existing);
10576
+ return stored !== expected || stored !== onDisk ? "changed" : null;
10577
+ }
9047
10578
  async function syncClaude(opts) {
9048
10579
  const config = parseClaudeConfig(opts.config);
9049
- const root = resolve5(opts.projectRoot);
10580
+ const root = resolve6(opts.projectRoot);
9050
10581
  const result = { files: [] };
9051
- for (const file of await renderFiles(root, opts.dsl, config)) {
9052
- const rel = relPath(file);
10582
+ const sources = await resolveDslSources(root, opts.dsl, config);
10583
+ const rendered = await renderFiles(root, opts.dsl, config, entryAgentPromptFor(sources, config));
10584
+ for (const file of rendered) {
10585
+ const rel = generatedFileRelPath(file);
9053
10586
  const abs = absPath(root, file);
9054
10587
  const existing = await readIfExists(abs);
9055
10588
  if (isHookBin(file.targetDir, file.path)) {
9056
- const expected = expectedBundleMarker(file.content);
9057
- const stored = existing === void 0 ? void 0 : readBundleMarker(existing);
9058
- const onDisk = existing === void 0 ? void 0 : recomputeMarkerFromDisk(existing);
9059
- const upToDate = existing !== void 0 && stored === expected && stored === onDisk;
9060
- const action2 = existing === void 0 ? "created" : upToDate ? "unchanged" : "updated";
9061
- if (action2 !== "unchanged" && !opts.dryRun) {
9062
- const assembled = assembleHookBin(file.content);
9063
- await mkdir3(dirname5(abs), { recursive: true });
9064
- await writeFile3(abs, assembled, "utf8");
9065
- }
9066
- result.files.push({ path: rel, action: action2 });
10589
+ const drift = checkHookBin(file, existing);
10590
+ const action2 = drift === "missing" ? "created" : drift === "changed" ? "updated" : "unchanged";
10591
+ result.files.push({
10592
+ path: rel,
10593
+ action: await writeArtifact({
10594
+ abs,
10595
+ content: () => file.content,
10596
+ action: action2,
10597
+ executable: file.executable === true,
10598
+ dryRun: opts.dryRun === true
10599
+ })
10600
+ });
9067
10601
  continue;
9068
10602
  }
9069
10603
  const { content, action } = resolveContent(file, existing);
9070
- if (action !== "unchanged" && !opts.dryRun) {
9071
- await mkdir3(dirname5(abs), { recursive: true });
9072
- await writeFile3(abs, content, "utf8");
9073
- }
9074
- result.files.push({ path: rel, action });
10604
+ result.files.push({
10605
+ path: rel,
10606
+ action: await writeArtifact({
10607
+ abs,
10608
+ content: () => content,
10609
+ action,
10610
+ executable: file.executable === true,
10611
+ dryRun: opts.dryRun === true
10612
+ })
10613
+ });
9075
10614
  }
9076
- const additive = [...workflowFiles(opts.dsl, config), ...await commandFiles(opts.dsl, config, root)];
10615
+ const workflows = workflowFiles(sources, config);
10616
+ const commands = await commandFiles(sources, config, root);
10617
+ const agents = agentFiles(sources, config);
10618
+ const additive = [...workflows, ...commands, ...agents];
9077
10619
  for (const file of additive) {
9078
10620
  const abs = join7(root, file.path);
9079
10621
  const existing = await readIfExists(abs);
9080
- const action = actionForOverwrite(existing, file.content);
9081
- if (action !== "unchanged" && !opts.dryRun) {
9082
- await mkdir3(dirname5(abs), { recursive: true });
9083
- await writeFile3(abs, file.content, "utf8");
10622
+ result.files.push({
10623
+ path: file.path,
10624
+ // Workflow scripts, slash commands and subagent files are read by the
10625
+ // harness, never exec'd by path, so none of them is executable.
10626
+ action: await writeArtifact({
10627
+ abs,
10628
+ content: () => file.content,
10629
+ action: actionForOverwrite(existing, file.content),
10630
+ executable: false,
10631
+ dryRun: opts.dryRun === true
10632
+ })
10633
+ });
10634
+ }
10635
+ for (const path of await orphanFiles(root, config, rendered, workflows, commands, agents)) {
10636
+ if (!opts.dryRun) {
10637
+ await rm(join7(root, path));
9084
10638
  }
9085
- result.files.push({ path: file.path, action });
10639
+ result.files.push({ path, action: "deleted" });
9086
10640
  }
9087
10641
  return result;
9088
10642
  }
9089
10643
  async function checkClaude(opts) {
9090
10644
  const config = parseClaudeConfig(opts.config);
9091
- const root = resolve5(opts.projectRoot);
10645
+ const root = resolve6(opts.projectRoot);
9092
10646
  const drift = [];
9093
- for (const file of await renderFiles(root, opts.dsl, config)) {
9094
- const rel = relPath(file);
9095
- const existing = await readIfExists(absPath(root, file));
9096
- if (isHookBin(file.targetDir, file.path)) {
9097
- if (existing === void 0) {
9098
- drift.push({ path: rel, reason: "missing" });
9099
- } else {
9100
- const stored = readBundleMarker(existing);
9101
- const expected = expectedBundleMarker(file.content);
9102
- const onDisk = recomputeMarkerFromDisk(existing);
9103
- if (stored !== expected || stored !== onDisk) {
9104
- drift.push({ path: rel, reason: "changed" });
9105
- }
9106
- }
9107
- continue;
9108
- }
9109
- const reason = checkContent(file, existing);
10647
+ const sources = await resolveDslSources(root, opts.dsl, config);
10648
+ const rendered = await renderFiles(root, opts.dsl, config, entryAgentPromptFor(sources, config));
10649
+ for (const file of rendered) {
10650
+ const rel = generatedFileRelPath(file);
10651
+ const abs = absPath(root, file);
10652
+ const existing = await readIfExists(abs);
10653
+ const contentReason = isHookBin(file.targetDir, file.path) ? checkHookBin(file, existing) : checkContent(file, existing);
10654
+ const modeDrift = contentReason === null && file.executable === true && existing !== void 0 && await execBitMissing(abs);
10655
+ const reason = contentReason ?? (modeDrift ? "changed" : null);
9110
10656
  if (reason) {
9111
10657
  drift.push({ path: rel, reason });
9112
10658
  }
9113
10659
  }
9114
- const additive = [...workflowFiles(opts.dsl, config), ...await commandFiles(opts.dsl, config, root)];
10660
+ const workflows = workflowFiles(sources, config);
10661
+ const commands = await commandFiles(sources, config, root);
10662
+ const agents = agentFiles(sources, config);
10663
+ const additive = [...workflows, ...commands, ...agents];
9115
10664
  for (const file of additive) {
9116
10665
  const existing = await readIfExists(join7(root, file.path));
9117
10666
  if (existing === void 0) {
@@ -9120,6 +10669,9 @@ async function checkClaude(opts) {
9120
10669
  drift.push({ path: file.path, reason: "changed" });
9121
10670
  }
9122
10671
  }
10672
+ for (const path of await orphanFiles(root, config, rendered, workflows, commands, agents)) {
10673
+ drift.push({ path, reason: "orphaned" });
10674
+ }
9123
10675
  return { inSync: drift.length === 0, drift };
9124
10676
  }
9125
10677
 
@@ -9181,14 +10733,17 @@ ${schema}
9181
10733
  function parseRouterResponse(response, validNames) {
9182
10734
  const yamlMatch = response.match(/```(?:yaml)?\n([\s\S]*?)```/);
9183
10735
  const content = yamlMatch ? yamlMatch[1].trim() : response.trim();
10736
+ const asMapping = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
9184
10737
  let parsed;
9185
10738
  try {
9186
- parsed = YAML2.parse(content);
10739
+ parsed = asMapping(YAML2.parse(content));
9187
10740
  } catch {
10741
+ }
10742
+ if (parsed === void 0) {
9188
10743
  const jsonMatch = response.match(/\{[\s\S]*"operation"[\s\S]*\}/);
9189
10744
  if (jsonMatch) {
9190
10745
  try {
9191
- parsed = JSON.parse(jsonMatch[0]);
10746
+ parsed = asMapping(JSON.parse(jsonMatch[0]));
9192
10747
  } catch {
9193
10748
  }
9194
10749
  }
@@ -9243,6 +10798,7 @@ var version = pkg.version;
9243
10798
  export {
9244
10799
  AgentLogWriter,
9245
10800
  BoundResolver,
10801
+ DEFAULT_COMPONENT_ID,
9246
10802
  DslValidationError,
9247
10803
  FileMemoryStore,
9248
10804
  InMemoryStore,
@@ -9250,6 +10806,8 @@ export {
9250
10806
  PROJECT_CONFIG_FILENAME,
9251
10807
  PluginRegistry,
9252
10808
  ToolchainManifestSchema,
10809
+ UNRESOLVED_GUARDRAIL_ACTION,
10810
+ UnresolvedScopeDeclarationError,
9253
10811
  WORKFLOW_INPUT_STEP_ID,
9254
10812
  WorkflowBuilder,
9255
10813
  buildCandidateAgents,
@@ -9270,7 +10828,6 @@ export {
9270
10828
  createComponentScope,
9271
10829
  createExecutionEnvelope,
9272
10830
  createGuardrailHooks,
9273
- createGuardrailHooksForAgent,
9274
10831
  createGuardrailHooksFromRules,
9275
10832
  createLibraryToolRegistry,
9276
10833
  createModelResolver,
@@ -9319,8 +10876,6 @@ export {
9319
10876
  listGuardrails,
9320
10877
  loadDslContext,
9321
10878
  loadPlugins,
9322
- loadPluginsFromDirectory,
9323
- loadPluginsFromPaths,
9324
10879
  operationsToTools,
9325
10880
  parseClaudeConfig,
9326
10881
  parseGateEvaluationResponse,